AndroidFileio.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platformAndroid/platformAndroid.h"
  24. #include "platform/platformFileIO.h"
  25. #include "collection/vector.h"
  26. #include "string/stringTable.h"
  27. #include "string/stringUnit.h"
  28. #include "console/console.h"
  29. #include "debug/profiler.h"
  30. #include "io/resource/resourceManager.h"
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <errno.h>
  34. #include <utime.h>
  35. #include <sys/types.h>
  36. #include <dirent.h>
  37. #include <unistd.h>
  38. #include <sys/stat.h>
  39. #include <sys/time.h>
  40. #define MAX_MAC_PATH_LONG 2048
  41. //-----------------------------------------------------------------------------
  42. //Cache handling functions
  43. //-----------------------------------------------------------------------------
  44. bool isCachePath(const char* path)
  45. {
  46. if (!path || !*path)
  47. return false;
  48. if (path[0] == '/')
  49. {
  50. if (strstr(path, Platform::getUserDataDirectory()) != NULL)
  51. {
  52. return true;
  53. }
  54. else
  55. {
  56. return false;
  57. }
  58. }
  59. else
  60. {
  61. const char* tmp = Platform::getUserDataDirectory();
  62. if (strstr(path, tmp+1) != NULL)
  63. {
  64. return true;
  65. }
  66. else
  67. {
  68. return false;
  69. }
  70. }
  71. }
  72. //-----------------------------------------------------------------------------
  73. bool Platform::fileDelete(const char * name)
  74. {
  75. if(!name )
  76. return(false);
  77. if (dStrlen(name) > MAX_MAC_PATH_LONG)
  78. Con::warnf("Platform::FileDelete() - Filename length is pretty long...");
  79. return(remove(name) == 0); // remove returns 0 on success
  80. }
  81. //-----------------------------------------------------------------------------
  82. bool dFileTouch(const char *path)
  83. {
  84. if (!path || !*path)
  85. return false;
  86. // set file at path's modification and access times to now.
  87. return( utimes( path, NULL) == 0); // utimes returns 0 on success.
  88. }
  89. //-----------------------------------------------------------------------------
  90. // Constructors & Destructor
  91. //-----------------------------------------------------------------------------
  92. //-----------------------------------------------------------------------------
  93. // After construction, the currentStatus will be Closed and the capabilities
  94. // will be 0.
  95. //-----------------------------------------------------------------------------
  96. File::File()
  97. : currentStatus(Closed), capability(0)
  98. {
  99. buffer = NULL;
  100. size = 0;
  101. filePointer = 0;
  102. handle = NULL;
  103. }
  104. //-----------------------------------------------------------------------------
  105. // insert a copy constructor here... (currently disabled)
  106. //-----------------------------------------------------------------------------
  107. //-----------------------------------------------------------------------------
  108. // Destructor
  109. //-----------------------------------------------------------------------------
  110. File::~File()
  111. {
  112. if (buffer != NULL || handle != NULL)
  113. close();
  114. handle = NULL;
  115. }
  116. //-----------------------------------------------------------------------------
  117. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  118. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  119. // true.
  120. //
  121. // Sets capability appropriate to the openMode.
  122. // Returns the currentStatus of the file.
  123. //-----------------------------------------------------------------------------
  124. File::Status File::open(const char *filename, const AccessMode openMode)
  125. {
  126. //If its a cache path then we need to open it using C methods not AssetManager
  127. if (isCachePath(filename))
  128. {
  129. if (dStrlen(filename) > MAX_MAC_PATH_LONG)
  130. Con::warnf("File::open: Filename length is pretty long...");
  131. // Close the file if it was already open...
  132. if (currentStatus != Closed)
  133. close();
  134. // create the appropriate type of file...
  135. switch (openMode)
  136. {
  137. case Read:
  138. handle = (void *)fopen(filename, "rb"); // read only
  139. break;
  140. case Write:
  141. handle = (void *)fopen(filename, "wb"); // write only
  142. break;
  143. case ReadWrite:
  144. handle = (void *)fopen(filename, "ab+"); // write(append) and read
  145. break;
  146. case WriteAppend:
  147. handle = (void *)fopen(filename, "ab"); // write(append) only
  148. break;
  149. default:
  150. AssertFatal(false, "File::open: bad access mode");
  151. }
  152. // handle not created successfully
  153. if (handle == NULL)
  154. return setStatus();
  155. // successfully created file, so set the file capabilities...
  156. switch (openMode)
  157. {
  158. case Read:
  159. capability = FileRead;
  160. break;
  161. case Write:
  162. case WriteAppend:
  163. capability = FileWrite;
  164. break;
  165. case ReadWrite:
  166. capability = FileRead | FileWrite;
  167. break;
  168. default:
  169. AssertFatal(false, "File::open: bad access mode");
  170. }
  171. // must set the file status before setting the position.
  172. currentStatus = Ok;
  173. if (openMode == ReadWrite)
  174. setPosition(0);
  175. // success!
  176. return currentStatus;
  177. }
  178. if (dStrlen(filename) > MAX_MAC_PATH_LONG)
  179. Con::warnf("File::open: Filename length is pretty long...");
  180. // Close the file if it was already open...
  181. if (currentStatus != Closed || buffer != NULL)
  182. close();
  183. // create the appropriate type of file...
  184. switch (openMode)
  185. {
  186. case Read:
  187. filePointer = 0;
  188. buffer = (U8*)_AndroidLoadFile(filename, &size);
  189. if (buffer == NULL) {
  190. currentStatus = UnknownError;
  191. capability = FileRead;
  192. return currentStatus;
  193. }
  194. break;
  195. case Write:
  196. //AssertFatal(false, "File::open: Write not supported on Android");
  197. //Platform::getUserDataDirectory()
  198. return currentStatus;
  199. case ReadWrite:
  200. //AssertFatal(false, "File::open: ReadWrite not supported on Android");
  201. return currentStatus;
  202. case WriteAppend:
  203. //AssertFatal(false, "File::open: WriteAppend not supported on Android");
  204. return currentStatus;
  205. default:
  206. AssertFatal(false, "File::open: bad access mode");
  207. }
  208. capability = FileRead;
  209. // must set the file status before setting the position.
  210. currentStatus = Ok;
  211. // success!
  212. return currentStatus;
  213. }
  214. //-----------------------------------------------------------------------------
  215. // Get the current position of the file pointer.
  216. //-----------------------------------------------------------------------------
  217. U32 File::getPosition() const
  218. {
  219. if (handle != NULL)
  220. {
  221. AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
  222. AssertFatal(handle != NULL, "File::getPosition: invalid file handle");
  223. return ftell((FILE*)handle);
  224. }
  225. AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
  226. AssertFatal(buffer != NULL, "File::getPosition: invalid file buffer");
  227. return filePointer;
  228. }
  229. //-----------------------------------------------------------------------------
  230. // Set the position of the file pointer.
  231. // Absolute and relative positioning is supported via the absolutePos
  232. // parameter.
  233. //
  234. // If positioning absolutely, position MUST be positive - an IOError results if
  235. // position is negative.
  236. // Position can be negative if positioning relatively, however positioning
  237. // before the start of the file is an IOError.
  238. //
  239. // Returns the currentStatus of the file.
  240. //-----------------------------------------------------------------------------
  241. File::Status File::setPosition(S32 position, bool absolutePos)
  242. {
  243. if (handle != NULL)
  244. {
  245. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  246. AssertFatal(handle != NULL, "File::setPosition: invalid file handle");
  247. if (currentStatus != Ok && currentStatus != EOS )
  248. return currentStatus;
  249. U32 finalPos;
  250. if(absolutePos)
  251. {
  252. // absolute position
  253. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  254. // position beyond EOS is OK
  255. fseek((FILE*)handle, position, SEEK_SET);
  256. finalPos = ftell((FILE*)handle);
  257. }
  258. else
  259. {
  260. // relative position
  261. AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
  262. // position beyond EOS is OK
  263. fseek((FILE*)handle, position, SEEK_CUR);
  264. finalPos = ftell((FILE*)handle);
  265. }
  266. // ftell returns -1 on error. set error status
  267. if (0xffffffff == finalPos)
  268. return setStatus();
  269. // success, at end of file
  270. else if (finalPos >= getSize())
  271. return currentStatus = EOS;
  272. // success!
  273. else
  274. return currentStatus = Ok;
  275. }
  276. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  277. AssertFatal(buffer != NULL, "File::setPosition: invalid file buffer");
  278. if (currentStatus != Ok && currentStatus != EOS )
  279. return currentStatus;
  280. U32 finalPos;
  281. if(absolutePos)
  282. {
  283. // absolute position
  284. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  285. // position beyond EOS is OK
  286. filePointer = position;
  287. finalPos = filePointer;
  288. }
  289. else
  290. {
  291. // relative position
  292. AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
  293. // position beyond EOS is OK
  294. filePointer += position;
  295. finalPos = filePointer;
  296. }
  297. // ftell returns -1 on error. set error status
  298. if (0xffffffff == finalPos)
  299. return setStatus();
  300. // success, at end of file
  301. else if (finalPos >= getSize())
  302. return currentStatus = EOS;
  303. // success!
  304. else
  305. return currentStatus = Ok;
  306. }
  307. //-----------------------------------------------------------------------------
  308. // Get the size of the file in bytes.
  309. // It is an error to query the file size for a Closed file, or for one with an
  310. // error status.
  311. //-----------------------------------------------------------------------------
  312. U32 File::getSize() const
  313. {
  314. if (handle != NULL)
  315. {
  316. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  317. AssertFatal(handle != NULL, "File::getSize: invalid file handle");
  318. if (Ok == currentStatus || EOS == currentStatus)
  319. {
  320. struct stat statData;
  321. if(fstat(fileno((FILE*)handle), &statData) != 0)
  322. return 0;
  323. // return the size in bytes
  324. return statData.st_size;
  325. }
  326. return 0;
  327. }
  328. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  329. AssertFatal(buffer != NULL, "File::getSize: invalid file buffer");
  330. if (Ok == currentStatus || EOS == currentStatus)
  331. {
  332. return size;
  333. }
  334. return 0;
  335. }
  336. //-----------------------------------------------------------------------------
  337. // Flush the file.
  338. // It is an error to flush a read-only file.
  339. // Returns the currentStatus of the file.
  340. //-----------------------------------------------------------------------------
  341. File::Status File::flush()
  342. {
  343. if (handle != NULL)
  344. {
  345. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  346. AssertFatal(handle != NULL, "File::flush: invalid file handle");
  347. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  348. if (fflush((FILE*)handle) != 0)
  349. return setStatus();
  350. else
  351. return currentStatus = Ok;
  352. }
  353. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  354. AssertFatal(buffer != NULL, "File::flush: invalid file buffer");
  355. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  356. return setStatus();
  357. }
  358. //-----------------------------------------------------------------------------
  359. // Close the File.
  360. //
  361. // Returns the currentStatus
  362. //-----------------------------------------------------------------------------
  363. File::Status File::close()
  364. {
  365. if (handle != NULL)
  366. {
  367. // check if it's already closed...
  368. if (Closed == currentStatus)
  369. return currentStatus;
  370. // it's not, so close it...
  371. if (handle != NULL)
  372. {
  373. if (fclose((FILE*)handle) != 0)
  374. return setStatus();
  375. }
  376. handle = NULL;
  377. return currentStatus = Closed;
  378. }
  379. // check if it's already closed...
  380. if (Closed == currentStatus)
  381. return currentStatus;
  382. // it's not, so close it...
  383. if (buffer != NULL)
  384. {
  385. delete[] buffer;
  386. buffer = NULL;
  387. size = 0;
  388. filePointer = 0;
  389. }
  390. return currentStatus = Closed;
  391. }
  392. //-----------------------------------------------------------------------------
  393. // Self-explanatory.
  394. //-----------------------------------------------------------------------------
  395. File::Status File::getStatus() const
  396. {
  397. return currentStatus;
  398. }
  399. //-----------------------------------------------------------------------------
  400. // Sets and returns the currentStatus when an error has been encountered.
  401. //-----------------------------------------------------------------------------
  402. File::Status File::setStatus()
  403. {
  404. if (handle != NULL)
  405. {
  406. switch (errno)
  407. {
  408. case EACCES: // permission denied
  409. currentStatus = IOError;
  410. break;
  411. case EBADF: // Bad File Pointer
  412. case EINVAL: // Invalid argument
  413. case ENOENT: // file not found
  414. case ENAMETOOLONG:
  415. default:
  416. currentStatus = UnknownError;
  417. }
  418. return currentStatus;
  419. }
  420. currentStatus = UnknownError;
  421. return currentStatus;
  422. }
  423. //-----------------------------------------------------------------------------
  424. // Sets and returns the currentStatus to status.
  425. //-----------------------------------------------------------------------------
  426. File::Status File::setStatus(File::Status status)
  427. {
  428. return currentStatus = status;
  429. }
  430. //-----------------------------------------------------------------------------
  431. // Read from a file.
  432. // The number of bytes to read is passed in size, the data is returned in src.
  433. // The number of bytes read is available in bytesRead if a non-Null pointer is
  434. // provided.
  435. //-----------------------------------------------------------------------------
  436. File::Status File::read(U32 _size, char *dst, U32 *bytesRead)
  437. {
  438. if (handle != NULL)
  439. {
  440. AssertFatal(Closed != currentStatus, "File::read: file closed");
  441. AssertFatal(handle != NULL, "File::read: invalid file handle");
  442. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  443. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  444. AssertWarn(0 != size, "File::read: size of zero");
  445. if (Ok != currentStatus || 0 == size)
  446. return currentStatus;
  447. // read from stream
  448. U32 nBytes = fread(dst, 1, size, (FILE*)handle);
  449. // did we hit the end of the stream?
  450. if( nBytes != size)
  451. currentStatus = EOS;
  452. // if bytesRead is a valid pointer, send number of bytes read there.
  453. if(bytesRead)
  454. *bytesRead = nBytes;
  455. // successfully read size bytes
  456. return currentStatus;
  457. }
  458. AssertFatal(Closed != currentStatus, "File::read: file closed");
  459. AssertFatal(buffer != NULL, "File::read: invalid file buffer");
  460. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  461. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  462. AssertWarn(0 != size, "File::read: size of zero");
  463. if (Ok != currentStatus || 0 == size)
  464. return currentStatus;
  465. // read from stream
  466. U32 nBytes = 0;
  467. if ((size-filePointer) > (_size))
  468. {
  469. memcpy(dst, buffer+filePointer, _size);
  470. nBytes = _size;
  471. }
  472. else if (size-filePointer <= 0)
  473. {
  474. nBytes = 0;
  475. }
  476. else
  477. {
  478. memcpy(dst, buffer+filePointer, size-filePointer);
  479. nBytes = size-filePointer;
  480. }
  481. //Advanced the pointer
  482. filePointer += nBytes;
  483. // did we hit the end of the stream?
  484. if( nBytes != _size)
  485. currentStatus = EOS;
  486. // if bytesRead is a valid pointer, send number of bytes read there.
  487. if(bytesRead)
  488. *bytesRead = nBytes;
  489. // successfully read size bytes
  490. return currentStatus;
  491. }
  492. //-----------------------------------------------------------------------------
  493. // Write to a file.
  494. // The number of bytes to write is passed in size, the data is passed in src.
  495. // The number of bytes written is available in bytesWritten if a non-Null
  496. // pointer is provided.
  497. //-----------------------------------------------------------------------------
  498. File::Status File::write(U32 size, const char *src, U32 *bytesWritten)
  499. {
  500. if (handle != NULL)
  501. {
  502. AssertFatal(Closed != currentStatus, "File::write: file closed");
  503. AssertFatal(handle != NULL, "File::write: invalid file handle");
  504. AssertFatal(NULL != src, "File::write: NULL source pointer");
  505. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  506. AssertWarn(0 != size, "File::write: size of zero");
  507. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  508. return currentStatus;
  509. // write bytes to the stream
  510. U32 nBytes = fwrite(src, 1, size,(FILE*)handle);
  511. // if we couldn't write everything, we've got a problem. set error status.
  512. if(nBytes != size)
  513. setStatus();
  514. // if bytesWritten is a valid pointer, put number of bytes read there.
  515. if(bytesWritten)
  516. *bytesWritten = nBytes;
  517. // return current File status, whether good or ill.
  518. return currentStatus;
  519. }
  520. AssertFatal(0, "File::write: Not supported on Android.");
  521. return setStatus();
  522. }
  523. //-----------------------------------------------------------------------------
  524. // Self-explanatory.
  525. //-----------------------------------------------------------------------------
  526. bool File::hasCapability(Capability cap) const
  527. {
  528. return (0 != (U32(cap) & capability));
  529. }
  530. //-----------------------------------------------------------------------------
  531. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  532. {
  533. if(a > b)
  534. return 1;
  535. if(a < b)
  536. return -1;
  537. return 0;
  538. }
  539. //-----------------------------------------------------------------------------
  540. // either time param COULD be null.
  541. //-----------------------------------------------------------------------------
  542. bool Platform::getFileTimes(const char *path, FileTime *createTime, FileTime *modifyTime)
  543. {
  544. // MacOSX is NOT guaranteed to be running off a HFS volume,
  545. // and UNIX does not keep a record of a file's creation time anywhere.
  546. // So instead of creation time we return changed time,
  547. // just like the Linux platform impl does.
  548. if (!path || !*path)
  549. return false;
  550. struct stat statData;
  551. if (stat(path, &statData) == -1)
  552. return false;
  553. if(createTime)
  554. *createTime = statData.st_ctime;
  555. if(modifyTime)
  556. *modifyTime = statData.st_mtime;
  557. return true;
  558. }
  559. //-----------------------------------------------------------------------------
  560. bool Platform::createPath(const char *file)
  561. {
  562. //<Mat> needless console noise
  563. //Con::warnf("creating path %s",file);
  564. // if the path exists, we're done.
  565. struct stat statData;
  566. if( stat(file, &statData) == 0 )
  567. {
  568. return true; // exists, rejoice.
  569. }
  570. // get the parent path.
  571. // we're not using basename because it's not thread safe.
  572. const U32 len = dStrlen(file) + 1;
  573. char parent[len];
  574. bool isDirPath = false;
  575. dSprintf(parent, len, "%s", file);
  576. if(parent[len - 2] == '/')
  577. {
  578. parent[len - 2] = '\0'; // cut off the trailing slash, if there is one
  579. isDirPath = true; // we got a trailing slash, so file is a directory.
  580. }
  581. // recusively create the parent path.
  582. // only recurse if newpath has a slash that isn't a leading slash.
  583. char *slash = dStrrchr(parent,'/');
  584. if( slash && slash != parent)
  585. {
  586. // snip the path just after the last slash.
  587. slash[1] = '\0';
  588. // recusively create the parent path. fail if parent path creation failed.
  589. if(!Platform::createPath(parent))
  590. return false;
  591. }
  592. // create *file if it is a directory path.
  593. if(isDirPath)
  594. {
  595. // try to create the directory
  596. if( mkdir(file, 0777) != 0) // app may reside in global apps dir, and so must be writable to all.
  597. return false;
  598. }
  599. return true;
  600. }
  601. #pragma mark ---- Directories ----
  602. //-----------------------------------------------------------------------------
  603. StringTableEntry Platform::getCurrentDirectory()
  604. {
  605. // get the current directory, the one that would be opened if we did a fopen(".")
  606. char* cwd = getcwd(NULL, 0);
  607. StringTableEntry ret = StringTable->insert(cwd);
  608. free(cwd);
  609. return ret;
  610. }
  611. //-----------------------------------------------------------------------------
  612. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  613. {
  614. return (chdir(newDir) == 0);
  615. }
  616. //-----------------------------------------------------------------------------
  617. void Platform::openFolder(const char* path )
  618. {
  619. // TODO: users can still run applications by calling openfolder on an app bundle.
  620. // this may be a bad thing.
  621. if(!Platform::isDirectory(path))
  622. {
  623. Con::errorf(avar("Error: not a directory: %s",path));
  624. return;
  625. }
  626. const char* arg = avar("open '%s'", path);
  627. U32 ret = system(arg);
  628. if(ret != 0)
  629. Con::printf(strerror(errno));
  630. }
  631. static bool isMainDotCsPresent(char *dir)
  632. {
  633. char maincsbuf[MAX_MAC_PATH_LONG];
  634. const char *maincsname = "/main.cs";
  635. const U32 len = dStrlen(dir) + dStrlen(maincsname)+1;
  636. AssertISV(len < MAX_MAC_PATH_LONG, "Sorry, path is too long, I can't run from this folder.");
  637. dSprintf(maincsbuf,MAX_MAC_PATH_LONG,"%s%s", dir, maincsname);
  638. return Platform::isFile(maincsbuf);
  639. }
  640. //-----------------------------------------------------------------------------
  641. /// Finds and sets the current working directory.
  642. /// Torque tries to automatically detect whether you have placed the game files
  643. /// inside or outside the application's bundle. It checks for the presence of
  644. /// the file 'main.cs'. If it finds it, Torque will assume that the other game
  645. /// files are there too. If Torque does not see 'main.cs' inside its bundle, it
  646. /// will assume the files are outside the bundle.
  647. /// Since you probably don't want to copy the game files into the app every time
  648. /// you build, you will want to leave them outside the bundle for development.
  649. ///
  650. /// Android reads all assets out of compressed bundle so we dont realy have an executable path
  651. StringTableEntry Platform::getExecutablePath()
  652. {
  653. if(platState.mainDotCsDir)
  654. return platState.mainDotCsDir;
  655. char* ret = NULL;
  656. if(StringTable)
  657. platState.mainDotCsDir = StringTable->insert(".");
  658. else
  659. ret = dStrdup(".");
  660. return ret ? ret : platState.mainDotCsDir;
  661. }
  662. //-----------------------------------------------------------------------------
  663. StringTableEntry Platform::getExecutableName()
  664. {
  665. return StringTable->insert("Torque2D");
  666. }
  667. //-----------------------------------------------------------------------------
  668. bool Platform::isFile(const char *path)
  669. {
  670. if (!path || !*path)
  671. return false;
  672. if (isCachePath(path))
  673. {
  674. // make sure we can stat the file
  675. struct stat statData;
  676. if( stat(path, &statData) < 0 )
  677. return false;
  678. // now see if it's a regular file
  679. if( (statData.st_mode & S_IFMT) == S_IFREG)
  680. return true;
  681. return false;
  682. }
  683. return android_IsFile(path);
  684. }
  685. //-----------------------------------------------------------------------------
  686. bool Platform::isDirectory(const char *path)
  687. {
  688. if (!path || !*path)
  689. return false;
  690. if (isCachePath(path))
  691. {
  692. // make sure we can stat the file
  693. struct stat statData;
  694. if( stat(path, &statData) < 0 )
  695. return false;
  696. // now see if it's a directory
  697. if( (statData.st_mode & S_IFMT) == S_IFDIR)
  698. return true;
  699. return false;
  700. }
  701. return android_IsDir(path);
  702. }
  703. S32 Platform::getFileSize(const char* pFilePath)
  704. {
  705. if (!pFilePath || !*pFilePath)
  706. return 0;
  707. if (isCachePath(pFilePath))
  708. {
  709. struct stat statData;
  710. if( stat(pFilePath, &statData) < 0 )
  711. return 0;
  712. // and return it's size in bytes
  713. return (S32)statData.st_size;
  714. }
  715. return android_GetFileSize(pFilePath);
  716. }
  717. //-----------------------------------------------------------------------------
  718. bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
  719. {
  720. char fullpath[MAX_MAC_PATH_LONG];
  721. dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
  722. return isDirectory((const char *)fullpath);
  723. }
  724. void getDirectoryName(const char* path, char* name)
  725. {
  726. int cnt = StringUnit::getUnitCount(path, "/");
  727. strcpy(name,StringUnit::getUnit(path, cnt-1, "/"));
  728. }
  729. //-----------------------------------------------------------------------------
  730. // utility for platform::hasSubDirectory() and platform::dumpDirectories()
  731. // ensures that the entry is a directory, and isnt on the ignore lists.
  732. inline bool isGoodDirectory(const char* path)
  733. {
  734. char name[80];
  735. getDirectoryName(path, name);
  736. return (Platform::isDirectory(path) // is a dir
  737. && dStrcmp(name,".") != 0 // not here
  738. && dStrcmp(name,"..") != 0 // not parent
  739. && !Platform::isExcludedDirectory(name)); // not excluded
  740. }
  741. inline bool isGoodDirectoryCache(dirent* entry)
  742. {
  743. return (entry->d_type == DT_DIR // is a dir
  744. && dStrcmp(entry->d_name,".") != 0 // not here
  745. && dStrcmp(entry->d_name,"..") != 0 // not parent
  746. && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
  747. }
  748. //-----------------------------------------------------------------------------
  749. bool Platform::hasSubDirectory(const char *path)
  750. {
  751. if (isCachePath(path))
  752. {
  753. DIR *dir;
  754. dirent *entry;
  755. dir = opendir(path);
  756. if(!dir)
  757. return false; // we got a bad path, so no, it has no subdirectory.
  758. while( true )
  759. {
  760. entry = readdir(dir);
  761. if ( entry == NULL )
  762. break;
  763. if(isGoodDirectoryCache(entry) )
  764. {
  765. closedir(dir);
  766. return true; // we have a subdirectory, that isnt on the exclude list.
  767. }
  768. }
  769. closedir(dir);
  770. return false; // either this dir had no subdirectories, or they were all on the exclude list.
  771. }
  772. android_InitDirList(path);
  773. char dir[80];
  774. char pdir[255];
  775. strcpy(dir,"");
  776. android_GetNextDir(path, dir);
  777. while(strcmp(dir,"") != 0)
  778. {
  779. sprintf(pdir, "%s/%s", path, dir);
  780. if (isGoodDirectory(pdir))
  781. return true;
  782. android_GetNextDir(path, dir);
  783. }
  784. return false;
  785. }
  786. //-----------------------------------------------------------------------------
  787. bool recurseDumpDirectories(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  788. {
  789. char aPath[80];
  790. if (basePath[0] == '/')
  791. {
  792. strcpy(aPath, basePath+1);
  793. }
  794. else
  795. {
  796. strcpy(aPath, basePath);
  797. }
  798. const U32 len = dStrlen(aPath) + dStrlen(path) + 2;
  799. char pathbuf[len];
  800. // construct the file path
  801. if (strcmp(path,"") != 0)
  802. dSprintf(pathbuf, len, "%s/%s", aPath, path);
  803. else
  804. strcpy(pathbuf, aPath);
  805. // be sure it opens.
  806. android_InitDirList(pathbuf);
  807. // look inside the current directory
  808. char dir[80];
  809. char pdir[255];
  810. strcpy(dir,"");
  811. android_GetNextDir(pathbuf, dir);
  812. while(strcmp(dir,"") != 0)
  813. {
  814. sprintf(pdir, "%s/%s", pathbuf, dir);
  815. if (!isGoodDirectory(pdir))
  816. return false;
  817. // construct the new path string, we'll need this below.
  818. const U32 newpathlen = dStrlen(path) + dStrlen(dir) + 2;
  819. char newpath[newpathlen];
  820. if(dStrlen(path) > 0)
  821. {
  822. dSprintf(newpath, newpathlen, "%s/%s", path, dir);
  823. }
  824. else
  825. {
  826. dSprintf(newpath, newpathlen, "%s", dir);
  827. }
  828. // we have a directory, add it to the list.
  829. if( noBasePath )
  830. {
  831. directoryVector.push_back(StringTable->insert(newpath));
  832. }
  833. else
  834. {
  835. const U32 fullpathlen = dStrlen(aPath) + dStrlen(newpath) + 2;
  836. char fullpath[fullpathlen];
  837. dSprintf(fullpath, fullpathlen, "%s/%s",aPath,newpath);
  838. directoryVector.push_back(StringTable->insert(fullpath));
  839. }
  840. // and recurse into it, unless we've run out of depth
  841. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  842. recurseDumpDirectories(aPath, newpath, directoryVector, depth-1, noBasePath);
  843. android_GetNextDir(pathbuf, dir);
  844. }
  845. return true;
  846. }
  847. //-----------------------------------------------------------------------------
  848. bool recurseDumpDirectoriesCache(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  849. {
  850. DIR *dir;
  851. dirent *entry;
  852. const U32 len = dStrlen(basePath) + dStrlen(path) + 2;
  853. char pathbuf[len];
  854. // construct the file path
  855. dSprintf(pathbuf, len, "%s/%s", basePath, path);
  856. // be sure it opens.
  857. dir = opendir(pathbuf);
  858. if(!dir)
  859. return false;
  860. // look inside the current directory
  861. while( true )
  862. {
  863. entry = readdir(dir);
  864. if ( entry == NULL )
  865. break;
  866. // we just want directories.
  867. if(!isGoodDirectoryCache(entry))
  868. continue;
  869. // TODO: better unicode file name handling
  870. // // Apple's file system stores unicode file names in decomposed form.
  871. // // ATSUI will not reliably draw out just the accent character by itself,
  872. // // so our text renderer has no chance of rendering decomposed form unicode.
  873. // // We have to convert the entry name to precomposed normalized form.
  874. // CFStringRef cfdname = CFStringCreateWithCString(NULL,entry->d_name,kCFStringEncodingUTF8);
  875. // CFMutableStringRef cfentryName = CFStringCreateMutableCopy(NULL,0,cfdname);
  876. // CFStringNormalize(cfentryName,kCFStringNormalizationFormC);
  877. //
  878. // U32 entryNameLen = CFStringGetLength(cfentryName) * 4 + 1;
  879. // char entryName[entryNameLen];
  880. // CFStringGetCString(cfentryName, entryName, entryNameLen, kCFStringEncodingUTF8);
  881. // entryName[entryNameLen-1] = NULL; // sometimes, CFStringGetCString() doesn't null terminate.
  882. // CFRelease(cfentryName);
  883. // CFRelease(cfdname);
  884. // construct the new path string, we'll need this below.
  885. const U32 newpathlen = dStrlen(path) + dStrlen(entry->d_name) + 2;
  886. char newpath[newpathlen];
  887. if(dStrlen(path) > 0)
  888. {
  889. dSprintf(newpath, newpathlen, "%s/%s", path, entry->d_name);
  890. }
  891. else
  892. {
  893. dSprintf(newpath, newpathlen, "%s", entry->d_name);
  894. }
  895. // we have a directory, add it to the list.
  896. if( noBasePath )
  897. {
  898. directoryVector.push_back(StringTable->insert(newpath));
  899. }
  900. else
  901. {
  902. const U32 fullpathlen = dStrlen(basePath) + dStrlen(newpath) + 2;
  903. char fullpath[fullpathlen];
  904. dSprintf(fullpath, fullpathlen, "%s/%s",basePath,newpath);
  905. directoryVector.push_back(StringTable->insert(fullpath));
  906. }
  907. // and recurse into it, unless we've run out of depth
  908. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  909. recurseDumpDirectoriesCache(basePath, newpath, directoryVector, depth-1, noBasePath);
  910. }
  911. closedir(dir);
  912. return true;
  913. }
  914. //-----------------------------------------------------------------------------
  915. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  916. {
  917. if (isCachePath(path))
  918. {
  919. PROFILE_START(dumpDirectories);
  920. ResourceManager->initExcludedDirectories();
  921. const S32 len = dStrlen(path)+1;
  922. char newpath[len];
  923. dSprintf(newpath, len, "%s", path);
  924. if(newpath[len - 1] == '/')
  925. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  926. // Insert base path to follow what Windows does.
  927. if ( !noBasePath )
  928. directoryVector.push_back(StringTable->insert(newpath));
  929. bool ret = recurseDumpDirectoriesCache(newpath, "", directoryVector, depth, noBasePath);
  930. PROFILE_END();
  931. return ret;
  932. }
  933. PROFILE_START(dumpDirectories);
  934. ResourceManager->initExcludedDirectories();
  935. const S32 len = dStrlen(path)+1;
  936. char newpath[len];
  937. if (path[0] == '/')
  938. {
  939. dSprintf(newpath, len-1, "%s", path+1);
  940. }
  941. else
  942. {
  943. dSprintf(newpath, len, "%s", path);
  944. }
  945. if(newpath[len - 1] == '/')
  946. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  947. // Insert base path to follow what Windows does.
  948. if ( !noBasePath )
  949. directoryVector.push_back(StringTable->insert(newpath));
  950. bool ret = recurseDumpDirectories(newpath, "", directoryVector, depth, noBasePath);
  951. PROFILE_END();
  952. return ret;
  953. }
  954. //-----------------------------------------------------------------------------
  955. static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  956. {
  957. android_InitDirList(curPath);
  958. // look inside the current directory
  959. char dir[80];
  960. char file[80];
  961. strcpy(dir,"");
  962. strcpy(file,"");
  963. android_GetNextDir(curPath, dir);
  964. android_GetNextFile(curPath, file);
  965. while(strcmp(file,"") != 0)
  966. {
  967. // construct the full file path. we need this to get the file size and to recurse
  968. const U32 len = dStrlen(curPath) + dStrlen(file) + 2;
  969. char pathbuf[len];
  970. dSprintf( pathbuf, len, "%s/%s", curPath, file);
  971. //add the file entry to the list
  972. // unlike recurseDumpDirectories(), we need to return more complex info here.
  973. //<Mat> commented this out in case we ever want a dir file printout again
  974. //printf( "File Name: %s ", entry->d_name );
  975. const U32 fileSize = Platform::getFileSize(pathbuf);
  976. fileVector.increment();
  977. Platform::FileInfo& rInfo = fileVector.last();
  978. rInfo.pFullPath = StringTable->insert(curPath);
  979. rInfo.pFileName = StringTable->insert(file);
  980. rInfo.fileSize = fileSize;
  981. android_GetNextFile(curPath, file);
  982. }
  983. while(strcmp(dir,"") != 0)
  984. {
  985. // construct the full file path. we need this to get the file size and to recurse
  986. const U32 len = dStrlen(curPath) + dStrlen(dir) + 2;
  987. char pathbuf[len];
  988. if (strcmp(curPath,"") == 0)
  989. dSprintf( pathbuf, len, "%s", dir);
  990. else
  991. dSprintf( pathbuf, len, "%s/%s", curPath, dir);
  992. if( depth == 0)
  993. {
  994. android_GetNextDir(curPath, dir);
  995. continue;
  996. }
  997. // filter out dirs we dont want.
  998. if( !isGoodDirectory(pathbuf) )
  999. {
  1000. android_GetNextDir(curPath, dir);
  1001. continue;
  1002. }
  1003. // recurse into the dir
  1004. recurseDumpPath( pathbuf, fileVector, depth-1);
  1005. android_GetNextDir(curPath, dir);
  1006. }
  1007. return true;
  1008. }
  1009. //-----------------------------------------------------------------------------
  1010. static bool recurseDumpPathCache(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  1011. {
  1012. DIR *dir;
  1013. dirent *entry;
  1014. // be sure it opens.
  1015. dir = opendir(curPath);
  1016. if(!dir)
  1017. return false;
  1018. // look inside the current directory
  1019. while( true )
  1020. {
  1021. entry = readdir(dir);
  1022. if ( entry == NULL )
  1023. break;
  1024. // construct the full file path. we need this to get the file size and to recurse
  1025. const U32 len = dStrlen(curPath) + entry->d_reclen + 2;
  1026. char pathbuf[255];
  1027. sprintf( pathbuf, "%s/%s", curPath, entry->d_name);
  1028. // ok, deal with directories and files seperately.
  1029. if( entry->d_type == DT_DIR )
  1030. {
  1031. if( depth == 0)
  1032. continue;
  1033. // filter out dirs we dont want.
  1034. if( !isGoodDirectoryCache(entry) )
  1035. continue;
  1036. // recurse into the dir
  1037. recurseDumpPathCache( pathbuf, fileVector, depth-1);
  1038. }
  1039. else
  1040. {
  1041. //add the file entry to the list
  1042. // unlike recurseDumpDirectories(), we need to return more complex info here.
  1043. //<Mat> commented this out in case we ever want a dir file printout again
  1044. //printf( "File Name: %s ", entry->d_name );
  1045. const U32 fileSize = Platform::getFileSize(pathbuf);
  1046. fileVector.increment();
  1047. Platform::FileInfo& rInfo = fileVector.last();
  1048. rInfo.pFullPath = StringTable->insert(curPath);
  1049. rInfo.pFileName = StringTable->insert(entry->d_name);
  1050. rInfo.fileSize = fileSize;
  1051. }
  1052. }
  1053. closedir(dir);
  1054. return true;
  1055. }
  1056. //-----------------------------------------------------------------------------
  1057. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  1058. {
  1059. if (isCachePath(path))
  1060. {
  1061. PROFILE_START(dumpPath);
  1062. const S32 len = dStrlen(path) + 1;
  1063. char newpath[255];
  1064. strcpy(newpath, path);
  1065. if(newpath[len - 2] == '/')
  1066. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  1067. bool ret = recurseDumpPathCache( newpath, fileVector, depth);
  1068. PROFILE_END();
  1069. return ret;
  1070. }
  1071. PROFILE_START(dumpPath);
  1072. char apath[80];
  1073. if (path[0] == '/')
  1074. {
  1075. strcpy(apath, path+1);
  1076. }
  1077. else
  1078. {
  1079. strcpy(apath, path);
  1080. }
  1081. const S32 len = dStrlen(apath) + 1;
  1082. char newpath[len];
  1083. dSprintf(newpath, len, "%s", apath);
  1084. if(newpath[len - 2] == '/')
  1085. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  1086. bool ret = recurseDumpPath( newpath, fileVector, depth);
  1087. PROFILE_END();
  1088. return ret;
  1089. }
  1090. //-----------------------------------------------------------------------------
  1091. #if defined(TORQUE_DEBUG)
  1092. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  1093. Con::printf("testing %s",argv[1]);
  1094. Platform::addExcludedDirectory(".svn");
  1095. if(Platform::hasSubDirectory(argv[1]))
  1096. Con::printf(" has subdir");
  1097. else
  1098. Con::printf(" does not have subdir");
  1099. }
  1100. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  1101. Vector<StringTableEntry> paths;
  1102. S32 depth = dAtoi(argv[2]);
  1103. Platform::addExcludedDirectory(".svn");
  1104. Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
  1105. Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
  1106. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  1107. Con::printf(*itr);
  1108. }
  1109. }
  1110. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  1111. {
  1112. Vector<Platform::FileInfo> files;
  1113. S32 depth = dAtoi(argv[2]);
  1114. Platform::addExcludedDirectory(".svn");
  1115. Platform::dumpPath(argv[1], files, depth);
  1116. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  1117. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  1118. }
  1119. }
  1120. //-----------------------------------------------------------------------------
  1121. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  1122. {
  1123. return dFileTouch(argv[1]);
  1124. }
  1125. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  1126. {
  1127. FileTime create, modify;
  1128. bool ok;
  1129. ok = Platform::getFileTimes(argv[1],&create, &modify);
  1130. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  1131. return ok;
  1132. }
  1133. #endif