FileSystem.cpp 34 KB

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