FileSystem.cpp 33 KB

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