CCFileUtilsWinRT.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /****************************************************************************
  2. Copyright (c) 2010 cocos2d-x.org
  3. Copyright (c) Microsoft Open Technologies, Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/winrt/CCFileUtilsWinRT.h"
  22. #include <regex>
  23. #include "platform/winrt/CCWinRTUtils.h"
  24. #include "platform/CCCommon.h"
  25. using namespace std;
  26. NS_CC_BEGIN
  27. static std::string s_pszResourcePath;
  28. // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
  29. static inline std::string convertPathFormatToUnixStyle(const std::string& path)
  30. {
  31. std::string ret = path;
  32. size_t len = ret.length();
  33. for (size_t i = 0; i < len; ++i)
  34. {
  35. if (ret[i] == '\\')
  36. {
  37. ret[i] = '/';
  38. }
  39. }
  40. return ret;
  41. }
  42. static std::string UTF8StringToMultiByte(const std::string& strUtf8)
  43. {
  44. std::string ret;
  45. if (!strUtf8.empty())
  46. {
  47. std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
  48. int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
  49. if (nNum)
  50. {
  51. char* ansiString = new char[nNum + 1];
  52. ansiString[0] = 0;
  53. nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
  54. ret = ansiString;
  55. delete[] ansiString;
  56. }
  57. else
  58. {
  59. CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
  60. }
  61. }
  62. return ret;
  63. }
  64. static void _checkPath()
  65. {
  66. if (s_pszResourcePath.empty())
  67. {
  68. // TODO: needs to be tested
  69. s_pszResourcePath = convertPathFormatToUnixStyle(CCFileUtilsWinRT::getAppPath() + '\\' + "Assets\\Resources" + '\\');
  70. }
  71. }
  72. FileUtils* FileUtils::getInstance()
  73. {
  74. if (s_sharedFileUtils == nullptr)
  75. {
  76. s_sharedFileUtils = new CCFileUtilsWinRT();
  77. if(!s_sharedFileUtils->init())
  78. {
  79. delete s_sharedFileUtils;
  80. s_sharedFileUtils = nullptr;
  81. CCLOG("ERROR: Could not init CCFileUtilsWinRT");
  82. }
  83. }
  84. return s_sharedFileUtils;
  85. }
  86. CCFileUtilsWinRT::CCFileUtilsWinRT()
  87. {
  88. }
  89. bool CCFileUtilsWinRT::init()
  90. {
  91. _checkPath();
  92. _defaultResRootPath = s_pszResourcePath;
  93. return FileUtils::init();
  94. }
  95. std::string CCFileUtilsWinRT::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  96. {
  97. std::string unixFileName = convertPathFormatToUnixStyle(filename);
  98. std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
  99. std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath);
  100. return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
  101. }
  102. std::string CCFileUtilsWinRT::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const
  103. {
  104. std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
  105. std::string unixFilename = convertPathFormatToUnixStyle(strFilename);
  106. return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
  107. }
  108. std::string CCFileUtilsWinRT::getSuitableFOpen(const std::string& filenameUtf8) const
  109. {
  110. return UTF8StringToMultiByte(filenameUtf8);
  111. }
  112. long CCFileUtilsWinRT::getFileSize(const std::string &filepath)
  113. {
  114. WIN32_FILE_ATTRIBUTE_DATA fad;
  115. if (!GetFileAttributesEx(StringUtf8ToWideChar(filepath).c_str(), GetFileExInfoStandard, &fad))
  116. {
  117. return 0; // error condition, could call GetLastError to find out more
  118. }
  119. LARGE_INTEGER size;
  120. size.HighPart = fad.nFileSizeHigh;
  121. size.LowPart = fad.nFileSizeLow;
  122. return (long)size.QuadPart;
  123. }
  124. FileUtils::Status CCFileUtilsWinRT::getContents(const std::string& filename, ResizableBuffer* buffer)
  125. {
  126. if (filename.empty())
  127. return FileUtils::Status::NotExists;
  128. // read the file from hardware
  129. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
  130. HANDLE fileHandle = ::CreateFile2(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, nullptr);
  131. if (fileHandle == INVALID_HANDLE_VALUE)
  132. return FileUtils::Status::OpenFailed;
  133. FILE_STANDARD_INFO info = {0};
  134. if (::GetFileInformationByHandleEx(fileHandle, FileStandardInfo, &info, sizeof(info)) == 0)
  135. {
  136. ::CloseHandle(fileHandle);
  137. return FileUtils::Status::OpenFailed;
  138. }
  139. if (info.EndOfFile.HighPart > 0)
  140. {
  141. ::CloseHandle(fileHandle);
  142. return FileUtils::Status::TooLarge;
  143. }
  144. buffer->resize(info.EndOfFile.LowPart);
  145. DWORD sizeRead = 0;
  146. BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), info.EndOfFile.LowPart, &sizeRead, nullptr);
  147. ::CloseHandle(fileHandle);
  148. if (!successed)
  149. {
  150. buffer->resize(sizeRead);
  151. CCLOG("Get data from file(%s) failed, error code is %s", filename.data(), std::to_string(::GetLastError()).data());
  152. return FileUtils::Status::ReadFailed;
  153. }
  154. return FileUtils::Status::OK;
  155. }
  156. bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const
  157. {
  158. bool ret = false;
  159. FILE * pf = nullptr;
  160. std::string strPath = strFilePath;
  161. if (!isAbsolutePath(strPath))
  162. { // Not absolute path, add the default root path at the beginning.
  163. strPath.insert(0, _defaultResRootPath);
  164. }
  165. strPath = getSuitableFOpen(strPath);
  166. if (!strPath.empty() && (pf = fopen(strPath.c_str(), "rb")))
  167. {
  168. ret = true;
  169. fclose(pf);
  170. }
  171. return ret;
  172. }
  173. bool CCFileUtilsWinRT::isDirectoryExistInternal(const std::string& dirPath) const
  174. {
  175. WIN32_FILE_ATTRIBUTE_DATA wfad;
  176. std::wstring wdirPath = StringUtf8ToWideChar(dirPath);
  177. if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
  178. {
  179. return true;
  180. }
  181. return false;
  182. }
  183. bool CCFileUtilsWinRT::createDirectory(const std::string& path)
  184. {
  185. CCASSERT(!path.empty(), "Invalid path");
  186. if (isDirectoryExist(path))
  187. return true;
  188. // Split the path
  189. size_t start = 0;
  190. size_t found = path.find_first_of("/\\", start);
  191. std::string subpath;
  192. std::vector<std::string> dirs;
  193. if (found != std::string::npos)
  194. {
  195. while (true)
  196. {
  197. subpath = path.substr(start, found - start + 1);
  198. if (!subpath.empty())
  199. dirs.push_back(subpath);
  200. start = found + 1;
  201. found = path.find_first_of("/\\", start);
  202. if (found == std::string::npos)
  203. {
  204. if (start < path.length())
  205. {
  206. dirs.push_back(path.substr(start));
  207. }
  208. break;
  209. }
  210. }
  211. }
  212. WIN32_FILE_ATTRIBUTE_DATA wfad;
  213. if (!(GetFileAttributesEx(StringUtf8ToWideChar(path).c_str(), GetFileExInfoStandard, &wfad)))
  214. {
  215. subpath = "";
  216. for (unsigned int i = 0, size = dirs.size(); i < size; ++i)
  217. {
  218. subpath += dirs[i];
  219. if (i > 0 && !isDirectoryExist(subpath))
  220. {
  221. BOOL ret = CreateDirectory(StringUtf8ToWideChar(subpath).c_str(), NULL);
  222. if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
  223. {
  224. return false;
  225. }
  226. }
  227. }
  228. }
  229. return true;
  230. }
  231. bool CCFileUtilsWinRT::removeDirectory(const std::string& path)
  232. {
  233. std::wstring wpath = StringUtf8ToWideChar(path);
  234. std::wstring files = wpath + L"*.*";
  235. WIN32_FIND_DATA wfd;
  236. HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
  237. bool ret = true;
  238. if (search != INVALID_HANDLE_VALUE)
  239. {
  240. BOOL find = true;
  241. while (find)
  242. {
  243. //. ..
  244. if (wfd.cFileName[0] != '.')
  245. {
  246. std::wstring temp = wpath + wfd.cFileName;
  247. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  248. {
  249. temp += '/';
  250. ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
  251. }
  252. else
  253. {
  254. SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
  255. ret = ret && DeleteFile(temp.c_str());
  256. }
  257. }
  258. find = FindNextFile(search, &wfd);
  259. }
  260. FindClose(search);
  261. }
  262. if (ret && RemoveDirectory(wpath.c_str()))
  263. {
  264. return true;
  265. }
  266. return false;
  267. }
  268. bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
  269. {
  270. if ( strPath.length() > 2
  271. && ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') )
  272. && strPath[1] == ':')
  273. {
  274. return true;
  275. }
  276. return false;
  277. }
  278. bool CCFileUtilsWinRT::removeFile(const std::string &path)
  279. {
  280. std::wstring wpath = StringUtf8ToWideChar(path);
  281. if (DeleteFile(wpath.c_str()))
  282. {
  283. return true;
  284. }
  285. else
  286. {
  287. CCLOG("Remove file failed with error: %d", GetLastError());
  288. return false;
  289. }
  290. }
  291. bool CCFileUtilsWinRT::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  292. {
  293. CCASSERT(!oldfullpath.empty(), "Invalid path");
  294. CCASSERT(!newfullpath.empty(), "Invalid path");
  295. std::regex pat("\\/");
  296. std::string _oldfullpath = std::regex_replace(oldfullpath, pat, "\\");
  297. std::string _newfullpath = std::regex_replace(newfullpath, pat, "\\");
  298. std::wstring _wNewfullpath = StringUtf8ToWideChar(_newfullpath);
  299. if (FileUtils::getInstance()->isFileExist(_newfullpath))
  300. {
  301. if (!DeleteFile(_wNewfullpath.c_str()))
  302. {
  303. CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError());
  304. }
  305. }
  306. if (MoveFileEx(StringUtf8ToWideChar(_oldfullpath).c_str(), _wNewfullpath.c_str(),
  307. MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
  308. {
  309. return true;
  310. }
  311. else
  312. {
  313. CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), GetLastError());
  314. return false;
  315. }
  316. }
  317. bool CCFileUtilsWinRT::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  318. {
  319. CCASSERT(!path.empty(), "Invalid path");
  320. std::string oldPath = path + oldname;
  321. std::string newPath = path + name;
  322. return renameFile(oldPath, newPath);
  323. }
  324. string CCFileUtilsWinRT::getWritablePath() const
  325. {
  326. auto localFolderPath = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
  327. return convertPathFormatToUnixStyle(std::string(PlatformStringToString(localFolderPath)) + '\\');
  328. }
  329. string CCFileUtilsWinRT::getAppPath()
  330. {
  331. Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current;
  332. return convertPathFormatToUnixStyle(std::string(PlatformStringToString(package->InstalledLocation->Path)));
  333. }
  334. NS_CC_END