FileSystem.cpp 29 KB

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