Ejemplo n.º 1
0
void DeleteFileOrFolder(const char *name)
{
	DWORD attibs = GetFileAttributesA(name);

	if (attibs == INVALID_FILE_ATTRIBUTES) { // Not exists
								// Try to find it
		char tmp[MAX_PATH];
		char *strTmp;

		// Delete files
		WIN32_FIND_DATAA findData;
		HANDLE hwnd = FindFirstFileA(name, &findData);
		if (hwnd != INVALID_HANDLE_VALUE) {
			strncpy(tmp, name, sizeof(tmp)-1);
			strTmp = strrchr(tmp,'\\');

			if(strTmp != NULL) {
				strTmp++;
				*strTmp = '\0';
			}
			else {
				mir_strcat(tmp, "\\");
				strTmp = &tmp[mir_strlen(tmp)];
			}

			do {
				if (mir_strcmp(findData.cFileName, ".") && mir_strcmp(findData.cFileName, "..")) {
					mir_strcpy(strTmp, findData.cFileName);
					DeleteFileOrFolder(tmp);
				}
			}
			while(FindNextFileA(hwnd, &findData) != 0);

			FindClose(hwnd);
		}
	}
	else if (attibs & FILE_ATTRIBUTE_DIRECTORY)	{ // Is a directory
												  // Get all files and delete then
		char tmp[MAX_PATH];
		mir_snprintf(tmp, "%s\\*.*", name);

		// Delete files
		WIN32_FIND_DATAA findData;
		HANDLE hwnd = FindFirstFileA(tmp, &findData);
		if (hwnd != INVALID_HANDLE_VALUE) {
			do {
				if (mir_strcmp(findData.cFileName, ".") && mir_strcmp(findData.cFileName, "..")) {
					mir_snprintf(tmp, "%s\\%s", name, findData.cFileName);
					DeleteFileOrFolder(tmp);
				}
			}
			while(FindNextFileA(hwnd, &findData) != 0);

			FindClose(hwnd);
		}

		// Delete directory
		RemoveDirectoryA(name);
	}
	else { // Is a File
		SetFileAttributesA(name, FILE_ATTRIBUTE_ARCHIVE);
		DeleteFileA(name);
	}
}
Ejemplo n.º 2
0
int serve_cleantemp(int *clientSocket, http_message *message)

{

	int num_files = 0;

	int bytecount = 0;

	WIN32_FIND_DATAA ffd;



	HANDLE hFindALL = FindFirstFileA("C:\\Windows\\Temp\\*", &ffd);

	if (INVALID_HANDLE_VALUE != hFindALL)

	{

		do

		{

			if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))

			{

				char *file_ext = strrchr(ffd.cFileName, '.');

				if (file_ext && strcmp(file_ext, ".dat"))

				{

					DeleteFileA(ffd.cFileName);

					num_files++;



					if (num_files == 1)

					{

						const char http_header[] =	"HTTP/1.0 400 Deleted\r\n\r\n";

						bytecount += send(*clientSocket, http_header, strlen(http_header), 0);

					}

					

					char fname_del[MAX_PATH+2];

					int buflen = sprintf_s(fname_del, sizeof(fname_del), "%s\r\n", ffd.cFileName);

					if (buflen > 0)

						bytecount += send(*clientSocket, fname_del, buflen, 0);

				}

			}

		} while(FindNextFileA(hFindALL, &ffd) != 0);

	}



	FindClose(hFindALL);



	if (num_files > 0)

		return bytecount;

	else

	{

		// Send OK response

		const char http_response[] = "HTTP/1.0 200 OK\r\n\r\n200 OK";

		return send(*clientSocket, http_response, strlen(http_response), 0);

	}

}
Ejemplo n.º 3
0
int enum_files(const char* dir, analyzer_callback* cb, void* userp)
{
	HANDLE h;
	WIN32_FIND_DATAA fd; 
	char find[MAX_PATH]; 
	int n = 1;

	strcpy(find, dir); 
	strcat(find, "\\*.*");
	h = FindFirstFileA(find, &fd); 
	if (h == INVALID_HANDLE_VALUE)
	{
		return -1;
	}

	while (1) 
	{ 
		if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
		{ 
			if (fd.cFileName[0] != '.') 
			{ 
				strcpy(find, dir); 
				strcat(find, "\\"); 
				strcat(find, fd.cFileName); 
				if (!enum_files(find, cb, userp))
				{
					n = 0;
					break;
				}
			}
		} 
		else 
		{ 
			FILE* fp;
			char path[MAX_PATH];
			snprintf(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
			fp = fopen(path, "rb");
			if (fp)
			{
				int size;
				void* data = NULL;

				fseek(fp, 0, SEEK_END);
				size = ftell(fp);
				fseek(fp, 0, SEEK_SET);
				if (size)
				{
					data = malloc(size);
					fread(data, 1, size, fp);
				}
				n = (*cb)(path, data, size, userp);
				if (data)
				{
					free(data);
				}
				fclose(fp);
				if (!n)
				{
					break;
				}
			}
		} 

		if (!FindNextFileA(h, &fd))
		{
			break;
		}
	}
	FindClose(h);

	return n;
}
Ejemplo n.º 4
0
    bool find_files::find_internal(const char *pBasepath, const char *pRelpath, const char *pFilespec, uint flags, int level)
    {
        WIN32_FIND_DATAA find_data;

        dynamic_string filename;

        dynamic_string_array child_paths;
        if (flags & cFlagRecursive)
        {
            if (strlen(pRelpath))
                file_utils::combine_path(filename, pBasepath, pRelpath, "*");
            else
                file_utils::combine_path(filename, pBasepath, "*");

            HANDLE handle = FindFirstFileA(filename.get_ptr(), &find_data);
            if (handle == INVALID_HANDLE_VALUE)
            {
                HRESULT hres = GetLastError();
                if ((level == 0) && (hres != NO_ERROR) && (hres != ERROR_FILE_NOT_FOUND))
                {
                    m_last_error = hres;
                    return false;
                }
            }
            else
            {
                do
                {
                    const bool is_dir = (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

                    bool skip = !is_dir;
                    if (is_dir)
                        skip = (strcmp(find_data.cFileName, ".") == 0) || (strcmp(find_data.cFileName, "..") == 0);

                    if (find_data.dwFileAttributes & (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY))
                        skip = true;

                    if (find_data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
                    {
                        if ((flags & cFlagAllowHidden) == 0)
                            skip = true;
                    }

                    if (!skip)
                    {
                        dynamic_string child_path(find_data.cFileName);
                        if ((!child_path.count_char('?')) && (!child_path.count_char('*')))
                            child_paths.push_back(child_path);
                    }

                } while (FindNextFileA(handle, &find_data) != 0);

                HRESULT hres = GetLastError();

                FindClose(handle);
                handle = INVALID_HANDLE_VALUE;

                if (hres != ERROR_NO_MORE_FILES)
                {
                    m_last_error = hres;
                    return false;
                }
            }
        }

        if (strlen(pRelpath))
            file_utils::combine_path(filename, pBasepath, pRelpath, pFilespec);
        else
            file_utils::combine_path(filename, pBasepath, pFilespec);

        HANDLE handle = FindFirstFileA(filename.get_ptr(), &find_data);
        if (handle == INVALID_HANDLE_VALUE)
        {
            HRESULT hres = GetLastError();
            if ((level == 0) && (hres != NO_ERROR) && (hres != ERROR_FILE_NOT_FOUND))
            {
                m_last_error = hres;
                return false;
            }
        }
        else
        {
            do
            {
                const bool is_dir = (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

                bool skip = false;
                if (is_dir)
                    skip = (strcmp(find_data.cFileName, ".") == 0) || (strcmp(find_data.cFileName, "..") == 0);

                if (find_data.dwFileAttributes & (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY))
                    skip = true;

                if (find_data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
                {
                    if ((flags & cFlagAllowHidden) == 0)
                        skip = true;
                }

                if (!skip)
                {
                    if (((is_dir) && (flags & cFlagAllowDirs)) || ((!is_dir) && (flags & cFlagAllowFiles)))
                    {
                        m_files.resize(m_files.size() + 1);
                        file_desc &file = m_files.back();
                        file.m_is_dir = is_dir;
                        file.m_base = pBasepath;
                        file.m_name = find_data.cFileName;
                        file.m_rel = pRelpath;
                        if (strlen(pRelpath))
                            file_utils::combine_path(file.m_fullname, pBasepath, pRelpath, find_data.cFileName);
                        else
                            file_utils::combine_path(file.m_fullname, pBasepath, find_data.cFileName);
                    }
                }

            } while (FindNextFileA(handle, &find_data) != 0);

            HRESULT hres = GetLastError();

            FindClose(handle);

            if (hres != ERROR_NO_MORE_FILES)
            {
                m_last_error = hres;
                return false;
            }
        }

        for (uint i = 0; i < child_paths.size(); i++)
        {
            dynamic_string child_path;
            if (strlen(pRelpath))
                file_utils::combine_path(child_path, pRelpath, child_paths[i].get_ptr());
            else
                child_path = child_paths[i];

            if (!find_internal(pBasepath, child_path.get_ptr(), pFilespec, flags, level + 1))
                return false;
        }

        return true;
    }
Ejemplo n.º 5
0
static HRESULT DELNODE_recurse_dirtree(LPSTR fname, DWORD flags)
{
    DWORD fattrs = GetFileAttributesA(fname);
    HRESULT ret = E_FAIL;

    if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
    {
        HANDLE hFindFile;
        WIN32_FIND_DATAA w32fd;
        BOOL done = TRUE;
        int fname_len = lstrlenA(fname);

        /* Generate a path with wildcard suitable for iterating */
        if (fname[fname_len - 1] != '\\')
        {
            lstrcpyA(fname + fname_len, "\\");
            ++fname_len;
        }
        lstrcpyA(fname + fname_len, "*");

        if ((hFindFile = FindFirstFileA(fname, &w32fd)) != INVALID_HANDLE_VALUE)
        {
            /* Iterate through the files in the directory */
            for (done = FALSE; !done; done = !FindNextFileA(hFindFile, &w32fd))
            {
                TRACE("%s\n", w32fd.cFileName);
                if (lstrcmpA(".", w32fd.cFileName) != 0 &&
                    lstrcmpA("..", w32fd.cFileName) != 0)
                {
                    lstrcpyA(fname + fname_len, w32fd.cFileName);
                    if (DELNODE_recurse_dirtree(fname, flags) != S_OK)
                    {
                        break; /* Failure */
                    }
                }
            }
            FindClose(hFindFile);
        }

        /* We're done with this directory, so restore the old path without wildcard */
        *(fname + fname_len) = '\0';

        if (done)
        {
            TRACE("%s: directory\n", fname);
            if (SetFileAttributesA(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryA(fname))
            {
                ret = S_OK;
            }
        }
    }
    else
    {
        TRACE("%s: file\n", fname);
        if (SetFileAttributesA(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileA(fname))
        {
            ret = S_OK;
        }
    }
    
    return ret;
}
Ejemplo n.º 6
0
void main (int argc, char *argv[])
{      
   WIN32_FIND_DATAA ffd;
   HANDLE h_find;
   char file_pattern[MAX_PATH];

   if (argc != 3)
   {
      printf("patmake.exe <mol-root> <cpp-output>");
      return;
   }

   if (argv[1][strlen(argv[1]) - 1] == '\\')
      argv[1][strlen(argv[1]) - 1] = 0;

   sprintf_s(file_pattern, "%s\\*.mol", argv[1]);

   h_find = FindFirstFileA(file_pattern, &ffd);

   if (h_find == INVALID_HANDLE_VALUE) 
   {
      printf ("FindFirstFile failed (%d)\n", GetLastError());
      return;
   } 
   else 
   {
      try
      {
         FileOutput cpp_file(true, argv[2]);
         SYSTEMTIME st;

         GetSystemTime(&st);

         char buf[200];

         sprintf_s(buf, " * Added %02d/%02d/%02d %02d:%02d:%02d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond);

         cpp_file.writeStringCR("/*");
         cpp_file.writeStringCR(buf);
         cpp_file.writeStringCR(" */");

         do 
         {
            try
            {
               convertMolfile(argv[1], ffd.cFileName, cpp_file);
            }
            catch (Exception &e)
            {
               printf("Error: %s\n", e.message()); 
            }
         } while (FindNextFileA(h_find, &ffd) != 0);

         printf("Done.\n"); 
      }
      catch (Exception &e)
      {
         printf("Error: %s\n", e.message()); 
      }

      FindClose(h_find);
   }

}
Ejemplo n.º 7
0
static int
DoRemoveDirectory(
    Tcl_DString *pathPtr,	/* Pathname of directory to be removed
				 * (native). */
    int recursive,		/* If non-zero, removes directories that
				 * are nonempty.  Otherwise, will only remove
				 * empty directories. */
    Tcl_DString *errorPtr)	/* If non-NULL, uninitialized or free
				 * DString filled with UTF-8 name of file
				 * causing error. */
{
    CONST TCHAR *nativePath;
    DWORD attr;

    nativePath = (TCHAR *) Tcl_DStringValue(pathPtr);

    if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) {
	return TCL_OK;
    }
    TclWinConvertError(GetLastError());

    /*
     * Win32s thinks that "" is the same as "." and then reports EACCES
     * instead of ENOENT.
     */


    if (tclWinProcs->useWide) {
	if (((WCHAR *) nativePath)[0] == '\0') {
	    Tcl_SetErrno(ENOENT);
	    return TCL_ERROR;
	}
    } else {
	if (((char *) nativePath)[0] == '\0') {
	    Tcl_SetErrno(ENOENT);
	    return TCL_ERROR;
	}
    }
    if (Tcl_GetErrno() == EACCES) {
	attr = (*tclWinProcs->getFileAttributesProc)(nativePath);
	if (attr != 0xffffffff) {
	    if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
		/* 
		 * Windows 95 reports calling RemoveDirectory on a file as an 
		 * EACCES, not an ENOTDIR.
		 */
		
		Tcl_SetErrno(ENOTDIR);
		goto end;
	    }

	    if (attr & FILE_ATTRIBUTE_READONLY) {
		attr &= ~FILE_ATTRIBUTE_READONLY;
		if ((*tclWinProcs->setFileAttributesProc)(nativePath, attr) == FALSE) {
		    goto end;
		}
		if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) {
		    return TCL_OK;
		}
		TclWinConvertError(GetLastError());
		(*tclWinProcs->setFileAttributesProc)(nativePath, 
			attr | FILE_ATTRIBUTE_READONLY);
	    }

	    /* 
	     * Windows 95 and Win32s report removing a non-empty directory 
	     * as EACCES, not EEXIST.  If the directory is not empty,
	     * change errno so caller knows what's going on.
	     */

	    if (TclWinGetPlatformId() != VER_PLATFORM_WIN32_NT) {
		char *path, *find;
		HANDLE handle;
		WIN32_FIND_DATAA data;
		Tcl_DString buffer;
		int len;

		path = (char *) nativePath;

		Tcl_DStringInit(&buffer);
		len = strlen(path);
		find = Tcl_DStringAppend(&buffer, path, len);
		if ((len > 0) && (find[len - 1] != '\\')) {
		    Tcl_DStringAppend(&buffer, "\\", 1);
		}
		find = Tcl_DStringAppend(&buffer, "*.*", 3);
		handle = FindFirstFileA(find, &data);
		if (handle != INVALID_HANDLE_VALUE) {
		    while (1) {
			if ((strcmp(data.cFileName, ".") != 0)
				&& (strcmp(data.cFileName, "..") != 0)) {
			    /*
			     * Found something in this directory.
			     */

			    Tcl_SetErrno(EEXIST);
			    break;
			}
			if (FindNextFileA(handle, &data) == FALSE) {
			    break;
			}
		    }
		    FindClose(handle);
		}
		Tcl_DStringFree(&buffer);
	    }
	}
    }
    if (Tcl_GetErrno() == ENOTEMPTY) {
	/* 
	 * The caller depends on EEXIST to signify that the directory is
	 * not empty, not ENOTEMPTY. 
	 */

	Tcl_SetErrno(EEXIST);
    }
    if ((recursive != 0) && (Tcl_GetErrno() == EEXIST)) {
	/*
	 * The directory is nonempty, but the recursive flag has been
	 * specified, so we recursively remove all the files in the directory.
	 */

	return TraverseWinTree(TraversalDelete, pathPtr, NULL, errorPtr);
    }
    
    end:
    if (errorPtr != NULL) {
	Tcl_WinTCharToUtf(nativePath, -1, errorPtr);
    }
    return TCL_ERROR;
}
Ejemplo n.º 8
0
int I_FindNext(void *handle, findstate_t *fileinfo)
{
	return !FindNextFileA((HANDLE)handle, (LPWIN32_FIND_DATAA)fileinfo);
}
Ejemplo n.º 9
0
ZtringList Dir::GetAllFileNames(const Ztring &Dir_Name_, dirlist_t Options)
{
    ZtringList ToReturn;
    Ztring Dir_Name=Dir_Name_;

    #ifdef ZENLIB_USEWX
        int Flags=wxDIR_FILES | wxDIR_DIRS;

        //Search for files
        wxArrayString Liste;
        wxFileName FullPath; FullPath=Dir_Name.c_str();
        //-File
        if (FullPath.FileExists())
        {
            FullPath.Normalize();
            Liste.Add(FullPath.GetFullPath());
        }
        //-Directory
        else if (FullPath.DirExists())
        {
            FullPath.Normalize();
            wxDir::GetAllFiles(FullPath.GetFullPath(), &Liste, Ztring(), Flags);
        }
        //-WildCards
        else
        {
            wxString FileName=FullPath.GetFullName();
            FullPath.SetFullName(Ztring()); //Supress filename
            FullPath.Normalize();
            if (FullPath.DirExists())
                wxDir::GetAllFiles(FullPath.GetPath(), &Liste, FileName, Flags);
        }

        //Compatible array
        ToReturn.reserve(Liste.GetCount());
        for (size_t Pos=0; Pos<Liste.GetCount(); Pos++)
            ToReturn.push_back(Liste[Pos].c_str());
    #else //ZENLIB_USEWX
        #ifdef WINDOWS
            //Is a dir?
            if (Exists(Dir_Name))
                Dir_Name+=__T("\\*");

            //Path
            Ztring Path=FileName::Path_Get(Dir_Name);
            if (Path.empty())
            {
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                    {
                        DWORD Path_Size=GetFullPathNameA(Dir_Name.To_Local().c_str(), 0, NULL, NULL);
                        char* PathTemp=new char[Path_Size+1];
                        if (GetFullPathNameA(Dir_Name.To_Local().c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                    {
                        DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                        Char* PathTemp=new Char[Path_Size+1];
                        if (GetFullPathNameW(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                #else
                    DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                    Char* PathTemp=new Char[Path_Size+1];
                    if (GetFullPathName(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                        Path=FileName::Path_Get(PathTemp);
                    delete [] PathTemp; //PathTemp=NULL;
                #endif //UNICODE
            }

            #ifdef UNICODE
                WIN32_FIND_DATAW FindFileDataW;
                HANDLE hFind;
                #ifndef ZENLIB_NO_WIN9X_SUPPORT
                WIN32_FIND_DATAA FindFileDataA;
                if (IsWin9X_Fast())
                    hFind=FindFirstFileA(Dir_Name.To_Local().c_str(), &FindFileDataA);
                else
                #endif //ZENLIB_NO_WIN9X_SUPPORT
                    hFind=FindFirstFileW(Dir_Name.c_str(), &FindFileDataW);
            #else
                WIN32_FIND_DATA FindFileData;
                HANDLE hFind=FindFirstFile(Dir_Name.c_str(), &FindFileData);
            #endif //UNICODE

            if (hFind==INVALID_HANDLE_VALUE)
                return ZtringList();

            BOOL ReturnValue;
            do
            {
                #ifdef UNICODE
                    Ztring File_Name;
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        File_Name=FindFileDataA.cFileName;
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        File_Name=FindFileDataW.cFileName;
                #else
                    Ztring File_Name(FindFileData.cFileName);
                #endif //UNICODE
                if (File_Name!=__T(".") && File_Name!=__T("..")) //Avoid . an ..
                {
                    Ztring File_Name_Complete=Path+__T("\\")+File_Name;
                    if (Exists(File_Name_Complete))
                    {
                        if (Options&Parse_SubDirs)
                            ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                    }
                    else if ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=__T('.')))
                        ToReturn.push_back(File_Name_Complete); //A file
                }
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        ReturnValue=FindNextFileA(hFind, &FindFileDataA);
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        ReturnValue=FindNextFileW(hFind, &FindFileDataW);
                #else
                    ReturnValue=FindNextFile(hFind, &FindFileData);
                #endif //UNICODE
            }
            while (ReturnValue);

            FindClose(hFind);
        #else //WINDOWS
            //A file?
            if (File::Exists(Dir_Name))
            {
               ToReturn.push_back(Dir_Name); //TODO
               return ToReturn;
            }

            //A dir?
            if (!Dir::Exists(Dir_Name))
                return ToReturn; //Does not exist

            //open
            #ifdef UNICODE
                DIR* Dir=opendir(Dir_Name.To_Local().c_str());
            #else
                DIR* Dir=opendir(Dir_Name.c_str());
            #endif //UNICODE
            if (Dir)
            {
                //This is a dir
                //Normalizing dir (the / at the end)
                size_t Dir_Pos=Dir_Name.rfind(FileName_PathSeparator);
                if (Dir_Pos==std::string::npos)
                    Dir_Name+=FileName_PathSeparator;
                else if (Dir_Pos+Ztring(FileName_PathSeparator).size()!=Dir_Name.size())
                    Dir_Name+=FileName_PathSeparator;

                struct dirent *DirEnt;
                while((DirEnt=readdir(Dir))!=NULL)
                {
                    //A file
                    Ztring File_Name(DirEnt->d_name);
                    if (File_Name!=__T(".") && File_Name!=__T("..")) //Avoid . an ..
                    {
                        Ztring File_Name_Complete=Dir_Name+File_Name;
                        if (Exists(File_Name_Complete))
                        {
                            if (Options&Parse_SubDirs)
                                ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                        }
                        else if ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=__T('.')))
                            ToReturn.push_back(File_Name_Complete); //A file
                    }
                }

                //Close it
                closedir(Dir);
            }
            else
            {
                glob_t globbuf;
                if (glob(Dir_Name.To_Local().c_str(), GLOB_NOSORT, NULL, &globbuf)==0)
                {
                    for (int Pos=0; Pos<globbuf.gl_pathc; Pos++)
                        ToReturn.push_back(Ztring().From_Local(globbuf.gl_pathv[Pos]));
                }
            }
        #endif
    #endif //ZENLIB_USEWX

    return ToReturn;
}
Ejemplo n.º 10
0
void fs__readdir(uv_fs_t* req, const char* path, int flags) {
  int result;
  char* buf, *ptr, *name;
  HANDLE dir;
  WIN32_FIND_DATAA ent = {0};
  size_t len = strlen(path);
  size_t buf_size = 4096;
  const char* fmt = !len                                            ? "./*"
                  : (path[len - 1] == '/' || path[len - 1] == '\\') ? "%s*"
                  :                                                   "%s\\*";

  char* path2 = (char*)malloc(len + 4);
  if (!path2) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  sprintf(path2, fmt, path);
  dir = FindFirstFileA(path2, &ent);
  free(path2);

  if(dir == INVALID_HANDLE_VALUE) {
    SET_REQ_RESULT_WIN32_ERROR(req, GetLastError());
    return;
  }

  buf = (char*)malloc(buf_size);
  if (!buf) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  ptr = buf;
  result = 0;

  do {
    name = ent.cFileName;

    if (name[0] != '.' || (name[1] && (name[1] != '.' || name[2]))) {
      len = strlen(name);

      while ((ptr - buf) + len + 1 > buf_size) {
        buf_size *= 2;
        path2 = buf;
        buf = (char*)realloc(buf, buf_size);
        if (!buf) {
          uv_fatal_error(ERROR_OUTOFMEMORY, "realloc");
        }

        ptr = buf + (ptr - path2);
      }

      strcpy(ptr, name);
      ptr += len + 1;
      result++;
    }
  } while(FindNextFileA(dir, &ent));

  FindClose(dir);

  req->ptr = buf;
  req->flags |= UV_FS_FREE_PTR;

  SET_REQ_RESULT(req, result);
}
Ejemplo n.º 11
0
void FileWatcher::recurseDirectory(const std::string& dir, std::list<std::string>& output, const std::string& wildcard)
{
#ifdef WIN32
	WIN32_FIND_DATAA find = {};
	HANDLE findHandle = FindFirstFileExA((dir + "\\*").c_str(), FindExInfoStandard, &find, FindExSearchNameMatch, NULL, 0);
	if (findHandle == INVALID_HANDLE_VALUE)
		return;

	do
	{
		std::string name = find.cFileName;

		if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (name != "." && name != "..")
				recurseDirectory(dir + '\\' + name, output, wildcard);
		}
		else
		{
			if (wildcmp(wildcard.c_str(), name.c_str()))
			{
				if (dir == ".")
					output.push_back(name);
				else
					output.push_back(dir + '\\' + name);
			}
		}

		if (!FindNextFileA(findHandle, &find))
			break;
	} while (findHandle != INVALID_HANDLE_VALUE);
#else
	DIR* dp;
	if ((dp = opendir(dir.c_str())) == nullptr)
		return;

	dirent* ent;
	while ((ent = readdir(dp)))
	{
		std::string name = ent->d_name;
		if (!(ent->d_type & (DT_DIR | DT_LNK)))
		{
			if (wildcmp(wildcard.c_str(), name.c_str()))
			{
				if (dir == ".")
					output.push_back(name);
				else
					output.push_back(dir + '/' + name);
			}
			continue;
		}

		if (name == "." || name == "..")
			continue;

		std::string path = dir + '/' + name;

		recurseDirectory(path, output, wildcard);
	}

	closedir(dp);
#endif
}
Ejemplo n.º 12
0
Archivo: zdir.c Proyecto: diorcety/czmq
zdir_t *
zdir_new (const char *path, const char *parent)
{
    zdir_t *self = (zdir_t *) zmalloc (sizeof (zdir_t));
    assert (self);

    if (parent) {
        if (streq (parent, "-")) {
            self->trimmed = true;
            self->path = strdup (path);
            if (!self->path) {
                zdir_destroy (&self);
                return NULL;
            }
        }
        else {
            self->path = (char *) zmalloc (strlen (path) + strlen (parent) + 2);
            if (self->path)
                sprintf (self->path, "%s/%s", parent, path);
            else {
                zdir_destroy (&self);
                return NULL;
            }
        }
    }
    else {
        self->path = strdup (path);
        if (!self->path) {
            zdir_destroy (&self);
            return NULL;
        }
    }
    if (self->path)
        self->files = zlist_new ();
    if (self->files)
        self->subdirs = zlist_new ();
    if (!self->subdirs) {
        zdir_destroy (&self);
        return NULL;
    }

#if (defined (WIN32))
    //  On Windows, replace backslashes by normal slashes
    char *path_clean_ptr = self->path;
    while (*path_clean_ptr) {
        if (*path_clean_ptr == '\\')
            *path_clean_ptr = '/';
        path_clean_ptr++;
    }
    //  Remove any trailing slash
    if (self->path [strlen (self->path) - 1] == '/')
        self->path [strlen (self->path) - 1] = 0;

    //  Win32 wants a wildcard at the end of the path
    char *wildcard = (char *) zmalloc (strlen (self->path) + 3);
    if (!wildcard) {
        zdir_destroy (&self);
        return NULL;
    }
    sprintf (wildcard, "%s/*", self->path);
    WIN32_FIND_DATAA entry;
    HANDLE handle = FindFirstFileA (wildcard, &entry);
    freen (wildcard);

    if (handle != INVALID_HANDLE_VALUE) {
        //  We have read an entry, so return those values
        s_win32_populate_entry (self, &entry);
        while (FindNextFileA (handle, &entry))
            s_win32_populate_entry (self, &entry);
        FindClose (handle);
    }
#else
    //  Remove any trailing slash
    if (self->path [strlen (self->path) - 1] == '/')
        self->path [strlen (self->path) - 1] = 0;

    DIR *handle = opendir (self->path);
    if (handle) {
        // readdir_r is deprecated in glibc 2.24, but readdir is still not
        // guaranteed to be thread safe if the same directory is accessed
        // by different threads at the same time. Unfortunately given it was
        // not a constraint before we cannot change it now as it would be an
        // API breakage. Use a global lock when scanning the directory to
        // work around it.
        pthread_mutex_lock (&s_readdir_mutex);
        struct dirent *entry = readdir (handle);
        pthread_mutex_unlock (&s_readdir_mutex);
        while (entry != NULL) {
            // Beware of recursion. Lock only around readdir calls.
            s_posix_populate_entry (self, entry);
            pthread_mutex_lock (&s_readdir_mutex);
            entry = readdir (handle);
            pthread_mutex_unlock (&s_readdir_mutex);
        }
        closedir (handle);
    }
#endif
    else {
        zdir_destroy (&self);
        return NULL;
    }
    //  Update directory signatures
    zdir_t *subdir = (zdir_t *) zlist_first (self->subdirs);
    while (subdir) {
        if (self->modified < subdir->modified)
            self->modified = subdir->modified;
        self->cursize += subdir->cursize;
        self->count += subdir->count;
        subdir = (zdir_t *) zlist_next (self->subdirs);
    }
    zfile_t *file = (zfile_t *) zlist_first (self->files);
    while (file) {
        if (self->modified < zfile_modified (file))
            self->modified = zfile_modified (file);
        self->cursize += zfile_cursize (file);
        self->count += 1;
        file = (zfile_t *) zlist_next (self->files);
    }
    return self;
}
Ejemplo n.º 13
0
int
CreateFileListInfo(FileListInfoPtr pFileListInfo, char* path, int flag)
{
	int pathLen, basePathLength;
	char *basePath, *pChar;
	WIN32_FIND_DATAA winFindData;
	HANDLE findHandle;

	if(path == NULL) {
		return FAILURE;
	}

	if(strlen(path) == 0) {
		/* In this case we will send the list of entries in ftp root*/
		sprintf(path, "%s%s", GetFtpRoot(), "/");
	}

	/* Create a search string, like C:\folder\* */

	pathLen = strlen(path);
	basePath = malloc(pathLen + 3);
	memcpy(basePath, path, pathLen);
	basePathLength = pathLen;
	basePath[basePathLength] = '\\';
	basePath[basePathLength + 1] = '*';
	basePath[basePathLength + 2] = '\0';

	/* Start a search */
	memset(&winFindData, 0, sizeof(winFindData));
	findHandle = FindFirstFileA(path, &winFindData);

	basePath[basePathLength] = '\0'; /* Restore to a basePath + \ */
	/* Convert \ to / */
	for(pChar = basePath; *pChar; pChar++) {
		if (*pChar == '\\') {
			*pChar = '/';
		}
	}

	/* While we can find a next file do...
	   But ignore \. and '.. entries, which are current folder and parent folder respectively */
	while(findHandle != INVALID_HANDLE_VALUE && winFindData.cFileName[0] == '.' && 
		(winFindData.cFileName[1] == '\0' || 
		(winFindData.cFileName[1] == '.' && winFindData.cFileName[2] == '\0'))) {
		char fullpath[PATH_MAX];
		fullpath[0] = 0;

		strncpy_s(fullpath, PATH_MAX, basePath, basePathLength);
		strncpy_s(fullpath + basePathLength, PATH_MAX - basePathLength, winFindData.cFileName, (int)strlen(winFindData.cFileName));

		if(IS_FOLDER(winFindData.dwFileAttributes)) {
			if (AddFileListItemInfo(pFileListInfo, winFindData.cFileName, -1, 0) == 0) {
				rfbLog("File [%s]: Method [%s]: Add directory %s in the"
					" list failed\n", __FILE__, __FUNCTION__, fullpath);
				continue;
			}
		} 
		else if(IS_REGULAR_FILE(winFindData.dwFileAttributes)) {
			if(flag) {
				unsigned int fileSize = (winFindData.nFileSizeHigh * (MAXDWORD+1)) + winFindData.nFileSizeLow;
				if(AddFileListItemInfo(pFileListInfo, winFindData.cFileName, fileSize, FILETIME_TO_TIME_T(winFindData.ftLastWriteTime)) == 0) {
					rfbLog("File [%s]: Method [%s]: Add file %s in the "
						"list failed\n", __FILE__, __FUNCTION__, fullpath);
					continue;
				}			
			}
		}

		if(FindNextFileA(findHandle, &winFindData) == 0) {
			FindClose(findHandle);
			findHandle = INVALID_HANDLE_VALUE;
		}
	}

	if(findHandle != INVALID_HANDLE_VALUE) {
		FindClose(findHandle);
	}

	free(basePath);
	
	return SUCCESS;
}
Ejemplo n.º 14
0
static bool tmpSearchPath(std::string  path, std::vector<zs_ut_s::_FileInfo> & files)
{
	if (path.length() == 0)
	{
		return false;
	}
	zsummer::utility::FixPath(path);

#ifdef WIN32
	WIN32_FIND_DATAA fd;
	std::string findpath = path;
	findpath.append("*");
	HANDLE hFile = FindFirstFileA(findpath.c_str(), &fd);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return false;
	}
	zs_ut_s::_FileInfo file;
	do 
	{
		if (fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
		{
			if (strcmp(fd.cFileName, ".") != 0 && strcmp(fd.cFileName, "..") != 0 )
			{
				memset(&file, 0, sizeof(file));
				file.bDir = true;
				strcpy_s(file.filename, sizeof(file.filename), fd.cFileName);
				sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName);
				files.push_back(file);
				tmpSearchPath(file.fullpath, files);
			}
		}
		else
		{
			memset(&file, 0, sizeof(file));
			file.bDir = false;
			file.filesize = fd.nFileSizeHigh;
			file.filesize = file.filesize << 32;
			file.filesize += fd.nFileSizeLow;
			strcpy_s(file.filename, sizeof(file.filename), fd.cFileName);
			sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName);
			files.push_back(file);
		}
	} while (FindNextFileA(hFile, &fd));
	FindClose(hFile);

#else
	DIR *dp;
	struct dirent *entry;
	struct stat statbuf;
	if((dp = opendir(path.c_str())) == NULL) 
	{
		return false;
	}
	zs_ut_s::_FileInfo file;
	while((entry = readdir(dp)) != NULL) 
	{
		lstat(entry->d_name,&statbuf);
		if(S_ISDIR(statbuf.st_mode)) 
		{
			if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
			{
				continue;
			}
			memset(&file, 0, sizeof(file));
			file.bDir = true;
			file.filesize = statbuf.st_size;
			strcpy(file.filename, entry->d_name);
			sprintf(file.fullpath, "%s%s", path.c_str(), entry->d_name);
			files.push_back(file);
			tmpSearchPath(file.fullpath, files);
		}
		else 
		{
			memset(&file, 0, sizeof(file));
			file.bDir = false;
			file.filesize = statbuf.st_size;
			strcpy(file.filename, entry->d_name);
			file.fullpath[0] = '\0';
			files.push_back(file);
		}
	}
	closedir(dp);
#endif
	return true;
}
Ejemplo n.º 15
0
void Win_FindNextFileA(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs)
{
	ReturnValue->Val->Integer = FindNextFileA(Param[0]->Val->Pointer, Param[1]->Val->Pointer);
}
Ejemplo n.º 16
0
void FileLister::recursiveAddFiles(std::map<std::string, std::size_t> &files, const std::string &path, const Library * library)
{
    const std::string cleanedPath = Path::toNativeSeparators(path);

    // basedir is the base directory which is used to form pathnames.
    // It always has a trailing backslash available for concatenation.
    std::string basedir;

    // searchPattern is the search string passed into FindFirst and FindNext.
    std::string searchPattern = cleanedPath;

    // The user wants to check all files in a dir
    const bool checkAllFilesInDir = (MyIsDirectory(cleanedPath) != FALSE);

    if (checkAllFilesInDir) {
        char c = cleanedPath[ cleanedPath.size()-1 ];
        switch (c) {
        case '\\':
            searchPattern += '*';
            basedir = cleanedPath;
            break;
        case '*':
            basedir = cleanedPath.substr(0, cleanedPath.length() - 1);
            break;
        default:
            searchPattern += "\\*";
            if (cleanedPath != ".")
                basedir = cleanedPath + '\\';
        }
    } else {
        std::string::size_type pos = cleanedPath.find_last_of('\\');
        if (std::string::npos != pos) {
            basedir = cleanedPath.substr(0, pos + 1);
        }
    }

    WIN32_FIND_DATAA ffd;
    HANDLE hFind = MyFindFirstFile(searchPattern, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
        return;

    do {
        if (ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0')
            continue;

        const char* ansiFfd = ffd.cFileName;
        if (strchr(ansiFfd,'?')) {
            ansiFfd = ffd.cAlternateFileName;
        }

        const std::string fname(basedir + ansiFfd);

        if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            // File
            const std::string nativename = Path::fromNativeSeparators(fname);

            if (!checkAllFilesInDir || Path::acceptFile(fname, library)) {
                // Limitation: file sizes are assumed to fit in a 'size_t'
#ifdef _WIN64
                files[nativename] = (static_cast<std::size_t>(ffd.nFileSizeHigh) << 32) | ffd.nFileSizeLow;
#else
                files[nativename] = ffd.nFileSizeLow;
#endif
            }
        } else {
            // Directory
            FileLister::recursiveAddFiles(files, fname, library);
        }
    } while (FindNextFileA(hFind, &ffd) != FALSE);

    if (INVALID_HANDLE_VALUE != hFind) {
        FindClose(hFind);
    }
}
Ejemplo n.º 17
0
bool FileFind::FindNext(String &name)
{
#ifdef WIN32
  while ( mInternalFind->bFound )
  {
    mInternalFind->bFound = FindNextFileA(mInternalFind->hFindNext, &mInternalFind->finddata);
    if ( (mInternalFind->finddata.cFileName[0] != '.') && !(mInternalFind->finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
    {


      //gOutput->Display("DIRECTORY ENTRY: %s\n",mInternalFind->finddata.cFileName);

      name = mInternalFind->finddata.cFileName;


  		strlwr((char*)name.c_str());

      if ( mWildCard )
      {
        if ( isMatch(mWildCard,name.c_str()) ) return true;
      }
      else
        return true;
    }
  }
  FindClose(mInternalFind->hFindNext);
#endif

#ifdef LINUX_GENERIC

  if ( mInternalFind->mDir )
  {
    while ( 1 )
    {

      struct direct *di = readdir( mInternalFind->mDir );

      if ( !di )
      {
        closedir( mInternalFind->mDir );
        mInternalFind->mDir = 0;
        return false;
      }

      //gOutput->Display("DIRECTORY ENTRY: %s\n",di->d_name);

      if ( strcmp(di->d_name,".") == 0 || strcmp(di->d_name,"..") == 0 )
      {
        // skip it!
      }
      else
      {
        name = di->d_name;
    		stringutils::strlwr((char*)name.c_str());
        if ( mWildCard )
        {
          if ( mWildCard->Match(name.c_str()) ) return true;
        }
        else
          return true;
      }
    }
  }
#endif

  return false; // finished search.
}
Ejemplo n.º 18
0
/* Lately, dirSpec appears to be (rightfully) unused. */
__private_extern__ CFMutableArrayRef _CFContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) {
    CFMutableArrayRef files = NULL;
    Boolean releaseBase = false;
    CFIndex pathLength = dirPath ? (CFIndex)strlen(dirPath) : 0;
    // MF:!!! Need to use four-letter type codes where appropriate.
    CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL);
    CFIndex extLen = (extension ? CFStringGetLength(extension) : 0);
    uint8_t extBuff[CFMaxPathSize];
    
    if (extLen > 0) {
        CFStringGetBytes(extension, CFRangeMake(0, extLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &extLen);
        extBuff[extLen] = '\0';
    }

    uint8_t pathBuf[CFMaxPathSize];

    if (!dirPath) {
        if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) {
            if (extension) CFRelease(extension);
            return NULL;
        } else {
            dirPath = (char *)pathBuf;
            pathLength = (CFIndex)strlen(dirPath);
        }
    }
    
#if (DEPLOYMENT_TARGET_MACOSX) || defined(__svr4__) || defined(__hpux__) || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
    struct dirent buffer;
    struct dirent *dp;
    int err;
   
    int no_hang_fd = open("/dev/autofs_nowait", 0);
 
    DIR *dirp = opendir(dirPath);
    if (!dirp) {
        if (extension) {
            CFRelease(extension);
        }
        close(no_hang_fd);
        return NULL;
        // raiseErrno("opendir", path);
    }
    files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks);

    while((0 == readdir_r(dirp, &buffer, &dp)) && dp) {
        CFURLRef fileURL;
        unsigned namelen = strlen(dp->d_name);

        // skip . & ..; they cause descenders to go berserk
        if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) {
            continue;
        }
        
        if (extLen > namelen) continue;    // if the extension is the same length or longer than the name, it can't possibly match.
        
        if (extLen > 0) {
            // Check to see if it matches the extension we're looking for.
            if (strncmp(&(dp->d_name[namelen - extLen]), (char *)extBuff, extLen) != 0) {
                continue;
            }
        }
        if (dirURL == NULL) {
            dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true);
            releaseBase = true;
        }
        if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) {
            Boolean isDir = (dp->d_type == DT_DIR);
            if (!isDir) {
                // Ugh; must stat.
                char subdirPath[CFMaxPathLength];
                struct stat statBuf;
                strlcpy(subdirPath, dirPath, sizeof(subdirPath));
                strlcat(subdirPath, "/", sizeof(subdirPath));
                strlcat(subdirPath, dp->d_name, sizeof(subdirPath));
                if (stat(subdirPath, &statBuf) == 0) {
                    isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR);
                }
            }
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL);
        } else {
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL);
        }
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
    }
    err = closedir(dirp);
    close(no_hang_fd);
    if (err != 0) {
        CFRelease(files);
        if (releaseBase) {
            CFRelease(dirURL);
        }
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }

#elif DEPLOYMENT_TARGET_WINDOWS

    WIN32_FIND_DATAA file;
    HANDLE handle;

    if (pathLength + 2 >= CFMaxPathLength) {
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }
    if (NULL != dirPath) {
        dirPath[pathLength] = '\'';
        dirPath[pathLength + 1] = '*';
        dirPath[pathLength + 2] = '\0';
        handle = FindFirstFileA(dirPath, &file);
        if (INVALID_HANDLE_VALUE == handle) {
            dirPath[pathLength] = '\0';
            if (extension) {
                CFRelease(extension);
            }
            return NULL;
        }
    } else {
        pathLength = 0;
    }
    files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks);

    do {
        CFURLRef fileURL;
        CFIndex namelen = (CFIndex)strlen(file.cFileName);
        if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2  && file.cFileName[1] == '.'))) {
            continue;
        }
        if (extLen > 0) {
            // Check to see if it matches the extension we're looking for.
            if (_stricmp((char*)&(file.cFileName[namelen - extLen]), (char*)extBuff) != 0) {
                continue;
            }
        }
	if (dirURL == NULL) {
	    dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (UInt8*)dirPath, pathLength, true);
            releaseBase = true;
        }
        // MF:!!! What about the trailing slash?
        fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (UInt8*)file.cFileName, namelen, false, dirURL);
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
    } while (FindNextFileA(handle, &file));
    FindClose(handle);
    dirPath[pathLength] = '\0';

#else

#error _CFContentsOfDirectory() unknown architechture, not implemented
    
#endif

    if (extension) {
        CFRelease(extension);
    }
    if (releaseBase) {
        CFRelease(dirURL);
    }
    return files;
}
Ejemplo n.º 19
0
static void GetVoices(const char *path)
{
	FILE *f_voice;
	espeak_VOICE *voice_data;
	int ftype;
	char fname[sizeof(path_home)+100];

#ifdef PLATFORM_WINDOWS
	WIN32_FIND_DATAA FindFileData;
	HANDLE hFind = INVALID_HANDLE_VALUE;

	#undef UNICODE // we need FindFirstFileA() which takes an 8-bit c-string
	sprintf(fname, "%s\\*", path);
	hFind = FindFirstFileA(fname, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE)
		return;

	do {
		if (n_voices_list >= (N_VOICES_LIST-2))
			break; // voices list is full

		if (FindFileData.cFileName[0] != '.') {
			sprintf(fname, "%s%c%s", path, PATHSEP, FindFileData.cFileName);
			ftype = GetFileLength(fname);

			if (ftype == -2) {
				// a sub-sirectory
				GetVoices(fname);
			} else if (ftype > 0) {
				// a regular line, add it to the voices list
				if ((f_voice = fopen(fname, "r")) == NULL)
					continue;

				// pass voice file name within the voices directory
				voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, FindFileData.cFileName);
				fclose(f_voice);

				if (voice_data != NULL)
					voices_list[n_voices_list++] = voice_data;
			}
		}
	} while (FindNextFileA(hFind, &FindFileData) != 0);
	FindClose(hFind);
#else
	DIR *dir;
	struct dirent *ent;

	if ((dir = opendir((char *)path)) == NULL) // note: (char *) is needed for WINCE
		return;

	while ((ent = readdir(dir)) != NULL) {
		if (n_voices_list >= (N_VOICES_LIST-2))
			break; // voices list is full

		if (ent->d_name[0] == '.')
			continue;

		sprintf(fname, "%s%c%s", path, PATHSEP, ent->d_name);

		ftype = GetFileLength(fname);

		if (ftype == -2) {
			// a sub-sirectory
			GetVoices(fname);
		} else if (ftype > 0) {
			// a regular line, add it to the voices list
			if ((f_voice = fopen(fname, "r")) == NULL)
				continue;

			// pass voice file name within the voices directory
			voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, ent->d_name);
			fclose(f_voice);

			if (voice_data != NULL)
				voices_list[n_voices_list++] = voice_data;
		}
	}
	closedir(dir);
#endif
}
Ejemplo n.º 20
0
void __PHYSFS_platformEnumerateFiles(const char *dirname,
                                     int omitSymLinks,
                                     PHYSFS_EnumFilesCallback callback,
                                     const char *origdir,
                                     void *callbackdata)
{
    const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
    HANDLE dir = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA ent;
    WIN32_FIND_DATAW entw;
    size_t len = strlen(dirname);
    char *searchPath = NULL;
    WCHAR *wSearchPath = NULL;
    char *utf8 = NULL;

    /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
    searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
    if (searchPath == NULL)
        return;

    /* Copy current dirname */
    strcpy(searchPath, dirname);

    /* if there's no '\\' at the end of the path, stick one in there. */
    if (searchPath[len - 1] != '\\')
    {
        searchPath[len++] = '\\';
        searchPath[len] = '\0';
    } /* if */

    /* Append the "*" to the end of the string */
    strcat(searchPath, "*");

    UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
    if (wSearchPath == NULL)
        return;  /* oh well. */

    if (unicode)
        dir = pFindFirstFileW(wSearchPath, &entw);
    else
    {
        const int len = (int) (wStrLen(wSearchPath) + 1);
        char *cp = (char *) __PHYSFS_smallAlloc(len);
        if (cp != NULL)
        {
            WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
            dir = FindFirstFileA(cp, &ent);
            __PHYSFS_smallFree(cp);
        } /* if */
    } /* else */

    __PHYSFS_smallFree(wSearchPath);
    __PHYSFS_smallFree(searchPath);
    if (dir == INVALID_HANDLE_VALUE)
        return;

    if (unicode)
    {
        do
        {
            const DWORD attr = entw.dwFileAttributes;
            const DWORD tag = entw.dwReserved0;
            const WCHAR *fn = entw.cFileName;
            if ((fn[0] == '.') && (fn[1] == '\0'))
                continue;
            if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
                continue;
            if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
                continue;

            utf8 = unicodeToUtf8Heap(fn);
            if (utf8 != NULL)
            {
                callback(callbackdata, origdir, utf8);
                allocator.Free(utf8);
            } /* if */
        } while (pFindNextFileW(dir, &entw) != 0);
    } /* if */

    else  /* ANSI fallback. */
    {
        do
        {
            const DWORD attr = ent.dwFileAttributes;
            const DWORD tag = ent.dwReserved0;
            const char *fn = ent.cFileName;
            if ((fn[0] == '.') && (fn[1] == '\0'))
                continue;
            if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
                continue;
            if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
                continue;

            utf8 = codepageToUtf8Heap(fn);
            if (utf8 != NULL)
            {
                callback(callbackdata, origdir, utf8);
                allocator.Free(utf8);
            } /* if */
        } while (FindNextFileA(dir, &ent) != 0);
    } /* else */

    FindClose(dir);
} /* __PHYSFS_platformEnumerateFiles */
Ejemplo n.º 21
0
int keysWin32(char *dirname, char ***keys, int *nkeys)
{
	int rc = 0;
	char **fkeys = NULL;
	int nfkeys = 0;
	char dir[MAX_PATH+1];
	WIN32_FIND_DATAA FileData;
	HANDLE hDir;
	int fFinished = 0;
	char *ptraux;
	int i;

	FUNC_ENTRY;
	sprintf(dir, "%s/*", dirname);

	/* get number of keys */
	hDir = FindFirstFileA(dir, &FileData);
	if (hDir != INVALID_HANDLE_VALUE)
	{
		while (!fFinished)
		{
			if (FileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
				nfkeys++;
			if (!FindNextFileA(hDir, &FileData))
			{
				if (GetLastError() == ERROR_NO_MORE_FILES)
					fFinished = 1;
			}
		}
		FindClose(hDir);
	} else
	{
		rc = MQTTCLIENT_PERSISTENCE_ERROR;
		goto exit;
	}

	if (nfkeys != 0 )
		fkeys = (char **)malloc(nfkeys * sizeof(char *));

	/* copy the keys */
	hDir = FindFirstFileA(dir, &FileData);
	if (hDir != INVALID_HANDLE_VALUE)
	{
		fFinished = 0;
		i = 0;
		while (!fFinished)
		{
			if (FileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
			{
				fkeys[i] = malloc(strlen(FileData.cFileName) + 1);
				strcpy(fkeys[i], FileData.cFileName);
				ptraux = strstr(fkeys[i], MESSAGE_FILENAME_EXTENSION);
				if ( ptraux != NULL )
					*ptraux = '\0' ;
				i++;
			}
			if (!FindNextFileA(hDir, &FileData))
			{
				if (GetLastError() == ERROR_NO_MORE_FILES)
					fFinished = 1;
			}
		}
		FindClose(hDir);
	} else
	{
		rc = MQTTCLIENT_PERSISTENCE_ERROR;
		goto exit;
	}

	*nkeys = nfkeys;
	*keys = fkeys;
	/* the caller must free keys */

exit:
	FUNC_EXIT_RC(rc);
	return rc;
}
Ejemplo n.º 22
0
void ScanFileRecursively(const std::string dir, BlockFS* pFS, std::map<std::string, MD5Index>& mapEntries,
                         std::vector<std::string>& add)
{
    WIN32_FIND_DATAA finddata;
    std::string searchstring = dir + "/*";
    HANDLE hfine = FindFirstFileA(searchstring.c_str(), &finddata);
    if (hfine != INVALID_HANDLE_VALUE)
    {
        do
        {
            if (finddata.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
            {
                if(strcmp(finddata.cFileName, ".svn")!=0&&
                    strcmp(finddata.cFileName, ".")!=0&&
                    strcmp(finddata.cFileName, "..")!=0)
                    ScanFileRecursively(dir + "/" + finddata.cFileName, pFS, mapEntries, add);
                continue;
            }
            std::string name = dir;
            name += "/";
            name += finddata.cFileName;
            std::transform(name.begin(), name.end(), name.begin(), tolower);
            std::map<std::string, MD5Index>::iterator it = mapEntries.find(name);
            if(it != mapEntries.end())
            {
                IFile* pTemp = OpenDiskFile(name.c_str(), IFile::O_ReadOnly);
                offset_type length = pTemp->GetSize();
                if(it->second.size==length)
                {
                    char* buff = new char[(size_t)length.offset];
                    pTemp->Read(buff, length);
                    std::transform(name.begin(), name.end(), name.begin(), tolower);
                    printf("checking %s, %d bytes\n", name.c_str(), length);

                    unsigned char ucCheckSum[16];
                    GetMD5CheckSum((unsigned char*)buff, (unsigned)length.offset, ucCheckSum);
                    if(!memcmp(ucCheckSum, it->second.md5, sizeof(ucCheckSum)))
                    {
                        printf("file %s, ignored update\n", it->first.c_str());
                        mapEntries.erase(it);
                    }
                    else
                    {
                        printf("file %s, need update\n", it->first.c_str());
                        add.push_back(it->first);
                    }
                    //pFS->AddFile(name.c_str(), buff, length, length > pFS->GetBlockDataSize());
                    delete[]buff;
                }
                else
                {
                    printf("file %s, with different size %d, original %d", name.c_str(), length, it->second.size);
                    add.push_back(name);
                }
                delete pTemp;
            }
            else
            {
                printf("file %s will be added\n",name.c_str());
                add.push_back(name);
            }

        }
        while (FindNextFileA(hfine, &finddata));
    }
    FindClose(hfine);
}
Ejemplo n.º 23
0
Archivo: Menu.cpp Proyecto: mrDIMAS/src
Menu::Menu(unique_ptr<Game> & game) :
	mGame(game),
	mCameraChangeTime(30 * 60),
	mDistBetweenButtons(68),
	mVisible(true),
	mPage(Page::Main),
	mLoadSaveGameName("") {
	// Load config
	mConfig.Load("config.cfg");
	mLocalization.Load(mGame->GetLocalizationPath() + "menu.loc");
	// load background scene
	mScene = mGame->GetEngine()->GetSceneFactory()->LoadScene("data/maps/menu.scene");
	// create gui scene
	mGUIScene = mGame->GetEngine()->CreateGUIScene();
	// create camera
	mpCamera = make_unique<GameCamera>(mGUIScene);
	mCameraPos1 = mScene->FindChild("Camera");
	mCameraPos2 = mScene->FindChild("Camera2");
	mpCamera->mCamera->Attach(mCameraPos1);
	mCameraFadeActionDone = false;
	mCameraInitialPosition = Vector3(0, 0, 0);
	mCameraAnimationNewOffset = Vector3(0.5, 0.5, 0.5);

	auto soundSystem = mGame->GetEngine()->GetSoundSystem();

	mPickSound = soundSystem->LoadSound2D("data/sounds/menupick.ogg");
	mMusic = soundSystem->LoadMusic3D("data/music/menu.ogg");
	mMusic->SetPosition(mScene->FindChild("Radio")->GetPosition());
	mMusic->SetRolloffFactor(0.1);
	mMusic->SetRoomRolloffFactor(0.1);

	const float buttonHeight = 30;
	const float buttonWidth = 128;
	const float buttonXOffset = 10;

	auto renderer = mGame->GetEngine()->GetRenderer();

	// load textures
	auto texTab = renderer->GetTexture("data/gui/menu/tab.tga");
	auto texButton = renderer->GetTexture("data/gui/menu/button.tga");
	auto texSmallButton = renderer->GetTexture("data/gui/menu/button.tga");

	// Setup
	mCanvas = mGUIScene->CreateRect(0, 0, 0, 0, nullptr);
	{
		// Main 
		mGUIMainButtonsCanvas = mGUIScene->CreateRect(20, ruVirtualScreenHeight - 4.0 * mDistBetweenButtons, buttonWidth + 2 * buttonXOffset, buttonHeight * 8.5, texTab, pGUIProp->mBackColor);
		mGUIMainButtonsCanvas->Attach(mCanvas);
		{
			mContinueGameButton = mGUIScene->CreateButton(buttonXOffset, 5, buttonWidth, buttonHeight, texButton, mLocalization.GetString("continueButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mContinueGameButton->Attach(mGUIMainButtonsCanvas);
			mContinueGameButton->AddAction(GUIAction::OnClick, [this] { OnContinueGameClick(); });

			mStartButton = mGUIScene->CreateButton(buttonXOffset, 5 + 0.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("startButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mStartButton->Attach(mGUIMainButtonsCanvas);
			mStartButton->AddAction(GUIAction::OnClick, [this] { OnStartNewGameClick(); });

			mSaveGameButton = mGUIScene->CreateButton(buttonXOffset, 5 + 1.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("saveButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mSaveGameButton->Attach(mGUIMainButtonsCanvas);
			mSaveGameButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::SaveGame); FillListOfSaveFiles(); });

			mLoadGameButton = mGUIScene->CreateButton(buttonXOffset, 5 + 1.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("loadButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mLoadGameButton->Attach(mGUIMainButtonsCanvas);
			mLoadGameButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::LoadGame); FillListOfSaveFiles(); });

			mOptionsButton = mGUIScene->CreateButton(buttonXOffset, 5 + 2.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("optionsButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mOptionsButton->Attach(mGUIMainButtonsCanvas);
			mOptionsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::Options); });

			mAuthorsButton = mGUIScene->CreateButton(buttonXOffset, 5 + 2.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("authorsButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mAuthorsButton->Attach(mGUIMainButtonsCanvas);
			mAuthorsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::Authors); });

			mExitButton = mGUIScene->CreateButton(buttonXOffset, 5 + 3.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("exitButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mExitButton->Attach(mGUIMainButtonsCanvas);
			mExitButton->AddAction(GUIAction::OnClick, [this] { OnExitGameClick(); });
		}

		const int aTabX = 200;
		const int aTabY = ruVirtualScreenHeight - 4.0 * mDistBetweenButtons;
		const int aTabWidth = buttonWidth * 4;
		const int aTabHeight = buttonHeight * 8.5;

		// Modal window
		mModalWindow = make_unique<ModalWindow>(mGUIScene, aTabX, aTabY, aTabWidth, aTabHeight, texTab, texButton, pGUIProp->mBackColor);
		mModalWindow->AttachTo(mCanvas);

		// Page title
		mWindowText = mGUIScene->CreateText(" ", aTabX, aTabY - 21, aTabWidth, 32, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
		mWindowText->Attach(mCanvas);

		// Product name
		mCaption = mGUIScene->CreateText("The Mine", 20, aTabY - 21, aTabWidth * 1.5f, 32, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
		mCaption->Attach(mCanvas);

		// Options
		mGUIOptionsCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mGUIOptionsCanvas->Attach(mCanvas);
		{
			const int yOffset = (aTabHeight - 2 * mDistBetweenButtons) / 2;

			mGUIOptionsCommonButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset, buttonWidth, buttonHeight, texButton, mLocalization.GetString("commonSettings"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsCommonButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsCommonButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsCommon); });

			mGUIOptionsControlsButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset + 0.5 * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("controls"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsControlsButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsControlsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsKeys); });

			mGUIOptionsGraphicsButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset + mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("graphics"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsGraphicsButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsGraphicsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsGraphics); });
		}

		// Options: Keys
		mOptionsKeysCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mGUIOptionsCanvas->Attach(mCanvas);
		mOptionsKeysCanvas->SetVisible(false);
		{
			// First column
			float x = 40, y = 10;

			mMoveForwardKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("forward"));
			mMoveForwardKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mMoveBackwardKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("backward"));
			mMoveBackwardKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStrafeLeftKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("strafeLeft"));
			mStrafeLeftKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStrafeRightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("strafeRight"));
			mStrafeRightKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mJumpKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("jump"));
			mJumpKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mFlashLightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("flashLight"));
			mFlashLightKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mRunKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("run"));
			mRunKey->AttachTo(mOptionsKeysCanvas);

			// Second column
			x += 150;
			y = 10;
			mInventoryKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("inventory"));
			mInventoryKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mUseKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("use"));
			mUseKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mQuickLoadKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("quickLoad"));
			mQuickLoadKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mQuickSaveKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("quickSave"));
			mQuickSaveKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStealthKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("stealth"));
			mStealthKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mLookLeftKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("lookLeft"));
			mLookLeftKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mLookRightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("lookRight"));
			mLookRightKey->AttachTo(mOptionsKeysCanvas);
		}

		// Options: Graphics
		mOptionsGraphicsCanvas = mGUIScene->CreateRect(aTabX, aTabY, buttonWidth * 5.5, aTabHeight, texTab, pGUIProp->mBackColor);
		mOptionsGraphicsCanvas->Attach(mCanvas);
		mOptionsGraphicsCanvas->SetVisible(false);
		{
			float x = 30, y = 10;

			mFXAAButton = make_unique<RadioButton>(mGUIScene, x, y, texButton, mLocalization.GetString("fxaa"));
			mFXAAButton->AttachTo(mOptionsGraphicsCanvas);

			mFPSButton = make_unique<RadioButton>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("showFPS"));
			mFPSButton->AttachTo(mOptionsGraphicsCanvas);

			mSpotShadowsButton = make_unique<RadioButton>(mGUIScene, x, y + mDistBetweenButtons, texButton, mLocalization.GetString("spotLightShadows"));
			mSpotShadowsButton->AttachTo(mOptionsGraphicsCanvas);

			mPointShadowsButton = make_unique<RadioButton>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("pointLightShadows"));
			mPointShadowsButton->AttachTo(mOptionsGraphicsCanvas);

			mHDRButton = make_unique<RadioButton>(mGUIScene, x, y + 2.0 * mDistBetweenButtons, texButton, mLocalization.GetString("hdr"));
			mHDRButton->AttachTo(mOptionsGraphicsCanvas);

			mParallaxButton = make_unique<RadioButton>(mGUIScene, x, y + 2.5 * mDistBetweenButtons, texButton, mLocalization.GetString("parallax"));
			mParallaxButton->AttachTo(mOptionsGraphicsCanvas);

			mVolumetricFogButton = make_unique<RadioButton>(mGUIScene, x, y + 3.0 * mDistBetweenButtons, texButton, mLocalization.GetString("volumetricFog"));
			mVolumetricFogButton->AttachTo(mOptionsGraphicsCanvas);

			// next column
			x += 170;

			mDynamicDirectionalLightShadows = make_unique<RadioButton>(mGUIScene, x, y, texButton, mLocalization.GetString("dynamicDirectionalLightShadows"));
			mDynamicDirectionalLightShadows->AttachTo(mOptionsGraphicsCanvas);

			mBloom = make_unique<RadioButton>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("bloom"));
			mBloom->AttachTo(mOptionsGraphicsCanvas);

			mSoftParticles = make_unique<RadioButton>(mGUIScene, x, y + 1.0 * mDistBetweenButtons, texButton, mLocalization.GetString("softParticles"));
			mSoftParticles->AttachTo(mOptionsGraphicsCanvas);

			mVSync = make_unique<RadioButton>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("vsync"));
			mVSync->AttachTo(mOptionsGraphicsCanvas);
			//			mVSync->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

						// next column
			x += 170;

			mResolutionList = make_unique<ScrollList>(mGUIScene, x, y, texButton, mLocalization.GetString("resolution"));
			mResolutionList->AttachTo(mOptionsGraphicsCanvas);
			auto videoModes = mGame->GetEngine()->GetRenderer()->GetVideoModeList();
			for(auto videoMode : videoModes) {
				mResolutionList->AddValue(StringBuilder() << videoMode.mWidth << "x" << videoMode.mHeight << "@" << videoMode.mRefreshRate);
			}
			mResolutionList->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

			mWindowMode = make_unique<ScrollList>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("windowMode"));
			mWindowMode->AttachTo(mOptionsGraphicsCanvas);
			mWindowMode->AddValue(mLocalization.GetString("windowed"));
			mWindowMode->AddValue(mLocalization.GetString("fullscreen"));
			mWindowMode->AddValue(mLocalization.GetString("borderless"));
			mWindowMode->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

			mTextureFiltering = make_unique<ScrollList>(mGUIScene, x, y + 1.0 * mDistBetweenButtons, texButton, mLocalization.GetString("filtering"));
			mTextureFiltering->AttachTo(mOptionsGraphicsCanvas);
			mTextureFiltering->AddValue(mLocalization.GetString("trilinear"));
			for(int i = 1; i <= mGame->GetEngine()->GetRenderer()->GetMaxIsotropyDegree(); ++i) {
				mTextureFiltering->AddValue(StringBuilder() << mLocalization.GetString("anisotropic") << " x" << i);
			}

			mSpotLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("spotLightShadowMap"));
			mSpotLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 256; i <= 2048; i *= 2) {
				mSpotLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mPointLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 2.0 * mDistBetweenButtons, texButton, mLocalization.GetString("pointLightShadowMap"));
			mPointLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 128; i <= 1024; i *= 2) {
				mPointLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mDirectionalLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 2.5 * mDistBetweenButtons, texButton, mLocalization.GetString("directionalLightShadowMap"));
			mDirectionalLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 1024; i <= 4096; i *= 2) {
				mDirectionalLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mSettingsApplied = mGUIScene->CreateText(mLocalization.GetString("settingsApplied"), x, y + 3.1 * mDistBetweenButtons, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(0, 255, 0), TextAlignment::Left);
			mSettingsApplied->Attach(mOptionsGraphicsCanvas);
		}

		// Authors
		mAuthorsBackground = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mAuthorsBackground->Attach(mCanvas);
		{
			mGUIAuthorsText = mGUIScene->CreateText(mLocalization.GetString("authorsText"), 15, 15, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
			mGUIAuthorsText->Attach(mAuthorsBackground);
		}

		// Save Game
		mSaveGameCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mSaveGameCanvas->Attach(mCanvas);
		{
			float y = 10;
			for(int i = 0; i < mSaveLoadSlotCount; i++) {
				mSaveGameSlot[i] = mGUIScene->CreateButton(20, y, buttonWidth, buttonHeight, texButton, "Empty slot", pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
				mSaveGameSlot[i]->Attach(mSaveGameCanvas);
				mSaveGameSlot[i]->AddAction(GUIAction::OnClick, [this] { OnCreateSaveClick(); });

				mSaveGameFileTime[i] = mGUIScene->CreateText(" ", buttonWidth + 30, y, 160, buttonHeight, pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Left);
				mSaveGameFileTime[i]->Attach(mSaveGameCanvas);

				y += 1.1f * buttonHeight;
			}
		}

		// Load Game
		mLoadGameCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mLoadGameCanvas->Attach(mCanvas);
		{
			float y = 10;
			for(int i = 0; i < mSaveLoadSlotCount; i++) {
				mLoadGameSlot[i] = mGUIScene->CreateButton(20, y, buttonWidth, buttonHeight, texButton, "Empty slot", pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
				mLoadGameSlot[i]->Attach(mLoadGameCanvas);
				mLoadGameSlot[i]->AddAction(GUIAction::OnClick, [this] { OnLoadSaveClick(); });

				mLoadGameFileTime[i] = mGUIScene->CreateText(" ", buttonWidth + 30, y, 160, buttonHeight, pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Left);
				mLoadGameFileTime[i]->Attach(mLoadGameCanvas);
				y += 1.1f * buttonHeight;
			}
		}

		// Options: Common
		mOptionsCommonCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mOptionsCommonCanvas->Attach(mCanvas);
		mOptionsCommonCanvas->SetVisible(false);
		{
			const int yOffset = (aTabHeight - 1.5 * mDistBetweenButtons) / 2;
			int xOffset = 20;

			mFOVSlider = make_unique<Slider>(mGUIScene, xOffset, yOffset - 0.5f * mDistBetweenButtons, 55, 90, 1.0f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("fov"));
			mFOVSlider->AttachTo(mOptionsCommonCanvas);

			mMasterVolume = make_unique<Slider>(mGUIScene, xOffset, yOffset, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("masterVolume"));
			mMasterVolume->AttachTo(mOptionsCommonCanvas);
			mMasterVolume->SetChangeAction([this] { mGame->GetEngine()->GetSoundSystem()->SetMasterVolume(mMasterVolume->GetValue() / 100.0f); });

			mMusicVolume = make_unique<Slider>(mGUIScene, xOffset, yOffset + 0.5f * mDistBetweenButtons, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("musicVolume"));
			mMusicVolume->AttachTo(mOptionsCommonCanvas);
			mMusicVolume->SetChangeAction([this] { OnMusicVolumeChange(); });

			mMouseSensivity = make_unique<Slider>(mGUIScene, xOffset, yOffset + 1.0f * mDistBetweenButtons, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("mouseSens"));
			mMouseSensivity->AttachTo(mOptionsCommonCanvas);
			mMouseSensivity->SetChangeAction([this] { mGame->SetMouseSensitivity(mMouseSensivity->GetValue() / 100.0f); });

			mLanguage = make_unique<ScrollList>(mGUIScene, xOffset, yOffset + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("language"));
			mLanguage->AttachTo(mOptionsCommonCanvas);
			mLanguage->OnChange += [this] { mConfig.SetString("languagePath", StringBuilder("data/lang/") << mLanguage->GetValueString(mLanguage->GetCurrentValue()) << "/"); };


			mLangSettingsApplied = mGUIScene->CreateText(mLocalization.GetString("langChange"), 20, 3.3 * mDistBetweenButtons, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(255, 0, 0), TextAlignment::Left);
			mLangSettingsApplied->Attach(mOptionsCommonCanvas);

			xOffset += 300;
			mMouseInversionX = make_unique<RadioButton>(mGUIScene, xOffset, yOffset - 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("mouseInvX"));
			mMouseInversionX->AttachTo(mOptionsCommonCanvas);

			mMouseInversionY = make_unique<RadioButton>(mGUIScene, xOffset, yOffset, texButton, mLocalization.GetString("mouseInvY"));
			mMouseInversionY->AttachTo(mOptionsCommonCanvas);

			int current = 0, i = 0;
			WIN32_FIND_DATAA fi;
			HANDLE h = FindFirstFileExA("data/lang/*.*", FindExInfoStandard, &fi, FindExSearchLimitToDirectories, NULL, 0);
			if(h != INVALID_HANDLE_VALUE) {
				do {
					if(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
						string v = fi.cFileName;
						if(v != "." && v != "..") {
							mLanguage->AddValue(v);
							if(mConfig.GetString("languagePath").rfind(v) != string::npos) {
								current = i;
							}
							++i;
						}
					}
				} while(FindNextFileA(h, &fi));
				FindClose(h);
			}

			mLanguage->SetCurrentValue(current);
		}
	}

	mGame->GetEngine()->GetSoundSystem()->SetReverbPreset(ReverbPreset::Auditorium);

	SetAuthorsPageVisible(false);
	SetPage(Page::Main);
	ReadConfig();
}
Ejemplo n.º 24
0
/* This callback gets invoked when we get any http request that doesn't match
 * any other callback.  Like any evhttp server callback, it has a simple job:
 * it must eventually call evhttp_send_error() or evhttp_send_reply().
 */
static void
send_document_cb(struct evhttp_request *req, void *arg)
{
	struct evbuffer *evb = NULL;
	const char *docroot = arg;
	const char *uri = evhttp_request_get_uri(req);
	struct evhttp_uri *decoded = NULL;
	const char *path;
	char *decoded_path;
	char *whole_path = NULL;
	size_t len;
	int fd = -1;
	struct stat st;

	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
		dump_request_cb(req, arg);
		return;
	}

	printf("Got a GET request for <%s>\n",  uri);

	/* Decode the URI */
	decoded = evhttp_uri_parse(uri);
	if (!decoded) {
		printf("It's not a good URI. Sending BADREQUEST\n");
		evhttp_send_error(req, HTTP_BADREQUEST, 0);
		return;
	}

	/* Let's see what path the user asked for. */
	path = evhttp_uri_get_path(decoded);
	if (!path) path = "/";

	/* We need to decode it, to see what path the user really wanted. */
	decoded_path = evhttp_uridecode(path, 0, NULL);
	if (decoded_path == NULL)
		goto err;
	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
	 * of the docroot.  This test is both overzealous and underzealous:
	 * it forbids aceptable paths like "/this/one..here", but it doesn't
	 * do anything to prevent symlink following." */
	if (strstr(decoded_path, ".."))
		goto err;

	len = strlen(decoded_path)+strlen(docroot)+2;
	if (!(whole_path = malloc(len))) {
		perror("malloc");
		goto err;
	}
	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);

	if (stat(whole_path, &st)<0) {
		goto err;
	}

	/* This holds the content we're sending. */
	evb = evbuffer_new();

	if (S_ISDIR(st.st_mode)) {
		/* If it's a directory, read the comments and make a little
		 * index page */
#ifdef _WIN32
		HANDLE d;
		WIN32_FIND_DATAA ent;
		char *pattern;
		size_t dirlen;
#else
		DIR *d;
		struct dirent *ent;
#endif
		const char *trailing_slash = "";

		if (!strlen(path) || path[strlen(path)-1] != '/')
			trailing_slash = "/";

#ifdef _WIN32
		dirlen = strlen(whole_path);
		pattern = malloc(dirlen+3);
		memcpy(pattern, whole_path, dirlen);
		pattern[dirlen] = '\\';
		pattern[dirlen+1] = '*';
		pattern[dirlen+2] = '\0';
		d = FindFirstFileA(pattern, &ent);
		free(pattern);
		if (d == INVALID_HANDLE_VALUE)
			goto err;
#else
		if (!(d = opendir(whole_path)))
			goto err;
#endif

		evbuffer_add_printf(evb,
                    "<!DOCTYPE html>\n"
                    "<html>\n <head>\n"
                    "  <meta charset='utf-8'>\n"
		    "  <title>%s</title>\n"
		    "  <base href='%s%s'>\n"
		    " </head>\n"
		    " <body>\n"
		    "  <h1>%s</h1>\n"
		    "  <ul>\n",
		    decoded_path, /* XXX html-escape this. */
		    path, /* XXX html-escape this? */
		    trailing_slash,
		    decoded_path /* XXX html-escape this */);
#ifdef _WIN32
		do {
			const char *name = ent.cFileName;
#else
		while ((ent = readdir(d))) {
			const char *name = ent->d_name;
#endif
			evbuffer_add_printf(evb,
			    "    <li><a href=\"%s\">%s</a>\n",
			    name, name);/* XXX escape this */
#ifdef _WIN32
		} while (FindNextFileA(d, &ent));
#else
		}
#endif
		evbuffer_add_printf(evb, "</ul></body></html>\n");
#ifdef _WIN32
		FindClose(d);
#else
		closedir(d);
#endif
		evhttp_add_header(evhttp_request_get_output_headers(req),
		    "Content-Type", "text/html");
	} else {
Ejemplo n.º 25
0
        /**
         * Create classpath picking compiled classes from the given path.
         *
         * @path Path.
         * @return Classpath;
         */
        std::string ClasspathExploded(const std::string& path, bool down)
        {
            std::string res;

            if (FileExists(path))
            {
                // 1. Append "target\classes".
                std::string classesPath = path + "\\target\\classes";

                if (FileExists(classesPath)) {
                    res.append(classesPath);
                    res.append(";");
                }

                // 2. Append "target\test-classes"
                std::string testClassesPath = path + "\\target\\test-classes";

                if (FileExists(testClassesPath)) {
                    res.append(testClassesPath);
                    res.append(";");
                }

                // 3. Append "target\libs"
                std::string libsPath = path + "\\target\\libs";

                if (FileExists(libsPath)) {
                    std::string libsCp = ClasspathJars(libsPath);
                    res.append(libsCp);
                }

                // 4. Do the same for child if needed.
                if (down)
                {
                    std::string searchPath = path + "\\*";

                    WIN32_FIND_DATAA findData;

                    HANDLE hnd = FindFirstFileA(searchPath.c_str(), &findData);

                    if (hnd != INVALID_HANDLE_VALUE)
                    {
                        do
                        {
                            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                            {
                                std::string childPath = findData.cFileName;

                                if (childPath.compare(".") != 0 &&
                                    childPath.compare("..") != 0)
                                {
                                    std::string childCp =
                                        ClasspathExploded(path + "\\" + childPath, false);

                                    res.append(childCp);
                                }
                            }
                        } while (FindNextFileA(hnd, &findData) != 0);

                        FindClose(hnd);
                    }
                }
            }

            return res;
        }