CCFileUtils-apple.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2011 Zynga Inc.
  4. Copyright (c) 2013-2017 Chukong Technologies Inc.
  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. #import <Foundation/Foundation.h>
  23. #include "platform/apple/CCFileUtils-apple.h"
  24. #include <ftw.h>
  25. #include <string>
  26. #include <stack>
  27. #include "base/CCDirector.h"
  28. #include "platform/CCFileUtils.h"
  29. #include "platform/CCSAXParser.h"
  30. NS_CC_BEGIN
  31. struct FileUtilsApple::IMPL {
  32. IMPL(NSBundle* bundle):bundle_([NSBundle mainBundle]) {}
  33. void setBundle(NSBundle* bundle) {
  34. bundle_ = bundle;
  35. }
  36. NSBundle* getBundle() const {
  37. return bundle_;
  38. }
  39. private:
  40. NSBundle* bundle_;
  41. };
  42. static id convertCCValueToNSObject(const cocos2d::Value &value);
  43. static cocos2d::Value convertNSObjectToCCValue(id object);
  44. static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict);
  45. static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict);
  46. static void addNSObjectToCCVector(id item, ValueVector& array);
  47. static void addCCValueToNSArray(const Value& value, NSMutableArray *array);
  48. static id convertCCValueToNSObject(const cocos2d::Value &value)
  49. {
  50. switch (value.getType())
  51. {
  52. case Value::Type::NONE:
  53. return [NSNull null];
  54. case Value::Type::STRING:
  55. return [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding];
  56. case Value::Type::BYTE:
  57. return [NSNumber numberWithInt:value.asByte()];
  58. case Value::Type::INTEGER:
  59. return [NSNumber numberWithInt:value.asInt()];
  60. case Value::Type::UNSIGNED:
  61. return [NSNumber numberWithUnsignedInt:value.asUnsignedInt()];
  62. case Value::Type::FLOAT:
  63. return [NSNumber numberWithFloat:value.asFloat()];
  64. case Value::Type::DOUBLE:
  65. return [NSNumber numberWithDouble:value.asDouble()];
  66. case Value::Type::BOOLEAN:
  67. return [NSNumber numberWithBool:value.asBool()];
  68. case Value::Type::VECTOR: {
  69. NSMutableArray *array = [NSMutableArray array];
  70. const ValueVector &vector = value.asValueVector();
  71. for (const auto &e : vector) {
  72. addCCValueToNSArray(e, array);
  73. }
  74. return array;
  75. }
  76. case Value::Type::MAP: {
  77. NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  78. const ValueMap &map = value.asValueMap();
  79. for (auto& iter : map) {
  80. addCCValueToNSDictionary(iter.first, iter.second, dictionary);
  81. }
  82. return dictionary;
  83. }
  84. case Value::Type::INT_KEY_MAP:
  85. break;
  86. }
  87. return [NSNull null];
  88. }
  89. static cocos2d::Value convertNSObjectToCCValue(id item)
  90. {
  91. // add string value into array
  92. if ([item isKindOfClass:[NSString class]])
  93. {
  94. return Value([item UTF8String]);
  95. }
  96. // add number value into array(such as int, float, bool and so on)
  97. // the value is a number
  98. if ([item isKindOfClass:[NSNumber class]])
  99. {
  100. NSNumber* num = item;
  101. const char* numType = [num objCType];
  102. if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue)
  103. {
  104. bool v = [num boolValue];
  105. return Value(v);
  106. }
  107. else if(strcmp(numType, @encode(float)) == 0)
  108. {
  109. return Value([num floatValue]);
  110. }
  111. else if(strcmp(numType, @encode(double)) == 0)
  112. {
  113. return Value([num doubleValue]);
  114. }
  115. else
  116. {
  117. return Value([num intValue]);
  118. }
  119. }
  120. // add dictionary value into array
  121. if ([item isKindOfClass:[NSDictionary class]])
  122. {
  123. ValueMap dict;
  124. for (id subKey in [item allKeys])
  125. {
  126. id subValue = [item objectForKey:subKey];
  127. addNSObjectToCCMap(subKey, subValue, dict);
  128. }
  129. return Value(dict);
  130. }
  131. // add array value into array
  132. if ([item isKindOfClass:[NSArray class]])
  133. {
  134. ValueVector subArray;
  135. for (id subItem in item)
  136. {
  137. addNSObjectToCCVector(subItem, subArray);
  138. }
  139. return Value(subArray);
  140. }
  141. return Value::Null;
  142. }
  143. static void addNSObjectToCCVector(id item, ValueVector& array)
  144. {
  145. array.push_back(convertNSObjectToCCValue(item));
  146. }
  147. static void addCCValueToNSArray(const Value& value, NSMutableArray *array)
  148. {
  149. [array addObject:convertCCValueToNSObject(value)];
  150. }
  151. static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict)
  152. {
  153. // the key must be a string
  154. CCASSERT([nsKey isKindOfClass:[NSString class]], "The key should be a string!");
  155. std::string key = [nsKey UTF8String];
  156. dict[key] = convertNSObjectToCCValue(nsValue);
  157. }
  158. static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict)
  159. {
  160. NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding];
  161. [dict setObject:convertCCValueToNSObject(value) forKey:NSkey];
  162. }
  163. FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) {
  164. }
  165. FileUtilsApple::~FileUtilsApple() = default;
  166. #if CC_FILEUTILS_APPLE_ENABLE_OBJC
  167. void FileUtilsApple::setBundle(NSBundle* bundle) {
  168. pimpl_->setBundle(bundle);
  169. }
  170. #endif
  171. #pragma mark - FileUtils
  172. static NSFileManager* s_fileManager = [NSFileManager defaultManager];
  173. FileUtils* FileUtils::getInstance()
  174. {
  175. if (s_sharedFileUtils == nullptr)
  176. {
  177. s_sharedFileUtils = new (std::nothrow) FileUtilsApple();
  178. if(!s_sharedFileUtils->init())
  179. {
  180. delete s_sharedFileUtils;
  181. s_sharedFileUtils = nullptr;
  182. CCLOG("ERROR: Could not init CCFileUtilsApple");
  183. }
  184. }
  185. return s_sharedFileUtils;
  186. }
  187. std::string FileUtilsApple::getWritablePath() const
  188. {
  189. if (_writablePath.length())
  190. {
  191. return _writablePath;
  192. }
  193. // save to document folder
  194. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  195. NSString *documentsDirectory = [paths objectAtIndex:0];
  196. std::string strRet = [documentsDirectory UTF8String];
  197. strRet.append("/");
  198. return strRet;
  199. }
  200. bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const
  201. {
  202. if (filePath.empty())
  203. {
  204. return false;
  205. }
  206. bool ret = false;
  207. if (filePath[0] != '/')
  208. {
  209. std::string path;
  210. std::string file;
  211. size_t pos = filePath.find_last_of("/");
  212. if (pos != std::string::npos)
  213. {
  214. file = filePath.substr(pos+1);
  215. path = filePath.substr(0, pos+1);
  216. }
  217. else
  218. {
  219. file = filePath;
  220. }
  221. NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:file.c_str()]
  222. ofType:nil
  223. inDirectory:[NSString stringWithUTF8String:path.c_str()]];
  224. if (fullpath != nil) {
  225. ret = true;
  226. }
  227. }
  228. else
  229. {
  230. // Search path is an absolute path.
  231. if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.c_str()]]) {
  232. ret = true;
  233. }
  234. }
  235. return ret;
  236. }
  237. static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  238. {
  239. auto ret = remove(fpath);
  240. if (ret)
  241. {
  242. log("Fail to remove: %s ",fpath);
  243. }
  244. return ret;
  245. }
  246. bool FileUtilsApple::removeDirectory(const std::string& path)
  247. {
  248. if (path.empty())
  249. {
  250. CCLOGERROR("Fail to remove directory, path is empty!");
  251. return false;
  252. }
  253. if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
  254. return false;
  255. else
  256. return true;
  257. }
  258. std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const
  259. {
  260. if (directory[0] != '/')
  261. {
  262. NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()]
  263. ofType:nil
  264. inDirectory:[NSString stringWithUTF8String:directory.c_str()]];
  265. if (fullpath != nil) {
  266. return [fullpath UTF8String];
  267. }
  268. }
  269. else
  270. {
  271. std::string fullPath = directory+filename;
  272. // Search path is an absolute path.
  273. if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) {
  274. return fullPath;
  275. }
  276. }
  277. return "";
  278. }
  279. ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename)
  280. {
  281. auto d(FileUtils::getInstance()->getDataFromFile(filename));
  282. return getValueMapFromData(reinterpret_cast<char*>(d.getBytes()), static_cast<int>(d.getSize()));
  283. }
  284. ValueMap FileUtilsApple::getValueMapFromData(const char* filedata, int filesize)
  285. {
  286. NSData* file = [NSData dataWithBytes:filedata length:filesize];
  287. NSPropertyListFormat format;
  288. NSError* error;
  289. NSDictionary* dict = [NSPropertyListSerialization propertyListWithData:file options:NSPropertyListImmutable format:&format error:&error];
  290. ValueMap ret;
  291. if (dict != nil)
  292. {
  293. for (id key in [dict allKeys])
  294. {
  295. id value = [dict objectForKey:key];
  296. addNSObjectToCCMap(key, value, ret);
  297. }
  298. }
  299. return ret;
  300. }
  301. bool FileUtilsApple::writeToFile(const ValueMap& dict, const std::string &fullPath)
  302. {
  303. return writeValueMapToFile(dict, fullPath);
  304. }
  305. bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath)
  306. {
  307. valueMapCompact(const_cast<ValueMap&>(dict));
  308. //CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
  309. NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
  310. for (auto& iter : dict)
  311. {
  312. addCCValueToNSDictionary(iter.first, iter.second, nsDict);
  313. }
  314. NSString *file = [NSString stringWithUTF8String:fullPath.c_str()];
  315. // do it atomically
  316. return [nsDict writeToFile:file atomically:YES];
  317. }
  318. void FileUtilsApple::valueMapCompact(ValueMap& valueMap)
  319. {
  320. auto itr = valueMap.begin();
  321. while(itr != valueMap.end()){
  322. auto vtype = itr->second.getType();
  323. switch(vtype){
  324. case Value::Type::NONE:{
  325. itr = valueMap.erase(itr);
  326. continue;
  327. }
  328. break;
  329. case Value::Type::MAP:{
  330. valueMapCompact(itr->second.asValueMap());
  331. }
  332. break;
  333. case Value::Type::VECTOR:{
  334. valueVectorCompact(itr->second.asValueVector());
  335. }
  336. break;
  337. default:
  338. break;
  339. }
  340. ++itr;
  341. }
  342. }
  343. void FileUtilsApple::valueVectorCompact(ValueVector& valueVector)
  344. {
  345. auto itr = valueVector.begin();
  346. while(itr != valueVector.end()){
  347. auto vtype = (*itr).getType();
  348. switch(vtype){
  349. case Value::Type::NONE:{
  350. itr = valueVector.erase(itr);
  351. continue;
  352. }
  353. break;
  354. case Value::Type::MAP:{
  355. valueMapCompact((*itr).asValueMap());
  356. }
  357. break;
  358. case Value::Type::VECTOR:{
  359. valueVectorCompact((*itr).asValueVector());
  360. }
  361. break;
  362. default:
  363. break;
  364. }
  365. ++itr;
  366. }
  367. }
  368. bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath)
  369. {
  370. NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
  371. NSMutableArray* array = [NSMutableArray array];
  372. for (const auto &e : vecData)
  373. {
  374. addCCValueToNSArray(e, array);
  375. }
  376. [array writeToFile:path atomically:YES];
  377. return true;
  378. }
  379. ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename)
  380. {
  381. // NSString* pPath = [NSString stringWithUTF8String:pFileName];
  382. // NSString* pathExtension= [pPath pathExtension];
  383. // pPath = [pPath stringByDeletingPathExtension];
  384. // pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
  385. // fixing cannot read data using Array::createWithContentsOfFile
  386. std::string fullPath = fullPathForFilename(filename);
  387. NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
  388. NSArray* array = [NSArray arrayWithContentsOfFile:path];
  389. ValueVector ret;
  390. for (id value in array)
  391. {
  392. addNSObjectToCCVector(value, ret);
  393. }
  394. return ret;
  395. }
  396. bool FileUtilsApple::createDirectory(const std::string& path)
  397. {
  398. CCASSERT(!path.empty(), "Invalid path");
  399. if (isDirectoryExist(path))
  400. return true;
  401. NSError* error;
  402. bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error];
  403. if(!result && error != nil)
  404. {
  405. CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]);
  406. }
  407. return result;
  408. }
  409. NS_CC_END