2
0

AndroidFileio.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. /// Placing all content inside the application bundle gives a much better user
  460. /// experience when you distribute your app.
  461. StringTableEntry Platform::getExecutablePath()
  462. {
  463. if(platState.mainDotCsDir)
  464. return platState.mainDotCsDir;
  465. char cwd_buf[MAX_MAC_PATH_LONG];
  466. //TODO: android
  467. /*
  468. CFBundleRef mainBundle = CFBundleGetMainBundle();
  469. CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
  470. bool inside = true;
  471. bool outside = false;
  472. bool done = false;
  473. while(!done)
  474. {
  475. // first look for game content inside the application bundle.
  476. // then we look outside the bundle
  477. // then we assume it's a tool, and the "bundle" = the binary file.
  478. CFURLRef workingUrl;
  479. if(inside)
  480. workingUrl = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault,bundleUrl,CFSTR("Contents/Resources"),true);
  481. else if(outside)
  482. workingUrl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, bundleUrl);
  483. else
  484. {
  485. workingUrl = bundleUrl;
  486. CFRetain(workingUrl); // so that we can release bundleUrl twice.
  487. }
  488. CFStringRef workingString = CFURLCopyFileSystemPath(workingUrl, kCFURLPOSIXPathStyle);
  489. CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
  490. CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
  491. CFStringGetCString(normalizedString, cwd_buf, sizeof(cwd_buf)-1, kCFStringEncodingUTF8);
  492. // if we dont see main.cs inside the bundle, try again looking outside
  493. // we're done if we find it, or if we find it neither inside or outside.
  494. if( isMainDotCsPresent(cwd_buf) || ( !inside && !outside))
  495. done = true;
  496. if(inside)
  497. inside = false, outside = true;
  498. else if(outside)
  499. outside = false;
  500. CFRelease(workingUrl);
  501. CFRelease(workingString);
  502. CFRelease(normalizedString);
  503. }
  504. //CFRelease(mainBundle); // apple docs say to release this, but that causes a sigsegv(11)
  505. CFRelease(bundleUrl);
  506. */
  507. // chdir(cwd_buf); // set the current working directory.
  508. char* ret = NULL;
  509. if(StringTable)
  510. platState.mainDotCsDir = StringTable->insert(cwd_buf);
  511. else
  512. ret = dStrdup(cwd_buf);
  513. return ret ? ret : platState.mainDotCsDir;
  514. }
  515. //-----------------------------------------------------------------------------
  516. StringTableEntry Platform::getExecutableName()
  517. {
  518. char path_buf[MAX_MAC_PATH_LONG];
  519. //TODO: android
  520. /*
  521. // get a cfurl to the executable name
  522. CFBundleRef mainBundle = CFBundleGetMainBundle();
  523. CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
  524. // get a cfstring of just the app name
  525. CFStringRef workingString = CFURLCopyLastPathComponent(bundleUrl);
  526. CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
  527. CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
  528. CFStringGetCString(normalizedString, path_buf, sizeof(path_buf)-1, kCFStringEncodingUTF8);
  529. CFRelease(bundleUrl);
  530. CFRelease(workingString);
  531. CFRelease(normalizedString);
  532. */
  533. return StringTable->insert(path_buf);
  534. }
  535. //-----------------------------------------------------------------------------
  536. bool Platform::isFile(const char *path)
  537. {
  538. if (!path || !*path)
  539. return false;
  540. // make sure we can stat the file
  541. struct stat statData;
  542. if( stat(path, &statData) < 0 )
  543. return false;
  544. // now see if it's a regular file
  545. if( (statData.st_mode & S_IFMT) == S_IFREG)
  546. return true;
  547. return false;
  548. }
  549. //-----------------------------------------------------------------------------
  550. bool Platform::isDirectory(const char *path)
  551. {
  552. if (!path || !*path)
  553. return false;
  554. // make sure we can stat the file
  555. struct stat statData;
  556. if( stat(path, &statData) < 0 )
  557. return false;
  558. // now see if it's a directory
  559. if( (statData.st_mode & S_IFMT) == S_IFDIR)
  560. return true;
  561. return false;
  562. }
  563. S32 Platform::getFileSize(const char* pFilePath)
  564. {
  565. if (!pFilePath || !*pFilePath)
  566. return 0;
  567. struct stat statData;
  568. if( stat(pFilePath, &statData) < 0 )
  569. return 0;
  570. // and return it's size in bytes
  571. return (S32)statData.st_size;
  572. }
  573. //-----------------------------------------------------------------------------
  574. bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
  575. {
  576. char fullpath[MAX_MAC_PATH_LONG];
  577. dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
  578. return isDirectory((const char *)fullpath);
  579. }
  580. //-----------------------------------------------------------------------------
  581. // utility for platform::hasSubDirectory() and platform::dumpDirectories()
  582. // ensures that the entry is a directory, and isnt on the ignore lists.
  583. inline bool isGoodDirectory(dirent* entry)
  584. {
  585. return (entry->d_type == DT_DIR // is a dir
  586. && dStrcmp(entry->d_name,".") != 0 // not here
  587. && dStrcmp(entry->d_name,"..") != 0 // not parent
  588. && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
  589. }
  590. //-----------------------------------------------------------------------------
  591. bool Platform::hasSubDirectory(const char *path)
  592. {
  593. DIR *dir;
  594. dirent *entry;
  595. dir = opendir(path);
  596. if(!dir)
  597. return false; // we got a bad path, so no, it has no subdirectory.
  598. while( true )
  599. {
  600. entry = readdir(dir);
  601. if ( entry == NULL )
  602. break;
  603. if(isGoodDirectory(entry) )
  604. {
  605. closedir(dir);
  606. return true; // we have a subdirectory, that isnt on the exclude list.
  607. }
  608. }
  609. closedir(dir);
  610. return false; // either this dir had no subdirectories, or they were all on the exclude list.
  611. }
  612. //-----------------------------------------------------------------------------
  613. bool recurseDumpDirectories(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  614. {
  615. DIR *dir;
  616. dirent *entry;
  617. const U32 len = dStrlen(basePath) + dStrlen(path) + 2;
  618. char pathbuf[len];
  619. // construct the file path
  620. dSprintf(pathbuf, len, "%s/%s", basePath, path);
  621. // be sure it opens.
  622. dir = opendir(pathbuf);
  623. if(!dir)
  624. return false;
  625. // look inside the current directory
  626. while( true )
  627. {
  628. entry = readdir(dir);
  629. if ( entry == NULL )
  630. break;
  631. // we just want directories.
  632. if(!isGoodDirectory(entry))
  633. continue;
  634. // TODO: better unicode file name handling
  635. // // Apple's file system stores unicode file names in decomposed form.
  636. // // ATSUI will not reliably draw out just the accent character by itself,
  637. // // so our text renderer has no chance of rendering decomposed form unicode.
  638. // // We have to convert the entry name to precomposed normalized form.
  639. // CFStringRef cfdname = CFStringCreateWithCString(NULL,entry->d_name,kCFStringEncodingUTF8);
  640. // CFMutableStringRef cfentryName = CFStringCreateMutableCopy(NULL,0,cfdname);
  641. // CFStringNormalize(cfentryName,kCFStringNormalizationFormC);
  642. //
  643. // U32 entryNameLen = CFStringGetLength(cfentryName) * 4 + 1;
  644. // char entryName[entryNameLen];
  645. // CFStringGetCString(cfentryName, entryName, entryNameLen, kCFStringEncodingUTF8);
  646. // entryName[entryNameLen-1] = NULL; // sometimes, CFStringGetCString() doesn't null terminate.
  647. // CFRelease(cfentryName);
  648. // CFRelease(cfdname);
  649. // construct the new path string, we'll need this below.
  650. const U32 newpathlen = dStrlen(path) + dStrlen(entry->d_name) + 2;
  651. char newpath[newpathlen];
  652. if(dStrlen(path) > 0)
  653. {
  654. dSprintf(newpath, newpathlen, "%s/%s", path, entry->d_name);
  655. }
  656. else
  657. {
  658. dSprintf(newpath, newpathlen, "%s", entry->d_name);
  659. }
  660. // we have a directory, add it to the list.
  661. if( noBasePath )
  662. {
  663. directoryVector.push_back(StringTable->insert(newpath));
  664. }
  665. else
  666. {
  667. const U32 fullpathlen = dStrlen(basePath) + dStrlen(newpath) + 2;
  668. char fullpath[fullpathlen];
  669. dSprintf(fullpath, fullpathlen, "%s/%s",basePath,newpath);
  670. directoryVector.push_back(StringTable->insert(fullpath));
  671. }
  672. // and recurse into it, unless we've run out of depth
  673. if( depth != 0) // passing a val of -1 as the recurse depth means go forever
  674. recurseDumpDirectories(basePath, newpath, directoryVector, depth-1, noBasePath);
  675. }
  676. closedir(dir);
  677. return true;
  678. }
  679. //-----------------------------------------------------------------------------
  680. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  681. {
  682. PROFILE_START(dumpDirectories);
  683. ResourceManager->initExcludedDirectories();
  684. const S32 len = dStrlen(path)+1;
  685. char newpath[len];
  686. dSprintf(newpath, len, "%s", path);
  687. if(newpath[len - 1] == '/')
  688. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  689. // Insert base path to follow what Windows does.
  690. if ( !noBasePath )
  691. directoryVector.push_back(StringTable->insert(newpath));
  692. bool ret = recurseDumpDirectories(newpath, "", directoryVector, depth, noBasePath);
  693. PROFILE_END();
  694. return ret;
  695. }
  696. //-----------------------------------------------------------------------------
  697. static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  698. {
  699. DIR *dir;
  700. dirent *entry;
  701. // be sure it opens.
  702. dir = opendir(curPath);
  703. if(!dir)
  704. return false;
  705. // look inside the current directory
  706. while( true )
  707. {
  708. entry = readdir(dir);
  709. if ( entry == NULL )
  710. break;
  711. // construct the full file path. we need this to get the file size and to recurse
  712. //TODO: android
  713. const U32 len = 0;//dStrlen(curPath) + entry->d_namlen + 2;
  714. char pathbuf[len];
  715. dSprintf( pathbuf, len, "%s/%s", curPath, entry->d_name);
  716. // ok, deal with directories and files seperately.
  717. if( entry->d_type == DT_DIR )
  718. {
  719. if( depth == 0)
  720. continue;
  721. // filter out dirs we dont want.
  722. if( !isGoodDirectory(entry) )
  723. continue;
  724. // recurse into the dir
  725. recurseDumpPath( pathbuf, fileVector, depth-1);
  726. }
  727. else
  728. {
  729. //add the file entry to the list
  730. // unlike recurseDumpDirectories(), we need to return more complex info here.
  731. //<Mat> commented this out in case we ever want a dir file printout again
  732. //printf( "File Name: %s ", entry->d_name );
  733. const U32 fileSize = Platform::getFileSize(pathbuf);
  734. fileVector.increment();
  735. Platform::FileInfo& rInfo = fileVector.last();
  736. rInfo.pFullPath = StringTable->insert(curPath);
  737. rInfo.pFileName = StringTable->insert(entry->d_name);
  738. rInfo.fileSize = fileSize;
  739. }
  740. }
  741. closedir(dir);
  742. return true;
  743. }
  744. //-----------------------------------------------------------------------------
  745. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  746. {
  747. PROFILE_START(dumpPath);
  748. const S32 len = dStrlen(path) + 1;
  749. char newpath[len];
  750. dSprintf(newpath, len, "%s", path);
  751. if(newpath[len - 2] == '/')
  752. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  753. bool ret = recurseDumpPath( newpath, fileVector, depth);
  754. PROFILE_END();
  755. return ret;
  756. }
  757. //-----------------------------------------------------------------------------
  758. #if defined(TORQUE_DEBUG)
  759. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  760. Con::printf("testing %s",argv[1]);
  761. Platform::addExcludedDirectory(".svn");
  762. if(Platform::hasSubDirectory(argv[1]))
  763. Con::printf(" has subdir");
  764. else
  765. Con::printf(" does not have subdir");
  766. }
  767. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  768. Vector<StringTableEntry> paths;
  769. S32 depth = dAtoi(argv[2]);
  770. Platform::addExcludedDirectory(".svn");
  771. Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
  772. Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
  773. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  774. Con::printf(*itr);
  775. }
  776. }
  777. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  778. {
  779. Vector<Platform::FileInfo> files;
  780. S32 depth = dAtoi(argv[2]);
  781. Platform::addExcludedDirectory(".svn");
  782. Platform::dumpPath(argv[1], files, depth);
  783. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  784. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  785. }
  786. }
  787. //-----------------------------------------------------------------------------
  788. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  789. {
  790. return dFileTouch(argv[1]);
  791. }
  792. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  793. {
  794. FileTime create, modify;
  795. bool ok;
  796. ok = Platform::getFileTimes(argv[1],&create, &modify);
  797. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  798. return ok;
  799. }
  800. #endif