FileSystem.cpp 35 KB

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