From 295e8532d21e8beb84d66ce97a64bf874cf8df90 Mon Sep 17 00:00:00 2001 From: Vladimir Perminov Date: Sun, 17 May 2015 12:40:14 +0300 Subject: [PATCH 1/2] FileUtilsWin32 correct use all unicode version winapi Move to FileUtilsWin32 implements: isDirectoryExistInternal isDirectoryExist createDirectory removeDirectory removeFile renameFile And use common convert to wide char. --- cocos/platform/CCFileUtils.cpp | 101 ++----- cocos/platform/win32/CCFileUtils-win32.cpp | 293 +++++++++++++++++---- cocos/platform/win32/CCFileUtils-win32.h | 47 +++- 3 files changed, 313 insertions(+), 128 deletions(-) diff --git a/cocos/platform/CCFileUtils.cpp b/cocos/platform/CCFileUtils.cpp index e1599b8082..fb0dcec330 100644 --- a/cocos/platform/CCFileUtils.cpp +++ b/cocos/platform/CCFileUtils.cpp @@ -989,24 +989,17 @@ bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const return true; } return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - unsigned long fAttrib = GetFileAttributesA(dirPath.c_str()); - if (fAttrib != INVALID_FILE_ATTRIBUTES && - (fAttrib & FILE_ATTRIBUTE_DIRECTORY)) - { - return true; - } - return false; -#else +#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) struct stat st; if (stat(dirPath.c_str(), &st) == 0) { return S_ISDIR(st.st_mode); } return false; +#else + CCASSERT(false, "FileUtils not support isDirectoryExistInternal"); + return false; #endif - - } bool FileUtils::isDirectoryExist(const std::string& dirPath) const @@ -1098,25 +1091,7 @@ bool FileUtils::createDirectory(const std::string& path) } } return true; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES) - { - subpath = ""; - for (unsigned int i = 0; i < dirs.size(); ++i) - { - subpath += dirs[i]; - if (!isDirectoryExist(subpath)) - { - BOOL ret = CreateDirectoryA(subpath.c_str(), NULL); - if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) - { - return false; - } - } - } - } - return true; -#else +#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) DIR *dir = NULL; // Create path recursively @@ -1145,6 +1120,9 @@ bool FileUtils::createDirectory(const std::string& path) } } return true; +#else + CCASSERT(false, "FileUtils not support createDirectory"); + return false; #endif } @@ -1206,21 +1184,12 @@ bool FileUtils::removeDirectory(const std::string& path) return true; } return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::string command = "cmd /c rd /s /q "; - // Path may include space. - command += "\"" + path + "\""; - - if (WinExec(command.c_str(), SW_HIDE) > 31) - return true; - else - return false; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) return false; else return true; -#else +#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) std::string command = "rm -r "; // Path may include space. command += "\"" + path + "\""; @@ -1228,6 +1197,9 @@ bool FileUtils::removeDirectory(const std::string& path) return true; else return false; +#else + CCASSERT(false, "FileUtils not support removeDirectory"); + return false; #endif } @@ -1242,29 +1214,15 @@ bool FileUtils::removeFile(const std::string &path) return true; } return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::string command = "cmd /c del /q "; - std::string win32path = path; - int len = win32path.length(); - for (int i = 0; i < len; ++i) - { - if (win32path[i] == '/') - { - win32path[i] = '\\'; - } - } - command += win32path; - - if (WinExec(command.c_str(), SW_HIDE) > 31) - return true; - else - return false; -#else +#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) if (remove(path.c_str())) { return false; } else { return true; } +#else + CCASSERT(false, "FileUtils not support removeFile"); + return false; #endif } @@ -1286,29 +1244,7 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname, return true; } return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::regex pat("\\/"); - std::string _old = std::regex_replace(oldPath, pat, "\\"); - std::string _new = std::regex_replace(newPath, pat, "\\"); - - if(FileUtils::getInstance()->isFileExist(_new)) - { - if (!DeleteFileA(_new.c_str())) - { - CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError()); - } - } - - if (MoveFileA(_old.c_str(), _new.c_str())) - { - return true; - } - else - { - CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError()); - return false; - } -#else +#elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) int errorCode = rename(oldPath.c_str(), newPath.c_str()); if (0 != errorCode) @@ -1317,6 +1253,9 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname, return false; } return true; +#else + CCASSERT(false, "FileUtils not support renameFile"); + return false; #endif } diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index c14c748563..2d9cca5d9f 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -30,6 +30,7 @@ THE SOFTWARE. #include "platform/CCCommon.h" #include #include +#include using namespace std; @@ -56,20 +57,80 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } +static std::wstring StringUtf8ToWideChar(const std::string& strUtf8) +{ + std::wstring ret; + if (!strUtf8.empty()) + { + int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); + if (nNum) + { + WCHAR* wideCharString = new WCHAR[nNum + 1]; + wideCharString[0] = 0; + + nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); + + ret = wideCharString; + delete[] wideCharString; + } + else + { + CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); + } + } + return ret; +} + +static std::string StringWideCharToUtf8(const std::wstring& strWideChar) +{ + std::string ret; + if (!strWideChar.empty()) + { + int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* utf8String = new char[nNum + 1]; + utf8String[0] = 0; + + nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); + + ret = utf8String; + delete[] utf8String; + } + else + { + CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError()); + } + } + + return ret; +} + static void _checkPath() { if (0 == s_resourcePath.length()) { - WCHAR *pUtf16ExePath = nullptr; - _get_wpgmptr(&pUtf16ExePath); + if (IsDebuggerPresent()) + { + WCHAR utf16Path[CC_MAX_PATH] = { 0 }; + GetCurrentDirectoryW(sizeof(utf16Path)-1, utf16Path); - // We need only directory part without exe - WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); + s_resourcePath = convertPathFormatToUnixStyle(StringWideCharToUtf8(utf16Path)); + s_resourcePath.append("/"); + } + else + { + WCHAR *pUtf16ExePath = nullptr; + _get_wpgmptr(&pUtf16ExePath); - char utf8ExeDir[CC_MAX_PATH] = { 0 }; - int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd-pUtf16ExePath+1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); + // We need only directory part without exe + WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); - s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); + char utf8ExeDir[CC_MAX_PATH] = { 0 }; + int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd - pUtf16ExePath + 1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); + + s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); + } } } @@ -99,6 +160,17 @@ bool FileUtilsWin32::init() return FileUtils::init(); } +bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const +{ + unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str()); + if (fAttrib != INVALID_FILE_ATTRIBUTES && + (fAttrib & FILE_ATTRIBUTE_DIRECTORY)) + { + return true; + } + return false; +} + bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const { if (0 == strFilePath.length()) @@ -112,10 +184,7 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const strPath.insert(0, _defaultResRootPath); } - WCHAR utf16Buf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0])); - - DWORD attr = GetFileAttributesW(utf16Buf); + DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str()); if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) return false; // not a file return true; @@ -195,10 +264,7 @@ static Data getData(const std::string& filename, bool forString) // check if the filename uses correct case characters CC_BREAK_IF(!checkFileName(fullPath, filename)); - WCHAR wszBuf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0])); - - HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); + HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); size = ::GetFileSize(fileHandle, nullptr); @@ -280,10 +346,7 @@ unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const ch // check if the filename uses correct case characters CC_BREAK_IF(!checkFileName(fullPath, filename)); - WCHAR wszBuf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0])); - - HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); + HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); *size = ::GetFileSize(fileHandle, nullptr); @@ -340,49 +403,191 @@ string FileUtilsWin32::getWritablePath() const } // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe - char full_path[CC_MAX_PATH + 1]; - ::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + 1); + WCHAR full_path[CC_MAX_PATH + 1] = { 0 }; + ::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1); // Debug app uses executable directory; Non-debug app uses local app data directory //#ifndef _DEBUG - // Get filename of executable only, e.g. MyGame.exe - char *base_name = strrchr(full_path, '\\'); + // Get filename of executable only, e.g. MyGame.exe + WCHAR *base_name = wcsrchr(full_path, '\\'); + wstring retPath; + if(base_name) + { + WCHAR app_data_path[CC_MAX_PATH + 1]; - if(base_name) + // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data + if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path))) { - char app_data_path[CC_MAX_PATH + 1]; + wstring ret(app_data_path); - // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data - if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path))) + // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe + ret += base_name; + + // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame + ret = ret.substr(0, ret.rfind(L".")); + + ret += L"\\"; + + // Create directory + if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr))) { - string ret((char*)app_data_path); + retPath = ret; + } + } + } + if (retPath.empty()) +//#endif // not defined _DEBUG + { + // If fetching of local app data directory fails, use the executable one + retPath = full_path; - // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe - ret += base_name; + // remove xxx.exe + retPath = retPath.substr(0, retPath.rfind(L"\\") + 1); + } - // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame - ret = ret.substr(0, ret.rfind(".")); + return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath)); +} - ret += "\\"; +bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name) +{ + CCASSERT(!path.empty(), "Invalid path"); + std::string oldPath = path + oldname; + std::string newPath = path + name; - // Create directory - if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr))) + std::regex pat("\\/"); + std::string _old = std::regex_replace(oldPath, pat, "\\"); + std::string _new = std::regex_replace(newPath, pat, "\\"); + + std::wstring _wNew = StringUtf8ToWideChar(_new); + + if (FileUtils::getInstance()->isFileExist(_new)) + { + if (!DeleteFile(_wNew.c_str())) + { + CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError()); + } + } + + if (MoveFile(StringUtf8ToWideChar(_old).c_str(), _wNew.c_str())) + { + return true; + } + else + { + CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError()); + return false; + } +} + +bool FileUtilsWin32::createDirectory(const std::string& dirPath) +{ + CCASSERT(!dirPath.empty(), "Invalid path"); + + if (isDirectoryExist(dirPath)) + return true; + + std::wstring path = StringUtf8ToWideChar(dirPath); + + // Split the path + size_t start = 0; + size_t found = path.find_first_of(L"/\\", start); + std::wstring subpath; + std::vector dirs; + + if (found != std::wstring::npos) + { + while (true) + { + subpath = path.substr(start, found - start + 1); + if (!subpath.empty()) + dirs.push_back(subpath); + start = found + 1; + found = path.find_first_of(L"/\\", start); + if (found == std::wstring::npos) + { + if (start < path.length()) { - return convertPathFormatToUnixStyle(ret); + dirs.push_back(path.substr(start)); + } + break; + } + } + } + + if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES) + { + subpath = L""; + for (unsigned int i = 0; i < dirs.size(); ++i) + { + subpath += dirs[i]; + + std::string utf8Path = StringWideCharToUtf8(subpath); + if (!isDirectoryExist(utf8Path)) + { + BOOL ret = CreateDirectory(subpath.c_str(), NULL); + if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) + { + CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError()); + return false; } } } -//#endif // not defined _DEBUG + } + return true; +} - // If fetching of local app data directory fails, use the executable one - string ret((char*)full_path); +bool FileUtilsWin32::removeFile(const std::string &filepath) +{ + std::regex pat("\\/"); + std::string win32path = std::regex_replace(filepath, pat, "\\"); - // remove xxx.exe - ret = ret.substr(0, ret.rfind("\\") + 1); + if (DeleteFile(StringUtf8ToWideChar(win32path).c_str())) + { + return true; + } + else + { + CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError()); + return false; + } +} - ret = convertPathFormatToUnixStyle(ret); - - return ret; +bool FileUtilsWin32::removeDirectory(const std::string& dirPath) +{ + std::wstring wpath = StringUtf8ToWideChar(dirPath); + std::wstring files = wpath + L"*.*"; + WIN32_FIND_DATA wfd; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; + if (search != INVALID_HANDLE_VALUE) + { + BOOL find = true; + while (find) + { + //. .. + if (wfd.cFileName[0] != '.') + { + std::wstring temp = wpath + wfd.cFileName; + if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + temp += '/'; + ret = ret && this->removeDirectory(StringWideCharToUtf8(temp)); + } + else + { + SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); + ret = ret && DeleteFile(temp.c_str()); + } + } + find = FindNextFile(search, &wfd); + } + FindClose(search); + } + if (ret && RemoveDirectory(wpath.c_str())) + { + return true; + } + return false; } NS_CC_END diff --git a/cocos/platform/win32/CCFileUtils-win32.h b/cocos/platform/win32/CCFileUtils-win32.h index 17f6c1ec01..fc6f95e9c8 100644 --- a/cocos/platform/win32/CCFileUtils-win32.h +++ b/cocos/platform/win32/CCFileUtils-win32.h @@ -49,11 +49,52 @@ class CC_DLL FileUtilsWin32 : public FileUtils public: /* override funtions */ bool init(); - virtual std::string getWritablePath() const; - virtual bool isAbsolutePath(const std::string& strPath) const; + virtual std::string getWritablePath() const override; + virtual bool isAbsolutePath(const std::string& strPath) const override; protected: - virtual bool isFileExistInternal(const std::string& strFilePath) const; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; + + /** + * Renames a file under the given directory. + * + * @param path The parent directory path of the file, it must be an absolute path. + * @param oldname The current name of the file. + * @param name The new name of the file. + * @return True if the file have been renamed successfully, false if not. + */ + virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override; + + /** + * Checks whether a directory exists without considering search paths and resolution orders. + * @param dirPath The directory (with absolute path) to look up for + * @return Returns true if the directory found at the given absolute path, otherwise returns false + */ + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + + /** + * Removes a file. + * + * @param filepath The full path of the file, it must be an absolute path. + * @return True if the file have been removed successfully, false if not. + */ + virtual bool removeFile(const std::string &filepath) override; + + /** + * Creates a directory. + * + * @param dirPath The path of the directory, it must be an absolute path. + * @return True if the directory have been created successfully, false if not. + */ + virtual bool createDirectory(const std::string& dirPath) override; + + /** + * Removes a directory. + * + * @param dirPath The full path of the directory, it must be an absolute path. + * @return True if the directory have been removed successfully, false if not. + */ + virtual bool removeDirectory(const std::string& dirPath) override; /** * Gets resource file data From bfb3fbb1c08937ec65e018ee196564db46b0959e Mon Sep 17 00:00:00 2001 From: Vladimir Perminov Date: Sun, 17 May 2015 19:24:57 +0300 Subject: [PATCH 2/2] Revert _checkPath --- cocos/platform/win32/CCFileUtils-win32.cpp | 25 ++++++---------------- 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index 2d9cca5d9f..213221f293 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -110,27 +110,16 @@ static void _checkPath() { if (0 == s_resourcePath.length()) { - if (IsDebuggerPresent()) - { - WCHAR utf16Path[CC_MAX_PATH] = { 0 }; - GetCurrentDirectoryW(sizeof(utf16Path)-1, utf16Path); + WCHAR *pUtf16ExePath = nullptr; + _get_wpgmptr(&pUtf16ExePath); - s_resourcePath = convertPathFormatToUnixStyle(StringWideCharToUtf8(utf16Path)); - s_resourcePath.append("/"); - } - else - { - WCHAR *pUtf16ExePath = nullptr; - _get_wpgmptr(&pUtf16ExePath); + // We need only directory part without exe + WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); - // We need only directory part without exe - WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); + char utf8ExeDir[CC_MAX_PATH] = { 0 }; + int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd-pUtf16ExePath+1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); - char utf8ExeDir[CC_MAX_PATH] = { 0 }; - int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd - pUtf16ExePath + 1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); - - s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); - } + s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); } }