CCFileUtilsWinRT.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. #include "tinydir/tinydir.h"
  26. using namespace std;
  27. NS_CC_BEGIN
  28. static std::string s_pszResourcePath;
  29. // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
  30. static inline std::string convertPathFormatToUnixStyle(const std::string& path)
  31. {
  32. std::string ret = path;
  33. size_t len = ret.length();
  34. for (size_t i = 0; i < len; ++i)
  35. {
  36. if (ret[i] == '\\')
  37. {
  38. ret[i] = '/';
  39. }
  40. }
  41. return ret;
  42. }
  43. static std::string UTF8StringToMultiByte(const std::string& strUtf8)
  44. {
  45. std::string ret;
  46. if (!strUtf8.empty())
  47. {
  48. std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
  49. int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
  50. if (nNum)
  51. {
  52. char* ansiString = new char[nNum + 1];
  53. ansiString[0] = 0;
  54. nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
  55. ret = ansiString;
  56. delete[] ansiString;
  57. }
  58. else
  59. {
  60. CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
  61. }
  62. }
  63. return ret;
  64. }
  65. static void _checkPath()
  66. {
  67. if (s_pszResourcePath.empty())
  68. {
  69. // TODO: needs to be tested
  70. s_pszResourcePath = convertPathFormatToUnixStyle(CCFileUtilsWinRT::getAppPath() + '\\' + "Assets\\Resources" + '\\');
  71. }
  72. }
  73. FileUtils* FileUtils::getInstance()
  74. {
  75. if (s_sharedFileUtils == nullptr)
  76. {
  77. s_sharedFileUtils = new CCFileUtilsWinRT();
  78. if(!s_sharedFileUtils->init())
  79. {
  80. delete s_sharedFileUtils;
  81. s_sharedFileUtils = nullptr;
  82. CCLOG("ERROR: Could not init CCFileUtilsWinRT");
  83. }
  84. }
  85. return s_sharedFileUtils;
  86. }
  87. CCFileUtilsWinRT::CCFileUtilsWinRT()
  88. {
  89. }
  90. bool CCFileUtilsWinRT::init()
  91. {
  92. _checkPath();
  93. _defaultResRootPath = s_pszResourcePath;
  94. return FileUtils::init();
  95. }
  96. std::string CCFileUtilsWinRT::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  97. {
  98. std::string unixFileName = convertPathFormatToUnixStyle(filename);
  99. std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
  100. std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath);
  101. return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
  102. }
  103. std::string CCFileUtilsWinRT::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const
  104. {
  105. std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
  106. std::string unixFilename = convertPathFormatToUnixStyle(strFilename);
  107. return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
  108. }
  109. std::string CCFileUtilsWinRT::getSuitableFOpen(const std::string& filenameUtf8) const
  110. {
  111. return UTF8StringToMultiByte(filenameUtf8);
  112. }
  113. long CCFileUtilsWinRT::getFileSize(const std::string &filepath)
  114. {
  115. WIN32_FILE_ATTRIBUTE_DATA fad;
  116. if (!GetFileAttributesEx(StringUtf8ToWideChar(filepath).c_str(), GetFileExInfoStandard, &fad))
  117. {
  118. return 0; // error condition, could call GetLastError to find out more
  119. }
  120. LARGE_INTEGER size;
  121. size.HighPart = fad.nFileSizeHigh;
  122. size.LowPart = fad.nFileSizeLow;
  123. return (long)size.QuadPart;
  124. }
  125. FileUtils::Status CCFileUtilsWinRT::getContents(const std::string& filename, ResizableBuffer* buffer)
  126. {
  127. if (filename.empty())
  128. return FileUtils::Status::NotExists;
  129. // read the file from hardware
  130. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
  131. HANDLE fileHandle = ::CreateFile2(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, nullptr);
  132. if (fileHandle == INVALID_HANDLE_VALUE)
  133. return FileUtils::Status::OpenFailed;
  134. FILE_STANDARD_INFO info = {0};
  135. if (::GetFileInformationByHandleEx(fileHandle, FileStandardInfo, &info, sizeof(info)) == 0)
  136. {
  137. ::CloseHandle(fileHandle);
  138. return FileUtils::Status::OpenFailed;
  139. }
  140. if (info.EndOfFile.HighPart > 0)
  141. {
  142. ::CloseHandle(fileHandle);
  143. return FileUtils::Status::TooLarge;
  144. }
  145. buffer->resize(info.EndOfFile.LowPart);
  146. DWORD sizeRead = 0;
  147. BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), info.EndOfFile.LowPart, &sizeRead, nullptr);
  148. ::CloseHandle(fileHandle);
  149. if (!successed)
  150. {
  151. buffer->resize(sizeRead);
  152. CCLOG("Get data from file(%s) failed, error code is %s", filename.data(), std::to_string(::GetLastError()).data());
  153. return FileUtils::Status::ReadFailed;
  154. }
  155. return FileUtils::Status::OK;
  156. }
  157. bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const
  158. {
  159. bool ret = false;
  160. FILE * pf = nullptr;
  161. std::string strPath = strFilePath;
  162. if (!isAbsolutePath(strPath))
  163. { // Not absolute path, add the default root path at the beginning.
  164. strPath.insert(0, _defaultResRootPath);
  165. }
  166. strPath = getSuitableFOpen(strPath);
  167. if (!strPath.empty() && (pf = fopen(strPath.c_str(), "rb")))
  168. {
  169. ret = true;
  170. fclose(pf);
  171. }
  172. return ret;
  173. }
  174. bool CCFileUtilsWinRT::isDirectoryExistInternal(const std::string& dirPath) const
  175. {
  176. WIN32_FILE_ATTRIBUTE_DATA wfad;
  177. std::wstring wdirPath = StringUtf8ToWideChar(dirPath);
  178. if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
  179. {
  180. return true;
  181. }
  182. return false;
  183. }
  184. bool CCFileUtilsWinRT::createDirectory(const std::string& path)
  185. {
  186. CCASSERT(!path.empty(), "Invalid path");
  187. if (isDirectoryExist(path))
  188. return true;
  189. // Split the path
  190. size_t start = 0;
  191. size_t found = path.find_first_of("/\\", start);
  192. std::string subpath;
  193. std::vector<std::string> dirs;
  194. if (found != std::string::npos)
  195. {
  196. while (true)
  197. {
  198. subpath = path.substr(start, found - start + 1);
  199. if (!subpath.empty())
  200. dirs.push_back(subpath);
  201. start = found + 1;
  202. found = path.find_first_of("/\\", start);
  203. if (found == std::string::npos)
  204. {
  205. if (start < path.length())
  206. {
  207. dirs.push_back(path.substr(start));
  208. }
  209. break;
  210. }
  211. }
  212. }
  213. WIN32_FILE_ATTRIBUTE_DATA wfad;
  214. if (!(GetFileAttributesEx(StringUtf8ToWideChar(path).c_str(), GetFileExInfoStandard, &wfad)))
  215. {
  216. subpath = "";
  217. for (unsigned int i = 0, size = dirs.size(); i < size; ++i)
  218. {
  219. subpath += dirs[i];
  220. if (i > 0 && !isDirectoryExist(subpath))
  221. {
  222. BOOL ret = CreateDirectory(StringUtf8ToWideChar(subpath).c_str(), NULL);
  223. if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
  224. {
  225. return false;
  226. }
  227. }
  228. }
  229. }
  230. return true;
  231. }
  232. bool CCFileUtilsWinRT::removeDirectory(const std::string& path)
  233. {
  234. std::wstring wpath = StringUtf8ToWideChar(path);
  235. std::wstring files = wpath + L"*.*";
  236. WIN32_FIND_DATA wfd;
  237. HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
  238. bool ret = true;
  239. if (search != INVALID_HANDLE_VALUE)
  240. {
  241. BOOL find = true;
  242. while (find)
  243. {
  244. //. ..
  245. if (wfd.cFileName[0] != '.')
  246. {
  247. std::wstring temp = wpath + wfd.cFileName;
  248. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  249. {
  250. temp += '/';
  251. ret = ret && this->removeDirectory(StringWideCharToUtf8(temp));
  252. }
  253. else
  254. {
  255. SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
  256. ret = ret && DeleteFile(temp.c_str());
  257. }
  258. }
  259. find = FindNextFile(search, &wfd);
  260. }
  261. FindClose(search);
  262. }
  263. if (ret && RemoveDirectory(wpath.c_str()))
  264. {
  265. return true;
  266. }
  267. return false;
  268. }
  269. bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
  270. {
  271. if ( strPath.length() > 2
  272. && ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') )
  273. && strPath[1] == ':')
  274. {
  275. return true;
  276. }
  277. return false;
  278. }
  279. bool CCFileUtilsWinRT::removeFile(const std::string &path)
  280. {
  281. std::wstring wpath = StringUtf8ToWideChar(path);
  282. if (DeleteFile(wpath.c_str()))
  283. {
  284. return true;
  285. }
  286. else
  287. {
  288. CCLOG("Remove file failed with error: %d", GetLastError());
  289. return false;
  290. }
  291. }
  292. bool CCFileUtilsWinRT::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  293. {
  294. CCASSERT(!oldfullpath.empty(), "Invalid path");
  295. CCASSERT(!newfullpath.empty(), "Invalid path");
  296. std::regex pat("\\/");
  297. std::string _oldfullpath = std::regex_replace(oldfullpath, pat, "\\");
  298. std::string _newfullpath = std::regex_replace(newfullpath, pat, "\\");
  299. std::wstring _wNewfullpath = StringUtf8ToWideChar(_newfullpath);
  300. if (FileUtils::getInstance()->isFileExist(_newfullpath))
  301. {
  302. if (!DeleteFile(_wNewfullpath.c_str()))
  303. {
  304. CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError());
  305. }
  306. }
  307. if (MoveFileEx(StringUtf8ToWideChar(_oldfullpath).c_str(), _wNewfullpath.c_str(),
  308. MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
  309. {
  310. return true;
  311. }
  312. else
  313. {
  314. CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), GetLastError());
  315. return false;
  316. }
  317. }
  318. bool CCFileUtilsWinRT::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  319. {
  320. CCASSERT(!path.empty(), "Invalid path");
  321. std::string oldPath = path + oldname;
  322. std::string newPath = path + name;
  323. return renameFile(oldPath, newPath);
  324. }
  325. string CCFileUtilsWinRT::getWritablePath() const
  326. {
  327. auto localFolderPath = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
  328. return convertPathFormatToUnixStyle(std::string(PlatformStringToString(localFolderPath)) + '\\');
  329. }
  330. void CCFileUtilsWinRT::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
  331. {
  332. std::string fullpath = fullPathForFilename(dirPath);
  333. if (isDirectoryExist(fullpath))
  334. {
  335. tinydir_dir dir;
  336. std::wstring fullpathstr = StringUtf8ToWideChar(fullpath);
  337. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  338. {
  339. while (dir.has_next)
  340. {
  341. tinydir_file file;
  342. if (tinydir_readfile(&dir, &file) == -1)
  343. {
  344. // Error getting file
  345. break;
  346. }
  347. std::string fileName = StringWideCharToUtf8(file.name);
  348. if (fileName != "." && fileName != "..")
  349. {
  350. std::string filepath = StringWideCharToUtf8(file.path);
  351. if (file.is_dir)
  352. {
  353. filepath.append("/");
  354. files->push_back(filepath);
  355. listFilesRecursively(filepath, files);
  356. }
  357. else
  358. {
  359. files->push_back(filepath);
  360. }
  361. }
  362. if (tinydir_next(&dir) == -1)
  363. {
  364. // Error getting next file
  365. break;
  366. }
  367. }
  368. }
  369. tinydir_close(&dir);
  370. }
  371. }
  372. std::vector<std::string> CCFileUtilsWinRT::listFiles(const std::string& dirPath) const
  373. {
  374. std::string fullpath = fullPathForFilename(dirPath);
  375. std::vector<std::string> files;
  376. if (isDirectoryExist(fullpath))
  377. {
  378. tinydir_dir dir;
  379. std::wstring fullpathstr = StringUtf8ToWideChar(fullpath);
  380. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  381. {
  382. while (dir.has_next)
  383. {
  384. tinydir_file file;
  385. if (tinydir_readfile(&dir, &file) == -1)
  386. {
  387. // Error getting file
  388. break;
  389. }
  390. std::string filepath = StringWideCharToUtf8(file.path);
  391. if (file.is_dir)
  392. {
  393. filepath.append("/");
  394. }
  395. files.push_back(filepath);
  396. if (tinydir_next(&dir) == -1)
  397. {
  398. // Error getting next file
  399. break;
  400. }
  401. }
  402. }
  403. tinydir_close(&dir);
  404. }
  405. return files;
  406. }
  407. string CCFileUtilsWinRT::getAppPath()
  408. {
  409. Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current;
  410. return convertPathFormatToUnixStyle(std::string(PlatformStringToString(package->InstalledLocation->Path)));
  411. }
  412. NS_CC_END