FileSystem.cpp 30 KB

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