macFileIO.mm 33 KB

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