AndroidFileio.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 "console/console.h"
  28. #include "debug/profiler.h"
  29. #include "io/resource/resourceManager.h"
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <errno.h>
  33. #include <utime.h>
  34. #include <sys/types.h>
  35. #include <dirent.h>
  36. #include <unistd.h>
  37. #include <sys/stat.h>
  38. #include <sys/time.h>
  39. //TODO: file io still needs some work...
  40. #define MAX_MAC_PATH_LONG 2048
  41. //-----------------------------------------------------------------------------
  42. bool Platform::fileDelete(const char * name)
  43. {
  44. if(!name )
  45. return(false);
  46. if (dStrlen(name) > MAX_MAC_PATH_LONG)
  47. Con::warnf("Platform::FileDelete() - Filename length is pretty long...");
  48. return(remove(name) == 0); // remove returns 0 on success
  49. }
  50. //-----------------------------------------------------------------------------
  51. bool dFileTouch(const char *path)
  52. {
  53. if (!path || !*path)
  54. return false;
  55. // set file at path's modification and access times to now.
  56. return( utimes( path, NULL) == 0); // utimes returns 0 on success.
  57. }
  58. //-----------------------------------------------------------------------------
  59. // Constructors & Destructor
  60. //-----------------------------------------------------------------------------
  61. //-----------------------------------------------------------------------------
  62. // After construction, the currentStatus will be Closed and the capabilities
  63. // will be 0.
  64. //-----------------------------------------------------------------------------
  65. File::File()
  66. : currentStatus(Closed), capability(0)
  67. {
  68. handle = NULL;
  69. }
  70. //-----------------------------------------------------------------------------
  71. // insert a copy constructor here... (currently disabled)
  72. //-----------------------------------------------------------------------------
  73. //-----------------------------------------------------------------------------
  74. // Destructor
  75. //-----------------------------------------------------------------------------
  76. File::~File()
  77. {
  78. close();
  79. handle = NULL;
  80. }
  81. //-----------------------------------------------------------------------------
  82. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  83. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  84. // true.
  85. //
  86. // Sets capability appropriate to the openMode.
  87. // Returns the currentStatus of the file.
  88. //-----------------------------------------------------------------------------
  89. File::Status File::open(const char *filename, const AccessMode openMode)
  90. {
  91. if (dStrlen(filename) > MAX_MAC_PATH_LONG)
  92. Con::warnf("File::open: Filename length is pretty long...");
  93. // Close the file if it was already open...
  94. if (currentStatus != Closed)
  95. close();
  96. // create the appropriate type of file...
  97. switch (openMode)
  98. {
  99. case Read:
  100. handle = (void *)fopen(filename, "rb"); // read only
  101. break;
  102. case Write:
  103. handle = (void *)fopen(filename, "wb"); // write only
  104. break;
  105. case ReadWrite:
  106. handle = (void *)fopen(filename, "ab+"); // write(append) and read
  107. break;
  108. case WriteAppend:
  109. handle = (void *)fopen(filename, "ab"); // write(append) only
  110. break;
  111. default:
  112. AssertFatal(false, "File::open: bad access mode");
  113. }
  114. // handle not created successfully
  115. if (handle == NULL)
  116. return setStatus();
  117. // successfully created file, so set the file capabilities...
  118. switch (openMode)
  119. {
  120. case Read:
  121. capability = FileRead;
  122. break;
  123. case Write:
  124. case WriteAppend:
  125. capability = FileWrite;
  126. break;
  127. case ReadWrite:
  128. capability = FileRead | FileWrite;
  129. break;
  130. default:
  131. AssertFatal(false, "File::open: bad access mode");
  132. }
  133. // must set the file status before setting the position.
  134. currentStatus = Ok;
  135. if (openMode == ReadWrite)
  136. setPosition(0);
  137. // success!
  138. return currentStatus;
  139. }
  140. //-----------------------------------------------------------------------------
  141. // Get the current position of the file pointer.
  142. //-----------------------------------------------------------------------------
  143. U32 File::getPosition() const
  144. {
  145. AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
  146. AssertFatal(handle != NULL, "File::getPosition: invalid file handle");
  147. return ftell((FILE*)handle);
  148. }
  149. //-----------------------------------------------------------------------------
  150. // Set the position of the file pointer.
  151. // Absolute and relative positioning is supported via the absolutePos
  152. // parameter.
  153. //
  154. // If positioning absolutely, position MUST be positive - an IOError results if
  155. // position is negative.
  156. // Position can be negative if positioning relatively, however positioning
  157. // before the start of the file is an IOError.
  158. //
  159. // Returns the currentStatus of the file.
  160. //-----------------------------------------------------------------------------
  161. File::Status File::setPosition(S32 position, bool absolutePos)
  162. {
  163. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  164. AssertFatal(handle != NULL, "File::setPosition: invalid file handle");
  165. if (currentStatus != Ok && currentStatus != EOS )
  166. return currentStatus;
  167. U32 finalPos;
  168. if(absolutePos)
  169. {
  170. // absolute position
  171. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  172. // position beyond EOS is OK
  173. fseek((FILE*)handle, position, SEEK_SET);
  174. finalPos = ftell((FILE*)handle);
  175. }
  176. else
  177. {
  178. // relative position
  179. AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
  180. // position beyond EOS is OK
  181. fseek((FILE*)handle, position, SEEK_CUR);
  182. finalPos = ftell((FILE*)handle);
  183. }
  184. // ftell returns -1 on error. set error status
  185. if (0xffffffff == finalPos)
  186. return setStatus();
  187. // success, at end of file
  188. else if (finalPos >= getSize())
  189. return currentStatus = EOS;
  190. // success!
  191. else
  192. return currentStatus = Ok;
  193. }
  194. //-----------------------------------------------------------------------------
  195. // Get the size of the file in bytes.
  196. // It is an error to query the file size for a Closed file, or for one with an
  197. // error status.
  198. //-----------------------------------------------------------------------------
  199. U32 File::getSize() const
  200. {
  201. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  202. AssertFatal(handle != NULL, "File::getSize: invalid file handle");
  203. if (Ok == currentStatus || EOS == currentStatus)
  204. {
  205. struct stat statData;
  206. if(fstat(fileno((FILE*)handle), &statData) != 0)
  207. return 0;
  208. // return the size in bytes
  209. return statData.st_size;
  210. }
  211. return 0;
  212. }
  213. //-----------------------------------------------------------------------------
  214. // Flush the file.
  215. // It is an error to flush a read-only file.
  216. // Returns the currentStatus of the file.
  217. //-----------------------------------------------------------------------------
  218. File::Status File::flush()
  219. {
  220. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  221. AssertFatal(handle != NULL, "File::flush: invalid file handle");
  222. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  223. if (fflush((FILE*)handle) != 0)
  224. return setStatus();
  225. else
  226. return currentStatus = Ok;
  227. }
  228. //-----------------------------------------------------------------------------
  229. // Close the File.
  230. //
  231. // Returns the currentStatus
  232. //-----------------------------------------------------------------------------
  233. File::Status File::close()
  234. {
  235. // check if it's already closed...
  236. if (Closed == currentStatus)
  237. return currentStatus;
  238. // it's not, so close it...
  239. if (handle != NULL)
  240. {
  241. if (fclose((FILE*)handle) != 0)
  242. return setStatus();
  243. }
  244. handle = NULL;
  245. return currentStatus = Closed;
  246. }
  247. //-----------------------------------------------------------------------------
  248. // Self-explanatory.
  249. //-----------------------------------------------------------------------------
  250. File::Status File::getStatus() const
  251. {
  252. return currentStatus;
  253. }
  254. //-----------------------------------------------------------------------------
  255. // Sets and returns the currentStatus when an error has been encountered.
  256. //-----------------------------------------------------------------------------
  257. File::Status File::setStatus()
  258. {
  259. switch (errno)
  260. {
  261. case EACCES: // permission denied
  262. currentStatus = IOError;
  263. break;
  264. case EBADF: // Bad File Pointer
  265. case EINVAL: // Invalid argument
  266. case ENOENT: // file not found
  267. case ENAMETOOLONG:
  268. default:
  269. currentStatus = UnknownError;
  270. }
  271. return currentStatus;
  272. }
  273. //-----------------------------------------------------------------------------
  274. // Sets and returns the currentStatus to status.
  275. //-----------------------------------------------------------------------------
  276. File::Status File::setStatus(File::Status status)
  277. {
  278. return currentStatus = status;
  279. }
  280. //-----------------------------------------------------------------------------
  281. // Read from a file.
  282. // The number of bytes to read is passed in size, the data is returned in src.
  283. // The number of bytes read is available in bytesRead if a non-Null pointer is
  284. // provided.
  285. //-----------------------------------------------------------------------------
  286. File::Status File::read(U32 size, char *dst, U32 *bytesRead)
  287. {
  288. AssertFatal(Closed != currentStatus, "File::read: file closed");
  289. AssertFatal(handle != NULL, "File::read: invalid file handle");
  290. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  291. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  292. AssertWarn(0 != size, "File::read: size of zero");
  293. if (Ok != currentStatus || 0 == size)
  294. return currentStatus;
  295. // read from stream
  296. U32 nBytes = fread(dst, 1, size, (FILE*)handle);
  297. // did we hit the end of the stream?
  298. if( nBytes != size)
  299. currentStatus = EOS;
  300. // if bytesRead is a valid pointer, send number of bytes read there.
  301. if(bytesRead)
  302. *bytesRead = nBytes;
  303. // successfully read size bytes
  304. return currentStatus;
  305. }
  306. //-----------------------------------------------------------------------------
  307. // Write to a file.
  308. // The number of bytes to write is passed in size, the data is passed in src.
  309. // The number of bytes written is available in bytesWritten if a non-Null
  310. // pointer is provided.
  311. //-----------------------------------------------------------------------------
  312. File::Status File::write(U32 size, const char *src, U32 *bytesWritten)
  313. {
  314. AssertFatal(Closed != currentStatus, "File::write: file closed");
  315. AssertFatal(handle != NULL, "File::write: invalid file handle");
  316. AssertFatal(NULL != src, "File::write: NULL source pointer");
  317. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  318. AssertWarn(0 != size, "File::write: size of zero");
  319. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  320. return currentStatus;
  321. // write bytes to the stream
  322. U32 nBytes = fwrite(src, 1, size,(FILE*)handle);
  323. // if we couldn't write everything, we've got a problem. set error status.
  324. if(nBytes != size)
  325. setStatus();
  326. // if bytesWritten is a valid pointer, put number of bytes read there.
  327. if(bytesWritten)
  328. *bytesWritten = nBytes;
  329. // return current File status, whether good or ill.
  330. return currentStatus;
  331. }
  332. //-----------------------------------------------------------------------------
  333. // Self-explanatory.
  334. //-----------------------------------------------------------------------------
  335. bool File::hasCapability(Capability cap) const
  336. {
  337. return (0 != (U32(cap) & capability));
  338. }
  339. //-----------------------------------------------------------------------------
  340. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  341. {
  342. if(a > b)
  343. return 1;
  344. if(a < b)
  345. return -1;
  346. return 0;
  347. }
  348. //-----------------------------------------------------------------------------
  349. // either time param COULD be null.
  350. //-----------------------------------------------------------------------------
  351. bool Platform::getFileTimes(const char *path, FileTime *createTime, FileTime *modifyTime)
  352. {
  353. // MacOSX is NOT guaranteed to be running off a HFS volume,
  354. // and UNIX does not keep a record of a file's creation time anywhere.
  355. // So instead of creation time we return changed time,
  356. // just like the Linux platform impl does.
  357. if (!path || !*path)
  358. return false;
  359. struct stat statData;
  360. if (stat(path, &statData) == -1)
  361. return false;
  362. if(createTime)
  363. *createTime = statData.st_ctime;
  364. if(modifyTime)
  365. *modifyTime = statData.st_mtime;
  366. return true;
  367. }
  368. //-----------------------------------------------------------------------------
  369. bool Platform::createPath(const char *file)
  370. {
  371. //<Mat> needless console noise
  372. //Con::warnf("creating path %s",file);
  373. // if the path exists, we're done.
  374. struct stat statData;
  375. if( stat(file, &statData) == 0 )
  376. {
  377. return true; // exists, rejoice.
  378. }
  379. // get the parent path.
  380. // we're not using basename because it's not thread safe.
  381. const U32 len = dStrlen(file) + 1;
  382. char parent[len];
  383. bool isDirPath = false;
  384. dSprintf(parent, len, "%s", file);
  385. if(parent[len - 2] == '/')
  386. {
  387. parent[len - 2] = '\0'; // cut off the trailing slash, if there is one
  388. isDirPath = true; // we got a trailing slash, so file is a directory.
  389. }
  390. // recusively create the parent path.
  391. // only recurse if newpath has a slash that isn't a leading slash.
  392. char *slash = dStrrchr(parent,'/');
  393. if( slash && slash != parent)
  394. {
  395. // snip the path just after the last slash.
  396. slash[1] = '\0';
  397. // recusively create the parent path. fail if parent path creation failed.
  398. if(!Platform::createPath(parent))
  399. return false;
  400. }
  401. // create *file if it is a directory path.
  402. if(isDirPath)
  403. {
  404. // try to create the directory
  405. if( mkdir(file, 0777) != 0) // app may reside in global apps dir, and so must be writable to all.
  406. return false;
  407. }
  408. return true;
  409. }
  410. #pragma mark ---- Directories ----
  411. //-----------------------------------------------------------------------------
  412. StringTableEntry Platform::getCurrentDirectory()
  413. {
  414. // get the current directory, the one that would be opened if we did a fopen(".")
  415. char* cwd = getcwd(NULL, 0);
  416. StringTableEntry ret = StringTable->insert(cwd);
  417. free(cwd);
  418. return ret;
  419. }
  420. //-----------------------------------------------------------------------------
  421. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  422. {
  423. return (chdir(newDir) == 0);
  424. }
  425. //-----------------------------------------------------------------------------
  426. void Platform::openFolder(const char* path )
  427. {
  428. // TODO: users can still run applications by calling openfolder on an app bundle.
  429. // this may be a bad thing.
  430. if(!Platform::isDirectory(path))
  431. {
  432. Con::errorf(avar("Error: not a directory: %s",path));
  433. return;
  434. }
  435. const char* arg = avar("open '%s'", path);
  436. U32 ret = system(arg);
  437. if(ret != 0)
  438. Con::printf(strerror(errno));
  439. }
  440. static bool isMainDotCsPresent(char *dir)
  441. {
  442. char maincsbuf[MAX_MAC_PATH_LONG];
  443. const char *maincsname = "/main.cs";
  444. const U32 len = dStrlen(dir) + dStrlen(maincsname)+1;
  445. AssertISV(len < MAX_MAC_PATH_LONG, "Sorry, path is too long, I can't run from this folder.");
  446. dSprintf(maincsbuf,MAX_MAC_PATH_LONG,"%s%s", dir, maincsname);
  447. return Platform::isFile(maincsbuf);
  448. }
  449. //-----------------------------------------------------------------------------
  450. /// Finds and sets the current working directory.
  451. /// Torque tries to automatically detect whether you have placed the game files
  452. /// inside or outside the application's bundle. It checks for the presence of
  453. /// the file 'main.cs'. If it finds it, Torque will assume that the other game
  454. /// files are there too. If Torque does not see 'main.cs' inside its bundle, it
  455. /// will assume the files are outside the bundle.
  456. /// Since you probably don't want to copy the game files into the app every time
  457. /// you build, you will want to leave them outside the bundle for development.
  458. ///
  459. /// Android reads all assets out of compressed bundle so we dont realy have an executable path
  460. StringTableEntry Platform::getExecutablePath()
  461. {
  462. if(platState.mainDotCsDir)
  463. return platState.mainDotCsDir;
  464. char* ret = NULL;
  465. if(StringTable)
  466. platState.mainDotCsDir = StringTable->insert(".");
  467. else
  468. ret = dStrdup(".");
  469. return ret ? ret : platState.mainDotCsDir;
  470. }
  471. //-----------------------------------------------------------------------------
  472. StringTableEntry Platform::getExecutableName()
  473. {
  474. //TODO: does this need anything further?
  475. return StringTable->insert("Torque2D");
  476. }
  477. //-----------------------------------------------------------------------------
  478. bool Platform::isFile(const char *path)
  479. {
  480. if (!path || !*path)
  481. return false;
  482. // make sure we can stat the file
  483. struct stat statData;
  484. if( stat(path, &statData) < 0 )
  485. return false;
  486. // now see if it's a regular file
  487. if( (statData.st_mode & S_IFMT) == S_IFREG)
  488. return true;
  489. return false;
  490. }
  491. //-----------------------------------------------------------------------------
  492. bool Platform::isDirectory(const char *path)
  493. {
  494. if (!path || !*path)
  495. return false;
  496. // make sure we can stat the file
  497. struct stat statData;
  498. if( stat(path, &statData) < 0 )
  499. return false;
  500. // now see if it's a directory
  501. if( (statData.st_mode & S_IFMT) == S_IFDIR)
  502. return true;
  503. return false;
  504. }
  505. S32 Platform::getFileSize(const char* pFilePath)
  506. {
  507. if (!pFilePath || !*pFilePath)
  508. return 0;
  509. struct stat statData;
  510. if( stat(pFilePath, &statData) < 0 )
  511. return 0;
  512. // and return it's size in bytes
  513. return (S32)statData.st_size;
  514. }
  515. //-----------------------------------------------------------------------------
  516. bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
  517. {
  518. char fullpath[MAX_MAC_PATH_LONG];
  519. dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
  520. return isDirectory((const char *)fullpath);
  521. }
  522. //-----------------------------------------------------------------------------
  523. // utility for platform::hasSubDirectory() and platform::dumpDirectories()
  524. // ensures that the entry is a directory, and isnt on the ignore lists.
  525. inline bool isGoodDirectory(dirent* entry)
  526. {
  527. return (entry->d_type == DT_DIR // is a dir
  528. && dStrcmp(entry->d_name,".") != 0 // not here
  529. && dStrcmp(entry->d_name,"..") != 0 // not parent
  530. && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
  531. }
  532. //-----------------------------------------------------------------------------
  533. bool Platform::hasSubDirectory(const char *path)
  534. {
  535. DIR *dir;
  536. dirent *entry;
  537. dir = opendir(path);
  538. if(!dir)
  539. return false; // we got a bad path, so no, it has no subdirectory.
  540. while( true )
  541. {
  542. entry = readdir(dir);
  543. if ( entry == NULL )
  544. break;
  545. if(isGoodDirectory(entry) )
  546. {
  547. closedir(dir);
  548. return true; // we have a subdirectory, that isnt on the exclude list.
  549. }
  550. }
  551. closedir(dir);
  552. return false; // either this dir had no subdirectories, or they were all on the exclude list.
  553. }
  554. //-----------------------------------------------------------------------------
  555. bool recurseDumpDirectories(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  556. {
  557. DIR *dir;
  558. dirent *entry;
  559. const U32 len = dStrlen(basePath) + dStrlen(path) + 2;
  560. char pathbuf[len];
  561. // construct the file path
  562. dSprintf(pathbuf, len, "%s/%s", basePath, path);
  563. // be sure it opens.
  564. dir = opendir(pathbuf);
  565. if(!dir)
  566. return false;
  567. // look inside the current directory
  568. while( true )
  569. {
  570. entry = readdir(dir);
  571. if ( entry == NULL )
  572. break;
  573. // we just want directories.
  574. if(!isGoodDirectory(entry))
  575. continue;
  576. // TODO: better unicode file name handling
  577. // // Apple's file system stores unicode file names in decomposed form.
  578. // // ATSUI will not reliably draw out just the accent character by itself,
  579. // // so our text renderer has no chance of rendering decomposed form unicode.
  580. // // We have to convert the entry name to precomposed normalized form.
  581. // CFStringRef cfdname = CFStringCreateWithCString(NULL,entry->d_name,kCFStringEncodingUTF8);
  582. // CFMutableStringRef cfentryName = CFStringCreateMutableCopy(NULL,0,cfdname);
  583. // CFStringNormalize(cfentryName,kCFStringNormalizationFormC);
  584. //
  585. // U32 entryNameLen = CFStringGetLength(cfentryName) * 4 + 1;
  586. // char entryName[entryNameLen];
  587. // CFStringGetCString(cfentryName, entryName, entryNameLen, kCFStringEncodingUTF8);
  588. // entryName[entryNameLen-1] = NULL; // sometimes, CFStringGetCString() doesn't null terminate.
  589. // CFRelease(cfentryName);
  590. // CFRelease(cfdname);
  591. // construct the new path string, we'll need this below.
  592. const U32 newpathlen = dStrlen(path) + dStrlen(entry->d_name) + 2;
  593. char newpath[newpathlen];
  594. if(dStrlen(path) > 0)
  595. {
  596. dSprintf(newpath, newpathlen, "%s/%s", path, entry->d_name);
  597. }
  598. else
  599. {
  600. dSprintf(newpath, newpathlen, "%s", entry->d_name);
  601. }
  602. // we have a directory, add it to the list.
  603. if( noBasePath )
  604. {
  605. directoryVector.push_back(StringTable->insert(newpath));
  606. }
  607. else
  608. {
  609. const U32 fullpathlen = dStrlen(basePath) + dStrlen(newpath) + 2;
  610. char fullpath[fullpathlen];
  611. dSprintf(fullpath, fullpathlen, "%s/%s",basePath,newpath);
  612. directoryVector.push_back(StringTable->insert(fullpath));
  613. }
  614. // and recurse into it, unless we've run out of depth
  615. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  616. recurseDumpDirectories(basePath, newpath, directoryVector, depth-1, noBasePath);
  617. }
  618. closedir(dir);
  619. return true;
  620. }
  621. //-----------------------------------------------------------------------------
  622. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  623. {
  624. PROFILE_START(dumpDirectories);
  625. ResourceManager->initExcludedDirectories();
  626. const S32 len = dStrlen(path)+1;
  627. char newpath[len];
  628. dSprintf(newpath, len, "%s", path);
  629. if(newpath[len - 1] == '/')
  630. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  631. // Insert base path to follow what Windows does.
  632. if ( !noBasePath )
  633. directoryVector.push_back(StringTable->insert(newpath));
  634. bool ret = recurseDumpDirectories(newpath, "", directoryVector, depth, noBasePath);
  635. PROFILE_END();
  636. return ret;
  637. }
  638. //-----------------------------------------------------------------------------
  639. static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  640. {
  641. DIR *dir;
  642. dirent *entry;
  643. // be sure it opens.
  644. dir = opendir(curPath);
  645. if(!dir)
  646. return false;
  647. // look inside the current directory
  648. while( true )
  649. {
  650. entry = readdir(dir);
  651. if ( entry == NULL )
  652. break;
  653. // construct the full file path. we need this to get the file size and to recurse
  654. //TODO: android
  655. const U32 len = 0;//dStrlen(curPath) + entry->d_namlen + 2;
  656. char pathbuf[len];
  657. dSprintf( pathbuf, len, "%s/%s", curPath, entry->d_name);
  658. // ok, deal with directories and files seperately.
  659. if( entry->d_type == DT_DIR )
  660. {
  661. if( depth == 0)
  662. continue;
  663. // filter out dirs we dont want.
  664. if( !isGoodDirectory(entry) )
  665. continue;
  666. // recurse into the dir
  667. recurseDumpPath( pathbuf, fileVector, depth-1);
  668. }
  669. else
  670. {
  671. //add the file entry to the list
  672. // unlike recurseDumpDirectories(), we need to return more complex info here.
  673. //<Mat> commented this out in case we ever want a dir file printout again
  674. //printf( "File Name: %s ", entry->d_name );
  675. const U32 fileSize = Platform::getFileSize(pathbuf);
  676. fileVector.increment();
  677. Platform::FileInfo& rInfo = fileVector.last();
  678. rInfo.pFullPath = StringTable->insert(curPath);
  679. rInfo.pFileName = StringTable->insert(entry->d_name);
  680. rInfo.fileSize = fileSize;
  681. }
  682. }
  683. closedir(dir);
  684. return true;
  685. }
  686. //-----------------------------------------------------------------------------
  687. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  688. {
  689. PROFILE_START(dumpPath);
  690. const S32 len = dStrlen(path) + 1;
  691. char newpath[len];
  692. dSprintf(newpath, len, "%s", path);
  693. if(newpath[len - 2] == '/')
  694. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  695. bool ret = recurseDumpPath( newpath, fileVector, depth);
  696. PROFILE_END();
  697. return ret;
  698. }
  699. //-----------------------------------------------------------------------------
  700. #if defined(TORQUE_DEBUG)
  701. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  702. Con::printf("testing %s",argv[1]);
  703. Platform::addExcludedDirectory(".svn");
  704. if(Platform::hasSubDirectory(argv[1]))
  705. Con::printf(" has subdir");
  706. else
  707. Con::printf(" does not have subdir");
  708. }
  709. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  710. Vector<StringTableEntry> paths;
  711. S32 depth = dAtoi(argv[2]);
  712. Platform::addExcludedDirectory(".svn");
  713. Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
  714. Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
  715. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  716. Con::printf(*itr);
  717. }
  718. }
  719. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  720. {
  721. Vector<Platform::FileInfo> files;
  722. S32 depth = dAtoi(argv[2]);
  723. Platform::addExcludedDirectory(".svn");
  724. Platform::dumpPath(argv[1], files, depth);
  725. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  726. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  727. }
  728. }
  729. //-----------------------------------------------------------------------------
  730. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  731. {
  732. return dFileTouch(argv[1]);
  733. }
  734. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  735. {
  736. FileTime create, modify;
  737. bool ok;
  738. ok = Platform::getFileTimes(argv[1],&create, &modify);
  739. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  740. return ok;
  741. }
  742. #endif