FileSystem.cpp 34 KB

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