FileSystem.cpp 33 KB

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