FileSystem.cpp 26 KB

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