winFileio.cc 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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 "platformWin32/platformWin32.h"
  24. #include "platform/platformFileIO.h"
  25. #include "collection/vector.h"
  26. #include "string/stringTable.h"
  27. #include "console/console.h"
  28. #include "io/resource/resourceManager.h"
  29. #include "string/unicode.h"
  30. // Microsoft VC++ has this POSIX header in the wrong directory
  31. #if defined(TORQUE_COMPILER_VISUALC)
  32. #include <sys/utime.h>
  33. #elif defined (TORQUE_COMPILER_GCC)
  34. #include <time.h>
  35. #include <sys/utime.h>
  36. #else
  37. #include <utime.h>
  38. #endif
  39. //------------------------------------------------------------------------------
  40. enum DriveType
  41. {
  42. DRIVETYPE_FIXED = 0,
  43. DRIVETYPE_REMOVABLE = 1,
  44. DRIVETYPE_REMOTE = 2,
  45. DRIVETYPE_CDROM = 3,
  46. DRIVETYPE_RAMDISK = 4,
  47. DRIVETYPE_UNKNOWN = 5
  48. };
  49. //-------------------------------------- Helper Functions
  50. static void forwardslash(char *str)
  51. {
  52. while(*str)
  53. {
  54. if(*str == '\\')
  55. *str = '/';
  56. str++;
  57. }
  58. }
  59. static void backslash(char *str)
  60. {
  61. while(*str)
  62. {
  63. if(*str == '/')
  64. *str = '\\';
  65. str++;
  66. }
  67. }
  68. //-----------------------------------------------------------------------------
  69. bool Platform::fileDelete(const char * name)
  70. {
  71. if(!name || (dStrlen(name) >= MAX_PATH))
  72. return(false);
  73. //return(::DeleteFile(name));
  74. if(Platform::isFile(name))
  75. return(remove(name) == 0);
  76. else
  77. return ::RemoveDirectoryA(name) != 0;
  78. }
  79. bool Platform::fileRename(const char *oldName, const char *newName)
  80. {
  81. if(oldName == NULL || newName == NULL || dStrlen(oldName) >= MAX_PATH || dStrlen(newName) > MAX_PATH)
  82. return false;
  83. char oldf[MAX_PATH], newf[MAX_PATH];
  84. dStrcpy(oldf, oldName);
  85. dStrcpy(newf, newName);
  86. backslash(oldf);
  87. backslash(newf);
  88. return rename(oldf, newf) == 0;
  89. }
  90. bool Platform::fileTouch(const char * name)
  91. {
  92. // change the modified time to the current time (0byte WriteFile fails!)
  93. return(utime(name, 0) != -1);
  94. };
  95. static S32 QSORT_CALLBACK pathCompare(const void* a,const void* b)
  96. {
  97. const char *aa = *((const char **)a), *ptrA;
  98. const char *bb = *((const char **)b), *ptrB;
  99. while(aa && bb && *aa && *bb)
  100. {
  101. ptrA = dStrchr(aa, '/');
  102. ptrB = dStrchr(bb, '/');
  103. if(ptrA && ptrB)
  104. {
  105. ++ptrA; ++ptrB;
  106. S32 len = ptrA - aa > ptrB - bb ? ptrA - aa : ptrB - bb;
  107. S32 ret = dStrnicmp(aa, bb, len);
  108. if(ret != 0)
  109. return ret;
  110. }
  111. aa = ptrA;
  112. bb = ptrB;
  113. }
  114. if(aa && ! bb)
  115. return -1;
  116. if(bb && ! aa)
  117. return 1;
  118. if(aa && bb)
  119. return dStricmp(aa, bb);
  120. return 0;
  121. }
  122. bool Platform::pathCopy(const char *fromName, const char *toName, bool nooverwrite)
  123. {
  124. if(!fromName || (dStrlen(fromName) >= MAX_PATH) ||
  125. !toName || (dStrlen(toName) >= MAX_PATH))
  126. return(false);
  127. static char filebuf[2048];
  128. dStrcpy(filebuf, fromName);
  129. backslash(filebuf);
  130. fromName = filebuf;
  131. static char filebuf2[2048];
  132. dStrcpy(filebuf2, toName);
  133. backslash(filebuf2);
  134. toName = filebuf2;
  135. // Copy File
  136. if (Platform::isFile(fromName))
  137. {
  138. #ifdef UNICODE
  139. UTF16 f[1024], t[1024];
  140. convertUTF8toUTF16((UTF8 *)fromName, f, sizeof(f));
  141. convertUTF8toUTF16((UTF8 *)toName, t, sizeof(t));
  142. #else
  143. char *f = (char*)fromName;
  144. char *t = (char*)toName;
  145. #endif
  146. if(::CopyFile((LPCWSTR)f, (LPCWSTR)t, nooverwrite))
  147. {
  148. return true;
  149. }
  150. return false;
  151. }
  152. // Copy Path
  153. else if (Platform::isDirectory(fromName))
  154. {
  155. // If the destination path exists and we don't want to overwrite, return.
  156. if ((Platform::isDirectory(toName) || Platform::isFile(toName)) && nooverwrite)
  157. return false;
  158. Vector<StringTableEntry> directoryInfo;
  159. Platform::dumpDirectories(fromName, directoryInfo, -1);
  160. ResourceManager->initExcludedDirectories();
  161. Vector<Platform::FileInfo> fileInfo;
  162. Platform::dumpPath(fromName, fileInfo);
  163. Platform::clearExcludedDirectories();
  164. // Create all the directories.
  165. for (S32 i = 0; i < directoryInfo.size(); i++)
  166. {
  167. const char* from = directoryInfo[i];
  168. char to[1024];
  169. Platform::makeFullPathName(from + dStrlen(fromName) + (dStricmp(from, fromName) ? 1 : 0), to, sizeof(to), toName);
  170. if(*(to + dStrlen(to) - 1) != '/')
  171. dStrcat(to, "/");
  172. forwardslash(to);
  173. if (!Platform::createPath(to))
  174. {
  175. // New directory should be deleted here.
  176. return false;
  177. }
  178. }
  179. for (S32 i = 0; i < fileInfo.size(); i++)
  180. {
  181. char from[1024];
  182. dSprintf(from, 1024, "%s/%s", fileInfo[i].pFullPath, fileInfo[i].pFileName);
  183. char to[1024];
  184. Platform::makeFullPathName(fileInfo[i].pFullPath + dStrlen(fromName) + (dStricmp(fileInfo[i].pFullPath, fromName) ? 1 : 0), to, sizeof(to), toName);
  185. dStrcat(to, "/");
  186. dStrcat(to, fileInfo[i].pFileName);
  187. backslash(from);
  188. backslash(to);
  189. #ifdef UNICODE
  190. UTF16 f[1024], t[1024];
  191. convertUTF8toUTF16((UTF8 *)from, f, sizeof(f));
  192. convertUTF8toUTF16((UTF8 *)to, t, sizeof(t));
  193. #else
  194. char *f = (char*)from;
  195. char *t = (char*)to;
  196. #endif
  197. if (!::CopyFile((LPCWSTR)f, (LPCWSTR)t, nooverwrite))
  198. {
  199. // New directory should be deleted here.
  200. return false;
  201. }
  202. }
  203. return true;
  204. }
  205. return false;
  206. }
  207. //-----------------------------------------------------------------------------
  208. // Constructors & Destructor
  209. //-----------------------------------------------------------------------------
  210. //-----------------------------------------------------------------------------
  211. // After construction, the currentStatus will be Closed and the capabilities
  212. // will be 0.
  213. //-----------------------------------------------------------------------------
  214. File::File()
  215. : currentStatus(Closed), capability(0)
  216. {
  217. AssertFatal(sizeof(HANDLE) == sizeof(void *), "File::File: cannot cast void* to HANDLE");
  218. handle = (void *)INVALID_HANDLE_VALUE;
  219. }
  220. //-----------------------------------------------------------------------------
  221. // insert a copy constructor here... (currently disabled)
  222. //-----------------------------------------------------------------------------
  223. //-----------------------------------------------------------------------------
  224. // Destructor
  225. //-----------------------------------------------------------------------------
  226. File::~File()
  227. {
  228. close();
  229. handle = (void *)INVALID_HANDLE_VALUE;
  230. }
  231. //-----------------------------------------------------------------------------
  232. // Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
  233. // Truncate the file if the mode is either Write or ReadWrite and truncate is
  234. // true.
  235. //
  236. // Sets capability appropriate to the openMode.
  237. // Returns the currentStatus of the file.
  238. //-----------------------------------------------------------------------------
  239. File::Status File::open(const char *filename, const AccessMode openMode)
  240. {
  241. static char filebuf[2048];
  242. dStrcpy(filebuf, filename);
  243. backslash(filebuf);
  244. #ifdef UNICODE
  245. UTF16 fname[2048];
  246. convertUTF8toUTF16((UTF8 *)filebuf, fname, sizeof(fname));
  247. #else
  248. char *fname;
  249. fname = filebuf;
  250. #endif
  251. AssertFatal(NULL != fname, "File::open: NULL fname");
  252. AssertWarn(INVALID_HANDLE_VALUE == (HANDLE)handle, "File::open: handle already valid");
  253. // Close the file if it was already open...
  254. if (Closed != currentStatus)
  255. close();
  256. // create the appropriate type of file...
  257. switch (openMode)
  258. {
  259. case Read:
  260. handle = (void *)CreateFile((LPCWSTR)fname,
  261. GENERIC_READ,
  262. FILE_SHARE_READ,
  263. NULL,
  264. OPEN_EXISTING,
  265. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
  266. NULL);
  267. break;
  268. case Write:
  269. handle = (void *)CreateFile((LPCWSTR)fname,
  270. GENERIC_WRITE,
  271. 0,
  272. NULL,
  273. CREATE_ALWAYS,
  274. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
  275. NULL);
  276. break;
  277. case ReadWrite:
  278. handle = (void *)CreateFile((LPCWSTR)fname,
  279. GENERIC_WRITE | GENERIC_READ,
  280. 0,
  281. NULL,
  282. OPEN_ALWAYS,
  283. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
  284. NULL);
  285. break;
  286. case WriteAppend:
  287. handle = (void *)CreateFile((LPCWSTR)fname,
  288. GENERIC_WRITE,
  289. 0,
  290. NULL,
  291. OPEN_ALWAYS,
  292. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
  293. NULL);
  294. break;
  295. default:
  296. AssertFatal(false, "File::open: bad access mode"); // impossible
  297. }
  298. if (INVALID_HANDLE_VALUE == (HANDLE)handle) // handle not created successfully
  299. {
  300. return setStatus();
  301. }
  302. else
  303. {
  304. // successfully created file, so set the file capabilities...
  305. switch (openMode)
  306. {
  307. case Read:
  308. capability = U32(FileRead);
  309. break;
  310. case Write:
  311. case WriteAppend:
  312. capability = U32(FileWrite);
  313. break;
  314. case ReadWrite:
  315. capability = U32(FileRead) |
  316. U32(FileWrite);
  317. break;
  318. default:
  319. AssertFatal(false, "File::open: bad access mode");
  320. }
  321. return currentStatus = Ok; // success!
  322. }
  323. }
  324. //-----------------------------------------------------------------------------
  325. // Get the current position of the file pointer.
  326. //-----------------------------------------------------------------------------
  327. U32 File::getPosition() const
  328. {
  329. AssertFatal(Closed != currentStatus, "File::getPosition: file closed");
  330. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::getPosition: invalid file handle");
  331. return SetFilePointer((HANDLE)handle,
  332. 0, // how far to move
  333. NULL, // pointer to high word
  334. FILE_CURRENT); // from what point
  335. }
  336. //-----------------------------------------------------------------------------
  337. // Set the position of the file pointer.
  338. // Absolute and relative positioning is supported via the absolutePos
  339. // parameter.
  340. //
  341. // If positioning absolutely, position MUST be positive - an IOError results if
  342. // position is negative.
  343. // Position can be negative if positioning relatively, however positioning
  344. // before the start of the file is an IOError.
  345. //
  346. // Returns the currentStatus of the file.
  347. //-----------------------------------------------------------------------------
  348. File::Status File::setPosition(S32 position, bool absolutePos)
  349. {
  350. AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
  351. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::setPosition: invalid file handle");
  352. if (Ok != currentStatus && EOS != currentStatus)
  353. return currentStatus;
  354. U32 finalPos;
  355. switch (absolutePos)
  356. {
  357. case true: // absolute position
  358. AssertFatal(0 <= position, "File::setPosition: negative absolute position");
  359. // position beyond EOS is OK
  360. finalPos = SetFilePointer((HANDLE)handle,
  361. position,
  362. NULL,
  363. FILE_BEGIN);
  364. break;
  365. case false: // relative position
  366. AssertFatal((getPosition() >= (U32)abs(position) && 0 > position) || 0 <= position, "File::setPosition: negative relative position");
  367. // position beyond EOS is OK
  368. finalPos = SetFilePointer((HANDLE)handle,
  369. position,
  370. NULL,
  371. FILE_CURRENT);
  372. }
  373. if (0xffffffff == finalPos)
  374. return setStatus(); // unsuccessful
  375. else if (finalPos >= getSize())
  376. return currentStatus = EOS; // success, at end of file
  377. else
  378. return currentStatus = Ok; // success!
  379. }
  380. //-----------------------------------------------------------------------------
  381. // Get the size of the file in bytes.
  382. // It is an error to query the file size for a Closed file, or for one with an
  383. // error status.
  384. //-----------------------------------------------------------------------------
  385. U32 File::getSize() const
  386. {
  387. AssertWarn(Closed != currentStatus, "File::getSize: file closed");
  388. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::getSize: invalid file handle");
  389. if (Ok == currentStatus || EOS == currentStatus)
  390. {
  391. DWORD high;
  392. return GetFileSize((HANDLE)handle, &high); // success!
  393. }
  394. else
  395. return 0; // unsuccessful
  396. }
  397. //-----------------------------------------------------------------------------
  398. // Flush the file.
  399. // It is an error to flush a read-only file.
  400. // Returns the currentStatus of the file.
  401. //-----------------------------------------------------------------------------
  402. File::Status File::flush()
  403. {
  404. AssertFatal(Closed != currentStatus, "File::flush: file closed");
  405. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::flush: invalid file handle");
  406. AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
  407. if (0 != FlushFileBuffers((HANDLE)handle))
  408. return setStatus(); // unsuccessful
  409. else
  410. return currentStatus = Ok; // success!
  411. }
  412. //-----------------------------------------------------------------------------
  413. // Close the File.
  414. //
  415. // Returns the currentStatus
  416. //-----------------------------------------------------------------------------
  417. File::Status File::close()
  418. {
  419. // check if it's already closed...
  420. if (Closed == currentStatus)
  421. return currentStatus;
  422. // it's not, so close it...
  423. if (INVALID_HANDLE_VALUE != (HANDLE)handle)
  424. {
  425. if (0 == CloseHandle((HANDLE)handle))
  426. return setStatus(); // unsuccessful
  427. }
  428. handle = (void *)INVALID_HANDLE_VALUE;
  429. return currentStatus = Closed;
  430. }
  431. //-----------------------------------------------------------------------------
  432. // Self-explanatory.
  433. //-----------------------------------------------------------------------------
  434. File::Status File::getStatus() const
  435. {
  436. return currentStatus;
  437. }
  438. //-----------------------------------------------------------------------------
  439. // Sets and returns the currentStatus when an error has been encountered.
  440. //-----------------------------------------------------------------------------
  441. File::Status File::setStatus()
  442. {
  443. switch (GetLastError())
  444. {
  445. case ERROR_INVALID_HANDLE:
  446. case ERROR_INVALID_ACCESS:
  447. case ERROR_TOO_MANY_OPEN_FILES:
  448. case ERROR_FILE_NOT_FOUND:
  449. case ERROR_SHARING_VIOLATION:
  450. case ERROR_HANDLE_DISK_FULL:
  451. return currentStatus = IOError;
  452. default:
  453. return currentStatus = UnknownError;
  454. }
  455. }
  456. //-----------------------------------------------------------------------------
  457. // Sets and returns the currentStatus to status.
  458. //-----------------------------------------------------------------------------
  459. File::Status File::setStatus(File::Status status)
  460. {
  461. return currentStatus = status;
  462. }
  463. //-----------------------------------------------------------------------------
  464. // Read from a file.
  465. // The number of bytes to read is passed in size, the data is returned in src.
  466. // The number of bytes read is available in bytesRead if a non-Null pointer is
  467. // provided.
  468. //-----------------------------------------------------------------------------
  469. File::Status File::read(U32 size, char *dst, U32 *bytesRead)
  470. {
  471. AssertFatal(Closed != currentStatus, "File::read: file closed");
  472. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::read: invalid file handle");
  473. AssertFatal(NULL != dst, "File::read: NULL destination pointer");
  474. AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
  475. AssertWarn(0 != size, "File::read: size of zero");
  476. if (Ok != currentStatus || 0 == size)
  477. return currentStatus;
  478. else
  479. {
  480. DWORD lastBytes;
  481. DWORD *bytes = (NULL == bytesRead) ? &lastBytes : (DWORD *)bytesRead;
  482. if (0 != ReadFile((HANDLE)handle, dst, size, bytes, NULL))
  483. {
  484. if(*((U32 *)bytes) != size)
  485. return currentStatus = EOS; // end of stream
  486. }
  487. else
  488. return setStatus(); // unsuccessful
  489. }
  490. return currentStatus = Ok; // successfully read size bytes
  491. }
  492. //-----------------------------------------------------------------------------
  493. // Write to a file.
  494. // The number of bytes to write is passed in size, the data is passed in src.
  495. // The number of bytes written is available in bytesWritten if a non-Null
  496. // pointer is provided.
  497. //-----------------------------------------------------------------------------
  498. File::Status File::write(U32 size, const char *src, U32 *bytesWritten)
  499. {
  500. AssertFatal(Closed != currentStatus, "File::write: file closed");
  501. AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::write: invalid file handle");
  502. AssertFatal(NULL != src, "File::write: NULL source pointer");
  503. AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
  504. AssertWarn(0 != size, "File::write: size of zero");
  505. if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
  506. return currentStatus;
  507. else
  508. {
  509. DWORD lastBytes;
  510. DWORD *bytes = (NULL == bytesWritten) ? &lastBytes : (DWORD *)bytesWritten;
  511. if (0 != WriteFile((HANDLE)handle, src, size, bytes, NULL))
  512. return currentStatus = Ok; // success!
  513. else
  514. return setStatus(); // unsuccessful
  515. }
  516. }
  517. //-----------------------------------------------------------------------------
  518. // Self-explanatory.
  519. //-----------------------------------------------------------------------------
  520. bool File::hasCapability(Capability cap) const
  521. {
  522. return (0 != (U32(cap) & capability));
  523. }
  524. S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
  525. {
  526. if(a.v2 > b.v2)
  527. return 1;
  528. if(a.v2 < b.v2)
  529. return -1;
  530. if(a.v1 > b.v1)
  531. return 1;
  532. if(a.v1 < b.v1)
  533. return -1;
  534. return 0;
  535. }
  536. static bool recurseDumpPath(const char *path, const char *pattern, Vector<Platform::FileInfo> &fileVector, S32 recurseDepth )
  537. {
  538. char buf[1024], fullPath[1024];
  539. WIN32_FIND_DATA findData;
  540. Platform::makeFullPathName(path, fullPath, sizeof(fullPath));
  541. dSprintf(buf, sizeof(buf), "%s/%s", fullPath, pattern);
  542. #ifdef UNICODE
  543. UTF16 search[1024];
  544. convertUTF8toUTF16((UTF8 *)buf, search, sizeof(search));
  545. #else
  546. char *search = buf;
  547. #endif
  548. HANDLE handle = FindFirstFile(search, &findData);
  549. if (handle == INVALID_HANDLE_VALUE)
  550. return false;
  551. do
  552. {
  553. #ifdef UNICODE
  554. char fnbuf[1024];
  555. convertUTF16toUTF8(findData.cFileName, (UTF8 *)fnbuf, sizeof(fnbuf));
  556. #else
  557. char *fnbuf = findData.cFileName;
  558. #endif
  559. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  560. {
  561. // make sure it is a directory
  562. if (findData.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_SYSTEM) )
  563. continue;
  564. // skip . and .. directories
  565. if (dStrcmp(fnbuf, ".") == 0 || dStrcmp(fnbuf, "..") == 0)
  566. continue;
  567. // Skip excluded directores
  568. if(Platform::isExcludedDirectory(fnbuf))
  569. continue;
  570. char child[1024];
  571. dSprintf(child, sizeof(child), "%s/%s", path, fnbuf);
  572. if( recurseDepth > 0 )
  573. recurseDumpPath(child, pattern, fileVector, recurseDepth - 1);
  574. else if (recurseDepth == -1)
  575. recurseDumpPath(child, pattern, fileVector, -1);
  576. }
  577. else
  578. {
  579. // make sure it is the kind of file we're looking for
  580. if (findData.dwFileAttributes &
  581. (FILE_ATTRIBUTE_DIRECTORY|
  582. FILE_ATTRIBUTE_OFFLINE|
  583. FILE_ATTRIBUTE_SYSTEM|
  584. FILE_ATTRIBUTE_TEMPORARY) )
  585. continue;
  586. // add it to the list
  587. fileVector.increment();
  588. Platform::FileInfo& rInfo = fileVector.last();
  589. rInfo.pFullPath = StringTable->insert(path);
  590. rInfo.pFileName = StringTable->insert(fnbuf);
  591. rInfo.fileSize = findData.nFileSizeLow;
  592. }
  593. }while(FindNextFile(handle, &findData));
  594. FindClose(handle);
  595. return true;
  596. }
  597. //--------------------------------------
  598. bool Platform::getFileTimes(const char *filePath, FileTime *createTime, FileTime *modifyTime)
  599. {
  600. WIN32_FIND_DATA findData;
  601. #ifdef UNICODE
  602. UTF16 fp[512];
  603. convertUTF8toUTF16((UTF8 *)filePath, fp, sizeof(fp));
  604. #else
  605. const char *fp = filePath;
  606. #endif
  607. HANDLE h = FindFirstFile(fp, &findData);
  608. if(h == INVALID_HANDLE_VALUE)
  609. return false;
  610. if(createTime)
  611. {
  612. createTime->v1 = findData.ftCreationTime.dwLowDateTime;
  613. createTime->v2 = findData.ftCreationTime.dwHighDateTime;
  614. }
  615. if(modifyTime)
  616. {
  617. modifyTime->v1 = findData.ftLastWriteTime.dwLowDateTime;
  618. modifyTime->v2 = findData.ftLastWriteTime.dwHighDateTime;
  619. }
  620. FindClose(h);
  621. return true;
  622. }
  623. //--------------------------------------
  624. bool Platform::createPath(const char *file)
  625. {
  626. char pathbuf[1024];
  627. const char *dir;
  628. pathbuf[0] = 0;
  629. U32 pathLen = 0;
  630. while((dir = dStrchr(file, '/')) != NULL)
  631. {
  632. dStrncpy(pathbuf + pathLen, file, dir - file);
  633. pathbuf[pathLen + dir-file] = 0;
  634. #ifdef UNICODE
  635. UTF16 b[1024];
  636. convertUTF8toUTF16((UTF8 *)pathbuf, b, sizeof(b));
  637. bool ret = CreateDirectory(b, NULL);
  638. #else
  639. bool ret = CreateDirectory(pathbuf, NULL);
  640. #endif
  641. pathLen += dir - file;
  642. pathbuf[pathLen++] = '/';
  643. file = dir + 1;
  644. }
  645. return true;
  646. }
  647. //--------------------------------------
  648. bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo> &fileVector, S32 recurseDepth)
  649. {
  650. return recurseDumpPath(path, "*", fileVector, recurseDepth );
  651. }
  652. //--------------------------------------
  653. StringTableEntry Platform::getCurrentDirectory()
  654. {
  655. char cwd_buf[2048];
  656. GetCurrentDirectoryA(2047, cwd_buf);
  657. #ifdef UNICODE
  658. int codePage = GetACP();
  659. if (codePage != CP_UTF8)
  660. {
  661. UTF16 b[2048];
  662. int size_w = MultiByteToWideChar(codePage, 0, cwd_buf, dStrlen(cwd_buf), nullptr, 0); // get the required buffer size for wchars
  663. MultiByteToWideChar(codePage, 0, cwd_buf, dStrlen(cwd_buf), b, size_w);
  664. int size_mb = WideCharToMultiByte(CP_UTF8, 0, b, size_w, nullptr, 0, NULL, NULL); // get the required buffer size for chars
  665. WideCharToMultiByte(CP_UTF8, 0, b, dStrlen(b), cwd_buf, size_mb, NULL, NULL);
  666. cwd_buf[size_mb] = '\0';
  667. }
  668. #endif
  669. forwardslash(cwd_buf);
  670. return StringTable->insert(cwd_buf);
  671. }
  672. bool Platform::setCurrentDirectory(StringTableEntry newDir)
  673. {
  674. //StringTableEntry lastDir = Platform::getCurrentDirectory();
  675. char cwd_buf[2048];
  676. dStrncpy(cwd_buf, newDir, sizeof(cwd_buf)-1);
  677. cwd_buf[sizeof(cwd_buf)-1] = 0;
  678. backslash(cwd_buf);
  679. return SetCurrentDirectoryA(cwd_buf);
  680. }
  681. StringTableEntry Platform::getExecutableName()
  682. {
  683. static StringTableEntry cen = NULL;
  684. if (!cen)
  685. {
  686. char cen_buf[2048];
  687. GetModuleFileNameA( NULL, cen_buf, 2047);
  688. forwardslash(cen_buf);
  689. char *delimiter = dStrrchr( cen_buf, '/' );
  690. if( delimiter != NULL )
  691. {
  692. *delimiter = 0x00;
  693. delimiter++;
  694. cen = StringTable->insert(delimiter);
  695. }
  696. else
  697. cen = StringTable->insert(cen_buf);
  698. }
  699. return cen;
  700. }
  701. StringTableEntry Platform::getExecutablePath()
  702. {
  703. static StringTableEntry cen = NULL;
  704. if (!cen)
  705. {
  706. char cen_buf[2048];
  707. GetModuleFileNameA( NULL, cen_buf, 2047);
  708. forwardslash(cen_buf);
  709. char *delimiter = dStrrchr( cen_buf, '/' );
  710. if( delimiter != NULL )
  711. *delimiter = 0x00;
  712. cen = StringTable->insert(cen_buf);
  713. }
  714. return cen;
  715. }
  716. //--------------------------------------
  717. bool Platform::isFile(const char *pFilePath)
  718. {
  719. if (!pFilePath || !*pFilePath)
  720. return false;
  721. // Get file info
  722. WIN32_FIND_DATA findData;
  723. #ifdef UNICODE
  724. UTF16 b[512];
  725. convertUTF8toUTF16((UTF8 *)pFilePath, b, sizeof(b));
  726. HANDLE handle = FindFirstFile(b, &findData);
  727. #else
  728. HANDLE handle = FindFirstFile(pFilePath, &findData);
  729. #endif
  730. // [neo, 4/6/2007]
  731. // This used to be after the FindClose() call
  732. if(handle == INVALID_HANDLE_VALUE)
  733. return false;
  734. FindClose(handle);
  735. // if the file is a Directory, Offline, System or Temporary then FALSE
  736. if (findData.dwFileAttributes &
  737. (FILE_ATTRIBUTE_DIRECTORY|
  738. FILE_ATTRIBUTE_OFFLINE|
  739. FILE_ATTRIBUTE_SYSTEM|
  740. FILE_ATTRIBUTE_TEMPORARY) )
  741. return false;
  742. // must be a real file then
  743. return true;
  744. }
  745. //--------------------------------------
  746. S32 Platform::getFileSize(const char *pFilePath)
  747. {
  748. if (!pFilePath || !*pFilePath)
  749. return -1;
  750. // Get file info
  751. WIN32_FIND_DATAA findData;
  752. HANDLE handle = FindFirstFileA(pFilePath, &findData);
  753. FindClose(handle);
  754. if(handle == INVALID_HANDLE_VALUE)
  755. return -1;
  756. // if the file is a Directory, Offline, System or Temporary then FALSE
  757. if (findData.dwFileAttributes &
  758. (FILE_ATTRIBUTE_DIRECTORY|
  759. FILE_ATTRIBUTE_OFFLINE|
  760. FILE_ATTRIBUTE_SYSTEM|
  761. FILE_ATTRIBUTE_TEMPORARY) )
  762. return -1;
  763. // must be a real file then
  764. return findData.nFileSizeLow;;
  765. }
  766. //--------------------------------------
  767. bool Platform::isDirectory(const char *pDirPath)
  768. {
  769. if (!pDirPath || !*pDirPath)
  770. return false;
  771. // Get file info
  772. WIN32_FIND_DATA findData;
  773. #ifdef UNICODE
  774. UTF16 b[512];
  775. convertUTF8toUTF16((UTF8 *)pDirPath, b, sizeof(b));
  776. HANDLE handle = FindFirstFile(b, &findData);
  777. #else
  778. HANDLE handle = FindFirstFile(pDirPath, &findData);
  779. #endif
  780. // [neo, 5/15/2007]
  781. // This check was AFTER FindClose for some reason - this is most probably the
  782. // original intent.
  783. if(handle == INVALID_HANDLE_VALUE)
  784. return false;
  785. FindClose(handle);
  786. // if the file is a Directory, Offline, System or Temporary then FALSE
  787. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  788. {
  789. // make sure it's a valid game directory
  790. if (findData.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_SYSTEM) )
  791. return false;
  792. // must be a directory
  793. return true;
  794. }
  795. return false;
  796. }
  797. //--------------------------------------
  798. bool Platform::isSubDirectory(const char *pParent, const char *pDir)
  799. {
  800. if (!pParent || !*pDir)
  801. return false;
  802. // this is somewhat of a brute force method but we need to be 100% sure
  803. // that the user cannot enter things like ../dir or /dir etc,...
  804. WIN32_FIND_DATAA findData;
  805. HANDLE handle = FindFirstFileA(avar("%s/*", pParent), &findData);
  806. if (handle == INVALID_HANDLE_VALUE)
  807. return false;
  808. do
  809. {
  810. // if it is a directory...
  811. if (findData.dwFileAttributes &
  812. (FILE_ATTRIBUTE_DIRECTORY|
  813. FILE_ATTRIBUTE_OFFLINE|
  814. FILE_ATTRIBUTE_SYSTEM|
  815. FILE_ATTRIBUTE_TEMPORARY) )
  816. {
  817. // and the names match
  818. if (dStrcmp(pDir, findData.cFileName ) == 0)
  819. {
  820. // then we have a real sub directory
  821. FindClose(handle);
  822. return true;
  823. }
  824. }
  825. }while(FindNextFileA(handle, &findData));
  826. FindClose(handle);
  827. return false;
  828. }
  829. bool Platform::hasSubDirectory(const char *pPath)
  830. {
  831. if( !pPath )
  832. return false;
  833. ResourceManager->initExcludedDirectories();
  834. char search[1024];
  835. WIN32_FIND_DATAA findData;
  836. // Compose our search string - Format : ([path]/[subpath]/*)
  837. char trail = pPath[ dStrlen(pPath) - 1 ];
  838. if( trail == '/' )
  839. dStrcpy( search, pPath );
  840. else
  841. dSprintf(search, 1024, "%s/*", pPath );
  842. // See if we get any hits
  843. HANDLE handle = FindFirstFileA(search, &findData);
  844. if (handle == INVALID_HANDLE_VALUE)
  845. return false;
  846. do
  847. {
  848. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  849. {
  850. // skip . and .. directories
  851. if (dStrcmp(findData.cFileName, ".") == 0 || dStrcmp(findData.cFileName, "..") == 0)
  852. continue;
  853. if( Platform::isExcludedDirectory( findData.cFileName ) )
  854. continue;
  855. Platform::clearExcludedDirectories();
  856. FindClose(handle);
  857. return true;
  858. }
  859. }
  860. while(FindNextFileA(handle, &findData));
  861. FindClose(handle);
  862. Platform::clearExcludedDirectories();
  863. return false;
  864. }
  865. static bool recurseDumpDirectories(const char *basePath, const char *subPath, Vector<StringTableEntry> &directoryVector, S32 currentDepth, S32 recurseDepth, bool noBasePath)
  866. {
  867. char search[1024];
  868. //-----------------------------------------------------------------------------
  869. // Compose our search string - Format : ([path]/[subpath]/*)
  870. //-----------------------------------------------------------------------------
  871. dsize_t trLen = basePath ? dStrlen(basePath) : 0;
  872. dsize_t subtrLen = subPath ? dStrlen(subPath) : 0;
  873. char trail = trLen > 0 ? basePath[trLen - 1] : '\0';
  874. char subTrail = subtrLen > 0 ? subPath[subtrLen - 1] : '\0';
  875. char subLead = subtrLen > 0 ? subPath[0] : '\0';
  876. if (trail == '/')
  877. {
  878. // we have a sub path and it's not an empty string
  879. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  880. {
  881. if (subTrail == '/')
  882. dSprintf(search, 1024, "%s%s*", basePath, subPath);
  883. else
  884. dSprintf(search, 1024, "%s%s/*", basePath, subPath);
  885. }
  886. else
  887. dSprintf(search, 1024, "%s*", basePath);
  888. }
  889. else
  890. {
  891. if (subPath && (dStrncmp(subPath, "", 1) != 0))
  892. if (subTrail == '/')
  893. dSprintf(search, 1024, "%s%s*", basePath, subPath);
  894. else
  895. dSprintf(search, 1024, "%s%s/*", basePath, subPath);
  896. else
  897. dSprintf(search, 1024, "%s/*", basePath);
  898. }
  899. //-----------------------------------------------------------------------------
  900. // See if we get any hits
  901. //-----------------------------------------------------------------------------
  902. #ifdef UNICODE
  903. UTF16 b[1024];
  904. convertUTF8toUTF16((UTF8*)search, b, sizeof(b));
  905. int nCodePage = GetACP();
  906. WideCharToMultiByte(nCodePage, 0, b, sizeof(b), search, sizeof(search), 0, 0);
  907. #endif
  908. WIN32_FIND_DATAA findData;
  909. HANDLE handle = FindFirstFileA(search, &findData);
  910. if (handle == INVALID_HANDLE_VALUE)
  911. return false;
  912. //-----------------------------------------------------------------------------
  913. // add path to our return list ( provided it is valid )
  914. //-----------------------------------------------------------------------------
  915. if (!Platform::isExcludedDirectory(subPath))
  916. {
  917. if (noBasePath)
  918. {
  919. // We have a path and it's not an empty string or an excluded directory
  920. if ((subPath && (dStrncmp(subPath, "", 1) != 0)))
  921. directoryVector.push_back(StringTable->insert(subPath));
  922. }
  923. else
  924. {
  925. if ((subPath && (dStrncmp(subPath, "", 1) != 0)))
  926. {
  927. char szPath[1024];
  928. dMemset(szPath, 0, 1024);
  929. if (trail == '/')
  930. {
  931. if (subLead == '/')
  932. dSprintf(szPath, 1024, "%s%s", basePath, &subPath[1]);
  933. else
  934. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  935. }
  936. else
  937. {
  938. if (subLead == '/')
  939. dSprintf(szPath, 1024, "%s%s", basePath, subPath);
  940. else
  941. dSprintf(szPath, 1024, "%s/%s", basePath, subPath);
  942. }
  943. directoryVector.push_back(StringTable->insert(szPath));
  944. }
  945. else
  946. directoryVector.push_back(StringTable->insert(basePath));
  947. }
  948. }
  949. //-----------------------------------------------------------------------------
  950. // Iterate through and grab valid directories
  951. //-----------------------------------------------------------------------------
  952. do
  953. {
  954. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  955. {
  956. // skip . and .. directories
  957. if (dStrcmp(findData.cFileName, ".") == 0 || dStrcmp(findData.cFileName, "..") == 0)
  958. continue;
  959. // skip excluded directories
  960. if (Platform::isExcludedDirectory(findData.cFileName))
  961. continue;
  962. if ((subPath && (dStrncmp(subPath, "", 1) != 0)))
  963. {
  964. char child[1024];
  965. if (subTrail == '/')
  966. dSprintf(child, sizeof(child), "%s%s", subPath, findData.cFileName);
  967. else
  968. dSprintf(child, sizeof(child), "%s/%s", subPath, findData.cFileName);
  969. if (currentDepth < recurseDepth || recurseDepth == -1)
  970. recurseDumpDirectories(basePath, child, directoryVector, currentDepth + 1, recurseDepth, noBasePath);
  971. }
  972. else
  973. {
  974. char child[1024];
  975. if (trail == '/')
  976. dStrcpy(child, findData.cFileName);
  977. else
  978. dSprintf(child, sizeof(child), "/%s", findData.cFileName);
  979. if (currentDepth < recurseDepth || recurseDepth == -1)
  980. recurseDumpDirectories(basePath, child, directoryVector, currentDepth + 1, recurseDepth, noBasePath);
  981. }
  982. }
  983. } while (FindNextFileA(handle, &findData));
  984. FindClose(handle);
  985. return true;
  986. }
  987. bool Platform::dumpDirectories( const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath )
  988. {
  989. ResourceManager->initExcludedDirectories();
  990. bool retVal = recurseDumpDirectories( path, "", directoryVector, -1, depth, noBasePath );
  991. clearExcludedDirectories();
  992. return retVal;
  993. }
  994. //-----------------------------------------------------------------------------
  995. StringTableEntry Platform::osGetTemporaryDirectory()
  996. {
  997. //#pragma message("Implement UNICODE support for osGetTemporaryDirectory [01/23/2007 tom]" )
  998. char buf[512];
  999. DWORD len = GetTempPathA(sizeof(buf), buf);
  1000. // Remove the trailing slash
  1001. buf[len-1] = 0;
  1002. forwardslash(buf);
  1003. return StringTable->insert(buf);
  1004. }