FileSystem.cpp 27 KB

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