iOSFileio.mm 34 KB

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