AndroidFileio.cpp 40 KB

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