CCFileUtils.h 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /****************************************************************************
  2. Copyright (c) 2010-2013 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #ifndef __CC_FILEUTILS_H__
  23. #define __CC_FILEUTILS_H__
  24. #include <string>
  25. #include <vector>
  26. #include <unordered_map>
  27. #include <type_traits>
  28. #include "platform/CCPlatformMacros.h"
  29. #include "base/ccTypes.h"
  30. #include "base/CCValue.h"
  31. #include "base/CCData.h"
  32. #include "base/CCAsyncTaskPool.h"
  33. #include "base/CCScheduler.h"
  34. #include "base/CCDirector.h"
  35. NS_CC_BEGIN
  36. /**
  37. * @addtogroup platform
  38. * @{
  39. */
  40. class ResizableBuffer {
  41. public:
  42. virtual ~ResizableBuffer() {}
  43. virtual void resize(size_t size) = 0;
  44. virtual void* buffer() const = 0;
  45. };
  46. template<typename T>
  47. class ResizableBufferAdapter { };
  48. template<typename CharT, typename Traits, typename Allocator>
  49. class ResizableBufferAdapter< std::basic_string<CharT, Traits, Allocator> > : public ResizableBuffer {
  50. typedef std::basic_string<CharT, Traits, Allocator> BufferType;
  51. BufferType* _buffer;
  52. public:
  53. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  54. virtual void resize(size_t size) override {
  55. _buffer->resize((size + sizeof(CharT) - 1) / sizeof(CharT));
  56. }
  57. virtual void* buffer() const override {
  58. // can not invoke string::front() if it is empty
  59. if (_buffer->empty())
  60. return nullptr;
  61. else
  62. return &_buffer->front();
  63. }
  64. };
  65. template<typename T, typename Allocator>
  66. class ResizableBufferAdapter< std::vector<T, Allocator> > : public ResizableBuffer {
  67. typedef std::vector<T, Allocator> BufferType;
  68. BufferType* _buffer;
  69. public:
  70. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  71. virtual void resize(size_t size) override {
  72. _buffer->resize((size + sizeof(T) - 1) / sizeof(T));
  73. }
  74. virtual void* buffer() const override {
  75. // can not invoke vector::front() if it is empty
  76. if (_buffer->empty())
  77. return nullptr;
  78. else
  79. return &_buffer->front();
  80. }
  81. };
  82. template<>
  83. class ResizableBufferAdapter<Data> : public ResizableBuffer {
  84. typedef Data BufferType;
  85. BufferType* _buffer;
  86. public:
  87. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  88. virtual void resize(size_t size) override {
  89. size_t oldSize = static_cast<size_t>(_buffer->getSize());
  90. if (oldSize != size) {
  91. auto old = _buffer->getBytes();
  92. void* buffer = realloc(old, size);
  93. if (buffer)
  94. _buffer->fastSet((unsigned char*)buffer, size);
  95. }
  96. }
  97. virtual void* buffer() const override {
  98. return _buffer->getBytes();
  99. }
  100. };
  101. /** Helper class to handle file operations. */
  102. class CC_DLL FileUtils
  103. {
  104. public:
  105. /**
  106. * Gets the instance of FileUtils.
  107. */
  108. static FileUtils* getInstance();
  109. /**
  110. * Destroys the instance of FileUtils.
  111. */
  112. static void destroyInstance();
  113. /**
  114. * You can inherit from platform dependent implementation of FileUtils, such as FileUtilsAndroid,
  115. * and use this function to set delegate, then FileUtils will invoke delegate's implementation.
  116. * For example, your resources are encrypted, so you need to decrypt it after reading data from
  117. * resources, then you can implement all getXXX functions, and engine will invoke your own getXX
  118. * functions when reading data of resources.
  119. *
  120. * If you don't want to system default implementation after setting delegate, you can just pass nullptr
  121. * to this function.
  122. *
  123. * @warning It will delete previous delegate
  124. * @lua NA
  125. */
  126. static void setDelegate(FileUtils *delegate);
  127. /** @deprecated Use getInstance() instead */
  128. CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils() { return getInstance(); }
  129. /** @deprecated Use destroyInstance() instead */
  130. CC_DEPRECATED_ATTRIBUTE static void purgeFileUtils() { destroyInstance(); }
  131. /**
  132. * The destructor of FileUtils.
  133. * @js NA
  134. * @lua NA
  135. */
  136. virtual ~FileUtils();
  137. /**
  138. * Purges full path caches.
  139. */
  140. virtual void purgeCachedEntries();
  141. /**
  142. * Gets string from a file.
  143. */
  144. virtual std::string getStringFromFile(const std::string& filename);
  145. /**
  146. * Gets string from a file, async off the main cocos thread
  147. *
  148. * @param path filepath for the string to be read. Can be relative or absolute path
  149. * @param callback Function that will be called when file is read. Will be called
  150. * on the main cocos thread.
  151. */
  152. virtual void getStringFromFile(const std::string& path, std::function<void(std::string)> callback);
  153. /**
  154. * Creates binary data from a file.
  155. * @return A data object.
  156. */
  157. virtual Data getDataFromFile(const std::string& filename);
  158. /**
  159. * Gets a binary data object from a file, async off the main cocos thread.
  160. *
  161. * @param filename filepath for the data to be read. Can be relative or absolute path
  162. * @param callback Function that will be called when file is read. Will be called
  163. * on the main cocos thread.
  164. */
  165. virtual void getDataFromFile(const std::string& filename, std::function<void(Data)> callback);
  166. enum class Status
  167. {
  168. OK = 0,
  169. NotExists = 1, // File not exists
  170. OpenFailed = 2, // Open file failed.
  171. ReadFailed = 3, // Read failed
  172. NotInitialized = 4, // FileUtils is not initializes
  173. TooLarge = 5, // The file is too large (great than 2^32-1)
  174. ObtainSizeFailed = 6 // Failed to obtain the file size.
  175. };
  176. /**
  177. * Gets whole file contents as string from a file.
  178. *
  179. * Unlike getStringFromFile, these getContents methods:
  180. * - read file in binary mode (does not convert CRLF to LF).
  181. * - does not truncate the string when '\0' is found (returned string of getContents may have '\0' in the middle.).
  182. *
  183. * The template version of can accept cocos2d::Data, std::basic_string and std::vector.
  184. *
  185. * @code
  186. * std::string sbuf;
  187. * FileUtils::getInstance()->getContents("path/to/file", &sbuf);
  188. *
  189. * std::vector<int> vbuf;
  190. * FileUtils::getInstance()->getContents("path/to/file", &vbuf);
  191. *
  192. * Data dbuf;
  193. * FileUtils::getInstance()->getContents("path/to/file", &dbuf);
  194. * @endcode
  195. *
  196. * Note: if you read to std::vector<T> and std::basic_string<T> where T is not 8 bit type,
  197. * you may get 0 ~ sizeof(T)-1 bytes padding.
  198. *
  199. * - To write a new buffer class works with getContents, just extend ResizableBuffer.
  200. * - To write a adapter for existing class, write a specialized ResizableBufferAdapter for that class, see follow code.
  201. *
  202. * @code
  203. * NS_CC_BEGIN // ResizableBufferAdapter needed in cocos2d namespace.
  204. * template<>
  205. * class ResizableBufferAdapter<AlreadyExistsBuffer> : public ResizableBuffer {
  206. * public:
  207. * ResizableBufferAdapter(AlreadyExistsBuffer* buffer) {
  208. * // your code here
  209. * }
  210. * virtual void resize(size_t size) override {
  211. * // your code here
  212. * }
  213. * virtual void* buffer() const override {
  214. * // your code here
  215. * }
  216. * };
  217. * NS_CC_END
  218. * @endcode
  219. *
  220. * @param[in] filename The resource file name which contains the path.
  221. * @param[out] buffer The buffer where the file contents are store to.
  222. * @return Returns:
  223. * - Status::OK when there is no error, the buffer is filled with the contents of file.
  224. * - Status::NotExists when file not exists, the buffer will not changed.
  225. * - Status::OpenFailed when cannot open file, the buffer will not changed.
  226. * - Status::ReadFailed when read end up before read whole, the buffer will fill with already read bytes.
  227. * - Status::NotInitialized when FileUtils is not initializes, the buffer will not changed.
  228. * - Status::TooLarge when there file to be read is too large (> 2^32-1), the buffer will not changed.
  229. * - Status::ObtainSizeFailed when failed to obtain the file size, the buffer will not changed.
  230. */
  231. template <
  232. typename T,
  233. typename Enable = typename std::enable_if<
  234. std::is_base_of< ResizableBuffer, ResizableBufferAdapter<T> >::value
  235. >::type
  236. >
  237. Status getContents(const std::string& filename, T* buffer) {
  238. ResizableBufferAdapter<T> buf(buffer);
  239. return getContents(filename, &buf);
  240. }
  241. virtual Status getContents(const std::string& filename, ResizableBuffer* buffer);
  242. /**
  243. * Gets resource file data
  244. *
  245. * @param[in] filename The resource file name which contains the path.
  246. * @param[in] mode The read mode of the file.
  247. * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
  248. * @return Upon success, a pointer to the data is returned, otherwise NULL.
  249. * @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
  250. */
  251. CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size);
  252. /**
  253. * Gets resource file data from a zip file.
  254. *
  255. * @param[in] filename The resource file name which contains the relative path of the zip file.
  256. * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
  257. * @return Upon success, a pointer to the data is returned, otherwise nullptr.
  258. * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
  259. */
  260. virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);
  261. /** Returns the fullpath for a given filename.
  262. First it will try to get a new filename from the "filenameLookup" dictionary.
  263. If a new filename can't be found on the dictionary, it will use the original filename.
  264. Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths.
  265. The file search is based on the array element order of search paths and resolution directories.
  266. For instance:
  267. We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths,
  268. and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd")
  269. to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/".
  270. If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains `key: sprite.png -> value: sprite.pvr.gz`.
  271. Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows:
  272. /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  273. /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next)
  274. /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  275. /mnt/sdcard/sprite.pvr.gz (if not found, search next)
  276. internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  277. internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next)
  278. internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  279. internal_dir/sprite.pvr.gz (if not found, return "sprite.png")
  280. If the filename contains relative path like "gamescene/uilayer/sprite.png",
  281. and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`.
  282. The file search order will be:
  283. /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  284. /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
  285. /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  286. /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next)
  287. internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  288. internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
  289. internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  290. internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png")
  291. If the new file can't be found on the file system, it will return the parameter filename directly.
  292. This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable,
  293. you might need to load different resources for a given file in the different platforms.
  294. @since v2.1
  295. */
  296. virtual std::string fullPathForFilename(const std::string &filename) const;
  297. /**
  298. * Loads the filenameLookup dictionary from the contents of a filename.
  299. *
  300. * @note The plist file name should follow the format below:
  301. *
  302. * @code
  303. * <?xml version="1.0" encoding="UTF-8"?>
  304. * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  305. * <plist version="1.0">
  306. * <dict>
  307. * <key>filenames</key>
  308. * <dict>
  309. * <key>sounds/click.wav</key>
  310. * <string>sounds/click.caf</string>
  311. * <key>sounds/endgame.wav</key>
  312. * <string>sounds/endgame.caf</string>
  313. * <key>sounds/gem-0.wav</key>
  314. * <string>sounds/gem-0.caf</string>
  315. * </dict>
  316. * <key>metadata</key>
  317. * <dict>
  318. * <key>version</key>
  319. * <integer>1</integer>
  320. * </dict>
  321. * </dict>
  322. * </plist>
  323. * @endcode
  324. * @param filename The plist file name.
  325. *
  326. @since v2.1
  327. * @js loadFilenameLookup
  328. * @lua loadFilenameLookup
  329. */
  330. virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
  331. /**
  332. * Sets the filenameLookup dictionary.
  333. *
  334. * @param filenameLookupDict The dictionary for replacing filename.
  335. * @since v2.1
  336. */
  337. virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
  338. /**
  339. * Gets full path from a file name and the path of the relative file.
  340. * @param filename The file name.
  341. * @param relativeFile The path of the relative file.
  342. * @return The full path.
  343. * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist
  344. * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )
  345. *
  346. */
  347. virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
  348. /**
  349. * Sets the array that contains the search order of the resources.
  350. *
  351. * @param searchResolutionsOrder The source array that contains the search order of the resources.
  352. * @see getSearchResolutionsOrder(), fullPathForFilename(const char*).
  353. * @since v2.1
  354. * In js:var setSearchResolutionsOrder(var jsval)
  355. * @lua NA
  356. */
  357. virtual void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);
  358. /**
  359. * Append search order of the resources.
  360. *
  361. * @see setSearchResolutionsOrder(), fullPathForFilename().
  362. * @since v2.1
  363. */
  364. virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false);
  365. /**
  366. * Gets the array that contains the search order of the resources.
  367. *
  368. * @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*).
  369. * @since v2.1
  370. * @lua NA
  371. */
  372. virtual const std::vector<std::string>& getSearchResolutionsOrder() const;
  373. /**
  374. * Sets the array of search paths.
  375. *
  376. * You can use this array to modify the search path of the resources.
  377. * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array.
  378. *
  379. * @note This method could access relative path and absolute path.
  380. * If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path.
  381. * For instance:
  382. * On Android, the default resource root path is "assets/".
  383. * If "/mnt/sdcard/" and "resources-large" were set to the search paths vector,
  384. * "resources-large" will be converted to "assets/resources-large" since it was a relative path.
  385. *
  386. * @param searchPaths The array contains search paths.
  387. * @see fullPathForFilename(const char*)
  388. * @since v2.1
  389. * In js:var setSearchPaths(var jsval);
  390. * @lua NA
  391. */
  392. virtual void setSearchPaths(const std::vector<std::string>& searchPaths);
  393. /**
  394. * Get default resource root path.
  395. */
  396. const std::string& getDefaultResourceRootPath() const;
  397. /**
  398. * Set default resource root path.
  399. */
  400. void setDefaultResourceRootPath(const std::string& path);
  401. /**
  402. * Add search path.
  403. *
  404. * @since v2.1
  405. */
  406. void addSearchPath(const std::string & path, const bool front=false);
  407. /**
  408. * Gets the array of search paths.
  409. *
  410. * @return The array of search paths which may contain the prefix of default resource root path.
  411. * @note In best practise, getter function should return the value of setter function passes in.
  412. * But since we should not break the compatibility, we keep using the old logic.
  413. * Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead.
  414. * @see fullPathForFilename(const char*).
  415. * @lua NA
  416. */
  417. virtual const std::vector<std::string>& getSearchPaths() const;
  418. /**
  419. * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'.
  420. * @return The array of the original search paths
  421. */
  422. virtual const std::vector<std::string>& getOriginalSearchPaths() const;
  423. /**
  424. * Gets the writable path.
  425. * @return The path that can be write/read a file in
  426. */
  427. virtual std::string getWritablePath() const = 0;
  428. /**
  429. * Sets writable path.
  430. */
  431. virtual void setWritablePath(const std::string& writablePath);
  432. /**
  433. * Sets whether to pop-up a message box when failed to load an image.
  434. */
  435. virtual void setPopupNotify(bool notify);
  436. /** Checks whether to pop up a message box when failed to load an image.
  437. * @return True if pop up a message box when failed to load an image, false if not.
  438. */
  439. virtual bool isPopupNotify() const;
  440. /**
  441. * Converts the contents of a file to a ValueMap.
  442. * @param filename The filename of the file to gets content.
  443. * @return ValueMap of the file contents.
  444. * @note This method is used internally.
  445. */
  446. virtual ValueMap getValueMapFromFile(const std::string& filename);
  447. /** Converts the contents of a file to a ValueMap.
  448. * This method is used internally.
  449. */
  450. virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
  451. /**
  452. * write a ValueMap into a plist file
  453. *
  454. *@param dict the ValueMap want to save
  455. *@param fullPath The full path to the file you want to save a string
  456. *@return bool
  457. */
  458. virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath);
  459. /**
  460. * write a string into a file
  461. *
  462. * @param dataStr the string want to save
  463. * @param fullPath The full path to the file you want to save a string
  464. * @return bool True if write success
  465. */
  466. virtual bool writeStringToFile(const std::string& dataStr, const std::string& fullPath);
  467. /**
  468. * Write a string to a file, done async off the main cocos thread
  469. * Use this function if you need file access without blocking the main thread.
  470. *
  471. * This function takes a std::string by value on purpose, to leverage move sematics.
  472. * If you want to avoid a copy of your datastr, use std::move/std::forward if appropriate
  473. *
  474. * @param dataStr the string want to save
  475. * @param fullPath The full path to the file you want to save a string
  476. * @param callback The function called once the string has been written to a file. This
  477. * function will be executed on the main cocos thread. It will have on boolean argument
  478. * signifying if the write was successful.
  479. */
  480. virtual void writeStringToFile(std::string dataStr, const std::string& fullPath, std::function<void(bool)> callback);
  481. /**
  482. * write Data into a file
  483. *
  484. *@param data the data want to save
  485. *@param fullPath The full path to the file you want to save a string
  486. *@return bool
  487. */
  488. virtual bool writeDataToFile(const Data& data, const std::string& fullPath);
  489. /**
  490. * Write Data into a file, done async off the main cocos thread.
  491. *
  492. * Use this function if you need to write Data while not blocking the main cocos thread.
  493. *
  494. * This function takes Data by value on purpose, to leverage move sematics.
  495. * If you want to avoid a copy of your data, use std::move/std::forward if appropriate
  496. *
  497. *@param data The data that will be written to disk
  498. *@param fullPath The absolute file path that the data will be written to
  499. *@param callback The function that will be called when data is written to disk. This
  500. * function will be executed on the main cocos thread. It will have on boolean argument
  501. * signifying if the write was successful.
  502. */
  503. virtual void writeDataToFile(Data data, const std::string& fullPath, std::function<void(bool)> callback);
  504. /**
  505. * write ValueMap into a plist file
  506. *
  507. *@param dict the ValueMap want to save
  508. *@param fullPath The full path to the file you want to save a string
  509. *@return bool
  510. */
  511. virtual bool writeValueMapToFile(const ValueMap& dict, const std::string& fullPath);
  512. /**
  513. * Write a ValueMap into a file, done async off the main cocos thread.
  514. *
  515. * Use this function if you need to write a ValueMap while not blocking the main cocos thread.
  516. *
  517. * This function takes ValueMap by value on purpose, to leverage move sematics.
  518. * If you want to avoid a copy of your dict, use std::move/std::forward if appropriate
  519. *
  520. *@param dict The ValueMap that will be written to disk
  521. *@param fullPath The absolute file path that the data will be written to
  522. *@param callback The function that will be called when dict is written to disk. This
  523. * function will be executed on the main cocos thread. It will have on boolean argument
  524. * signifying if the write was successful.
  525. */
  526. virtual void writeValueMapToFile(ValueMap dict, const std::string& fullPath, std::function<void(bool)> callback);
  527. /**
  528. * write ValueVector into a plist file
  529. *
  530. *@param vecData the ValueVector want to save
  531. *@param fullPath The full path to the file you want to save a string
  532. *@return bool
  533. */
  534. virtual bool writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath);
  535. /**
  536. * Write a ValueVector into a file, done async off the main cocos thread.
  537. *
  538. * Use this function if you need to write a ValueVector while not blocking the main cocos thread.
  539. *
  540. * This function takes ValueVector by value on purpose, to leverage move sematics.
  541. * If you want to avoid a copy of your dict, use std::move/std::forward if appropriate
  542. *
  543. *@param vecData The ValueVector that will be written to disk
  544. *@param fullPath The absolute file path that the data will be written to
  545. *@param callback The function that will be called when vecData is written to disk. This
  546. * function will be executed on the main cocos thread. It will have on boolean argument
  547. * signifying if the write was successful.
  548. */
  549. virtual void writeValueVectorToFile(ValueVector vecData, const std::string& fullPath, std::function<void(bool)> callback);
  550. /**
  551. * Windows fopen can't support UTF-8 filename
  552. * Need convert all parameters fopen and other 3rd-party libs
  553. *
  554. * @param filenameUtf8 std::string name file for conversion from utf-8
  555. * @return std::string ansi filename in current locale
  556. */
  557. virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const;
  558. // Converts the contents of a file to a ValueVector.
  559. // This method is used internally.
  560. virtual ValueVector getValueVectorFromFile(const std::string& filename);
  561. /**
  562. * Checks whether a file exists.
  563. *
  564. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  565. * @param filename The path of the file, it could be a relative or absolute path.
  566. * @return True if the file exists, false if not.
  567. */
  568. virtual bool isFileExist(const std::string& filename) const;
  569. /**
  570. * Checks if a file exists, done async off the main cocos thread.
  571. *
  572. * Use this function if you need to check if a file exists while not blocking the main cocos thread.
  573. *
  574. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  575. * @param filename The path of the file, it could be a relative or absolute path.
  576. * @param callback The function that will be called when the operation is complete. Will have one boolean
  577. * argument, true if the file exists, false otherwise.
  578. */
  579. virtual void isFileExist(const std::string& filename, std::function<void(bool)> callback);
  580. /**
  581. * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.
  582. * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.
  583. * @param filePath The path of the file, it could be a relative or absolute path.
  584. * @return suffix for filename in lower case or empty if a dot not found.
  585. */
  586. virtual std::string getFileExtension(const std::string& filePath) const;
  587. /**
  588. * Checks whether the path is an absolute path.
  589. *
  590. * @note On Android, if the parameter passed in is relative to "assets/", this method will treat it as an absolute path.
  591. * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path.
  592. *
  593. * @param path The path that needs to be checked.
  594. * @return True if it's an absolute path, false if not.
  595. */
  596. virtual bool isAbsolutePath(const std::string& path) const;
  597. /**
  598. * Checks whether the path is a directory.
  599. *
  600. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  601. * @return True if the directory exists, false if not.
  602. */
  603. virtual bool isDirectoryExist(const std::string& dirPath) const;
  604. /**
  605. * Checks whether the absoulate path is a directory, async off of the main cocos thread.
  606. *
  607. * @param dirPath The path of the directory, it must be an absolute path
  608. * @param callback that will accept a boolean, true if the file exists, false otherwise.
  609. * Callback will happen on the main cocos thread.
  610. */
  611. virtual void isDirectoryExist(const std::string& fullPath, std::function<void(bool)> callback);
  612. /**
  613. * Creates a directory.
  614. *
  615. * @param dirPath The path of the directory, it must be an absolute path.
  616. * @return True if the directory have been created successfully, false if not.
  617. */
  618. virtual bool createDirectory(const std::string& dirPath);
  619. /**
  620. * Create a directory, async off the main cocos thread.
  621. *
  622. * @param dirPath the path of the directory, it must be an absolute path
  623. * @param callback The function that will be called when the operation is complete. Will have one boolean
  624. * argument, true if the directory was successfully, false otherwise.
  625. */
  626. virtual void createDirectory(const std::string& dirPath, std::function<void(bool)> callback);
  627. /**
  628. * Removes a directory.
  629. *
  630. * @param dirPath The full path of the directory, it must be an absolute path.
  631. * @return True if the directory have been removed successfully, false if not.
  632. */
  633. virtual bool removeDirectory(const std::string& dirPath);
  634. /**
  635. * Removes a directory, async off the main cocos thread.
  636. *
  637. * @param dirPath the path of the directory, it must be an absolute path
  638. * @param callback The function that will be called when the operation is complete. Will have one boolean
  639. * argument, true if the directory was successfully removed, false otherwise.
  640. */
  641. virtual void removeDirectory(const std::string& dirPath, std::function<void(bool)> callback);
  642. /**
  643. * Removes a file.
  644. *
  645. * @param filepath The full path of the file, it must be an absolute path.
  646. * @return True if the file have been removed successfully, false if not.
  647. */
  648. virtual bool removeFile(const std::string &filepath);
  649. /**
  650. * Removes a file, async off the main cocos thread.
  651. *
  652. * @param filepath the path of the file to remove, it must be an absolute path
  653. * @param callback The function that will be called when the operation is complete. Will have one boolean
  654. * argument, true if the file was successfully removed, false otherwise.
  655. */
  656. virtual void removeFile(const std::string &filepath, std::function<void(bool)> callback);
  657. /**
  658. * Renames a file under the given directory.
  659. *
  660. * @param path The parent directory path of the file, it must be an absolute path.
  661. * @param oldname The current name of the file.
  662. * @param name The new name of the file.
  663. * @return True if the file have been renamed successfully, false if not.
  664. */
  665. virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name);
  666. /**
  667. * Renames a file under the given directory, async off the main cocos thread.
  668. *
  669. * @param path The parent directory path of the file, it must be an absolute path.
  670. * @param oldname The current name of the file.
  671. * @param name The new name of the file.
  672. * @param callback The function that will be called when the operation is complete. Will have one boolean
  673. * argument, true if the file was successfully renamed, false otherwise.
  674. */
  675. virtual void renameFile(const std::string &path, const std::string &oldname, const std::string &name, std::function<void(bool)> callback);
  676. /**
  677. * Renames a file under the given directory.
  678. *
  679. * @param oldfullpath The current fullpath of the file. Includes path and name.
  680. * @param newfullpath The new fullpath of the file. Includes path and name.
  681. * @return True if the file have been renamed successfully, false if not.
  682. */
  683. virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath);
  684. /**
  685. * Renames a file under the given directory, async off the main cocos thread.
  686. *
  687. * @param oldfullpath The current fullpath of the file. Includes path and name.
  688. * @param newfullpath The new fullpath of the file. Includes path and name.
  689. * @param callback The function that will be called when the operation is complete. Will have one boolean
  690. * argument, true if the file was successfully renamed, false otherwise.
  691. */
  692. virtual void renameFile(const std::string &oldfullpath, const std::string &newfullpath, std::function<void(bool)> callback);
  693. /**
  694. * Retrieve the file size.
  695. *
  696. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  697. * @param filepath The path of the file, it could be a relative or absolute path.
  698. * @return The file size.
  699. */
  700. virtual long getFileSize(const std::string &filepath);
  701. /**
  702. * Retrieve the file size, async off the main cocos thread.
  703. *
  704. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  705. * @param filepath The path of the file, it could be a relative or absolute path.
  706. * @param callback The function that will be called when the operation is complete. Will have one long
  707. * argument, the file size.
  708. */
  709. virtual void getFileSize(const std::string &filepath, std::function<void(long)> callback);
  710. /**
  711. * List all files in a directory.
  712. *
  713. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  714. * @return File paths in a string vector
  715. */
  716. virtual std::vector<std::string> listFiles(const std::string& dirPath) const;
  717. /**
  718. * List all files in a directory async, off of the main cocos thread.
  719. *
  720. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  721. * @param callback The callback to be called once the list operation is complete. Will be called on the main cocos thread.
  722. * @js NA
  723. * @lua NA
  724. */
  725. virtual void listFilesAsync(const std::string& dirPath, std::function<void(std::vector<std::string>)> callback) const;
  726. /**
  727. * List all files recursively in a directory.
  728. *
  729. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  730. * @return File paths in a string vector
  731. */
  732. virtual void listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const;
  733. /**
  734. * List all files recursively in a directory, async off the main cocos thread.
  735. *
  736. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  737. * @param callback The callback to be called once the list operation is complete.
  738. * Will be called on the main cocos thread.
  739. * @js NA
  740. * @lua NA
  741. */
  742. virtual void listFilesRecursivelyAsync(const std::string& dirPath, std::function<void(std::vector<std::string>)> callback) const;
  743. /** Returns the full path cache. */
  744. const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }
  745. /**
  746. * Gets the new filename from the filename lookup dictionary.
  747. * It is possible to have a override names.
  748. * @param filename The original filename.
  749. * @return The new filename after searching in the filename lookup dictionary.
  750. * If the original filename wasn't in the dictionary, it will return the original filename.
  751. */
  752. virtual std::string getNewFilename(const std::string &filename) const;
  753. protected:
  754. /**
  755. * The default constructor.
  756. */
  757. FileUtils();
  758. /**
  759. * Initializes the instance of FileUtils. It will set _searchPathArray and _searchResolutionsOrderArray to default values.
  760. *
  761. * @note When you are porting Cocos2d-x to a new platform, you may need to take care of this method.
  762. * You could assign a default value to _defaultResRootPath in the subclass of FileUtils(e.g. FileUtilsAndroid). Then invoke the FileUtils::init().
  763. * @return true if succeed, otherwise it returns false.
  764. *
  765. */
  766. virtual bool init();
  767. /**
  768. * Checks whether a file exists without considering search paths and resolution orders.
  769. * @param filename The file (with absolute path) to look up for
  770. * @return Returns true if the file found at the given absolute path, otherwise returns false
  771. */
  772. virtual bool isFileExistInternal(const std::string& filename) const = 0;
  773. /**
  774. * Checks whether a directory exists without considering search paths and resolution orders.
  775. * @param dirPath The directory (with absolute path) to look up for
  776. * @return Returns true if the directory found at the given absolute path, otherwise returns false
  777. */
  778. virtual bool isDirectoryExistInternal(const std::string& dirPath) const;
  779. /**
  780. * Gets full path for filename, resolution directory and search path.
  781. *
  782. * @param filename The file name.
  783. * @param resolutionDirectory The resolution directory.
  784. * @param searchPath The search path.
  785. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist.
  786. */
  787. virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const;
  788. /**
  789. * Gets full path for the directory and the filename.
  790. *
  791. * @note Only iOS and Mac need to override this method since they are using
  792. * `[[NSBundle mainBundle] pathForResource: ofType: inDirectory:]` to make a full path.
  793. * Other platforms will use the default implementation of this method.
  794. * @param directory The directory contains the file we are looking for.
  795. * @param filename The name of the file.
  796. * @return The full path of the file, if the file can't be found, it will return an empty string.
  797. */
  798. virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const;
  799. /** Dictionary used to lookup filenames based on a key.
  800. * It is used internally by the following methods:
  801. *
  802. * std::string fullPathForFilename(const char*);
  803. *
  804. * @since v2.1
  805. */
  806. ValueMap _filenameLookupDict;
  807. /**
  808. * The vector contains resolution folders.
  809. * The lower index of the element in this vector, the higher priority for this resolution directory.
  810. */
  811. std::vector<std::string> _searchResolutionsOrderArray;
  812. /**
  813. * The vector contains search paths.
  814. * The lower index of the element in this vector, the higher priority for this search path.
  815. */
  816. std::vector<std::string> _searchPathArray;
  817. /**
  818. * The search paths which was set by 'setSearchPaths' / 'addSearchPath'.
  819. */
  820. std::vector<std::string> _originalSearchPaths;
  821. /**
  822. * The default root path of resources.
  823. * If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass.
  824. * For instance:
  825. * On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init().
  826. * Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
  827. */
  828. std::string _defaultResRootPath;
  829. /**
  830. * The full path cache. When a file is found, it will be added into this cache.
  831. * This variable is used for improving the performance of file search.
  832. */
  833. mutable std::unordered_map<std::string, std::string> _fullPathCache;
  834. /**
  835. * Writable path.
  836. */
  837. std::string _writablePath;
  838. /**
  839. * The singleton pointer of FileUtils.
  840. */
  841. static FileUtils* s_sharedFileUtils;
  842. /**
  843. * Remove null value key (for iOS)
  844. */
  845. virtual void valueMapCompact(ValueMap& valueMap);
  846. virtual void valueVectorCompact(ValueVector& valueVector);
  847. template<typename T, typename R, typename ...ARGS>
  848. static void performOperationOffthread(T&& action, R&& callback, ARGS&& ...args)
  849. {
  850. // Visual Studio 2013 does not support using std::bind to forward template parameters into
  851. // a lambda. To get around this, we will just copy these arguments via lambda capture
  852. #if defined(_MSC_VER) && _MSC_VER < 1900
  853. auto lambda = [action, callback, args...]()
  854. {
  855. Director::getInstance()->getScheduler()->performFunctionInCocosThread(std::bind(callback, action(args...)));
  856. };
  857. #else
  858. // As cocos2d-x uses c++11, we will use std::bind to leverage move sematics to
  859. // move our arguments into our lambda, to potentially avoid copying.
  860. auto lambda = std::bind([](const T& actionIn, const R& callbackIn, const ARGS& ...argsIn)
  861. {
  862. Director::getInstance()->getScheduler()->performFunctionInCocosThread(std::bind(callbackIn, actionIn(argsIn...)));
  863. }, std::forward<T>(action), std::forward<R>(callback), std::forward<ARGS>(args)...);
  864. #endif
  865. AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, [](void*){}, nullptr, std::move(lambda));
  866. }
  867. };
  868. // end of support group
  869. /** @} */
  870. NS_CC_END
  871. #endif // __CC_FILEUTILS_H__