CCFileUtils.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 "base/ccMacros.h"
  29. #include "base/ccTypes.h"
  30. #include "base/CCValue.h"
  31. #include "base/CCData.h"
  32. NS_CC_BEGIN
  33. /**
  34. * @addtogroup platform
  35. * @{
  36. */
  37. class ResizableBuffer {
  38. public:
  39. virtual ~ResizableBuffer() {}
  40. virtual void resize(size_t size) = 0;
  41. virtual void* buffer() const = 0;
  42. };
  43. template<typename T>
  44. class ResizableBufferAdapter { };
  45. template<typename CharT, typename Traits, typename Allocator>
  46. class ResizableBufferAdapter< std::basic_string<CharT, Traits, Allocator> > : public ResizableBuffer {
  47. typedef std::basic_string<CharT, Traits, Allocator> BufferType;
  48. BufferType* _buffer;
  49. public:
  50. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  51. virtual void resize(size_t size) override {
  52. _buffer->resize((size + sizeof(CharT) - 1) / sizeof(CharT));
  53. }
  54. virtual void* buffer() const override {
  55. // can not invoke string::front() if it is empty
  56. if (_buffer->empty())
  57. return nullptr;
  58. else
  59. return &_buffer->front();
  60. }
  61. };
  62. template<typename T, typename Allocator>
  63. class ResizableBufferAdapter< std::vector<T, Allocator> > : public ResizableBuffer {
  64. typedef std::vector<T, Allocator> BufferType;
  65. BufferType* _buffer;
  66. public:
  67. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  68. virtual void resize(size_t size) override {
  69. _buffer->resize((size + sizeof(T) - 1) / sizeof(T));
  70. }
  71. virtual void* buffer() const override {
  72. // can not invoke vector::front() if it is empty
  73. if (_buffer->empty())
  74. return nullptr;
  75. else
  76. return &_buffer->front();
  77. }
  78. };
  79. template<>
  80. class ResizableBufferAdapter<Data> : public ResizableBuffer {
  81. typedef Data BufferType;
  82. BufferType* _buffer;
  83. public:
  84. explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {}
  85. virtual void resize(size_t size) override {
  86. size_t oldSize = static_cast<size_t>(_buffer->getSize());
  87. if (oldSize != size) {
  88. // need to take buffer ownership for outer memory control
  89. auto old = _buffer->takeBuffer();
  90. void* buffer = realloc(old, size);
  91. if (buffer)
  92. _buffer->fastSet((unsigned char*)buffer, size);
  93. }
  94. }
  95. virtual void* buffer() const override {
  96. return _buffer->getBytes();
  97. }
  98. };
  99. /** Helper class to handle file operations. */
  100. class CC_DLL FileUtils
  101. {
  102. public:
  103. /**
  104. * Gets the instance of FileUtils.
  105. */
  106. static FileUtils* getInstance();
  107. /**
  108. * Destroys the instance of FileUtils.
  109. */
  110. static void destroyInstance();
  111. /**
  112. * You can inherit from platform dependent implementation of FileUtils, such as FileUtilsAndroid,
  113. * and use this function to set delegate, then FileUtils will invoke delegate's implementation.
  114. * For example, your resources are encrypted, so you need to decrypt it after reading data from
  115. * resources, then you can implement all getXXX functions, and engine will invoke your own getXX
  116. * functions when reading data of resources.
  117. *
  118. * If you don't want to system default implementation after setting delegate, you can just pass nullptr
  119. * to this function.
  120. *
  121. * @warning It will delete previous delegate
  122. * @lua NA
  123. */
  124. static void setDelegate(FileUtils *delegate);
  125. /**
  126. * The destructor of FileUtils.
  127. * @js NA
  128. * @lua NA
  129. */
  130. virtual ~FileUtils();
  131. /**
  132. * Purges full path caches.
  133. */
  134. virtual void purgeCachedEntries();
  135. // 加密处理
  136. static bool isEncrypted(const unsigned char *data);
  137. static unsigned char * decrypt(const unsigned char * data, ssize_t dataLen, bool isMalloc);
  138. /**
  139. * Gets string from a file.
  140. */
  141. virtual std::string getStringFromFile(const std::string& filename);
  142. /**
  143. * Creates binary data from a file.
  144. * @return A data object.
  145. */
  146. virtual Data getDataFromFile(const std::string& filename);
  147. enum class Status
  148. {
  149. OK = 0,
  150. NotExists = 1, // File not exists
  151. OpenFailed = 2, // Open file failed.
  152. ReadFailed = 3, // Read failed
  153. NotInitialized = 4, // FileUtils is not initializes
  154. TooLarge = 5, // The file is too large (great than 2^32-1)
  155. ObtainSizeFailed = 6 // Failed to obtain the file size.
  156. };
  157. /**
  158. * Gets whole file contents as string from a file.
  159. *
  160. * Unlike getStringFromFile, these getContents methods:
  161. * - read file in binary mode (does not convert CRLF to LF).
  162. * - does not truncate the string when '\0' is found (returned string of getContents may have '\0' in the middle.).
  163. *
  164. * The template version of can accept cocos2d::Data, std::basic_string and std::vector.
  165. *
  166. * @code
  167. * std::string sbuf;
  168. * FileUtils::getInstance()->getContents("path/to/file", &sbuf);
  169. *
  170. * std::vector<int> vbuf;
  171. * FileUtils::getInstance()->getContents("path/to/file", &vbuf);
  172. *
  173. * Data dbuf;
  174. * FileUtils::getInstance()->getContents("path/to/file", &dbuf);
  175. * @endcode
  176. *
  177. * Note: if you read to std::vector<T> and std::basic_string<T> where T is not 8 bit type,
  178. * you may get 0 ~ sizeof(T)-1 bytes padding.
  179. *
  180. * - To write a new buffer class works with getContents, just extend ResizableBuffer.
  181. * - To write a adapter for existing class, write a specialized ResizableBufferAdapter for that class, see follow code.
  182. *
  183. * @code
  184. * NS_CC_BEGIN // ResizableBufferAdapter needed in cocos2d namespace.
  185. * template<>
  186. * class ResizableBufferAdapter<AlreadyExistsBuffer> : public ResizableBuffer {
  187. * public:
  188. * ResizableBufferAdapter(AlreadyExistsBuffer* buffer) {
  189. * // your code here
  190. * }
  191. * virtual void resize(size_t size) override {
  192. * // your code here
  193. * }
  194. * virtual void* buffer() const override {
  195. * // your code here
  196. * }
  197. * };
  198. * NS_CC_END
  199. * @endcode
  200. *
  201. * @param[in] filename The resource file name which contains the path.
  202. * @param[out] buffer The buffer where the file contents are store to.
  203. * @return Returns:
  204. * - Status::OK when there is no error, the buffer is filled with the contents of file.
  205. * - Status::NotExists when file not exists, the buffer will not changed.
  206. * - Status::OpenFailed when cannot open file, the buffer will not changed.
  207. * - Status::ReadFailed when read end up before read whole, the buffer will fill with already read bytes.
  208. * - Status::NotInitialized when FileUtils is not initializes, the buffer will not changed.
  209. * - Status::TooLarge when there file to be read is too large (> 2^32-1), the buffer will not changed.
  210. * - Status::ObtainSizeFailed when failed to obtain the file size, the buffer will not changed.
  211. */
  212. template <
  213. typename T,
  214. typename Enable = typename std::enable_if<
  215. std::is_base_of< ResizableBuffer, ResizableBufferAdapter<T> >::value
  216. >::type
  217. >
  218. Status getContents(const std::string& filename, T* buffer) {
  219. ResizableBufferAdapter<T> buf(buffer);
  220. return getContents(filename, &buf);
  221. }
  222. virtual Status getContents(const std::string& filename, ResizableBuffer* buffer);
  223. /**
  224. * Gets resource file data
  225. *
  226. * @param[in] filename The resource file name which contains the path.
  227. * @param[in] mode The read mode of the file.
  228. * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
  229. * @return Upon success, a pointer to the data is returned, otherwise NULL.
  230. * @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
  231. */
  232. CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size);
  233. /**
  234. * Gets resource file data from a zip file.
  235. *
  236. * @param[in] filename The resource file name which contains the relative path of the zip file.
  237. * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
  238. * @return Upon success, a pointer to the data is returned, otherwise nullptr.
  239. * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
  240. */
  241. virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);
  242. /** Returns the fullpath for a given filename.
  243. First it will try to get a new filename from the "filenameLookup" dictionary.
  244. If a new filename can't be found on the dictionary, it will use the original filename.
  245. Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths.
  246. The file search is based on the array element order of search paths and resolution directories.
  247. For instance:
  248. We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths,
  249. and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd")
  250. to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/".
  251. If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains `key: sprite.png -> value: sprite.pvr.gz`.
  252. Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows:
  253. /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  254. /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next)
  255. /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  256. /mnt/sdcard/sprite.pvr.gz (if not found, search next)
  257. internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  258. internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next)
  259. internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  260. internal_dir/sprite.pvr.gz (if not found, return "sprite.png")
  261. If the filename contains relative path like "gamescene/uilayer/sprite.png",
  262. and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`.
  263. The file search order will be:
  264. /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  265. /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
  266. /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  267. /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next)
  268. internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
  269. internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
  270. internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
  271. internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png")
  272. If the new file can't be found on the file system, it will return the parameter filename directly.
  273. This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable,
  274. you might need to load different resources for a given file in the different platforms.
  275. @since v2.1
  276. */
  277. virtual std::string fullPathForFilename(const std::string &filename) const;
  278. /**
  279. * Loads the filenameLookup dictionary from the contents of a filename.
  280. *
  281. * @note The plist file name should follow the format below:
  282. *
  283. * @code
  284. * <?xml version="1.0" encoding="UTF-8"?>
  285. * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  286. * <plist version="1.0">
  287. * <dict>
  288. * <key>filenames</key>
  289. * <dict>
  290. * <key>sounds/click.wav</key>
  291. * <string>sounds/click.caf</string>
  292. * <key>sounds/endgame.wav</key>
  293. * <string>sounds/endgame.caf</string>
  294. * <key>sounds/gem-0.wav</key>
  295. * <string>sounds/gem-0.caf</string>
  296. * </dict>
  297. * <key>metadata</key>
  298. * <dict>
  299. * <key>version</key>
  300. * <integer>1</integer>
  301. * </dict>
  302. * </dict>
  303. * </plist>
  304. * @endcode
  305. * @param filename The plist file name.
  306. *
  307. @since v2.1
  308. * @js loadFilenameLookup
  309. * @lua loadFilenameLookup
  310. */
  311. virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
  312. /**
  313. * Sets the filenameLookup dictionary.
  314. *
  315. * @param filenameLookupDict The dictionary for replacing filename.
  316. * @since v2.1
  317. */
  318. virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
  319. /**
  320. * Gets full path from a file name and the path of the relative file.
  321. * @param filename The file name.
  322. * @param relativeFile The path of the relative file.
  323. * @return The full path.
  324. * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist
  325. * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )
  326. *
  327. */
  328. virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
  329. /**
  330. * Sets the array that contains the search order of the resources.
  331. *
  332. * @param searchResolutionsOrder The source array that contains the search order of the resources.
  333. * @see getSearchResolutionsOrder(), fullPathForFilename(const char*).
  334. * @since v2.1
  335. * In js:var setSearchResolutionsOrder(var jsval)
  336. * @lua NA
  337. */
  338. virtual void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);
  339. /**
  340. * Append search order of the resources.
  341. *
  342. * @see setSearchResolutionsOrder(), fullPathForFilename().
  343. * @since v2.1
  344. */
  345. virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false);
  346. /**
  347. * Gets the array that contains the search order of the resources.
  348. *
  349. * @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*).
  350. * @since v2.1
  351. * @lua NA
  352. */
  353. virtual const std::vector<std::string>& getSearchResolutionsOrder() const;
  354. /**
  355. * Sets the array of search paths.
  356. *
  357. * You can use this array to modify the search path of the resources.
  358. * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array.
  359. *
  360. * @note This method could access relative path and absolute path.
  361. * If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path.
  362. * For instance:
  363. * On Android, the default resource root path is "@assets/".
  364. * If "/mnt/sdcard/" and "resources-large" were set to the search paths vector,
  365. * "resources-large" will be converted to "@assets/resources-large" since it was a relative path.
  366. *
  367. * @param searchPaths The array contains search paths.
  368. * @see fullPathForFilename(const char*)
  369. * @since v2.1
  370. * In js:var setSearchPaths(var jsval);
  371. * @lua NA
  372. */
  373. virtual void setSearchPaths(const std::vector<std::string>& searchPaths);
  374. /**
  375. * Get default resource root path.
  376. */
  377. const std::string& getDefaultResourceRootPath() const;
  378. /**
  379. * Set default resource root path.
  380. */
  381. void setDefaultResourceRootPath(const std::string& path);
  382. /**
  383. * Add search path.
  384. *
  385. * @since v2.1
  386. */
  387. void addSearchPath(const std::string & path, const bool front=false);
  388. /**
  389. * Gets the array of search paths.
  390. *
  391. * @return The array of search paths which may contain the prefix of default resource root path.
  392. * @note In best practise, getter function should return the value of setter function passes in.
  393. * But since we should not break the compatibility, we keep using the old logic.
  394. * Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead.
  395. * @see fullPathForFilename(const char*).
  396. * @lua NA
  397. */
  398. virtual const std::vector<std::string>& getSearchPaths() const;
  399. /**
  400. * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'.
  401. * @return The array of the original search paths
  402. */
  403. virtual const std::vector<std::string>& getOriginalSearchPaths() const;
  404. /**
  405. * Gets the writable path.
  406. * @return The path that can be write/read a file in
  407. */
  408. virtual std::string getWritablePath() const = 0;
  409. /**
  410. * Sets writable path.
  411. */
  412. virtual void setWritablePath(const std::string& writablePath);
  413. /**
  414. * Sets whether to pop-up a message box when failed to load an image.
  415. */
  416. virtual void setPopupNotify(bool notify);
  417. /** Checks whether to pop up a message box when failed to load an image.
  418. * @return True if pop up a message box when failed to load an image, false if not.
  419. */
  420. virtual bool isPopupNotify() const;
  421. /**
  422. * Converts the contents of a file to a ValueMap.
  423. * @param filename The filename of the file to gets content.
  424. * @return ValueMap of the file contents.
  425. * @note This method is used internally.
  426. */
  427. virtual ValueMap getValueMapFromFile(const std::string& filename);
  428. /** Converts the contents of a file to a ValueMap.
  429. * This method is used internally.
  430. */
  431. virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
  432. /**
  433. * write a ValueMap into a plist file
  434. *
  435. *@param dict the ValueMap want to save
  436. *@param fullPath The full path to the file you want to save a string
  437. *@return bool
  438. */
  439. virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath);
  440. /**
  441. * write a string into a file
  442. *
  443. * @param dataStr the string want to save
  444. * @param fullPath The full path to the file you want to save a string
  445. * @return bool True if write success
  446. */
  447. virtual bool writeStringToFile(const std::string& dataStr, const std::string& fullPath);
  448. /**
  449. * write Data into a file
  450. *
  451. *@param data the data want to save
  452. *@param fullPath The full path to the file you want to save a string
  453. *@return bool
  454. */
  455. virtual bool writeDataToFile(const Data& data, const std::string& fullPath);
  456. /**
  457. * write ValueMap into a plist file
  458. *
  459. *@param dict the ValueMap want to save
  460. *@param fullPath The full path to the file you want to save a string
  461. *@return bool
  462. */
  463. virtual bool writeValueMapToFile(const ValueMap& dict, const std::string& fullPath);
  464. /**
  465. * write ValueVector into a plist file
  466. *
  467. *@param vecData the ValueVector want to save
  468. *@param fullPath The full path to the file you want to save a string
  469. *@return bool
  470. */
  471. virtual bool writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath);
  472. /**
  473. * Windows fopen can't support UTF-8 filename
  474. * Need convert all parameters fopen and other 3rd-party libs
  475. *
  476. * @param filenameUtf8 std::string name file for conversion from utf-8
  477. * @return std::string ansi filename in current locale
  478. */
  479. virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const;
  480. // Converts the contents of a file to a ValueVector.
  481. // This method is used internally.
  482. virtual ValueVector getValueVectorFromFile(const std::string& filename);
  483. /**
  484. * Checks whether a file exists.
  485. *
  486. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  487. * @param filename The path of the file, it could be a relative or absolute path.
  488. * @return True if the file exists, false if not.
  489. */
  490. virtual bool isFileExist(const std::string& filename) const;
  491. /**
  492. * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.
  493. * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.
  494. * @param filePath The path of the file, it could be a relative or absolute path.
  495. * @return suffix for filename in lower case or empty if a dot not found.
  496. */
  497. virtual std::string getFileExtension(const std::string& filePath) const;
  498. /**
  499. * Checks whether the path is an absolute path.
  500. *
  501. * @note On Android, if the parameter passed in is relative to "@assets/", this method will treat it as an absolute path.
  502. * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path.
  503. *
  504. * @param path The path that needs to be checked.
  505. * @return True if it's an absolute path, false if not.
  506. */
  507. virtual bool isAbsolutePath(const std::string& path) const;
  508. /**
  509. * Checks whether the path is a directory.
  510. *
  511. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  512. * @return True if the directory exists, false if not.
  513. */
  514. virtual bool isDirectoryExist(const std::string& dirPath) const;
  515. /**
  516. * List all files in a directory.
  517. *
  518. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  519. * @return File paths in a string vector
  520. */
  521. virtual std::vector<std::string> listFiles(const std::string& dirPath) const;
  522. /**
  523. * List all files recursively in a directory.
  524. *
  525. * @param dirPath The path of the directory, it could be a relative or an absolute path.
  526. * @return File paths in a string vector
  527. */
  528. virtual void listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const;
  529. /**
  530. * Creates a directory.
  531. *
  532. * @param dirPath The path of the directory, it must be an absolute path.
  533. * @return True if the directory have been created successfully, false if not.
  534. */
  535. virtual bool createDirectory(const std::string& dirPath);
  536. /**
  537. * Removes a directory.
  538. *
  539. * @param dirPath The full path of the directory, it must be an absolute path.
  540. * @return True if the directory have been removed successfully, false if not.
  541. */
  542. virtual bool removeDirectory(const std::string& dirPath);
  543. /**
  544. * Removes a file.
  545. *
  546. * @param filepath The full path of the file, it must be an absolute path.
  547. * @return True if the file have been removed successfully, false if not.
  548. */
  549. virtual bool removeFile(const std::string &filepath);
  550. /**
  551. * Renames a file under the given directory.
  552. *
  553. * @param path The parent directory path of the file, it must be an absolute path.
  554. * @param oldname The current name of the file.
  555. * @param name The new name of the file.
  556. * @return True if the file have been renamed successfully, false if not.
  557. */
  558. virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name);
  559. /**
  560. * Renames a file under the given directory.
  561. *
  562. * @param oldfullpath The current fullpath of the file. Includes path and name.
  563. * @param newfullpath The new fullpath of the file. Includes path and name.
  564. * @return True if the file have been renamed successfully, false if not.
  565. */
  566. virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath);
  567. /**
  568. * Retrieve the file size.
  569. *
  570. * @note If a relative path was passed in, it will be inserted a default root path at the beginning.
  571. * @param filepath The path of the file, it could be a relative or absolute path.
  572. * @return The file size.
  573. */
  574. virtual long getFileSize(const std::string &filepath);
  575. /** Returns the full path cache. */
  576. const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }
  577. std::string normalizePath(const std::string& path) const;
  578. std::string getFileDir(const std::string& path) const;
  579. protected:
  580. /**
  581. * The default constructor.
  582. */
  583. FileUtils();
  584. /**
  585. * Initializes the instance of FileUtils. It will set _searchPathArray and _searchResolutionsOrderArray to default values.
  586. *
  587. * @note When you are porting Cocos2d-x to a new platform, you may need to take care of this method.
  588. * You could assign a default value to _defaultResRootPath in the subclass of FileUtils(e.g. FileUtilsAndroid). Then invoke the FileUtils::init().
  589. * @return true if succeed, otherwise it returns false.
  590. *
  591. */
  592. virtual bool init();
  593. /**
  594. * Gets the new filename from the filename lookup dictionary.
  595. * It is possible to have a override names.
  596. * @param filename The original filename.
  597. * @return The new filename after searching in the filename lookup dictionary.
  598. * If the original filename wasn't in the dictionary, it will return the original filename.
  599. */
  600. virtual std::string getNewFilename(const std::string &filename) const;
  601. /**
  602. * Checks whether a file exists without considering search paths and resolution orders.
  603. * @param filename The file (with absolute path) to look up for
  604. * @return Returns true if the file found at the given absolute path, otherwise returns false
  605. */
  606. virtual bool isFileExistInternal(const std::string& filename) const = 0;
  607. /**
  608. * Checks whether a directory exists without considering search paths and resolution orders.
  609. * @param dirPath The directory (with absolute path) to look up for
  610. * @return Returns true if the directory found at the given absolute path, otherwise returns false
  611. */
  612. virtual bool isDirectoryExistInternal(const std::string& dirPath) const;
  613. /**
  614. * Gets full path for filename, resolution directory and search path.
  615. *
  616. * @param filename The file name.
  617. * @param resolutionDirectory The resolution directory.
  618. * @param searchPath The search path.
  619. * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist.
  620. */
  621. virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const;
  622. /**
  623. * Gets full path for the directory and the filename.
  624. *
  625. * @note Only iOS and Mac need to override this method since they are using
  626. * `[[NSBundle mainBundle] pathForResource: ofType: inDirectory:]` to make a full path.
  627. * Other platforms will use the default implementation of this method.
  628. * @param directory The directory contains the file we are looking for.
  629. * @param filename The name of the file.
  630. * @return The full path of the file, if the file can't be found, it will return an empty string.
  631. */
  632. virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const;
  633. /** Dictionary used to lookup filenames based on a key.
  634. * It is used internally by the following methods:
  635. *
  636. * std::string fullPathForFilename(const char*);
  637. *
  638. * @since v2.1
  639. */
  640. ValueMap _filenameLookupDict;
  641. /**
  642. * The vector contains resolution folders.
  643. * The lower index of the element in this vector, the higher priority for this resolution directory.
  644. */
  645. std::vector<std::string> _searchResolutionsOrderArray;
  646. /**
  647. * The vector contains search paths.
  648. * The lower index of the element in this vector, the higher priority for this search path.
  649. */
  650. std::vector<std::string> _searchPathArray;
  651. /**
  652. * The search paths which was set by 'setSearchPaths' / 'addSearchPath'.
  653. */
  654. std::vector<std::string> _originalSearchPaths;
  655. /**
  656. * The default root path of resources.
  657. * If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass.
  658. * For instance:
  659. * On Android, the default root path of resources will be assigned with "@assets/" in FileUtilsAndroid::init().
  660. * Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
  661. */
  662. std::string _defaultResRootPath;
  663. /**
  664. * The full path cache. When a file is found, it will be added into this cache.
  665. * This variable is used for improving the performance of file search.
  666. */
  667. mutable std::unordered_map<std::string, std::string> _fullPathCache;
  668. /**
  669. * Writable path.
  670. */
  671. std::string _writablePath;
  672. /**
  673. * The singleton pointer of FileUtils.
  674. */
  675. static FileUtils* s_sharedFileUtils;
  676. /**
  677. * Remove null value key (for iOS)
  678. */
  679. virtual void valueMapCompact(ValueMap& valueMap);
  680. virtual void valueVectorCompact(ValueVector& valueVector);
  681. };
  682. // end of support group
  683. /** @} */
  684. NS_CC_END
  685. #endif // __CC_FILEUTILS_H__