Filesystem.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. /**
  2. * Copyright (c) 2006-2020 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include <iostream>
  21. #include <sstream>
  22. #include <algorithm>
  23. #include "common/utf8.h"
  24. #include "common/b64.h"
  25. #include "Filesystem.h"
  26. #include "File.h"
  27. // PhysFS
  28. #include "libraries/physfs/physfs.h"
  29. // For great CWD. (Current Working Directory)
  30. // Using this instead of boost::filesystem which totally
  31. // cramped our style.
  32. #ifdef LOVE_WINDOWS
  33. # include <windows.h>
  34. # include <direct.h>
  35. # include <initguid.h>
  36. # include <Shlobj.h>
  37. # include <Knownfolders.h>
  38. #else
  39. # include <sys/param.h>
  40. # include <unistd.h>
  41. #endif
  42. #if defined(LOVE_IOS) || defined(LOVE_MACOS)
  43. # include "common/apple.h"
  44. #endif
  45. #ifdef LOVE_IOS
  46. # include "common/ios.h"
  47. #endif
  48. #ifdef LOVE_MACOS
  49. # include "common/macos.h"
  50. #endif
  51. #include <string>
  52. #ifdef LOVE_ANDROID
  53. #include <SDL.h>
  54. #include "common/android.h"
  55. #endif
  56. namespace love
  57. {
  58. namespace filesystem
  59. {
  60. namespace physfs
  61. {
  62. static std::string normalize(const std::string &input)
  63. {
  64. std::stringstream out;
  65. bool seenSep = false, isSep = false;
  66. for (size_t i = 0; i < input.size(); ++i)
  67. {
  68. isSep = (input[i] == LOVE_PATH_SEPARATOR[0]);
  69. if (!isSep || !seenSep)
  70. out << input[i];
  71. seenSep = isSep;
  72. }
  73. return out.str();
  74. }
  75. static const Filesystem::CommonPath appCommonPaths[] =
  76. {
  77. Filesystem::COMMONPATH_APP_SAVEDIR,
  78. Filesystem::COMMONPATH_APP_DOCUMENTS
  79. };
  80. static bool isAppCommonPath(Filesystem::CommonPath path)
  81. {
  82. switch (path)
  83. {
  84. case Filesystem::COMMONPATH_APP_SAVEDIR:
  85. case Filesystem::COMMONPATH_APP_DOCUMENTS:
  86. return true;
  87. default:
  88. return false;
  89. }
  90. }
  91. Filesystem::Filesystem()
  92. : appendIdentityToPath(false)
  93. , fused(false)
  94. , fusedSet(false)
  95. , fullPaths()
  96. , commonPathMountInfo()
  97. , saveDirectoryNeedsMounting(false)
  98. {
  99. requirePath = {"?.lua", "?/init.lua"};
  100. cRequirePath = {"??"};
  101. }
  102. Filesystem::~Filesystem()
  103. {
  104. #ifdef LOVE_ANDROID
  105. love::android::deinitializeVirtualArchive();
  106. #endif
  107. if (PHYSFS_isInit())
  108. PHYSFS_deinit();
  109. }
  110. const char *Filesystem::getName() const
  111. {
  112. return "love.filesystem.physfs";
  113. }
  114. void Filesystem::init(const char *arg0)
  115. {
  116. if (!PHYSFS_init(arg0))
  117. throw love::Exception("Failed to initialize filesystem: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
  118. // Enable symlinks by default.
  119. setSymlinksEnabled(true);
  120. }
  121. void Filesystem::setFused(bool fused)
  122. {
  123. if (fusedSet)
  124. return;
  125. this->fused = fused;
  126. fusedSet = true;
  127. }
  128. bool Filesystem::isFused() const
  129. {
  130. if (!fusedSet)
  131. return false;
  132. return fused;
  133. }
  134. bool Filesystem::setIdentity(const char *ident, bool appendToPath)
  135. {
  136. if (!PHYSFS_isInit())
  137. return false;
  138. if (ident == nullptr || strlen(ident) == 0)
  139. return false;
  140. // Validate whether re-mounting will work.
  141. for (CommonPath p : appCommonPaths)
  142. {
  143. if (!commonPathMountInfo[p].mounted)
  144. continue;
  145. // If a file is still open, unmount will fail.
  146. std::string fullPath = getFullCommonPath(p);
  147. if (!fullPath.empty() && !PHYSFS_canUnmount(fullPath.c_str()))
  148. return false;
  149. }
  150. bool oldMountedCommonPaths[COMMONPATH_MAX_ENUM] = {false};
  151. // We don't want old save paths to accumulate when we set a new identity.
  152. for (CommonPath p : appCommonPaths)
  153. {
  154. oldMountedCommonPaths[p] = commonPathMountInfo[p].mounted;
  155. if (commonPathMountInfo[p].mounted)
  156. unmount(p);
  157. }
  158. // These will be re-populated by getFullCommonPath.
  159. for (CommonPath p : appCommonPaths)
  160. fullPaths[p].clear();
  161. // Store the save directory. getFullCommonPath(COMMONPATH_APP_*) uses this.
  162. saveIdentity = std::string(ident);
  163. appendIdentityToPath = appendToPath;
  164. // Try to mount as readwrite without creating missing directories in the
  165. // path hierarchy. If this fails, setupWriteDirectory will attempt to create
  166. // them and try again.
  167. // This is done so the save directory is only created on-demand.
  168. if (!mountCommonPathInternal(COMMONPATH_APP_SAVEDIR, nullptr, MOUNT_PERMISSIONS_READWRITE, appendToPath, false))
  169. saveDirectoryNeedsMounting = true;
  170. // Mount any other app common paths with directory creation immediately
  171. // instead of on-demand, since to get to this point they would have to be
  172. // explicitly mounted already beforehand.
  173. for (CommonPath p : appCommonPaths)
  174. {
  175. if (oldMountedCommonPaths[p] && p != COMMONPATH_APP_SAVEDIR)
  176. {
  177. // TODO: error handling?
  178. auto info = commonPathMountInfo[p];
  179. mountCommonPathInternal(p, info.mountPoint.c_str(), info.permissions, appendToPath, true);
  180. }
  181. }
  182. return true;
  183. }
  184. const char *Filesystem::getIdentity() const
  185. {
  186. return saveIdentity.c_str();
  187. }
  188. bool Filesystem::setSource(const char *source)
  189. {
  190. if (!PHYSFS_isInit())
  191. return false;
  192. // Check whether directory is already set.
  193. if (!gameSource.empty())
  194. return false;
  195. std::string new_search_path = source;
  196. #ifdef LOVE_ANDROID
  197. if (!love::android::createStorageDirectories())
  198. SDL_Log("Error creating storage directories!");
  199. new_search_path = "";
  200. PHYSFS_Io *gameLoveIO;
  201. bool hasFusedGame = love::android::checkFusedGame((void **) &gameLoveIO);
  202. if (hasFusedGame)
  203. {
  204. if (gameLoveIO)
  205. {
  206. // Actually we should just be able to mount gameLoveIO, but that's experimental.
  207. gameLoveIO->destroy(gameLoveIO);
  208. goto oldschool;
  209. }
  210. else
  211. {
  212. if (!love::android::initializeVirtualArchive())
  213. {
  214. SDL_Log("Unable to mount AAsset: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
  215. return false;
  216. }
  217. }
  218. }
  219. else
  220. {
  221. oldschool:
  222. new_search_path = love::android::getSelectedGameFile();
  223. // try mounting first, if that fails, load to memory and mount
  224. if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1))
  225. {
  226. // PHYSFS cannot yet mount a zip file inside an .apk
  227. SDL_Log("Mounting %s did not work. Loading to memory.",
  228. new_search_path.c_str());
  229. char* game_archive_ptr = NULL;
  230. size_t game_archive_size = 0;
  231. if (!love::android::loadGameArchiveToMemory(
  232. new_search_path.c_str(), &game_archive_ptr,
  233. &game_archive_size))
  234. {
  235. SDL_Log("Failure memory loading archive %s", new_search_path.c_str());
  236. return false;
  237. }
  238. if (!PHYSFS_mountMemory(
  239. game_archive_ptr, game_archive_size,
  240. love::android::freeGameArchiveMemory, "archive.zip", "/", 0))
  241. {
  242. SDL_Log("Failure mounting in-memory archive.");
  243. love::android::freeGameArchiveMemory(game_archive_ptr);
  244. return false;
  245. }
  246. }
  247. }
  248. #else
  249. // Add the directory.
  250. if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1))
  251. return false;
  252. #endif
  253. // Save the game source.
  254. gameSource = new_search_path;
  255. return true;
  256. }
  257. const char *Filesystem::getSource() const
  258. {
  259. return gameSource.c_str();
  260. }
  261. bool Filesystem::setupWriteDirectory()
  262. {
  263. if (!PHYSFS_isInit())
  264. return false;
  265. if (!saveDirectoryNeedsMounting)
  266. return true;
  267. if (saveIdentity.empty())
  268. return false;
  269. // Only the save directory is mounted on-demand if it doesn't exist yet.
  270. // Other app common paths are immediately re-mounted in setIdentity.
  271. bool createdir = true;
  272. if (!mountCommonPathInternal(COMMONPATH_APP_SAVEDIR, nullptr, MOUNT_PERMISSIONS_READWRITE, appendIdentityToPath, createdir))
  273. return false;
  274. saveDirectoryNeedsMounting = false;
  275. return true;
  276. }
  277. bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendToPath)
  278. {
  279. if (!PHYSFS_isInit() || !archive)
  280. return false;
  281. std::string realPath;
  282. std::string sourceBase = getSourceBaseDirectory();
  283. // Check whether the given archive path is in the list of allowed full paths.
  284. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  285. if (it != allowedMountPaths.end())
  286. realPath = *it;
  287. else if (isFused() && sourceBase.compare(archive) == 0)
  288. {
  289. // Special case: if the game is fused and the archive is the source's
  290. // base directory, mount it even though it's outside of the save dir.
  291. realPath = sourceBase;
  292. }
  293. else
  294. {
  295. // Not allowed for safety reasons.
  296. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  297. return false;
  298. const char *realDir = PHYSFS_getRealDir(archive);
  299. if (!realDir)
  300. return false;
  301. realPath = realDir;
  302. // Always disallow mounting of files inside the game source, since it
  303. // won't work anyway if the game source is a zipped .love file.
  304. if (realPath.find(gameSource) == 0)
  305. return false;
  306. realPath += LOVE_PATH_SEPARATOR;
  307. realPath += archive;
  308. }
  309. return mountFullPath(realPath.c_str(), mountpoint, MOUNT_PERMISSIONS_READ, appendToPath);
  310. }
  311. bool Filesystem::mountFullPath(const char *archive, const char *mountpoint, MountPermissions permissions, bool appendToPath)
  312. {
  313. if (!PHYSFS_isInit() || !archive)
  314. return false;
  315. if (permissions == MOUNT_PERMISSIONS_READWRITE)
  316. return PHYSFS_mountRW(archive, mountpoint, appendToPath) != 0;
  317. return PHYSFS_mount(archive, mountpoint, appendToPath) != 0;
  318. }
  319. bool Filesystem::mountCommonPathInternal(CommonPath path, const char *mountpoint, MountPermissions permissions, bool appendToPath, bool createDir)
  320. {
  321. std::string fullpath = getFullCommonPath(path);
  322. if (fullpath.empty())
  323. return false;
  324. if (createDir && isAppCommonPath(path) && !isRealDirectory(fullpath))
  325. {
  326. if (!createRealDirectory(fullpath))
  327. return false;
  328. }
  329. if (mountFullPath(fullpath.c_str(), mountpoint, permissions, appendToPath))
  330. {
  331. std::string mp = mountpoint != nullptr ? mountpoint : "/";
  332. commonPathMountInfo[path] = {true, mp, permissions};
  333. return true;
  334. }
  335. return false;
  336. }
  337. bool Filesystem::mountCommonPath(CommonPath path, const char *mountpoint, MountPermissions permissions, bool appendToPath)
  338. {
  339. return mountCommonPathInternal(path, mountpoint, permissions, appendToPath, true);
  340. }
  341. bool Filesystem::mount(Data *data, const char *archivename, const char *mountpoint, bool appendToPath)
  342. {
  343. if (!PHYSFS_isInit())
  344. return false;
  345. if (PHYSFS_mountMemory(data->getData(), data->getSize(), nullptr, archivename, mountpoint, appendToPath) != 0)
  346. {
  347. mountedData[archivename] = data;
  348. return true;
  349. }
  350. return false;
  351. }
  352. bool Filesystem::unmount(const char *archive)
  353. {
  354. if (!PHYSFS_isInit() || !archive)
  355. return false;
  356. auto datait = mountedData.find(archive);
  357. if (datait != mountedData.end() && PHYSFS_unmount(archive) != 0)
  358. {
  359. mountedData.erase(datait);
  360. return true;
  361. }
  362. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  363. if (it != allowedMountPaths.end())
  364. return unmountFullPath(archive);
  365. std::string sourceBase = getSourceBaseDirectory();
  366. if (isFused() && sourceBase.compare(archive) == 0)
  367. return unmountFullPath(archive);
  368. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  369. return false;
  370. const char *realDir = PHYSFS_getRealDir(archive);
  371. if (!realDir)
  372. return false;
  373. std::string realPath = realDir;
  374. realPath += LOVE_PATH_SEPARATOR;
  375. realPath += archive;
  376. if (PHYSFS_getMountPoint(realPath.c_str()) == nullptr)
  377. return false;
  378. return PHYSFS_unmount(realPath.c_str()) != 0;
  379. }
  380. bool Filesystem::unmountFullPath(const char *fullpath)
  381. {
  382. if (!PHYSFS_isInit() || !fullpath)
  383. return false;
  384. return PHYSFS_unmount(fullpath) != 0;
  385. }
  386. bool Filesystem::unmount(CommonPath path)
  387. {
  388. std::string fullpath = getFullCommonPath(path);
  389. if (!fullpath.empty() && unmountFullPath(fullpath.c_str()))
  390. {
  391. commonPathMountInfo[path].mounted = false;
  392. return true;
  393. }
  394. return false;
  395. }
  396. bool Filesystem::unmount(Data *data)
  397. {
  398. for (const auto &datapair : mountedData)
  399. {
  400. if (datapair.second.get() == data)
  401. {
  402. std::string archive = datapair.first;
  403. return unmount(archive.c_str());
  404. }
  405. }
  406. return false;
  407. }
  408. love::filesystem::File *Filesystem::newFile(const char *filename) const
  409. {
  410. return new File(filename);
  411. }
  412. std::string Filesystem::getFullCommonPath(CommonPath path)
  413. {
  414. if (!fullPaths[path].empty())
  415. return fullPaths[path];
  416. if (isAppCommonPath(path))
  417. {
  418. if (saveIdentity.empty())
  419. return fullPaths[path];
  420. std::string rootpath;
  421. switch (path)
  422. {
  423. case COMMONPATH_APP_SAVEDIR:
  424. rootpath = getFullCommonPath(COMMONPATH_USER_APPDATA);
  425. break;
  426. case COMMONPATH_APP_DOCUMENTS:
  427. rootpath = getFullCommonPath(COMMONPATH_USER_DOCUMENTS);
  428. break;
  429. default:
  430. break;
  431. }
  432. if (rootpath.empty())
  433. return fullPaths[path];
  434. std::string suffix;
  435. if (isFused())
  436. suffix = std::string(LOVE_PATH_SEPARATOR) + saveIdentity;
  437. else
  438. suffix = std::string(LOVE_PATH_SEPARATOR LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + saveIdentity;
  439. fullPaths[path] = normalize(rootpath + suffix);
  440. return fullPaths[path];
  441. }
  442. #if defined(LOVE_MACOS) || defined(LOVE_IOS)
  443. switch (path)
  444. {
  445. case COMMONPATH_APP_SAVEDIR:
  446. case COMMONPATH_APP_DOCUMENTS:
  447. // Handled above.
  448. break;
  449. case COMMONPATH_USER_HOME:
  450. fullPaths[path] = apple::getUserDirectory(apple::USER_DIRECTORY_HOME);
  451. break;
  452. case COMMONPATH_USER_APPDATA:
  453. fullPaths[path] = apple::getUserDirectory(apple::USER_DIRECTORY_APPSUPPORT);
  454. break;
  455. case COMMONPATH_USER_DESKTOP:
  456. fullPaths[path] = apple::getUserDirectory(apple::USER_DIRECTORY_DESKTOP);
  457. break;
  458. case COMMONPATH_USER_DOCUMENTS:
  459. fullPaths[path] = apple::getUserDirectory(apple::USER_DIRECTORY_DOCUMENTS);
  460. break;
  461. case COMMONPATH_MAX_ENUM:
  462. break;
  463. }
  464. #elif defined(LOVE_WINDOWS)
  465. PWSTR winpath = nullptr;
  466. HRESULT hr = E_FAIL;
  467. switch (path)
  468. {
  469. case COMMONPATH_APP_SAVEDIR:
  470. case COMMONPATH_APP_DOCUMENTS:
  471. // Handled above.
  472. break;
  473. case COMMONPATH_USER_HOME:
  474. hr = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &winpath);
  475. break;
  476. case COMMONPATH_USER_APPDATA:
  477. hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &winpath);
  478. break;
  479. case COMMONPATH_USER_DESKTOP:
  480. hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &winpath);
  481. break;
  482. case COMMONPATH_USER_DOCUMENTS:
  483. hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &winpath);
  484. break;
  485. case COMMONPATH_MAX_ENUM:
  486. break;
  487. }
  488. if (SUCCEEDED(hr))
  489. {
  490. fullPaths[path] = to_utf8(winpath);
  491. CoTaskMemFree(winpath);
  492. }
  493. #elif defined(LOVE_ANDROID)
  494. std::string storagepath;
  495. if (isAndroidSaveExternal())
  496. storagepath = SDL_AndroidGetExternalStoragePath();
  497. else
  498. storagepath = SDL_AndroidGetInternalStoragePath();
  499. switch (path)
  500. {
  501. case COMMONPATH_APP_SAVEDIR:
  502. case COMMONPATH_APP_DOCUMENTS:
  503. // Handled above.
  504. break;
  505. case COMMONPATH_USER_HOME:
  506. fullPaths[path] = normalize(PHYSFS_getUserDir());
  507. break;
  508. case COMMONPATH_USER_APPDATA:
  509. fullPaths[path] = normalize(storagepath + "/save/");
  510. break;
  511. case COMMONPATH_USER_DESKTOP:
  512. // No such thing on Android?
  513. break;
  514. case COMMONPATH_USER_DOCUMENTS:
  515. // TODO: something more idiomatic / useful?
  516. fullPaths[path] = normalize(storagepath + "/Documents/");
  517. break;
  518. case COMMONPATH_MAX_ENUM:
  519. break;
  520. }
  521. #elif defined(LOVE_LINUX)
  522. const char *xdgdir = nullptr;
  523. switch (path)
  524. {
  525. case COMMONPATH_APP_SAVEDIR:
  526. case COMMONPATH_APP_DOCUMENTS:
  527. // Handled above.
  528. break;
  529. case COMMONPATH_USER_HOME:
  530. fullPaths[path] = normalize(PHYSFS_getUserDir());
  531. break;
  532. case COMMONPATH_USER_APPDATA:
  533. xdgdir = getenv("XDG_DATA_HOME");
  534. if (!xdgdir)
  535. fullPaths[path] = normalize(std::string(getUserDirectory()) + "/.local/share/");
  536. else
  537. fullPaths[path] = xdgdir;
  538. break;
  539. case COMMONPATH_USER_DESKTOP:
  540. fullPaths[path] = normalize(std::string(getUserDirectory()) + "/Desktop/");
  541. break;
  542. case COMMONPATH_USER_DOCUMENTS:
  543. fullPaths[path] = normalize(std::string(getUserDirectory()) + "/Documents/");
  544. break;
  545. case COMMONPATH_MAX_ENUM:
  546. break;
  547. }
  548. #endif
  549. return fullPaths[path];
  550. }
  551. const char *Filesystem::getWorkingDirectory()
  552. {
  553. if (cwd.empty())
  554. {
  555. #ifdef LOVE_WINDOWS
  556. WCHAR w_cwd[LOVE_MAX_PATH];
  557. _wgetcwd(w_cwd, LOVE_MAX_PATH);
  558. cwd = to_utf8(w_cwd);
  559. replace_char(cwd, '\\', '/');
  560. #else
  561. char *cwd_char = new char[LOVE_MAX_PATH];
  562. if (getcwd(cwd_char, LOVE_MAX_PATH))
  563. cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
  564. delete[] cwd_char;
  565. #endif
  566. }
  567. return cwd.c_str();
  568. }
  569. std::string Filesystem::getUserDirectory()
  570. {
  571. return getFullCommonPath(COMMONPATH_USER_HOME);
  572. }
  573. std::string Filesystem::getAppdataDirectory()
  574. {
  575. return getFullCommonPath(COMMONPATH_USER_APPDATA);
  576. }
  577. std::string Filesystem::getSaveDirectory()
  578. {
  579. return getFullCommonPath(COMMONPATH_APP_SAVEDIR);
  580. }
  581. std::string Filesystem::getSourceBaseDirectory() const
  582. {
  583. size_t source_len = gameSource.length();
  584. if (source_len == 0)
  585. return "";
  586. // FIXME: This doesn't take into account parent and current directory
  587. // symbols (i.e. '..' and '.')
  588. #ifdef LOVE_WINDOWS
  589. // In windows, delimiters can be either '/' or '\'.
  590. size_t base_end_pos = gameSource.find_last_of("/\\", source_len - 2);
  591. #else
  592. size_t base_end_pos = gameSource.find_last_of('/', source_len - 2);
  593. #endif
  594. if (base_end_pos == std::string::npos)
  595. return "";
  596. // If the source is in the unix root (aka '/'), we want to keep the '/'.
  597. if (base_end_pos == 0)
  598. base_end_pos = 1;
  599. return gameSource.substr(0, base_end_pos);
  600. }
  601. std::string Filesystem::getRealDirectory(const char *filename) const
  602. {
  603. if (!PHYSFS_isInit())
  604. throw love::Exception("PhysFS is not initialized.");
  605. const char *dir = PHYSFS_getRealDir(filename);
  606. if (dir == nullptr)
  607. throw love::Exception("File does not exist on disk.");
  608. return std::string(dir);
  609. }
  610. bool Filesystem::getInfo(const char *filepath, Info &info) const
  611. {
  612. if (!PHYSFS_isInit())
  613. return false;
  614. PHYSFS_Stat stat = {};
  615. if (!PHYSFS_stat(filepath, &stat))
  616. return false;
  617. info.size = (int64) stat.filesize;
  618. info.modtime = (int64) stat.modtime;
  619. info.readonly = stat.readonly != 0;
  620. if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
  621. info.type = FILETYPE_FILE;
  622. else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
  623. info.type = FILETYPE_DIRECTORY;
  624. else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
  625. info.type = FILETYPE_SYMLINK;
  626. else
  627. info.type = FILETYPE_OTHER;
  628. return true;
  629. }
  630. bool Filesystem::createDirectory(const char *dir)
  631. {
  632. if (!PHYSFS_isInit())
  633. return false;
  634. if (!setupWriteDirectory())
  635. return false;
  636. if (!PHYSFS_mkdir(dir))
  637. return false;
  638. return true;
  639. }
  640. bool Filesystem::remove(const char *file)
  641. {
  642. if (!PHYSFS_isInit())
  643. return false;
  644. if (!setupWriteDirectory())
  645. return false;
  646. if (!PHYSFS_delete(file))
  647. return false;
  648. return true;
  649. }
  650. FileData *Filesystem::read(const char *filename, int64 size) const
  651. {
  652. File file(filename);
  653. file.open(File::MODE_READ);
  654. // close() is called in the File destructor.
  655. return file.read(size);
  656. }
  657. void Filesystem::write(const char *filename, const void *data, int64 size) const
  658. {
  659. File file(filename);
  660. file.open(File::MODE_WRITE);
  661. // close() is called in the File destructor.
  662. if (!file.write(data, size))
  663. throw love::Exception("Data could not be written.");
  664. }
  665. void Filesystem::append(const char *filename, const void *data, int64 size) const
  666. {
  667. File file(filename);
  668. file.open(File::MODE_APPEND);
  669. // close() is called in the File destructor.
  670. if (!file.write(data, size))
  671. throw love::Exception("Data could not be written.");
  672. }
  673. bool Filesystem::getDirectoryItems(const char *dir, std::vector<std::string> &items)
  674. {
  675. if (!PHYSFS_isInit())
  676. return false;
  677. char **rc = PHYSFS_enumerateFiles(dir);
  678. if (rc == nullptr)
  679. return false;
  680. for (char **i = rc; *i != 0; i++)
  681. items.push_back(*i);
  682. PHYSFS_freeList(rc);
  683. return true;
  684. }
  685. void Filesystem::setSymlinksEnabled(bool enable)
  686. {
  687. if (!PHYSFS_isInit())
  688. return;
  689. PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
  690. }
  691. bool Filesystem::areSymlinksEnabled() const
  692. {
  693. if (!PHYSFS_isInit())
  694. return false;
  695. return PHYSFS_symbolicLinksPermitted() != 0;
  696. }
  697. std::vector<std::string> &Filesystem::getRequirePath()
  698. {
  699. return requirePath;
  700. }
  701. std::vector<std::string> &Filesystem::getCRequirePath()
  702. {
  703. return cRequirePath;
  704. }
  705. void Filesystem::allowMountingForPath(const std::string &path)
  706. {
  707. if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
  708. allowedMountPaths.push_back(path);
  709. }
  710. } // physfs
  711. } // filesystem
  712. } // love