FileSystem.cpp 30 KB

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