AndroidFileio.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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. //Checking for . to avoid multiple JNI calls for performance.
  684. if (strstr(path, ".") == NULL)
  685. return false;
  686. return true;
  687. //return android_IsFile(path);
  688. }
  689. //-----------------------------------------------------------------------------
  690. bool Platform::isDirectory(const char *path)
  691. {
  692. if (!path || !*path)
  693. return false;
  694. if (isCachePath(path))
  695. {
  696. // make sure we can stat the file
  697. struct stat statData;
  698. if( stat(path, &statData) < 0 )
  699. return false;
  700. // now see if it's a directory
  701. if( (statData.st_mode & S_IFMT) == S_IFDIR)
  702. return true;
  703. return false;
  704. }
  705. return android_IsDir(path);
  706. }
  707. S32 Platform::getFileSize(const char* pFilePath)
  708. {
  709. if (!pFilePath || !*pFilePath)
  710. return 0;
  711. if (isCachePath(pFilePath))
  712. {
  713. struct stat statData;
  714. if( stat(pFilePath, &statData) < 0 )
  715. return 0;
  716. // and return it's size in bytes
  717. return (S32)statData.st_size;
  718. }
  719. return android_GetFileSize(pFilePath);
  720. }
  721. //-----------------------------------------------------------------------------
  722. bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
  723. {
  724. char fullpath[MAX_MAC_PATH_LONG];
  725. dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
  726. return isDirectory((const char *)fullpath);
  727. }
  728. void getDirectoryName(const char* path, char* name)
  729. {
  730. int cnt = StringUnit::getUnitCount(path, "/");
  731. strcpy(name,StringUnit::getUnit(path, cnt-1, "/"));
  732. }
  733. //-----------------------------------------------------------------------------
  734. // utility for platform::hasSubDirectory() and platform::dumpDirectories()
  735. // ensures that the entry is a directory, and isnt on the ignore lists.
  736. inline bool isGoodDirectory(const char* path)
  737. {
  738. char name[80];
  739. getDirectoryName(path, name);
  740. return (Platform::isDirectory(path) // is a dir
  741. && dStrcmp(name,".") != 0 // not here
  742. && dStrcmp(name,"..") != 0 // not parent
  743. && !Platform::isExcludedDirectory(name)); // not excluded
  744. }
  745. inline bool isGoodDirectoryCache(dirent* entry)
  746. {
  747. return (entry->d_type == DT_DIR // is a dir
  748. && dStrcmp(entry->d_name,".") != 0 // not here
  749. && dStrcmp(entry->d_name,"..") != 0 // not parent
  750. && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
  751. }
  752. //-----------------------------------------------------------------------------
  753. bool Platform::hasSubDirectory(const char *path)
  754. {
  755. if (isCachePath(path))
  756. {
  757. DIR *dir;
  758. dirent *entry;
  759. dir = opendir(path);
  760. if(!dir)
  761. return false; // we got a bad path, so no, it has no subdirectory.
  762. while( true )
  763. {
  764. entry = readdir(dir);
  765. if ( entry == NULL )
  766. break;
  767. if(isGoodDirectoryCache(entry) )
  768. {
  769. closedir(dir);
  770. return true; // we have a subdirectory, that isnt on the exclude list.
  771. }
  772. }
  773. closedir(dir);
  774. return false; // either this dir had no subdirectories, or they were all on the exclude list.
  775. }
  776. android_InitDirList(path);
  777. char dir[80];
  778. char pdir[255];
  779. strcpy(dir,"");
  780. android_GetNextDir(path, dir);
  781. while(strcmp(dir,"") != 0)
  782. {
  783. sprintf(pdir, "%s/%s", path, dir);
  784. if (isGoodDirectory(pdir))
  785. return true;
  786. android_GetNextDir(path, dir);
  787. }
  788. return false;
  789. }
  790. //-----------------------------------------------------------------------------
  791. /*bool recurseDumpDirectories(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  792. {
  793. char aPath[80];
  794. if (basePath[0] == '/')
  795. {
  796. strcpy(aPath, basePath+1);
  797. }
  798. else
  799. {
  800. strcpy(aPath, basePath);
  801. }
  802. const U32 len = dStrlen(aPath) + dStrlen(path) + 2;
  803. char pathbuf[len];
  804. // construct the file path
  805. if (strcmp(path,"") != 0)
  806. dSprintf(pathbuf, len, "%s/%s", aPath, path);
  807. else
  808. strcpy(pathbuf, aPath);
  809. // be sure it opens.
  810. android_InitDirList(pathbuf);
  811. // look inside the current directory
  812. char dir[80];
  813. char pdir[255];
  814. strcpy(dir,"");
  815. android_GetNextDir(pathbuf, dir);
  816. while(strcmp(dir,"") != 0)
  817. {
  818. sprintf(pdir, "%s/%s", pathbuf, dir);
  819. if (!isGoodDirectory(pdir))
  820. return false;
  821. // construct the new path string, we'll need this below.
  822. const U32 newpathlen = dStrlen(path) + dStrlen(dir) + 2;
  823. char newpath[newpathlen];
  824. if(dStrlen(path) > 0)
  825. {
  826. dSprintf(newpath, newpathlen, "%s/%s", path, dir);
  827. }
  828. else
  829. {
  830. dSprintf(newpath, newpathlen, "%s", dir);
  831. }
  832. // we have a directory, add it to the list.
  833. if( noBasePath )
  834. {
  835. directoryVector.push_back(StringTable->insert(newpath));
  836. }
  837. else
  838. {
  839. const U32 fullpathlen = dStrlen(aPath) + dStrlen(newpath) + 2;
  840. char fullpath[fullpathlen];
  841. dSprintf(fullpath, fullpathlen, "%s/%s",aPath,newpath);
  842. directoryVector.push_back(StringTable->insert(fullpath));
  843. }
  844. // and recurse into it, unless we've run out of depth
  845. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  846. recurseDumpDirectories(aPath, newpath, directoryVector, depth-1, noBasePath);
  847. android_GetNextDir(pathbuf, dir);
  848. }
  849. return true;
  850. }*/
  851. //-----------------------------------------------------------------------------
  852. bool recurseDumpDirectoriesCache(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  853. {
  854. DIR *dir;
  855. dirent *entry;
  856. const U32 len = dStrlen(basePath) + dStrlen(path) + 2;
  857. char pathbuf[len];
  858. // construct the file path
  859. dSprintf(pathbuf, len, "%s/%s", basePath, path);
  860. // be sure it opens.
  861. dir = opendir(pathbuf);
  862. if(!dir)
  863. return false;
  864. // look inside the current directory
  865. while( true )
  866. {
  867. entry = readdir(dir);
  868. if ( entry == NULL )
  869. break;
  870. // we just want directories.
  871. if(!isGoodDirectoryCache(entry))
  872. continue;
  873. // TODO: better unicode file name handling
  874. // // Apple's file system stores unicode file names in decomposed form.
  875. // // ATSUI will not reliably draw out just the accent character by itself,
  876. // // so our text renderer has no chance of rendering decomposed form unicode.
  877. // // We have to convert the entry name to precomposed normalized form.
  878. // CFStringRef cfdname = CFStringCreateWithCString(NULL,entry->d_name,kCFStringEncodingUTF8);
  879. // CFMutableStringRef cfentryName = CFStringCreateMutableCopy(NULL,0,cfdname);
  880. // CFStringNormalize(cfentryName,kCFStringNormalizationFormC);
  881. //
  882. // U32 entryNameLen = CFStringGetLength(cfentryName) * 4 + 1;
  883. // char entryName[entryNameLen];
  884. // CFStringGetCString(cfentryName, entryName, entryNameLen, kCFStringEncodingUTF8);
  885. // entryName[entryNameLen-1] = NULL; // sometimes, CFStringGetCString() doesn't null terminate.
  886. // CFRelease(cfentryName);
  887. // CFRelease(cfdname);
  888. // construct the new path string, we'll need this below.
  889. const U32 newpathlen = dStrlen(path) + dStrlen(entry->d_name) + 2;
  890. char newpath[newpathlen];
  891. if(dStrlen(path) > 0)
  892. {
  893. dSprintf(newpath, newpathlen, "%s/%s", path, entry->d_name);
  894. }
  895. else
  896. {
  897. dSprintf(newpath, newpathlen, "%s", entry->d_name);
  898. }
  899. // we have a directory, add it to the list.
  900. if( noBasePath )
  901. {
  902. directoryVector.push_back(StringTable->insert(newpath));
  903. }
  904. else
  905. {
  906. const U32 fullpathlen = dStrlen(basePath) + dStrlen(newpath) + 2;
  907. char fullpath[fullpathlen];
  908. dSprintf(fullpath, fullpathlen, "%s/%s",basePath,newpath);
  909. directoryVector.push_back(StringTable->insert(fullpath));
  910. }
  911. // and recurse into it, unless we've run out of depth
  912. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  913. recurseDumpDirectoriesCache(basePath, newpath, directoryVector, depth-1, noBasePath);
  914. }
  915. closedir(dir);
  916. return true;
  917. }
  918. //-----------------------------------------------------------------------------
  919. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  920. {
  921. if (isCachePath(path))
  922. {
  923. PROFILE_START(dumpDirectories);
  924. ResourceManager->initExcludedDirectories();
  925. const S32 len = dStrlen(path)+1;
  926. char newpath[len];
  927. dSprintf(newpath, len, "%s", path);
  928. if(newpath[len - 1] == '/')
  929. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  930. // Insert base path to follow what Windows does.
  931. if ( !noBasePath )
  932. directoryVector.push_back(StringTable->insert(newpath));
  933. bool ret = recurseDumpDirectoriesCache(newpath, "", directoryVector, depth, noBasePath);
  934. PROFILE_END();
  935. return ret;
  936. }
  937. PROFILE_START(dumpDirectories);
  938. ResourceManager->initExcludedDirectories();
  939. bool ret = android_DumpDirectories(path, "", directoryVector, depth, noBasePath);
  940. PROFILE_END();
  941. return ret;
  942. }
  943. //-----------------------------------------------------------------------------
  944. /*static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  945. {
  946. android_InitDirList(curPath);
  947. // look inside the current directory
  948. char dir[80];
  949. char file[80];
  950. strcpy(dir,"");
  951. strcpy(file,"");
  952. android_GetNextDir(curPath, dir);
  953. android_GetNextFile(curPath, file);
  954. while(strcmp(file,"") != 0)
  955. {
  956. // construct the full file path. we need this to get the file size and to recurse
  957. const U32 len = dStrlen(curPath) + dStrlen(file) + 2;
  958. char pathbuf[len];
  959. dSprintf( pathbuf, len, "%s/%s", curPath, file);
  960. //add the file entry to the list
  961. // unlike recurseDumpDirectories(), we need to return more complex info here.
  962. //<Mat> commented this out in case we ever want a dir file printout again
  963. //printf( "File Name: %s ", entry->d_name );
  964. const U32 fileSize = Platform::getFileSize(pathbuf);
  965. fileVector.increment();
  966. Platform::FileInfo& rInfo = fileVector.last();
  967. rInfo.pFullPath = StringTable->insert(curPath);
  968. rInfo.pFileName = StringTable->insert(file);
  969. rInfo.fileSize = fileSize;
  970. android_GetNextFile(curPath, file);
  971. }
  972. while(strcmp(dir,"") != 0)
  973. {
  974. // construct the full file path. we need this to get the file size and to recurse
  975. const U32 len = dStrlen(curPath) + dStrlen(dir) + 2;
  976. char pathbuf[len];
  977. if (strcmp(curPath,"") == 0)
  978. dSprintf( pathbuf, len, "%s", dir);
  979. else
  980. dSprintf( pathbuf, len, "%s/%s", curPath, dir);
  981. if( depth == 0)
  982. {
  983. android_GetNextDir(curPath, dir);
  984. continue;
  985. }
  986. // filter out dirs we dont want.
  987. if( !isGoodDirectory(pathbuf) )
  988. {
  989. android_GetNextDir(curPath, dir);
  990. continue;
  991. }
  992. // recurse into the dir
  993. recurseDumpPath( pathbuf, fileVector, depth-1);
  994. android_GetNextDir(curPath, dir);
  995. }
  996. return true;
  997. }*/
  998. //-----------------------------------------------------------------------------
  999. static bool recurseDumpPathCache(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  1000. {
  1001. DIR *dir;
  1002. dirent *entry;
  1003. // be sure it opens.
  1004. dir = opendir(curPath);
  1005. if(!dir)
  1006. return false;
  1007. // look inside the current directory
  1008. while( true )
  1009. {
  1010. entry = readdir(dir);
  1011. if ( entry == NULL )
  1012. break;
  1013. // construct the full file path. we need this to get the file size and to recurse
  1014. const U32 len = dStrlen(curPath) + entry->d_reclen + 2;
  1015. char pathbuf[255];
  1016. sprintf( pathbuf, "%s/%s", curPath, entry->d_name);
  1017. // ok, deal with directories and files seperately.
  1018. if( entry->d_type == DT_DIR )
  1019. {
  1020. if( depth == 0)
  1021. continue;
  1022. // filter out dirs we dont want.
  1023. if( !isGoodDirectoryCache(entry) )
  1024. continue;
  1025. // recurse into the dir
  1026. recurseDumpPathCache( pathbuf, fileVector, depth-1);
  1027. }
  1028. else
  1029. {
  1030. //add the file entry to the list
  1031. // unlike recurseDumpDirectories(), we need to return more complex info here.
  1032. //<Mat> commented this out in case we ever want a dir file printout again
  1033. //printf( "File Name: %s ", entry->d_name );
  1034. const U32 fileSize = Platform::getFileSize(pathbuf);
  1035. fileVector.increment();
  1036. Platform::FileInfo& rInfo = fileVector.last();
  1037. rInfo.pFullPath = StringTable->insert(curPath);
  1038. rInfo.pFileName = StringTable->insert(entry->d_name);
  1039. rInfo.fileSize = fileSize;
  1040. }
  1041. }
  1042. closedir(dir);
  1043. return true;
  1044. }
  1045. //-----------------------------------------------------------------------------
  1046. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  1047. {
  1048. if (isCachePath(path))
  1049. {
  1050. PROFILE_START(dumpPath);
  1051. const S32 len = dStrlen(path) + 1;
  1052. char newpath[255];
  1053. strcpy(newpath, path);
  1054. if(newpath[len - 2] == '/')
  1055. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  1056. bool ret = recurseDumpPathCache( newpath, fileVector, depth);
  1057. PROFILE_END();
  1058. return ret;
  1059. }
  1060. PROFILE_START(dumpPath);
  1061. bool ret = android_DumpPath( path, fileVector, depth);
  1062. PROFILE_END();
  1063. return ret;
  1064. }
  1065. //-----------------------------------------------------------------------------
  1066. #if defined(TORQUE_DEBUG)
  1067. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  1068. Con::printf("testing %s",argv[1]);
  1069. Platform::addExcludedDirectory(".svn");
  1070. if(Platform::hasSubDirectory(argv[1]))
  1071. Con::printf(" has subdir");
  1072. else
  1073. Con::printf(" does not have subdir");
  1074. }
  1075. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  1076. Vector<StringTableEntry> paths;
  1077. S32 depth = dAtoi(argv[2]);
  1078. Platform::addExcludedDirectory(".svn");
  1079. Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
  1080. Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
  1081. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  1082. Con::printf(*itr);
  1083. }
  1084. }
  1085. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  1086. {
  1087. Vector<Platform::FileInfo> files;
  1088. S32 depth = dAtoi(argv[2]);
  1089. Platform::addExcludedDirectory(".svn");
  1090. Platform::dumpPath(argv[1], files, depth);
  1091. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  1092. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  1093. }
  1094. }
  1095. //-----------------------------------------------------------------------------
  1096. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  1097. {
  1098. return dFileTouch(argv[1]);
  1099. }
  1100. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  1101. {
  1102. FileTime create, modify;
  1103. bool ok;
  1104. ok = Platform::getFileTimes(argv[1],&create, &modify);
  1105. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  1106. return ok;
  1107. }
  1108. #endif