2
0

FileSystem.cpp 28 KB

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