FileSystem.cpp 27 KB

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