FileSystem.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. #include "Base.h"
  2. #include "FileSystem.h"
  3. #include "Properties.h"
  4. #include "Stream.h"
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #ifdef WIN32
  8. #include <windows.h>
  9. #include <tchar.h>
  10. #include <stdio.h>
  11. #define gp_stat _stat
  12. #define gp_stat_struct struct stat
  13. #else
  14. #include <dirent.h>
  15. #define gp_stat stat
  16. #define gp_stat_struct struct stat
  17. #endif
  18. #ifdef __ANDROID__
  19. #include <android/asset_manager.h>
  20. extern AAssetManager* __assetManager;
  21. #endif
  22. namespace gameplay
  23. {
  24. #ifdef __ANDROID__
  25. #include <unistd.h>
  26. static void makepath(std::string path, int mode)
  27. {
  28. std::vector<std::string> dirs;
  29. while (path.length() > 0)
  30. {
  31. int index = path.find('/');
  32. std::string dir = (index == -1 ) ? path : path.substr(0, index);
  33. if (dir.length() > 0)
  34. dirs.push_back(dir);
  35. if (index + 1 >= path.length() || index == -1)
  36. break;
  37. path = path.substr(index + 1);
  38. }
  39. struct stat s;
  40. std::string dirPath;
  41. for (unsigned int i = 0; i < dirs.size(); i++)
  42. {
  43. dirPath += "/";
  44. dirPath += dirs[i];
  45. if (stat(dirPath.c_str(), &s) != 0)
  46. {
  47. // Directory does not exist.
  48. if (mkdir(dirPath.c_str(), 0777) != 0)
  49. {
  50. GP_ERROR("Failed to create directory: '%s'", dirPath.c_str());
  51. return;
  52. }
  53. }
  54. }
  55. return;
  56. }
  57. /**
  58. * Returns true if the file exists in the android read-only asset directory.
  59. */
  60. static bool androidFileExists(const char* filePath)
  61. {
  62. AAsset* asset = AAssetManager_open(__assetManager, filePath, AASSET_MODE_RANDOM);
  63. if (asset)
  64. {
  65. int lenght = AAsset_getLength(asset);
  66. AAsset_close(asset);
  67. return length > 0;
  68. }
  69. return false;
  70. }
  71. #endif
  72. /** @script{ignore} */
  73. static std::string __resourcePath("./");
  74. static std::map<std::string, std::string> __aliases;
  75. /**
  76. *
  77. * @script{ignore}
  78. */
  79. class FileStream : public Stream
  80. {
  81. public:
  82. friend class FileSystem;
  83. ~FileStream();
  84. virtual bool canRead();
  85. virtual bool canWrite();
  86. virtual bool canSeek();
  87. virtual void close();
  88. virtual size_t read(void* ptr, size_t size, size_t count);
  89. virtual char* readLine(char* str, int num);
  90. virtual size_t write(const void* ptr, size_t size, size_t count);
  91. virtual bool eof();
  92. virtual size_t length();
  93. virtual long int position();
  94. virtual bool seek(long int offset, int origin);
  95. virtual bool rewind();
  96. static FileStream* create(const char* filePath, const char* mode);
  97. private:
  98. FileStream(FILE* file);
  99. private:
  100. FILE* _file;
  101. bool _canRead;
  102. bool _canWrite;
  103. };
  104. #ifdef __ANDROID__
  105. /**
  106. *
  107. * @script{ignore}
  108. */
  109. class FileStreamAndroid : public Stream
  110. {
  111. public:
  112. friend class FileSystem;
  113. ~FileStreamAndroid();
  114. virtual bool canRead();
  115. virtual bool canWrite();
  116. virtual bool canSeek();
  117. virtual void close();
  118. virtual size_t read(void* ptr, size_t size, size_t count);
  119. virtual char* readLine(char* str, int num);
  120. virtual size_t write(const void* ptr, size_t size, size_t count);
  121. virtual bool eof();
  122. virtual size_t length();
  123. virtual long int position();
  124. virtual bool seek(long int offset, int origin);
  125. virtual bool rewind();
  126. static FileStreamAndroid* create(const char* filePath, const char* mode);
  127. private:
  128. FileStreamAndroid(AAsset* asset);
  129. private:
  130. AAsset* _asset;
  131. };
  132. #endif
  133. /////////////////////////////
  134. FileSystem::FileSystem()
  135. {
  136. }
  137. FileSystem::~FileSystem()
  138. {
  139. }
  140. void FileSystem::setResourcePath(const char* path)
  141. {
  142. __resourcePath = path == NULL ? "" : path;
  143. }
  144. const char* FileSystem::getResourcePath()
  145. {
  146. return __resourcePath.c_str();
  147. }
  148. void FileSystem::loadResourceAliases(const char* aliasFilePath)
  149. {
  150. Properties* properties = Properties::create(aliasFilePath);
  151. if (properties)
  152. {
  153. Properties* aliases;
  154. while ((aliases = properties->getNextNamespace()) != NULL)
  155. {
  156. loadResourceAliases(aliases);
  157. }
  158. }
  159. SAFE_DELETE(properties);
  160. }
  161. void FileSystem::loadResourceAliases(Properties* properties)
  162. {
  163. assert(properties);
  164. const char* name;
  165. while ((name = properties->getNextProperty()) != NULL)
  166. {
  167. __aliases[name] = properties->getString();
  168. }
  169. }
  170. const char* FileSystem::resolvePath(const char* path)
  171. {
  172. GP_ASSERT(path);
  173. size_t len = strlen(path);
  174. if (len > 1 && path[0] == '@')
  175. {
  176. std::string alias(path + 1);
  177. std::map<std::string, std::string>::const_iterator itr = __aliases.find(alias);
  178. if (itr == __aliases.end())
  179. return path; // no matching alias found
  180. return itr->second.c_str();
  181. }
  182. return path;
  183. }
  184. bool FileSystem::listFiles(const char* dirPath, std::vector<std::string>& files)
  185. {
  186. #ifdef WIN32
  187. std::string path(FileSystem::getResourcePath());
  188. if (dirPath && strlen(dirPath) > 0)
  189. {
  190. path.append(dirPath);
  191. }
  192. path.append("/*");
  193. // Convert char to wchar
  194. std::basic_string<TCHAR> wPath;
  195. wPath.assign(path.begin(), path.end());
  196. WIN32_FIND_DATA FindFileData;
  197. HANDLE hFind = FindFirstFile(wPath.c_str(), &FindFileData);
  198. if (hFind == INVALID_HANDLE_VALUE)
  199. {
  200. return false;
  201. }
  202. do
  203. {
  204. // Add to the list if this is not a directory
  205. if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
  206. {
  207. // Convert wchar to char
  208. std::basic_string<TCHAR> wfilename(FindFileData.cFileName);
  209. std::string filename;
  210. filename.assign(wfilename.begin(), wfilename.end());
  211. files.push_back(filename);
  212. }
  213. } while (FindNextFile(hFind, &FindFileData) != 0);
  214. FindClose(hFind);
  215. return true;
  216. #else
  217. std::string path(FileSystem::getResourcePath());
  218. if (dirPath && strlen(dirPath) > 0)
  219. {
  220. path.append(dirPath);
  221. }
  222. path.append("/.");
  223. struct dirent* dp;
  224. DIR* dir = opendir(path.c_str());
  225. if (!dir)
  226. {
  227. return false;
  228. }
  229. while ((dp = readdir(dir)) != NULL)
  230. {
  231. std::string filepath(path);
  232. filepath.append("/");
  233. filepath.append(dp->d_name);
  234. struct stat buf;
  235. if (!stat(filepath.c_str(), &buf))
  236. {
  237. // Add to the list if this is not a directory
  238. if (!S_ISDIR(buf.st_mode))
  239. {
  240. files.push_back(dp->d_name);
  241. }
  242. }
  243. }
  244. closedir(dir);
  245. return true;
  246. #endif
  247. }
  248. bool FileSystem::fileExists(const char* filePath)
  249. {
  250. GP_ASSERT(filePath);
  251. #ifdef __ANDROID__
  252. if (androidFileExists(filePath))
  253. {
  254. return true;
  255. }
  256. #endif
  257. std::string fullPath(__resourcePath);
  258. fullPath += resolvePath(filePath);
  259. gp_stat_struct s;
  260. #ifdef WIN32
  261. if (stat(fullPath.c_str(), &s) != 0)
  262. {
  263. fullPath = __resourcePath;
  264. fullPath += "../../gameplay/";
  265. fullPath += filePath;
  266. int result = stat(fullPath.c_str(), &s);
  267. if (result != 0)
  268. {
  269. fullPath = __resourcePath;
  270. fullPath += "../gameplay/";
  271. fullPath += filePath;
  272. return stat(fullPath.c_str(), &s) == 0;
  273. }
  274. }
  275. return true;
  276. #else
  277. return stat(fullPath.c_str(), &s) == 0;
  278. #endif
  279. }
  280. Stream* FileSystem::open(const char* path, size_t mode)
  281. {
  282. char modeStr[] = "rb";
  283. if ((mode & WRITE) != 0)
  284. modeStr[0] = 'w';
  285. #ifdef __ANDROID__
  286. if ((mode & WRITE) != 0)
  287. {
  288. // Open a file on the SD card
  289. std::string fullPath(__resourcePath);
  290. fullPath += resolvePath(path);
  291. size_t index = fullPath.rfind('/');
  292. if (index != std::string::npos)
  293. {
  294. std::string directoryPath = fullPath.substr(0, index);
  295. struct stat s;
  296. if (stat(directoryPath.c_str(), &s) != 0)
  297. makepath(directoryPath, 0777);
  298. }
  299. return FileStream::create(fullPath.c_str(), modeStr);
  300. }
  301. else
  302. {
  303. // Open a file in the read-only asset directory
  304. return FileStreamAndroid::create(resolvePath(path), modeStr);
  305. }
  306. #else
  307. std::string fullPath(__resourcePath);
  308. fullPath += resolvePath(path);
  309. #ifdef WIN32
  310. gp_stat_struct s;
  311. if (stat(fullPath.c_str(), &s) != 0 && (mode & WRITE) == 0)
  312. {
  313. fullPath = __resourcePath;
  314. fullPath += "../../gameplay/";
  315. fullPath += path;
  316. int result = stat(fullPath.c_str(), &s);
  317. if (result != 0)
  318. {
  319. fullPath = __resourcePath;
  320. fullPath += "../gameplay/";
  321. fullPath += path;
  322. if (stat(fullPath.c_str(), &s) != 0)
  323. {
  324. return NULL;
  325. }
  326. }
  327. }
  328. #endif
  329. FileStream* stream = FileStream::create(fullPath.c_str(), modeStr);
  330. return stream;
  331. #endif
  332. }
  333. FILE* FileSystem::openFile(const char* filePath, const char* mode)
  334. {
  335. GP_ASSERT(filePath);
  336. GP_ASSERT(mode);
  337. std::string fullPath(__resourcePath);
  338. fullPath += resolvePath(filePath);
  339. createFileFromAsset(filePath);
  340. FILE* fp = fopen(fullPath.c_str(), mode);
  341. #ifdef WIN32
  342. if (fp == NULL)
  343. {
  344. fullPath = __resourcePath;
  345. fullPath += "../../gameplay/";
  346. fullPath += filePath;
  347. fp = fopen(fullPath.c_str(), mode);
  348. if (!fp)
  349. {
  350. fullPath = __resourcePath;
  351. fullPath += "../gameplay/";
  352. fullPath += filePath;
  353. fp = fopen(fullPath.c_str(), mode);
  354. }
  355. }
  356. #endif
  357. return fp;
  358. }
  359. char* FileSystem::readAll(const char* filePath, int* fileSize)
  360. {
  361. GP_ASSERT(filePath);
  362. // Open file for reading.
  363. std::auto_ptr<Stream> stream(open(filePath));
  364. if (stream.get() == NULL)
  365. {
  366. GP_ERROR("Failed to load file: %s", filePath);
  367. return NULL;
  368. }
  369. size_t size = stream->length();
  370. // Read entire file contents.
  371. char* buffer = new char[size + 1];
  372. size_t read = stream->read(buffer, 1, size);
  373. if (read != size)
  374. {
  375. GP_ERROR("Failed to read complete contents of file '%s' (amount read vs. file size: %u < %u).", filePath, read, size);
  376. SAFE_DELETE_ARRAY(buffer);
  377. return NULL;
  378. }
  379. // Force the character buffer to be NULL-terminated.
  380. buffer[size] = '\0';
  381. if (fileSize)
  382. {
  383. *fileSize = (int)size;
  384. }
  385. return buffer;
  386. }
  387. bool FileSystem::isAbsolutePath(const char* filePath)
  388. {
  389. if (filePath == 0 || filePath[0] == '\0')
  390. return false;
  391. #ifdef WIN32
  392. if (strlen(filePath) >= 2)
  393. {
  394. char first = filePath[0];
  395. if (filePath[1] == ':' && ((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z')))
  396. return true;
  397. }
  398. return false;
  399. #else
  400. return filePath[0] == '/';
  401. #endif
  402. }
  403. void FileSystem::createFileFromAsset(const char* path)
  404. {
  405. #ifdef __ANDROID__
  406. static std::set<std::string> upToDateAssets;
  407. GP_ASSERT(path);
  408. std::string fullPath(__resourcePath);
  409. std::string resolvedPath = FileSystem::resolvePath(path);
  410. fullPath += resolvedPath;
  411. std::string directoryPath = fullPath.substr(0, fullPath.rfind('/'));
  412. struct stat s;
  413. if (stat(directoryPath.c_str(), &s) != 0)
  414. makepath(directoryPath, 0777);
  415. // To ensure that the files on the file system corresponding to the assets in the APK bundle
  416. // are always up to date (and in sync), we copy them from the APK to the file system once
  417. // for each time the process (game) runs.
  418. if (upToDateAssets.find(fullPath) == upToDateAssets.end())
  419. {
  420. AAsset* asset = AAssetManager_open(__assetManager, resolvedPath.c_str(), AASSET_MODE_RANDOM);
  421. if (asset)
  422. {
  423. const void* data = AAsset_getBuffer(asset);
  424. int length = AAsset_getLength(asset);
  425. FILE* file = fopen(fullPath.c_str(), "wb");
  426. if (file != NULL)
  427. {
  428. int ret = fwrite(data, sizeof(unsigned char), length, file);
  429. if (fclose(file) != 0)
  430. {
  431. GP_ERROR("Failed to close file on file system created from APK asset '%s'.", path);
  432. return;
  433. }
  434. if (ret != length)
  435. {
  436. GP_ERROR("Failed to write all data from APK asset '%s' to file on file system.", path);
  437. return;
  438. }
  439. }
  440. else
  441. {
  442. GP_ERROR("Failed to create file on file system from APK asset '%s'.", path);
  443. return;
  444. }
  445. upToDateAssets.insert(fullPath);
  446. }
  447. }
  448. #endif
  449. }
  450. std::string FileSystem::getExtension(const char* path)
  451. {
  452. const char* str = strrchr(path, '.');
  453. if (str == NULL)
  454. return "";
  455. std::string ext;
  456. size_t len = strlen(str);
  457. for (size_t i = 0; i < len; ++i)
  458. ext += std::toupper(str[i]);
  459. return ext;
  460. }
  461. //////////////////
  462. FileStream::FileStream(FILE* file)
  463. : _file(file), _canRead(false), _canWrite(false)
  464. {
  465. }
  466. FileStream::~FileStream()
  467. {
  468. if (_file)
  469. {
  470. close();
  471. }
  472. }
  473. FileStream* FileStream::create(const char* filePath, const char* mode)
  474. {
  475. FILE* file = fopen(filePath, mode);
  476. if (file)
  477. {
  478. FileStream* stream = new FileStream(file);
  479. const char* s = mode;
  480. while (s != NULL && *s != '\0')
  481. {
  482. if (*s == 'r')
  483. stream->_canRead = true;
  484. else if (*s == 'w')
  485. stream->_canWrite = true;
  486. ++s;
  487. }
  488. return stream;
  489. }
  490. return NULL;
  491. }
  492. bool FileStream::canRead()
  493. {
  494. return _file && _canRead;
  495. }
  496. bool FileStream::canWrite()
  497. {
  498. return _file && _canWrite;
  499. }
  500. bool FileStream::canSeek()
  501. {
  502. return _file != NULL;
  503. }
  504. void FileStream::close()
  505. {
  506. if (_file)
  507. fclose(_file);
  508. _file = NULL;
  509. }
  510. size_t FileStream::read(void* ptr, size_t size, size_t count)
  511. {
  512. if (!_file)
  513. return 0;
  514. return fread(ptr, size, count, _file);
  515. }
  516. char* FileStream::readLine(char* str, int num)
  517. {
  518. if (!_file)
  519. return 0;
  520. return fgets(str, num, _file);
  521. }
  522. size_t FileStream::write(const void* ptr, size_t size, size_t count)
  523. {
  524. if (!_file)
  525. return 0;
  526. return fwrite(ptr, size, count, _file);
  527. }
  528. bool FileStream::eof()
  529. {
  530. if (!_file || feof(_file))
  531. return true;
  532. return ((size_t)position()) >= length();
  533. }
  534. size_t FileStream::length()
  535. {
  536. size_t len = 0;
  537. if (canSeek())
  538. {
  539. long int pos = position();
  540. if (seek(0, SEEK_END))
  541. {
  542. len = position();
  543. }
  544. seek(pos, SEEK_SET);
  545. }
  546. return len;
  547. }
  548. long int FileStream::position()
  549. {
  550. if (!_file)
  551. return -1;
  552. return ftell(_file);
  553. }
  554. bool FileStream::seek(long int offset, int origin)
  555. {
  556. if (!_file)
  557. return false;
  558. return fseek(_file, offset, origin) == 0;
  559. }
  560. bool FileStream::rewind()
  561. {
  562. if (canSeek())
  563. {
  564. ::rewind(_file);
  565. return true;
  566. }
  567. return false;
  568. }
  569. ////////////////////////////////
  570. #ifdef __ANDROID__
  571. FileStreamAndroid::FileStreamAndroid(AAsset* asset)
  572. : _asset(asset)
  573. {
  574. }
  575. FileStreamAndroid::~FileStreamAndroid()
  576. {
  577. if (_asset)
  578. close();
  579. }
  580. FileStreamAndroid* FileStreamAndroid::create(const char* filePath, const char* mode)
  581. {
  582. AAsset* asset = AAssetManager_open(__assetManager, filePath, AASSET_MODE_RANDOM);
  583. if (asset)
  584. {
  585. FileStreamAndroid* stream = new FileStreamAndroid(asset);
  586. return stream;
  587. }
  588. return NULL;
  589. }
  590. bool FileStreamAndroid::canRead()
  591. {
  592. return true;
  593. }
  594. bool FileStreamAndroid::canWrite()
  595. {
  596. return false;
  597. }
  598. bool FileStreamAndroid::canSeek()
  599. {
  600. return true;
  601. }
  602. void FileStreamAndroid::close()
  603. {
  604. if (_asset)
  605. AAsset_close(_asset);
  606. _asset = NULL;
  607. }
  608. size_t FileStreamAndroid::read(void* ptr, size_t size, size_t count)
  609. {
  610. int result = AAsset_read(_asset, ptr, size * count);
  611. return result > 0 ? ((size_t)result) / size : 0;
  612. }
  613. char* FileStreamAndroid::readLine(char* str, int num)
  614. {
  615. if (num <= 0)
  616. return NULL;
  617. char c = 0;
  618. size_t maxCharsToRead = num - 1;
  619. for (size_t i = 0; i < maxCharsToRead; ++i)
  620. {
  621. size_t result = read(&c, 1, 1);
  622. if (result != 1)
  623. {
  624. str[i] = '\0';
  625. break;
  626. }
  627. if (c == '\n')
  628. {
  629. str[i] = c;
  630. str[i + 1] = '\0';
  631. break;
  632. }
  633. else if(c == '\r')
  634. {
  635. str[i] = c;
  636. // next may be '\n'
  637. size_t pos = position();
  638. char nextChar = 0;
  639. if (read(&nextChar, 1, 1) != 1)
  640. {
  641. // no more characters
  642. str[i + 1] = '\0';
  643. break;
  644. }
  645. if (nextChar == '\n')
  646. {
  647. if (i == maxCharsToRead - 1)
  648. {
  649. str[i + 1] = '\0';
  650. break;
  651. }
  652. else
  653. {
  654. str[i + 1] = nextChar;
  655. str[i + 2] = '\0';
  656. break;
  657. }
  658. }
  659. else
  660. {
  661. seek(pos, SEEK_SET);
  662. str[i + 1] = '\0';
  663. break;
  664. }
  665. }
  666. str[i] = c;
  667. }
  668. return str; // what if first read failed?
  669. }
  670. size_t FileStreamAndroid::write(const void* ptr, size_t size, size_t count)
  671. {
  672. return 0;
  673. }
  674. bool FileStreamAndroid::eof()
  675. {
  676. return position() >= length();
  677. }
  678. size_t FileStreamAndroid::length()
  679. {
  680. return (size_t)AAsset_getLength(_asset);
  681. }
  682. long int FileStreamAndroid::position()
  683. {
  684. return AAsset_getLength(_asset) - AAsset_getRemainingLength(_asset);
  685. }
  686. bool FileStreamAndroid::seek(long int offset, int origin)
  687. {
  688. return AAsset_seek(_asset, offset, origin) != -1;
  689. }
  690. bool FileStreamAndroid::rewind()
  691. {
  692. if (canSeek())
  693. {
  694. return AAsset_seek(_asset, 0, SEEK_SET) != -1;
  695. }
  696. return false;
  697. }
  698. #endif
  699. }