FileSystem.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "IOEvents.h"
  29. #include "Log.h"
  30. #include "Thread.h"
  31. #include <cstdio>
  32. #include <cstring>
  33. #ifdef WIN32
  34. #ifndef _MSC_VER
  35. #define _WIN32_IE 0x501
  36. #endif
  37. #include <windows.h>
  38. #include <shellapi.h>
  39. #include <direct.h>
  40. #include <shlobj.h>
  41. #else
  42. #include <dirent.h>
  43. #include <errno.h>
  44. #include <unistd.h>
  45. #include <sys/stat.h>
  46. #include <sys/wait.h>
  47. #define MAX_PATH 256
  48. #endif
  49. #if defined(__APPLE__)
  50. #include <mach-o/dyld.h>
  51. #endif
  52. #ifdef ANDROID
  53. extern "C" const char* SDL_Android_GetFilesDir();
  54. #endif
  55. #ifdef IOS
  56. extern "C" const char* SDL_IOS_GetResourceDir();
  57. #endif
  58. #include "DebugNew.h"
  59. namespace Urho3D
  60. {
  61. int DoSystemCommand(const String& commandLine)
  62. {
  63. return system(commandLine.CString());
  64. }
  65. int DoSystemRun(const String& fileName, const Vector<String>& arguments)
  66. {
  67. String fixedFileName = GetNativePath(fileName);
  68. #ifdef WIN32
  69. // Add .exe extension if no extension defined
  70. if (GetExtension(fixedFileName).Empty())
  71. fixedFileName += ".exe";
  72. String commandLine = "\"" + fixedFileName + "\"";
  73. for (unsigned i = 0; i < arguments.Size(); ++i)
  74. commandLine += " " + arguments[i];
  75. STARTUPINFOW startupInfo;
  76. PROCESS_INFORMATION processInfo;
  77. memset(&startupInfo, 0, sizeof startupInfo);
  78. memset(&processInfo, 0, sizeof processInfo);
  79. WString commandLineW(commandLine);
  80. if (!CreateProcessW(NULL, (wchar_t*)commandLineW.CString(), 0, 0, 0, CREATE_NO_WINDOW, 0, 0, &startupInfo, &processInfo))
  81. return -1;
  82. WaitForSingleObject(processInfo.hProcess, INFINITE);
  83. DWORD exitCode;
  84. GetExitCodeProcess(processInfo.hProcess, &exitCode);
  85. CloseHandle(processInfo.hProcess);
  86. CloseHandle(processInfo.hThread);
  87. return exitCode;
  88. #else
  89. pid_t pid = fork();
  90. if (!pid)
  91. {
  92. PODVector<const char*> argPtrs;
  93. argPtrs.Push(fixedFileName.CString());
  94. for (unsigned i = 0; i < arguments.Size(); ++i)
  95. argPtrs.Push(arguments[i].CString());
  96. argPtrs.Push(0);
  97. execvp(argPtrs[0], (char**)&argPtrs[0]);
  98. return -1; // Return -1 if we could not spawn the process
  99. }
  100. else if (pid > 0)
  101. {
  102. int exitCode;
  103. wait(&exitCode);
  104. return exitCode;
  105. }
  106. else
  107. return -1;
  108. #endif
  109. }
  110. /// Base class for async execution requests.
  111. class AsyncExecRequest : public Thread
  112. {
  113. public:
  114. /// Construct.
  115. AsyncExecRequest(unsigned& requestID) :
  116. requestID_(requestID),
  117. completed_(false)
  118. {
  119. // Increment ID for next request
  120. ++requestID;
  121. if (requestID == M_MAX_UNSIGNED)
  122. requestID = 1;
  123. }
  124. /// Return request ID.
  125. unsigned GetRequestID() const { return requestID_; }
  126. /// Return exit code. Valid when IsCompleted() is true.
  127. int GetExitCode() const { return exitCode_; }
  128. /// Return completion status.
  129. bool IsCompleted() const { return completed_; }
  130. protected:
  131. /// Request ID.
  132. unsigned requestID_;
  133. /// Exit code.
  134. int exitCode_;
  135. /// Completed flag.
  136. volatile bool completed_;
  137. };
  138. /// Async system command operation.
  139. class AsyncSystemCommand : public AsyncExecRequest
  140. {
  141. public:
  142. /// Construct and run.
  143. AsyncSystemCommand(unsigned requestID, const String& commandLine) :
  144. AsyncExecRequest(requestID),
  145. commandLine_(commandLine)
  146. {
  147. Run();
  148. }
  149. /// The function to run in the thread.
  150. virtual void ThreadFunction()
  151. {
  152. exitCode_ = DoSystemCommand(commandLine_);
  153. completed_ = true;
  154. }
  155. private:
  156. /// Command line.
  157. String commandLine_;
  158. };
  159. /// Async system run operation.
  160. class AsyncSystemRun : public AsyncExecRequest
  161. {
  162. public:
  163. /// Construct and run.
  164. AsyncSystemRun(unsigned requestID, const String& fileName, const Vector<String>& arguments) :
  165. AsyncExecRequest(requestID),
  166. fileName_(fileName),
  167. arguments_(arguments)
  168. {
  169. Run();
  170. }
  171. /// The function to run in the thread.
  172. virtual void ThreadFunction()
  173. {
  174. exitCode_ = DoSystemRun(fileName_, arguments_);
  175. completed_ = true;
  176. }
  177. private:
  178. /// File to run.
  179. String fileName_;
  180. /// Command line split in arguments.
  181. const Vector<String>& arguments_;
  182. };
  183. FileSystem::FileSystem(Context* context) :
  184. Object(context),
  185. nextAsyncExecID_(1)
  186. {
  187. SubscribeToEvent(E_BEGINFRAME, HANDLER(FileSystem, HandleBeginFrame));
  188. }
  189. FileSystem::~FileSystem()
  190. {
  191. // If any async exec items pending, delete them
  192. if (asyncExecQueue_.Size())
  193. {
  194. for (List<AsyncExecRequest*>::Iterator i = asyncExecQueue_.Begin(); i != asyncExecQueue_.End(); ++i)
  195. delete(*i);
  196. asyncExecQueue_.Clear();
  197. }
  198. }
  199. bool FileSystem::SetCurrentDir(const String& pathName)
  200. {
  201. if (!CheckAccess(pathName))
  202. {
  203. LOGERROR("Access denied to " + pathName);
  204. return false;
  205. }
  206. #ifdef WIN32
  207. if (SetCurrentDirectoryW(GetWideNativePath(pathName).CString()) == FALSE)
  208. {
  209. LOGERROR("Failed to change directory to " + pathName);
  210. return false;
  211. }
  212. #else
  213. if (chdir(GetNativePath(pathName).CString()) != 0)
  214. {
  215. LOGERROR("Failed to change directory to " + pathName);
  216. return false;
  217. }
  218. #endif
  219. return true;
  220. }
  221. bool FileSystem::CreateDir(const String& pathName)
  222. {
  223. if (!CheckAccess(pathName))
  224. {
  225. LOGERROR("Access denied to " + pathName);
  226. return false;
  227. }
  228. #ifdef WIN32
  229. bool success = (CreateDirectoryW(GetWideNativePath(RemoveTrailingSlash(pathName)).CString(), 0) == TRUE) ||
  230. (GetLastError() == ERROR_ALREADY_EXISTS);
  231. #else
  232. bool success = mkdir(GetNativePath(RemoveTrailingSlash(pathName)).CString(), S_IRWXU) == 0 || errno == EEXIST;
  233. #endif
  234. if (success)
  235. LOGDEBUG("Created directory " + pathName);
  236. else
  237. LOGERROR("Failed to create directory " + pathName);
  238. return success;
  239. }
  240. int FileSystem::SystemCommand(const String& commandLine)
  241. {
  242. if (allowedPaths_.Empty())
  243. return DoSystemCommand(commandLine);
  244. else
  245. {
  246. LOGERROR("Executing an external command is not allowed");
  247. return -1;
  248. }
  249. }
  250. int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments)
  251. {
  252. if (allowedPaths_.Empty())
  253. return DoSystemRun(fileName, arguments);
  254. else
  255. {
  256. LOGERROR("Executing an external command is not allowed");
  257. return -1;
  258. }
  259. }
  260. unsigned FileSystem::SystemCommandAsync(const String& commandLine)
  261. {
  262. if (allowedPaths_.Empty())
  263. {
  264. unsigned requestID = nextAsyncExecID_;
  265. AsyncSystemCommand* cmd = new AsyncSystemCommand(nextAsyncExecID_, commandLine);
  266. asyncExecQueue_.Push(cmd);
  267. return requestID;
  268. }
  269. else
  270. {
  271. LOGERROR("Executing an external command is not allowed");
  272. return M_MAX_UNSIGNED;
  273. }
  274. }
  275. unsigned FileSystem::SystemRunAsync(const String& fileName, const Vector<String>& arguments)
  276. {
  277. if (allowedPaths_.Empty())
  278. {
  279. unsigned requestID = nextAsyncExecID_;
  280. AsyncSystemRun* cmd = new AsyncSystemRun(nextAsyncExecID_, fileName, arguments);
  281. asyncExecQueue_.Push(cmd);
  282. return requestID;
  283. }
  284. else
  285. {
  286. LOGERROR("Executing an external command is not allowed");
  287. return M_MAX_UNSIGNED;
  288. }
  289. }
  290. bool FileSystem::SystemOpen(const String& fileName, const String& mode)
  291. {
  292. if (allowedPaths_.Empty())
  293. {
  294. if (!FileExists(fileName) && !DirExists(fileName))
  295. {
  296. LOGERROR("File or directory " + fileName + " not found");
  297. return false;
  298. }
  299. #ifdef WIN32
  300. bool success = (size_t)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
  301. GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
  302. #else
  303. Vector<String> arguments;
  304. arguments.Push(fileName);
  305. bool success = SystemRun(
  306. #if defined(__APPLE__)
  307. "/usr/bin/open",
  308. #else
  309. "/usr/bin/xdg-open",
  310. #endif
  311. arguments) == 0;
  312. #endif
  313. if (!success)
  314. LOGERROR("Failed to open " + fileName + " externally");
  315. return success;
  316. }
  317. else
  318. {
  319. LOGERROR("Opening a file externally is not allowed");
  320. return false;
  321. }
  322. }
  323. bool FileSystem::Copy(const String& srcFileName, const String& destFileName)
  324. {
  325. if (!CheckAccess(GetPath(srcFileName)))
  326. {
  327. LOGERROR("Access denied to " + srcFileName);
  328. return false;
  329. }
  330. if (!CheckAccess(GetPath(destFileName)))
  331. {
  332. LOGERROR("Access denied to " + destFileName);
  333. return false;
  334. }
  335. SharedPtr<File> srcFile(new File(context_, srcFileName, FILE_READ));
  336. if (!srcFile->IsOpen())
  337. return false;
  338. SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE));
  339. if (!destFile->IsOpen())
  340. return false;
  341. unsigned fileSize = srcFile->GetSize();
  342. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  343. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  344. unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize);
  345. return bytesRead == fileSize && bytesWritten == fileSize;
  346. }
  347. bool FileSystem::Rename(const String& srcFileName, const String& destFileName)
  348. {
  349. if (!CheckAccess(GetPath(srcFileName)))
  350. {
  351. LOGERROR("Access denied to " + srcFileName);
  352. return false;
  353. }
  354. if (!CheckAccess(GetPath(destFileName)))
  355. {
  356. LOGERROR("Access denied to " + destFileName);
  357. return false;
  358. }
  359. #ifdef WIN32
  360. return MoveFileW(GetWideNativePath(srcFileName).CString(), GetWideNativePath(destFileName).CString()) != 0;
  361. #else
  362. return rename(GetNativePath(srcFileName).CString(), GetNativePath(destFileName).CString()) == 0;
  363. #endif
  364. }
  365. bool FileSystem::Delete(const String& fileName)
  366. {
  367. if (!CheckAccess(GetPath(fileName)))
  368. {
  369. LOGERROR("Access denied to " + fileName);
  370. return false;
  371. }
  372. #ifdef WIN32
  373. return DeleteFileW(GetWideNativePath(fileName).CString()) != 0;
  374. #else
  375. return remove(GetNativePath(fileName).CString()) == 0;
  376. #endif
  377. }
  378. String FileSystem::GetCurrentDir() const
  379. {
  380. #ifdef WIN32
  381. wchar_t path[MAX_PATH];
  382. path[0] = 0;
  383. GetCurrentDirectoryW(MAX_PATH, path);
  384. return AddTrailingSlash(String(path));
  385. #else
  386. char path[MAX_PATH];
  387. path[0] = 0;
  388. getcwd(path, MAX_PATH);
  389. return AddTrailingSlash(String(path));
  390. #endif
  391. }
  392. bool FileSystem::CheckAccess(const String& pathName) const
  393. {
  394. String fixedPath = AddTrailingSlash(pathName);
  395. // If no allowed directories defined, succeed always
  396. if (allowedPaths_.Empty())
  397. return true;
  398. // If there is any attempt to go to a parent directory, disallow
  399. if (fixedPath.Contains(".."))
  400. return false;
  401. // Check if the path is a partial match of any of the allowed directories
  402. for (HashSet<String>::ConstIterator i = allowedPaths_.Begin(); i != allowedPaths_.End(); ++i)
  403. {
  404. if (fixedPath.Find(*i) == 0)
  405. return true;
  406. }
  407. // Not found, so disallow
  408. return false;
  409. }
  410. unsigned FileSystem::GetLastModifiedTime(const String& fileName) const
  411. {
  412. if (fileName.Empty() || !CheckAccess(fileName))
  413. return 0;
  414. #ifdef WIN32
  415. WIN32_FILE_ATTRIBUTE_DATA fileAttrData;
  416. memset(&fileAttrData, 0, sizeof fileAttrData);
  417. if (GetFileAttributesExW(WString(fileName).CString(), GetFileExInfoStandard, &fileAttrData))
  418. {
  419. ULARGE_INTEGER ull;
  420. ull.LowPart = fileAttrData.ftLastWriteTime.dwLowDateTime;
  421. ull.HighPart = fileAttrData.ftLastWriteTime.dwHighDateTime;
  422. return (unsigned)(ull.QuadPart / 10000000ULL - 11644473600ULL);
  423. }
  424. else
  425. return 0;
  426. #else
  427. struct stat st;
  428. if (!stat(fileName.CString(), &st))
  429. return (unsigned)st.st_mtime;
  430. else
  431. return 0;
  432. #endif
  433. }
  434. bool FileSystem::FileExists(const String& fileName) const
  435. {
  436. if (!CheckAccess(GetPath(fileName)))
  437. return false;
  438. String fixedName = GetNativePath(RemoveTrailingSlash(fileName));
  439. #ifdef ANDROID
  440. if (fixedName.StartsWith("/apk/"))
  441. {
  442. SDL_RWops* rwOps = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
  443. if (rwOps)
  444. {
  445. SDL_RWclose(rwOps);
  446. return true;
  447. }
  448. else
  449. return false;
  450. }
  451. #endif
  452. #ifdef WIN32
  453. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  454. if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
  455. return false;
  456. #else
  457. struct stat st;
  458. if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
  459. return false;
  460. #endif
  461. return true;
  462. }
  463. bool FileSystem::DirExists(const String& pathName) const
  464. {
  465. if (!CheckAccess(pathName))
  466. return false;
  467. #ifndef WIN32
  468. // Always return true for the root directory
  469. if (pathName == "/")
  470. return true;
  471. #endif
  472. String fixedName = GetNativePath(RemoveTrailingSlash(pathName));
  473. #ifdef ANDROID
  474. /// \todo Actually check for existence, now true is always returned for directories within the APK
  475. if (fixedName.StartsWith("/apk/"))
  476. return true;
  477. #endif
  478. #ifdef WIN32
  479. DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
  480. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY))
  481. return false;
  482. #else
  483. struct stat st;
  484. if (stat(fixedName.CString(), &st) || !(st.st_mode & S_IFDIR))
  485. return false;
  486. #endif
  487. return true;
  488. }
  489. void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const
  490. {
  491. result.Clear();
  492. if (CheckAccess(pathName))
  493. {
  494. String initialPath = AddTrailingSlash(pathName);
  495. ScanDirInternal(result, initialPath, initialPath, filter, flags, recursive);
  496. }
  497. }
  498. String FileSystem::GetProgramDir() const
  499. {
  500. // Return cached value if possible
  501. if (!programDir_.Empty())
  502. return programDir_;
  503. #if defined(ANDROID)
  504. // This is an internal directory specifier pointing to the assets in the .apk
  505. // Files from this directory will be opened using special handling
  506. programDir_ = "/apk/";
  507. return programDir_;
  508. #elif defined(IOS)
  509. programDir_ = AddTrailingSlash(SDL_IOS_GetResourceDir());
  510. return programDir_;
  511. #elif defined(WIN32)
  512. wchar_t exeName[MAX_PATH];
  513. exeName[0] = 0;
  514. GetModuleFileNameW(0, exeName, MAX_PATH);
  515. programDir_ = GetPath(String(exeName));
  516. #elif defined(__APPLE__)
  517. char exeName[MAX_PATH];
  518. memset(exeName, 0, MAX_PATH);
  519. unsigned size = MAX_PATH;
  520. _NSGetExecutablePath(exeName, &size);
  521. programDir_ = GetPath(String(exeName));
  522. #elif defined(__linux__)
  523. char exeName[MAX_PATH];
  524. memset(exeName, 0, MAX_PATH);
  525. pid_t pid = getpid();
  526. String link = "/proc/" + String(pid) + "/exe";
  527. readlink(link.CString(), exeName, MAX_PATH);
  528. programDir_ = GetPath(String(exeName));
  529. #endif
  530. // If the executable directory does not contain CoreData & Data directories, but the current working directory does, use the
  531. // current working directory instead
  532. /// \todo Should not rely on such fixed convention
  533. String currentDir = GetCurrentDir();
  534. if (!DirExists(programDir_ + "CoreData") && !DirExists(programDir_ + "Data") && (DirExists(currentDir + "CoreData") ||
  535. DirExists(currentDir + "Data")))
  536. programDir_ = currentDir;
  537. // Sanitate /./ construct away
  538. programDir_.Replace("/./", "/");
  539. return programDir_;
  540. }
  541. String FileSystem::GetUserDocumentsDir() const
  542. {
  543. #if defined(ANDROID)
  544. return AddTrailingSlash(SDL_Android_GetFilesDir());
  545. #elif defined(IOS)
  546. return AddTrailingSlash(SDL_IOS_GetResourceDir());
  547. #elif defined(WIN32)
  548. wchar_t pathName[MAX_PATH];
  549. pathName[0] = 0;
  550. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  551. return AddTrailingSlash(String(pathName));
  552. #else
  553. char pathName[MAX_PATH];
  554. pathName[0] = 0;
  555. strcpy(pathName, getenv("HOME"));
  556. return AddTrailingSlash(String(pathName));
  557. #endif
  558. }
  559. void FileSystem::RegisterPath(const String& pathName)
  560. {
  561. if (pathName.Empty())
  562. return;
  563. allowedPaths_.Insert(AddTrailingSlash(pathName));
  564. }
  565. void FileSystem::ScanDirInternal(Vector<String>& result, String path, const String& startPath,
  566. const String& filter, unsigned flags, bool recursive) const
  567. {
  568. path = AddTrailingSlash(path);
  569. String deltaPath;
  570. if (path.Length() > startPath.Length())
  571. deltaPath = path.Substring(startPath.Length());
  572. String filterExtension = filter.Substring(filter.Find('.'));
  573. if (filterExtension.Contains('*'))
  574. filterExtension.Clear();
  575. #ifdef WIN32
  576. WIN32_FIND_DATAW info;
  577. HANDLE handle = FindFirstFileW(WString(path + "*").CString(), &info);
  578. if (handle != INVALID_HANDLE_VALUE)
  579. {
  580. do
  581. {
  582. String fileName(info.cFileName);
  583. if (!fileName.Empty())
  584. {
  585. if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(flags & SCAN_HIDDEN))
  586. continue;
  587. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  588. {
  589. if (flags & SCAN_DIRS)
  590. result.Push(deltaPath + fileName);
  591. if (recursive && fileName != "." && fileName != "..")
  592. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  593. }
  594. else if (flags & SCAN_FILES)
  595. {
  596. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  597. result.Push(deltaPath + fileName);
  598. }
  599. }
  600. }
  601. while (FindNextFileW(handle, &info));
  602. FindClose(handle);
  603. }
  604. #else
  605. DIR *dir;
  606. struct dirent *de;
  607. struct stat st;
  608. dir = opendir(GetNativePath(path).CString());
  609. if (dir)
  610. {
  611. while ((de = readdir(dir)))
  612. {
  613. /// \todo Filename may be unnormalized Unicode on Mac OS X. Re-normalize as necessary
  614. String fileName(de->d_name);
  615. bool normalEntry = fileName != "." && fileName != "..";
  616. if (normalEntry && !(flags & SCAN_HIDDEN) && fileName.StartsWith("."))
  617. continue;
  618. String pathAndName = path + fileName;
  619. if (!stat(pathAndName.CString(), &st))
  620. {
  621. if (st.st_mode & S_IFDIR)
  622. {
  623. if (flags & SCAN_DIRS)
  624. result.Push(deltaPath + fileName);
  625. if (recursive && normalEntry)
  626. ScanDirInternal(result, path + fileName, startPath, filter, flags, recursive);
  627. }
  628. else if (flags & SCAN_FILES)
  629. {
  630. if (filterExtension.Empty() || fileName.EndsWith(filterExtension))
  631. result.Push(deltaPath + fileName);
  632. }
  633. }
  634. }
  635. closedir(dir);
  636. }
  637. #endif
  638. }
  639. void FileSystem::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  640. {
  641. /// Go through the execution queue and post + remove completed requests
  642. for (List<AsyncExecRequest*>::Iterator i = asyncExecQueue_.Begin(); i != asyncExecQueue_.End();)
  643. {
  644. AsyncExecRequest* request = *i;
  645. if (request->IsCompleted())
  646. {
  647. using namespace AsyncExecFinished;
  648. VariantMap& eventData = GetEventDataMap();
  649. eventData[P_REQUESTID] = request->GetRequestID();
  650. eventData[P_EXITCODE] = request->GetExitCode();
  651. SendEvent(E_ASYNCEXECFINISHED, eventData);
  652. delete request;
  653. i = asyncExecQueue_.Erase(i);
  654. }
  655. else
  656. ++i;
  657. }
  658. }
  659. void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension, bool lowercaseExtension)
  660. {
  661. String fullPathCopy = GetInternalPath(fullPath);
  662. unsigned extPos = fullPathCopy.FindLast('.');
  663. unsigned pathPos = fullPathCopy.FindLast('/');
  664. if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
  665. {
  666. extension = fullPathCopy.Substring(extPos);
  667. if (lowercaseExtension)
  668. extension = extension.ToLower();
  669. fullPathCopy = fullPathCopy.Substring(0, extPos);
  670. }
  671. else
  672. extension.Clear();
  673. pathPos = fullPathCopy.FindLast('/');
  674. if (pathPos != String::NPOS)
  675. {
  676. fileName = fullPathCopy.Substring(pathPos + 1);
  677. pathName = fullPathCopy.Substring(0, pathPos + 1);
  678. }
  679. else
  680. {
  681. fileName = fullPathCopy;
  682. pathName.Clear();
  683. }
  684. }
  685. String GetPath(const String& fullPath)
  686. {
  687. String path, file, extension;
  688. SplitPath(fullPath, path, file, extension);
  689. return path;
  690. }
  691. String GetFileName(const String& fullPath)
  692. {
  693. String path, file, extension;
  694. SplitPath(fullPath, path, file, extension);
  695. return file;
  696. }
  697. String GetExtension(const String& fullPath, bool lowercaseExtension)
  698. {
  699. String path, file, extension;
  700. SplitPath(fullPath, path, file, extension, lowercaseExtension);
  701. return extension;
  702. }
  703. String GetFileNameAndExtension(const String& fileName, bool lowercaseExtension)
  704. {
  705. String path, file, extension;
  706. SplitPath(fileName, path, file, extension, lowercaseExtension);
  707. return file + extension;
  708. }
  709. String ReplaceExtension(const String& fullPath, const String& newExtension)
  710. {
  711. String path, file, extension;
  712. SplitPath(fullPath, path, file, extension);
  713. return path + file + newExtension;
  714. }
  715. String AddTrailingSlash(const String& pathName)
  716. {
  717. String ret = pathName.Trimmed();
  718. ret.Replace('\\', '/');
  719. if (!ret.Empty() && ret.Back() != '/')
  720. ret += '/';
  721. return ret;
  722. }
  723. String RemoveTrailingSlash(const String& pathName)
  724. {
  725. String ret = pathName.Trimmed();
  726. ret.Replace('\\', '/');
  727. if (!ret.Empty() && ret.Back() == '/')
  728. ret.Resize(ret.Length() - 1);
  729. return ret;
  730. }
  731. String GetParentPath(const String& path)
  732. {
  733. unsigned pos = RemoveTrailingSlash(path).FindLast('/');
  734. if (pos != String::NPOS)
  735. return path.Substring(0, pos + 1);
  736. else
  737. return String();
  738. }
  739. String GetInternalPath(const String& pathName)
  740. {
  741. return pathName.Replaced('\\', '/');
  742. }
  743. String GetNativePath(const String& pathName)
  744. {
  745. #ifdef WIN32
  746. return pathName.Replaced('/', '\\');
  747. #else
  748. return pathName;
  749. #endif
  750. }
  751. WString GetWideNativePath(const String& pathName)
  752. {
  753. #ifdef WIN32
  754. return WString(pathName.Replaced('/', '\\'));
  755. #else
  756. return WString(pathName);
  757. #endif
  758. }
  759. bool IsAbsolutePath(const String& pathName)
  760. {
  761. if (pathName.Empty())
  762. return false;
  763. String path = GetInternalPath(pathName);
  764. if (path[0] == '/')
  765. return true;
  766. #ifdef WIN32
  767. if (path.Length() > 1 && IsAlpha(path[0]) && path[1] == ':')
  768. return true;
  769. #endif
  770. return false;
  771. }
  772. }