2
0

FileSystem.cpp 30 KB

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