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 <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. //#if defined(TORQUE_OS_MAC_OSX)
  43. #include <CoreFoundation/CFBundle.h>
  44. //#else
  45. //#include <CFBundle.h>
  46. //#endif
  47. //-----------------------------------------------------------------------------
  48. bool Platform::fileDelete(const char * name)
  49. {
  50. if(!name )
  51. return(false);
  52. if (dStrlen(name) > MAX_MAC_PATH_LONG)
  53. Con::warnf("Platform::FileDelete() - Filename length is pretty long...");
  54. return(remove(name) == 0); // remove returns 0 on success
  55. }
  56. //-----------------------------------------------------------------------------
  57. bool dFileTouch(const char *path)
  58. {
  59. if (!path || !*path)
  60. return false;
  61. // set file at path's modification and access times to now.
  62. return( utimes( path, NULL) == 0); // utimes returns 0 on success.
  63. }
  64. //-----------------------------------------------------------------------------
  65. // Constructors & Destructor
  66. //-----------------------------------------------------------------------------
  67. //-----------------------------------------------------------------------------
  68. // After construction, the currentStatus will be Closed and the capabilities
  69. // will be 0.
  70. //-----------------------------------------------------------------------------
  71. File::File()
  72. : currentStatus(Closed), capability(0)
  73. {
  74. handle = NULL;
  75. }
  76. //-----------------------------------------------------------------------------
  77. // insert a copy constructor here... (currently disabled)
  78. //-----------------------------------------------------------------------------
  79. //-----------------------------------------------------------------------------
  80. // Destructor
  81. //-----------------------------------------------------------------------------
  82. File::~File()
  83. {
  84. close();
  85. handle = NULL;
  86. }
  87. //-----------------------------------------------------------------------------
  88. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  89. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  90. // true.
  91. //
  92. // Sets capability appropriate to the openMode.
  93. // Returns the currentStatus of the file.
  94. //-----------------------------------------------------------------------------
  95. File::Status File::open(const char *filename, const AccessMode openMode)
  96. {
  97. if (dStrlen(filename) > MAX_MAC_PATH_LONG)
  98. Con::warnf("File::open: Filename length is pretty long...");
  99. // Close the file if it was already open...
  100. if (currentStatus != Closed)
  101. close();
  102. // create the appropriate type of file...
  103. switch (openMode)
  104. {
  105. case Read:
  106. handle = (void *)fopen(filename, "rb"); // read only
  107. break;
  108. case Write:
  109. handle = (void *)fopen(filename, "wb"); // write only
  110. break;
  111. case ReadWrite:
  112. handle = (void *)fopen(filename, "ab+"); // write(append) and read
  113. break;
  114. case WriteAppend:
  115. handle = (void *)fopen(filename, "ab"); // write(append) only
  116. break;
  117. default:
  118. AssertFatal(false, "File::open: bad access mode");
  119. }
  120. // handle not created successfully
  121. if (handle == NULL)
  122. return setStatus();
  123. // successfully created file, so set the file capabilities...
  124. switch (openMode)
  125. {
  126. case Read:
  127. capability = FileRead;
  128. break;
  129. case Write:
  130. case WriteAppend:
  131. capability = FileWrite;
  132. break;
  133. case ReadWrite:
  134. capability = FileRead | FileWrite;
  135. break;
  136. default:
  137. AssertFatal(false, "File::open: bad access mode");
  138. }
  139. // must set the file status before setting the position.
  140. currentStatus = Ok;
  141. if (openMode == ReadWrite)
  142. setPosition(0);
  143. // success!
  144. return currentStatus;
  145. }
  146. //-----------------------------------------------------------------------------
  147. // Get the current position of the file pointer.
  148. //-----------------------------------------------------------------------------
  149. U32 File::getPosition() const
  150. {
  151. AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
  152. AssertFatal(handle != NULL, "File::getPosition: invalid file handle");
  153. return ftell((FILE*)handle);
  154. }
  155. //-----------------------------------------------------------------------------
  156. // Set the position of the file pointer.
  157. // Absolute and relative positioning is supported via the absolutePos
  158. // parameter.
  159. //
  160. // If positioning absolutely, position MUST be positive - an IOError results if
  161. // position is negative.
  162. // Position can be negative if positioning relatively, however positioning
  163. // before the start of the file is an IOError.
  164. //
  165. // Returns the currentStatus of the file.
  166. //-----------------------------------------------------------------------------
  167. File::Status File::setPosition(S32 position, bool absolutePos)
  168. {
  169. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  170. AssertFatal(handle != NULL, "File::setPosition: invalid file handle");
  171. if (currentStatus != Ok && currentStatus != EOS )
  172. return currentStatus;
  173. U32 finalPos;
  174. if(absolutePos)
  175. {
  176. // absolute position
  177. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  178. // position beyond EOS is OK
  179. fseek((FILE*)handle, position, SEEK_SET);
  180. finalPos = ftell((FILE*)handle);
  181. }
  182. else
  183. {
  184. // relative position
  185. AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
  186. // position beyond EOS is OK
  187. fseek((FILE*)handle, position, SEEK_CUR);
  188. finalPos = ftell((FILE*)handle);
  189. }
  190. // ftell returns -1 on error. set error status
  191. if (0xffffffff == finalPos)
  192. return setStatus();
  193. // success, at end of file
  194. else if (finalPos >= getSize())
  195. return currentStatus = EOS;
  196. // success!
  197. else
  198. return currentStatus = Ok;
  199. }
  200. //-----------------------------------------------------------------------------
  201. // Get the size of the file in bytes.
  202. // It is an error to query the file size for a Closed file, or for one with an
  203. // error status.
  204. //-----------------------------------------------------------------------------
  205. U32 File::getSize() const
  206. {
  207. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  208. AssertFatal(handle != NULL, "File::getSize: invalid file handle");
  209. if (Ok == currentStatus || EOS == currentStatus)
  210. {
  211. struct stat statData;
  212. if(fstat(fileno((FILE*)handle), &statData) != 0)
  213. return 0;
  214. // return the size in bytes
  215. return statData.st_size;
  216. }
  217. return 0;
  218. }
  219. //-----------------------------------------------------------------------------
  220. // Flush the file.
  221. // It is an error to flush a read-only file.
  222. // Returns the currentStatus of the file.
  223. //-----------------------------------------------------------------------------
  224. File::Status File::flush()
  225. {
  226. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  227. AssertFatal(handle != NULL, "File::flush: invalid file handle");
  228. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  229. if (fflush((FILE*)handle) != 0)
  230. return setStatus();
  231. else
  232. return currentStatus = Ok;
  233. }
  234. //-----------------------------------------------------------------------------
  235. // Close the File.
  236. //
  237. // Returns the currentStatus
  238. //-----------------------------------------------------------------------------
  239. File::Status File::close()
  240. {
  241. // check if it's already closed...
  242. if (Closed == currentStatus)
  243. return currentStatus;
  244. // it's not, so close it...
  245. if (handle != NULL)
  246. {
  247. if (fclose((FILE*)handle) != 0)
  248. return setStatus();
  249. }
  250. handle = NULL;
  251. return currentStatus = Closed;
  252. }
  253. //-----------------------------------------------------------------------------
  254. // Self-explanatory.
  255. //-----------------------------------------------------------------------------
  256. File::Status File::getStatus() const
  257. {
  258. return currentStatus;
  259. }
  260. //-----------------------------------------------------------------------------
  261. // Sets and returns the currentStatus when an error has been encountered.
  262. //-----------------------------------------------------------------------------
  263. File::Status File::setStatus()
  264. {
  265. switch (errno)
  266. {
  267. case EACCES: // permission denied
  268. currentStatus = IOError;
  269. break;
  270. case EBADF: // Bad File Pointer
  271. case EINVAL: // Invalid argument
  272. case ENOENT: // file not found
  273. case ENAMETOOLONG:
  274. default:
  275. currentStatus = UnknownError;
  276. }
  277. return currentStatus;
  278. }
  279. //-----------------------------------------------------------------------------
  280. // Sets and returns the currentStatus to status.
  281. //-----------------------------------------------------------------------------
  282. File::Status File::setStatus(File::Status status)
  283. {
  284. return currentStatus = status;
  285. }
  286. //-----------------------------------------------------------------------------
  287. // Read from a file.
  288. // The number of bytes to read is passed in size, the data is returned in src.
  289. // The number of bytes read is available in bytesRead if a non-Null pointer is
  290. // provided.
  291. //-----------------------------------------------------------------------------
  292. File::Status File::read(U32 size, char *dst, U32 *bytesRead)
  293. {
  294. AssertFatal(Closed != currentStatus, "File::read: file closed");
  295. AssertFatal(handle != NULL, "File::read: invalid file handle");
  296. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  297. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  298. AssertWarn(0 != size, "File::read: size of zero");
  299. if (Ok != currentStatus || 0 == size)
  300. return currentStatus;
  301. // read from stream
  302. U32 nBytes = fread(dst, 1, size, (FILE*)handle);
  303. // did we hit the end of the stream?
  304. if( nBytes != size)
  305. currentStatus = EOS;
  306. // if bytesRead is a valid pointer, send number of bytes read there.
  307. if(bytesRead)
  308. *bytesRead = nBytes;
  309. // successfully read size bytes
  310. return currentStatus;
  311. }
  312. //-----------------------------------------------------------------------------
  313. // Write to a file.
  314. // The number of bytes to write is passed in size, the data is passed in src.
  315. // The number of bytes written is available in bytesWritten if a non-Null
  316. // pointer is provided.
  317. //-----------------------------------------------------------------------------
  318. File::Status File::write(U32 size, const char *src, U32 *bytesWritten)
  319. {
  320. AssertFatal(Closed != currentStatus, "File::write: file closed");
  321. AssertFatal(handle != NULL, "File::write: invalid file handle");
  322. AssertFatal(NULL != src, "File::write: NULL source pointer");
  323. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  324. AssertWarn(0 != size, "File::write: size of zero");
  325. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  326. return currentStatus;
  327. // write bytes to the stream
  328. U32 nBytes = fwrite(src, 1, size,(FILE*)handle);
  329. // if we couldn't write everything, we've got a problem. set error status.
  330. if(nBytes != size)
  331. setStatus();
  332. // if bytesWritten is a valid pointer, put number of bytes read there.
  333. if(bytesWritten)
  334. *bytesWritten = nBytes;
  335. // return current File status, whether good or ill.
  336. return currentStatus;
  337. }
  338. //-----------------------------------------------------------------------------
  339. // Self-explanatory.
  340. //-----------------------------------------------------------------------------
  341. bool File::hasCapability(Capability cap) const
  342. {
  343. return (0 != (U32(cap) & capability));
  344. }
  345. //-----------------------------------------------------------------------------
  346. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  347. {
  348. if(a > b)
  349. return 1;
  350. if(a < b)
  351. return -1;
  352. return 0;
  353. }
  354. //-----------------------------------------------------------------------------
  355. // either time param COULD be null.
  356. //-----------------------------------------------------------------------------
  357. bool Platform::getFileTimes(const char *path, FileTime *createTime, FileTime *modifyTime)
  358. {
  359. // MacOSX is NOT guaranteed to be running off a HFS volume,
  360. // and UNIX does not keep a record of a file's creation time anywhere.
  361. // So instead of creation time we return changed time,
  362. // just like the Linux platform impl does.
  363. if (!path || !*path)
  364. return false;
  365. struct stat statData;
  366. if (stat(path, &statData) == -1)
  367. return false;
  368. if(createTime)
  369. *createTime = statData.st_ctime;
  370. if(modifyTime)
  371. *modifyTime = statData.st_mtime;
  372. return true;
  373. }
  374. //-----------------------------------------------------------------------------
  375. bool Platform::createPath(const char *file)
  376. {
  377. //<Mat> needless console noise
  378. //Con::warnf("creating path %s",file);
  379. // if the path exists, we're done.
  380. struct stat statData;
  381. if( stat(file, &statData) == 0 )
  382. {
  383. return true; // exists, rejoice.
  384. }
  385. // get the parent path.
  386. // we're not using basename because it's not thread safe.
  387. const U32 len = dStrlen(file) + 1;
  388. char parent[len];
  389. bool isDirPath = false;
  390. dSprintf(parent, len, "%s", file);
  391. if(parent[len - 2] == '/')
  392. {
  393. parent[len - 2] = '\0'; // cut off the trailing slash, if there is one
  394. isDirPath = true; // we got a trailing slash, so file is a directory.
  395. }
  396. // recusively create the parent path.
  397. // only recurse if newpath has a slash that isn't a leading slash.
  398. char *slash = dStrrchr(parent,'/');
  399. if( slash && slash != parent)
  400. {
  401. // snip the path just after the last slash.
  402. slash[1] = '\0';
  403. // recusively create the parent path. fail if parent path creation failed.
  404. if(!Platform::createPath(parent))
  405. return false;
  406. }
  407. // create *file if it is a directory path.
  408. if(isDirPath)
  409. {
  410. // try to create the directory
  411. if( mkdir(file, 0777) != 0) // app may reside in global apps dir, and so must be writable to all.
  412. return false;
  413. }
  414. return true;
  415. }
  416. #pragma mark ---- Directories ----
  417. //-----------------------------------------------------------------------------
  418. StringTableEntry Platform::getCurrentDirectory()
  419. {
  420. // get the current directory, the one that would be opened if we did a fopen(".")
  421. char* cwd = getcwd(NULL, 0);
  422. StringTableEntry ret = StringTable->insert(cwd);
  423. free(cwd);
  424. return ret;
  425. }
  426. //-----------------------------------------------------------------------------
  427. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  428. {
  429. return (chdir(newDir) == 0);
  430. }
  431. //-----------------------------------------------------------------------------
  432. void Platform::openFolder(const char* path )
  433. {
  434. // TODO: users can still run applications by calling openfolder on an app bundle.
  435. // this may be a bad thing.
  436. if(!Platform::isDirectory(path))
  437. {
  438. Con::errorf(avar("Error: not a directory: %s",path));
  439. return;
  440. }
  441. const char* arg = avar("open '%s'", path);
  442. U32 ret = system(arg);
  443. if(ret != 0)
  444. Con::printf(strerror(errno));
  445. }
  446. static bool isMainDotCsPresent(char *dir)
  447. {
  448. char maincsbuf[MAX_MAC_PATH_LONG];
  449. const char *maincsname = "/main.cs";
  450. const U32 len = dStrlen(dir) + dStrlen(maincsname)+1;
  451. AssertISV(len < MAX_MAC_PATH_LONG, "Sorry, path is too long, I can't run from this folder.");
  452. dSprintf(maincsbuf,MAX_MAC_PATH_LONG,"%s%s", dir, maincsname);
  453. return Platform::isFile(maincsbuf);
  454. }
  455. //-----------------------------------------------------------------------------
  456. /// Finds and sets the current working directory.
  457. /// Torque tries to automatically detect whether you have placed the game files
  458. /// inside or outside the application's bundle. It checks for the presence of
  459. /// the file 'main.cs'. If it finds it, Torque will assume that the other game
  460. /// files are there too. If Torque does not see 'main.cs' inside its bundle, it
  461. /// will assume the files are outside the bundle.
  462. /// Since you probably don't want to copy the game files into the app every time
  463. /// you build, you will want to leave them outside the bundle for development.
  464. ///
  465. /// Placing all content inside the application bundle gives a much better user
  466. /// experience when you distribute your app.
  467. StringTableEntry Platform::getExecutablePath()
  468. {
  469. if(platState.mainDotCsDir)
  470. return platState.mainDotCsDir;
  471. char cwd_buf[MAX_MAC_PATH_LONG];
  472. CFBundleRef mainBundle = CFBundleGetMainBundle();
  473. CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
  474. bool inside = true;
  475. bool outside = false;
  476. bool done = false;
  477. while(!done)
  478. {
  479. // first look for game content inside the application bundle.
  480. // then we look outside the bundle
  481. // then we assume it's a tool, and the "bundle" = the binary file.
  482. CFURLRef workingUrl;
  483. if(inside)
  484. workingUrl = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault,bundleUrl,CFSTR("Contents/Resources"),true);
  485. else if(outside)
  486. workingUrl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, bundleUrl);
  487. else
  488. {
  489. workingUrl = bundleUrl;
  490. CFRetain(workingUrl); // so that we can release bundleUrl twice.
  491. }
  492. CFStringRef workingString = CFURLCopyFileSystemPath(workingUrl, kCFURLPOSIXPathStyle);
  493. CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
  494. CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
  495. CFStringGetCString(normalizedString, cwd_buf, sizeof(cwd_buf)-1, kCFStringEncodingUTF8);
  496. // if we dont see main.cs inside the bundle, try again looking outside
  497. // we're done if we find it, or if we find it neither inside or outside.
  498. if( isMainDotCsPresent(cwd_buf) || ( !inside && !outside))
  499. done = true;
  500. if(inside)
  501. inside = false, outside = true;
  502. else if(outside)
  503. outside = false;
  504. CFRelease(workingUrl);
  505. CFRelease(workingString);
  506. CFRelease(normalizedString);
  507. }
  508. //CFRelease(mainBundle); // apple docs say to release this, but that causes a sigsegv(11)
  509. CFRelease(bundleUrl);
  510. // chdir(cwd_buf); // set the current working directory.
  511. char* ret = NULL;
  512. if(StringTable)
  513. platState.mainDotCsDir = StringTable->insert(cwd_buf);
  514. else
  515. ret = dStrdup(cwd_buf);
  516. return ret ? ret : platState.mainDotCsDir;
  517. }
  518. //-----------------------------------------------------------------------------
  519. StringTableEntry Platform::getExecutableName()
  520. {
  521. char path_buf[MAX_MAC_PATH_LONG];
  522. // get a cfurl to the executable name
  523. CFBundleRef mainBundle = CFBundleGetMainBundle();
  524. CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
  525. // get a cfstring of just the app name
  526. CFStringRef workingString = CFURLCopyLastPathComponent(bundleUrl);
  527. CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
  528. CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
  529. CFStringGetCString(normalizedString, path_buf, sizeof(path_buf)-1, kCFStringEncodingUTF8);
  530. CFRelease(bundleUrl);
  531. CFRelease(workingString);
  532. CFRelease(normalizedString);
  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. const U32 len = dStrlen(curPath) + entry->d_namlen + 2;
  713. char pathbuf[len];
  714. dSprintf( pathbuf, len, "%s/%s", curPath, entry->d_name);
  715. // ok, deal with directories and files seperately.
  716. if( entry->d_type == DT_DIR )
  717. {
  718. if( depth == 0)
  719. continue;
  720. // filter out dirs we dont want.
  721. if( !isGoodDirectory(entry) )
  722. continue;
  723. // recurse into the dir
  724. recurseDumpPath( pathbuf, fileVector, depth-1);
  725. }
  726. else
  727. {
  728. //add the file entry to the list
  729. // unlike recurseDumpDirectories(), we need to return more complex info here.
  730. //<Mat> commented this out in case we ever want a dir file printout again
  731. //printf( "File Name: %s ", entry->d_name );
  732. const U32 fileSize = Platform::getFileSize(pathbuf);
  733. fileVector.increment();
  734. Platform::FileInfo& rInfo = fileVector.last();
  735. rInfo.pFullPath = StringTable->insert(curPath);
  736. rInfo.pFileName = StringTable->insert(entry->d_name);
  737. rInfo.fileSize = fileSize;
  738. }
  739. }
  740. closedir(dir);
  741. return true;
  742. }
  743. //-----------------------------------------------------------------------------
  744. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  745. {
  746. PROFILE_START(dumpPath);
  747. const S32 len = dStrlen(path) + 1;
  748. char newpath[len];
  749. dSprintf(newpath, len, "%s", path);
  750. if(newpath[len - 2] == '/')
  751. newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
  752. bool ret = recurseDumpPath( newpath, fileVector, depth);
  753. PROFILE_END();
  754. return ret;
  755. }
  756. //----------------------------------------------------------------------------
  757. // Loading and Saving of data to the NSUserDefaults on the iOS / iPod Touch
  758. void iOSSaveStringToDevice( const char* saveNameField, const char* dataString)
  759. {
  760. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  761. NSString *convertedString = [[NSString alloc] initWithUTF8String:dataString];
  762. NSString *convertedSaveFieldName = [[NSString alloc] initWithUTF8String:saveNameField];
  763. [prefs setObject:convertedString forKey:convertedSaveFieldName];
  764. [prefs synchronize];
  765. }
  766. static const char* iOSLoadStringFromDevice(const char* saveNameField)
  767. {
  768. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  769. NSString *convertedSaveFieldName = [[NSString alloc] initWithUTF8String:saveNameField];
  770. NSString *myString = [prefs stringForKey:convertedSaveFieldName];
  771. return [myString UTF8String];
  772. }
  773. 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"
  774. "@keyString: The string to store in this key.\n"
  775. "@keyName: The name for the key to store the string under.")
  776. {
  777. iOSSaveStringToDevice( argv[1] , argv[2] );
  778. }
  779. ConsoleFunction(iOSLoadStringFromDevice, const char*, 2, 2, "(keyName) Loads a string from a key defined in the iOS user defaults (saved with iOSSaveStringToDevice)\n"
  780. "@keyName: The name for the string that it was stored under.")
  781. {
  782. const char* result = iOSLoadStringFromDevice( argv[1] );
  783. return result;
  784. }
  785. //-----------------------------------------------------------------------------
  786. #if defined(TORQUE_DEBUG)
  787. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  788. Con::printf("testing %s",argv[1]);
  789. Platform::addExcludedDirectory(".svn");
  790. if(Platform::hasSubDirectory(argv[1]))
  791. Con::printf(" has subdir");
  792. else
  793. Con::printf(" does not have subdir");
  794. }
  795. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  796. Vector<StringTableEntry> paths;
  797. S32 depth = dAtoi(argv[2]);
  798. Platform::addExcludedDirectory(".svn");
  799. Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
  800. Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
  801. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  802. Con::printf(*itr);
  803. }
  804. }
  805. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  806. {
  807. Vector<Platform::FileInfo> files;
  808. S32 depth = dAtoi(argv[2]);
  809. Platform::addExcludedDirectory(".svn");
  810. Platform::dumpPath(argv[1], files, depth);
  811. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  812. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  813. }
  814. }
  815. //-----------------------------------------------------------------------------
  816. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  817. {
  818. return dFileTouch(argv[1]);
  819. }
  820. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  821. {
  822. FileTime create, modify;
  823. bool ok;
  824. ok = Platform::getFileTimes(argv[1],&create, &modify);
  825. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  826. return ok;
  827. }
  828. #endif