FileSystem.cpp 30 KB

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