macFileIO.mm 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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. #import <Cocoa/Cocoa.h>
  23. #import <stdio.h>
  24. #import <stdlib.h>
  25. #import <errno.h>
  26. #import <utime.h>
  27. #import <sys/time.h>
  28. #import <sys/types.h>
  29. #import <dirent.h>
  30. #import <unistd.h>
  31. #import <sys/stat.h>
  32. #import "core/fileio.h"
  33. #import "core/util/tVector.h"
  34. #import "core/stringTable.h"
  35. #import "core/strings/stringFunctions.h"
  36. #import "console/console.h"
  37. #import "platform/profiler.h"
  38. #import "cinterface/cinterface.h"
  39. #import "core/volume.h"
  40. //TODO: file io still needs some work...
  41. #define MAX_MAC_PATH_LONG 2048
  42. bool dFileDelete(const char * name)
  43. {
  44. if(!name )
  45. return(false);
  46. if (dStrlen(name) > MAX_MAC_PATH_LONG)
  47. Con::warnf("dFileDelete: 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. bool dPathCopy(const char* source, const char* dest, bool nooverwrite)
  60. {
  61. if(source == NULL || dest == NULL)
  62. return false;
  63. @autoreleasepool {
  64. NSFileManager *manager = [NSFileManager defaultManager];
  65. NSString *nsource = [manager stringWithFileSystemRepresentation:source length:dStrlen(source)];
  66. NSString *ndest = [manager stringWithFileSystemRepresentation:dest length:dStrlen(dest)];
  67. NSString *ndestFolder = [ndest stringByDeletingLastPathComponent];
  68. if(! [manager fileExistsAtPath:nsource])
  69. {
  70. Con::errorf("dPathCopy: no file exists at %s",source);
  71. return false;
  72. }
  73. if( [manager fileExistsAtPath:ndest] )
  74. {
  75. if(nooverwrite)
  76. {
  77. Con::errorf("dPathCopy: file already exists at %s",dest);
  78. return false;
  79. }
  80. Con::warnf("Deleting files at path: %s", dest);
  81. if(![manager removeItemAtPath:ndest error:nil] || [manager fileExistsAtPath:ndest])
  82. {
  83. Con::errorf("Copy failed! Could not delete files at path: %s", dest);
  84. return false;
  85. }
  86. }
  87. if([manager fileExistsAtPath:ndestFolder] == NO)
  88. {
  89. ndestFolder = [ndestFolder stringByAppendingString:@"/"]; // createpath requires a trailing slash
  90. Platform::createPath([ndestFolder UTF8String]);
  91. }
  92. bool ret = [manager copyItemAtPath:nsource toPath:ndest error:nil];
  93. // n.b.: The "success" semantics don't guarantee a copy actually took place, so we'll verify
  94. // because this is surprising behavior for a method called copy.
  95. if( ![manager fileExistsAtPath:ndest] )
  96. {
  97. Con::warnf("The filemanager returned success, but the file was not copied. Something strange is happening");
  98. ret = false;
  99. }
  100. return ret;
  101. }
  102. }
  103. //-----------------------------------------------------------------------------
  104. bool dFileRename(const char *source, const char *dest)
  105. {
  106. if(source == NULL || dest == NULL)
  107. return false;
  108. @autoreleasepool {
  109. NSFileManager *manager = [NSFileManager defaultManager];
  110. NSString *nsource = [manager stringWithFileSystemRepresentation:source length:dStrlen(source)];
  111. NSString *ndest = [manager stringWithFileSystemRepresentation:dest length:dStrlen(dest)];
  112. if(! [manager fileExistsAtPath:nsource])
  113. {
  114. Con::errorf("dFileRename: no file exists at %s",source);
  115. return false;
  116. }
  117. if( [manager fileExistsAtPath:ndest] )
  118. {
  119. Con::warnf("dFileRename: Deleting files at path: %s", dest);
  120. }
  121. bool ret = [manager moveItemAtPath:nsource toPath:ndest error:nil];
  122. // n.b.: The "success" semantics don't guarantee a move actually took place, so we'll verify
  123. // because this is surprising behavior for a method called rename.
  124. if( ![manager fileExistsAtPath:ndest] )
  125. {
  126. Con::warnf("The filemanager returned success, but the file was not moved. Something strange is happening");
  127. ret = false;
  128. }
  129. return ret;
  130. }
  131. }
  132. //-----------------------------------------------------------------------------
  133. // Constructors & Destructor
  134. //-----------------------------------------------------------------------------
  135. //-----------------------------------------------------------------------------
  136. // After construction, the currentStatus will be Closed and the capabilities
  137. // will be 0.
  138. //-----------------------------------------------------------------------------
  139. File::File()
  140. : currentStatus(Closed), capability(0)
  141. {
  142. handle = NULL;
  143. }
  144. //-----------------------------------------------------------------------------
  145. // insert a copy constructor here... (currently disabled)
  146. //-----------------------------------------------------------------------------
  147. //-----------------------------------------------------------------------------
  148. // Destructor
  149. //-----------------------------------------------------------------------------
  150. File::~File()
  151. {
  152. close();
  153. handle = NULL;
  154. }
  155. //-----------------------------------------------------------------------------
  156. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  157. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  158. // true.
  159. //
  160. // Sets capability appropriate to the openMode.
  161. // Returns the currentStatus of the file.
  162. //-----------------------------------------------------------------------------
  163. File::FileStatus File::open(const char *filename, const AccessMode openMode)
  164. {
  165. if (dStrlen(filename) > MAX_MAC_PATH_LONG)
  166. Con::warnf("File::open: Filename length is pretty long...");
  167. // Close the file if it was already open...
  168. if (currentStatus != Closed)
  169. close();
  170. // create the appropriate type of file...
  171. switch (openMode)
  172. {
  173. case Read:
  174. handle = (void *)fopen(filename, "rb"); // read only
  175. break;
  176. case Write:
  177. handle = (void *)fopen(filename, "wb"); // write only
  178. break;
  179. case ReadWrite:
  180. handle = (void *)fopen(filename, "ab+"); // write(append) and read
  181. break;
  182. case WriteAppend:
  183. handle = (void *)fopen(filename, "ab"); // write(append) only
  184. break;
  185. default:
  186. AssertFatal(false, "File::open: bad access mode");
  187. }
  188. // handle not created successfully
  189. if (handle == NULL)
  190. return setStatus();
  191. // successfully created file, so set the file capabilities...
  192. switch (openMode)
  193. {
  194. case Read:
  195. capability = FileRead;
  196. break;
  197. case Write:
  198. case WriteAppend:
  199. capability = FileWrite;
  200. break;
  201. case ReadWrite:
  202. capability = FileRead | FileWrite;
  203. break;
  204. default:
  205. AssertFatal(false, "File::open: bad access mode");
  206. }
  207. // must set the file status before setting the position.
  208. currentStatus = Ok;
  209. if (openMode == ReadWrite)
  210. setPosition(0);
  211. // success!
  212. return currentStatus;
  213. }
  214. //-----------------------------------------------------------------------------
  215. // Get the current position of the file pointer.
  216. //-----------------------------------------------------------------------------
  217. U32 File::getPosition() const
  218. {
  219. AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
  220. AssertFatal(handle != NULL, "File::getPosition: invalid file handle");
  221. return ftell((FILE*)handle);
  222. }
  223. //-----------------------------------------------------------------------------
  224. // Set the position of the file pointer.
  225. // Absolute and relative positioning is supported via the absolutePos
  226. // parameter.
  227. //
  228. // If positioning absolutely, position MUST be positive - an IOError results if
  229. // position is negative.
  230. // Position can be negative if positioning relatively, however positioning
  231. // before the start of the file is an IOError.
  232. //
  233. // Returns the currentStatus of the file.
  234. //-----------------------------------------------------------------------------
  235. File::FileStatus File::setPosition(S32 position, bool absolutePos)
  236. {
  237. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  238. AssertFatal(handle != NULL, "File::setPosition: invalid file handle");
  239. if (currentStatus != Ok && currentStatus != EOS )
  240. return currentStatus;
  241. U32 finalPos;
  242. if(absolutePos)
  243. {
  244. // absolute position
  245. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  246. // position beyond EOS is OK
  247. fseek((FILE*)handle, position, SEEK_SET);
  248. finalPos = ftell((FILE*)handle);
  249. }
  250. else
  251. {
  252. // relative position
  253. AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
  254. // position beyond EOS is OK
  255. fseek((FILE*)handle, position, SEEK_CUR);
  256. finalPos = ftell((FILE*)handle);
  257. }
  258. // ftell returns -1 on error. set error status
  259. if (0xffffffff == finalPos)
  260. return setStatus();
  261. // success, at end of file
  262. else if (finalPos >= getSize())
  263. return currentStatus = EOS;
  264. // success!
  265. else
  266. return currentStatus = Ok;
  267. }
  268. //-----------------------------------------------------------------------------
  269. // Get the size of the file in bytes.
  270. // It is an error to query the file size for a Closed file, or for one with an
  271. // error status.
  272. //-----------------------------------------------------------------------------
  273. U32 File::getSize() const
  274. {
  275. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  276. AssertFatal(handle != NULL, "File::getSize: invalid file handle");
  277. if (Ok == currentStatus || EOS == currentStatus)
  278. {
  279. struct stat statData;
  280. if(fstat(fileno((FILE*)handle), &statData) != 0)
  281. return 0;
  282. // return the size in bytes
  283. return statData.st_size;
  284. }
  285. return 0;
  286. }
  287. //-----------------------------------------------------------------------------
  288. // Flush the file.
  289. // It is an error to flush a read-only file.
  290. // Returns the currentStatus of the file.
  291. //-----------------------------------------------------------------------------
  292. File::FileStatus File::flush()
  293. {
  294. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  295. AssertFatal(handle != NULL, "File::flush: invalid file handle");
  296. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  297. if (fflush((FILE*)handle) != 0)
  298. return setStatus();
  299. else
  300. return currentStatus = Ok;
  301. }
  302. //-----------------------------------------------------------------------------
  303. // Close the File.
  304. //
  305. // Returns the currentStatus
  306. //-----------------------------------------------------------------------------
  307. File::FileStatus File::close()
  308. {
  309. // check if it's already closed...
  310. if (Closed == currentStatus)
  311. return currentStatus;
  312. // it's not, so close it...
  313. if (handle != NULL)
  314. {
  315. if (fclose((FILE*)handle) != 0)
  316. return setStatus();
  317. }
  318. handle = NULL;
  319. return currentStatus = Closed;
  320. }
  321. //-----------------------------------------------------------------------------
  322. // Self-explanatory.
  323. //-----------------------------------------------------------------------------
  324. File::FileStatus File::getStatus() const
  325. {
  326. return currentStatus;
  327. }
  328. //-----------------------------------------------------------------------------
  329. // Sets and returns the currentStatus when an error has been encountered.
  330. //-----------------------------------------------------------------------------
  331. File::FileStatus File::setStatus()
  332. {
  333. switch (errno)
  334. {
  335. case EACCES: // permission denied
  336. currentStatus = IOError;
  337. break;
  338. case EBADF: // Bad File Pointer
  339. case EINVAL: // Invalid argument
  340. case ENOENT: // file not found
  341. case ENAMETOOLONG:
  342. default:
  343. currentStatus = UnknownError;
  344. }
  345. return currentStatus;
  346. }
  347. //-----------------------------------------------------------------------------
  348. // Sets and returns the currentStatus to status.
  349. //-----------------------------------------------------------------------------
  350. File::FileStatus File::setStatus(File::FileStatus status)
  351. {
  352. return currentStatus = status;
  353. }
  354. //-----------------------------------------------------------------------------
  355. // Read from a file.
  356. // The number of bytes to read is passed in size, the data is returned in src.
  357. // The number of bytes read is available in bytesRead if a non-Null pointer is
  358. // provided.
  359. //-----------------------------------------------------------------------------
  360. File::FileStatus File::read(U32 size, char *dst, U32 *bytesRead)
  361. {
  362. AssertFatal(Closed != currentStatus, "File::read: file closed");
  363. AssertFatal(handle != NULL, "File::read: invalid file handle");
  364. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  365. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  366. AssertWarn(0 != size, "File::read: size of zero");
  367. if (Ok != currentStatus || 0 == size)
  368. return currentStatus;
  369. // read from stream
  370. U32 nBytes = fread(dst, 1, size, (FILE*)handle);
  371. // did we hit the end of the stream?
  372. if( nBytes != size)
  373. currentStatus = EOS;
  374. // if bytesRead is a valid pointer, send number of bytes read there.
  375. if(bytesRead)
  376. *bytesRead = nBytes;
  377. // successfully read size bytes
  378. return currentStatus;
  379. }
  380. //-----------------------------------------------------------------------------
  381. // Write to a file.
  382. // The number of bytes to write is passed in size, the data is passed in src.
  383. // The number of bytes written is available in bytesWritten if a non-Null
  384. // pointer is provided.
  385. //-----------------------------------------------------------------------------
  386. File::FileStatus File::write(U32 size, const char *src, U32 *bytesWritten)
  387. {
  388. AssertFatal(Closed != currentStatus, "File::write: file closed");
  389. AssertFatal(handle != NULL, "File::write: invalid file handle");
  390. AssertFatal(NULL != src, "File::write: NULL source pointer");
  391. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  392. AssertWarn(0 != size, "File::write: size of zero");
  393. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  394. return currentStatus;
  395. // write bytes to the stream
  396. U32 nBytes = fwrite(src, 1, size,(FILE*)handle);
  397. // if we couldn't write everything, we've got a problem. set error status.
  398. if(nBytes != size)
  399. setStatus();
  400. // if bytesWritten is a valid pointer, put number of bytes read there.
  401. if(bytesWritten)
  402. *bytesWritten = nBytes;
  403. // return current File status, whether good or ill.
  404. return currentStatus;
  405. }
  406. //-----------------------------------------------------------------------------
  407. // Self-explanatory.
  408. //-----------------------------------------------------------------------------
  409. bool File::hasCapability(Capability cap) const
  410. {
  411. return (0 != (U32(cap) & capability));
  412. }
  413. //-----------------------------------------------------------------------------
  414. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  415. {
  416. if(a > b)
  417. return 1;
  418. if(a < b)
  419. return -1;
  420. return 0;
  421. }
  422. //-----------------------------------------------------------------------------
  423. // either time param COULD be null.
  424. //-----------------------------------------------------------------------------
  425. bool Platform::getFileTimes(const char *path, FileTime *createTime, FileTime *modifyTime)
  426. {
  427. // MacOSX is NOT guaranteed to be running off a HFS volume,
  428. // and UNIX does not keep a record of a file's creation time anywhere.
  429. // So instead of creation time we return changed time,
  430. // just like the Linux platform impl does.
  431. if (!path || !*path)
  432. return false;
  433. struct stat statData;
  434. if (stat(path, &statData) == -1)
  435. return false;
  436. if(createTime)
  437. *createTime = statData.st_ctime;
  438. if(modifyTime)
  439. *modifyTime = statData.st_mtime;
  440. return true;
  441. }
  442. //-----------------------------------------------------------------------------
  443. bool Platform::createPath(const char *file)
  444. {
  445. // if the path exists, we're done.
  446. struct stat statData;
  447. if( stat(file, &statData) == 0 )
  448. {
  449. return true; // exists, rejoice.
  450. }
  451. Con::warnf( "creating path %s", file );
  452. // get the parent path.
  453. // we're not using basename because it's not thread safe.
  454. U32 len = dStrlen(file);
  455. char parent[len];
  456. bool isDirPath = false;
  457. dStrncpy(parent,file,len);
  458. parent[len] = '\0';
  459. if(parent[len - 1] == '/')
  460. {
  461. parent[len - 1] = '\0'; // cut off the trailing slash, if there is one
  462. isDirPath = true; // we got a trailing slash, so file is a directory.
  463. }
  464. // recusively create the parent path.
  465. // only recurse if newpath has a slash that isn't a leading slash.
  466. char *slash = dStrrchr(parent,'/');
  467. if( slash && slash != parent)
  468. {
  469. // snip the path just after the last slash.
  470. slash[1] = '\0';
  471. // recusively create the parent path. fail if parent path creation failed.
  472. if(!Platform::createPath(parent))
  473. return false;
  474. }
  475. // create *file if it is a directory path.
  476. if(isDirPath)
  477. {
  478. // try to create the directory
  479. if( mkdir(file, 0777) != 0) // app may reside in global apps dir, and so must be writable to all.
  480. return false;
  481. }
  482. return true;
  483. }
  484. //-----------------------------------------------------------------------------
  485. bool Platform::cdFileExists(const char *filePath, const char *volumeName, S32 serialNum)
  486. {
  487. return true;
  488. }
  489. #pragma mark ---- Directories ----
  490. //-----------------------------------------------------------------------------
  491. StringTableEntry Platform::getCurrentDirectory()
  492. {
  493. // get the current directory, the one that would be opened if we did a fopen(".")
  494. char* cwd = getcwd(NULL, 0);
  495. StringTableEntry ret = StringTable->insert(cwd);
  496. free(cwd);
  497. return ret;
  498. }
  499. //-----------------------------------------------------------------------------
  500. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  501. {
  502. return (chdir(newDir) == 0);
  503. }
  504. //-----------------------------------------------------------------------------
  505. // helper func for getWorkingDirectory
  506. bool isMainDotCsPresent(NSString* dir)
  507. {
  508. return [[NSFileManager defaultManager] fileExistsAtPath:[dir stringByAppendingPathComponent:@"main.cs"]] == YES;
  509. }
  510. //-----------------------------------------------------------------------------
  511. /// Finds and sets the current working directory.
  512. /// Torque tries to automatically detect whether you have placed the game files
  513. /// inside or outside the application's bundle. It checks for the presence of
  514. /// the file 'main.cs'. If it finds it, Torque will assume that the other game
  515. /// files are there too. If Torque does not see 'main.cs' inside its bundle, it
  516. /// will assume the files are outside the bundle.
  517. /// Since you probably don't want to copy the game files into the app every time
  518. /// you build, you will want to leave them outside the bundle for development.
  519. ///
  520. /// Placing all content inside the application bundle gives a much better user
  521. /// experience when you distribute your app.
  522. StringTableEntry Platform::getExecutablePath()
  523. {
  524. static const char* cwd = NULL;
  525. // this isn't actually being used due to some static constructors at bundle load time
  526. // calling this method (before there is a chance to set it)
  527. // for instance, FMOD sound provider (this should be fixed in FMOD as it is with windows)
  528. if (!cwd && torque_getexecutablepath())
  529. {
  530. // we're in a plugin using the cinterface
  531. cwd = torque_getexecutablepath();
  532. chdir(cwd);
  533. }
  534. else if(!cwd)
  535. {
  536. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  537. //first check the cwd for main.cs
  538. static char buf[4096];
  539. NSString* currentDir = [[NSString alloc ] initWithUTF8String:getcwd(buf,(4096 * sizeof(char))) ];
  540. if (isMainDotCsPresent(currentDir))
  541. {
  542. cwd = buf;
  543. [pool release];
  544. [currentDir release];
  545. return cwd;
  546. }
  547. NSString* string = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"cs"];
  548. if(!string)
  549. string = [[NSBundle mainBundle] bundlePath];
  550. string = [string stringByDeletingLastPathComponent];
  551. AssertISV(isMainDotCsPresent(string), "Platform::getExecutablePath - Failed to find main.cs!");
  552. cwd = dStrdup([string UTF8String]);
  553. chdir(cwd);
  554. [pool release];
  555. [currentDir release];
  556. }
  557. return cwd;
  558. }
  559. //-----------------------------------------------------------------------------
  560. StringTableEntry Platform::getExecutableName()
  561. {
  562. static const char* name = NULL;
  563. if(!name)
  564. name = [[[[NSBundle mainBundle] bundlePath] lastPathComponent] UTF8String];
  565. return name;
  566. }
  567. //-----------------------------------------------------------------------------
  568. bool Platform::isFile(const char *path)
  569. {
  570. if (!path || !*path)
  571. return false;
  572. // make sure we can stat the file
  573. struct stat statData;
  574. if( stat(path, &statData) < 0 )
  575. {
  576. // Since file does not exist on disk see if it exists in a zip file loaded
  577. return Torque::FS::IsFile(path);
  578. }
  579. // now see if it's a regular file
  580. if( (statData.st_mode & S_IFMT) == S_IFREG)
  581. return true;
  582. return false;
  583. }
  584. //-----------------------------------------------------------------------------
  585. bool Platform::isDirectory(const char *path)
  586. {
  587. if (!path || !*path)
  588. return false;
  589. // make sure we can stat the file
  590. struct stat statData;
  591. if( stat(path, &statData) < 0 )
  592. return false;
  593. // now see if it's a directory
  594. if( (statData.st_mode & S_IFMT) == S_IFDIR)
  595. return true;
  596. return false;
  597. }
  598. S32 Platform::getFileSize(const char* pFilePath)
  599. {
  600. if (!pFilePath || !*pFilePath)
  601. return 0;
  602. struct stat statData;
  603. if( stat(pFilePath, &statData) < 0 )
  604. return 0;
  605. // and return it's size in bytes
  606. return (S32)statData.st_size;
  607. }
  608. //-----------------------------------------------------------------------------
  609. bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
  610. {
  611. char fullpath[MAX_MAC_PATH_LONG];
  612. dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
  613. return isDirectory((const char *)fullpath);
  614. }
  615. //-----------------------------------------------------------------------------
  616. // utility for platform::hasSubDirectory() and platform::dumpDirectories()
  617. // ensures that the entry is a directory, and isnt on the ignore lists.
  618. inline bool isGoodDirectory(dirent* entry)
  619. {
  620. return (entry->d_type == DT_DIR // is a dir
  621. && dStrcmp(entry->d_name,".") != 0 // not here
  622. && dStrcmp(entry->d_name,"..") != 0 // not parent
  623. && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
  624. }
  625. //-----------------------------------------------------------------------------
  626. bool Platform::hasSubDirectory(const char *path)
  627. {
  628. DIR *dir;
  629. dirent *entry;
  630. dir = opendir(path);
  631. if(!dir)
  632. return false; // we got a bad path, so no, it has no subdirectory.
  633. while( (entry = readdir(dir)) )
  634. {
  635. if(isGoodDirectory(entry) )
  636. {
  637. closedir(dir);
  638. return true; // we have a subdirectory, that isnt on the exclude list.
  639. }
  640. }
  641. closedir(dir);
  642. return false; // either this dir had no subdirectories, or they were all on the exclude list.
  643. }
  644. bool Platform::fileDelete(const char * name)
  645. {
  646. return dFileDelete(name);
  647. }
  648. static bool recurseDumpDirectories(const char *basePath, const char *subPath, Vector<StringTableEntry> &directoryVector, S32 currentDepth, S32 recurseDepth, bool noBasePath)
  649. {
  650. char Path[1024];
  651. DIR *dip;
  652. struct dirent *d;
  653. dsize_t trLen = basePath ? dStrlen(basePath) : 0;
  654. dsize_t subtrLen = subPath ? dStrlen(subPath) : 0;
  655. char trail = trLen > 0 ? basePath[trLen - 1] : '\0';
  656. char subTrail = subtrLen > 0 ? subPath[subtrLen - 1] : '\0';
  657. if (trail == '/')
  658. {
  659. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  660. {
  661. if (subTrail == '/')
  662. dSprintf(Path, 1024, "%s%s", basePath, subPath);
  663. else
  664. dSprintf(Path, 1024, "%s%s/", basePath, subPath);
  665. }
  666. else
  667. dSprintf(Path, 1024, "%s", basePath);
  668. }
  669. else
  670. {
  671. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  672. {
  673. if (subTrail == '/')
  674. dSprintf(Path, 1024, "%s%s", basePath, subPath);
  675. else
  676. dSprintf(Path, 1024, "%s%s/", basePath, subPath);
  677. }
  678. else
  679. dSprintf(Path, 1024, "%s/", basePath);
  680. }
  681. dip = opendir(Path);
  682. if (dip == NULL)
  683. return false;
  684. //////////////////////////////////////////////////////////////////////////
  685. // add path to our return list ( provided it is valid )
  686. //////////////////////////////////////////////////////////////////////////
  687. if (!Platform::isExcludedDirectory(subPath))
  688. {
  689. if (noBasePath)
  690. {
  691. // We have a path and it's not an empty string or an excluded directory
  692. if ( (subPath && (dStrncmp (subPath, "", 1) != 0)) )
  693. directoryVector.push_back(StringTable->insert(subPath));
  694. }
  695. else
  696. {
  697. if ( (subPath && (dStrncmp(subPath, "", 1) != 0)) )
  698. {
  699. char szPath[1024];
  700. dMemset(szPath, 0, 1024);
  701. if (trail == '/')
  702. {
  703. if ((basePath[dStrlen(basePath) - 1]) != '/')
  704. dSprintf(szPath, 1024, "%s%s", basePath, &subPath[1]);
  705. else
  706. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  707. }
  708. else
  709. {
  710. if ((basePath[dStrlen(basePath) - 1]) != '/')
  711. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  712. else
  713. dSprintf(szPath, 1024, "%s/%s", basePath, subPath);
  714. }
  715. directoryVector.push_back(StringTable->insert(szPath));
  716. }
  717. else
  718. directoryVector.push_back(StringTable->insert(basePath));
  719. }
  720. }
  721. //////////////////////////////////////////////////////////////////////////
  722. // Iterate through and grab valid directories
  723. //////////////////////////////////////////////////////////////////////////
  724. while (d = readdir(dip))
  725. {
  726. bool isDir;
  727. isDir = false;
  728. if (d->d_type == DT_UNKNOWN)
  729. {
  730. char child [1024];
  731. if ((Path[dStrlen(Path) - 1] == '/'))
  732. dSprintf(child, 1024, "%s%s", Path, d->d_name);
  733. else
  734. dSprintf(child, 1024, "%s/%s", Path, d->d_name);
  735. isDir = Platform::isDirectory (child);
  736. }
  737. else if (d->d_type & DT_DIR)
  738. isDir = true;
  739. if ( isDir )
  740. {
  741. if (dStrcmp(d->d_name, ".") == 0 ||
  742. dStrcmp(d->d_name, "..") == 0)
  743. continue;
  744. if (Platform::isExcludedDirectory(d->d_name))
  745. continue;
  746. if ( (subPath && (dStrncmp(subPath, "", 1) != 0)) )
  747. {
  748. char child[1024];
  749. if ((subPath[dStrlen(subPath) - 1] == '/'))
  750. dSprintf(child, 1024, "%s%s", subPath, d->d_name);
  751. else
  752. dSprintf(child, 1024, "%s/%s", subPath, d->d_name);
  753. if (currentDepth < recurseDepth || recurseDepth == -1 )
  754. recurseDumpDirectories(basePath, child, directoryVector,
  755. currentDepth + 1, recurseDepth,
  756. noBasePath);
  757. }
  758. else
  759. {
  760. char child[1024];
  761. if ( (basePath[dStrlen(basePath) - 1]) == '/')
  762. dStrcpy (child, d->d_name);
  763. else
  764. dSprintf(child, 1024, "/%s", d->d_name);
  765. if (currentDepth < recurseDepth || recurseDepth == -1)
  766. recurseDumpDirectories(basePath, child, directoryVector,
  767. currentDepth + 1, recurseDepth,
  768. noBasePath);
  769. }
  770. }
  771. }
  772. closedir(dip);
  773. return true;
  774. }
  775. //-----------------------------------------------------------------------------
  776. bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
  777. {
  778. bool retVal = recurseDumpDirectories(path, "", directoryVector, 0, depth, noBasePath);
  779. clearExcludedDirectories();
  780. return retVal;
  781. }
  782. //-----------------------------------------------------------------------------
  783. static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
  784. {
  785. DIR *dir;
  786. dirent *entry;
  787. // be sure it opens.
  788. dir = opendir(curPath);
  789. if(!dir)
  790. return false;
  791. // look inside the current directory
  792. while( (entry = readdir(dir)) )
  793. {
  794. // construct the full file path. we need this to get the file size and to recurse
  795. U32 len = dStrlen(curPath) + entry->d_namlen + 2;
  796. char pathbuf[len];
  797. dSprintf( pathbuf, len, "%s/%s", curPath, entry->d_name);
  798. pathbuf[len] = '\0';
  799. // ok, deal with directories and files seperately.
  800. if( entry->d_type == DT_DIR )
  801. {
  802. if( depth == 0)
  803. continue;
  804. // filter out dirs we dont want.
  805. if( !isGoodDirectory(entry) )
  806. continue;
  807. // recurse into the dir
  808. recurseDumpPath( pathbuf, fileVector, depth-1);
  809. }
  810. else
  811. {
  812. //add the file entry to the list
  813. // unlike recurseDumpDirectories(), we need to return more complex info here.
  814. U32 fileSize = Platform::getFileSize(pathbuf);
  815. fileVector.increment();
  816. Platform::FileInfo& rInfo = fileVector.last();
  817. rInfo.pFullPath = StringTable->insert(curPath);
  818. rInfo.pFileName = StringTable->insert(entry->d_name);
  819. rInfo.fileSize = fileSize;
  820. }
  821. }
  822. closedir(dir);
  823. return true;
  824. }
  825. //-----------------------------------------------------------------------------
  826. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
  827. {
  828. PROFILE_START(dumpPath);
  829. int len = dStrlen(path);
  830. char newpath[len+1];
  831. dStrncpy(newpath,path,len);
  832. newpath[len] = '\0'; // null terminate
  833. if(newpath[len - 1] == '/')
  834. newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
  835. bool ret = recurseDumpPath( newpath, fileVector, depth);
  836. PROFILE_END();
  837. return ret;
  838. }
  839. // TODO: implement stringToFileTime()
  840. bool Platform::stringToFileTime(const char * string, FileTime * time) { return false;}
  841. // TODO: implement fileTimeToString()
  842. bool Platform::fileTimeToString(FileTime * time, char * string, U32 strLen) { return false;}
  843. //-----------------------------------------------------------------------------
  844. #if defined(TORQUE_DEBUG)
  845. ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
  846. Con::printf("testing %s",(const char*)argv[1]);
  847. Platform::addExcludedDirectory(".svn");
  848. if(Platform::hasSubDirectory(argv[1]))
  849. Con::printf(" has subdir");
  850. else
  851. Con::printf(" does not have subdir");
  852. }
  853. ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
  854. Vector<StringTableEntry> paths;
  855. const S32 depth = dAtoi(argv[2]);
  856. const bool noBasePath = dAtob(argv[3]);
  857. Platform::addExcludedDirectory(".svn");
  858. Platform::dumpDirectories(argv[1], paths, depth, noBasePath);
  859. Con::printf("Dumping directories starting from %s with depth %i", (const char*)argv[1],depth);
  860. for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
  861. Con::printf(*itr);
  862. }
  863. }
  864. ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
  865. {
  866. Vector<Platform::FileInfo> files;
  867. S32 depth = dAtoi(argv[2]);
  868. Platform::addExcludedDirectory(".svn");
  869. Platform::dumpPath(argv[1], files, depth);
  870. for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
  871. Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
  872. }
  873. }
  874. //-----------------------------------------------------------------------------
  875. ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
  876. {
  877. return dFileTouch(argv[1]);
  878. }
  879. ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
  880. {
  881. FileTime create, modify;
  882. bool ok = Platform::getFileTimes(argv[1], &create, &modify);
  883. Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
  884. return ok;
  885. }
  886. #endif