FileSystem.cpp 30 KB

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