FileSystem.cpp 30 KB

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