FileSystem.cpp 30 KB

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