FileSystem.cpp 32 KB

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