file_util.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/common.h"
  5. #include "common/file_util.h"
  6. #ifdef _WIN32
  7. #include <windows.h>
  8. #include <shlobj.h> // for SHGetFolderPath
  9. #include <shellapi.h>
  10. #include <commdlg.h> // for GetSaveFileName
  11. #include <io.h>
  12. #include <direct.h> // getcwd
  13. #include <tchar.h>
  14. #else
  15. #include <sys/param.h>
  16. #include <sys/types.h>
  17. #include <dirent.h>
  18. #include <pwd.h>
  19. #include <unistd.h>
  20. #endif
  21. #if defined(__APPLE__)
  22. #include <CoreFoundation/CFString.h>
  23. #include <CoreFoundation/CFURL.h>
  24. #include <CoreFoundation/CFBundle.h>
  25. #endif
  26. #include <algorithm>
  27. #include <sys/stat.h>
  28. #ifndef S_ISDIR
  29. #define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
  30. #endif
  31. #ifdef BSD4_4
  32. #define stat64 stat
  33. #define fstat64 fstat
  34. #endif
  35. // This namespace has various generic functions related to files and paths.
  36. // The code still needs a ton of cleanup.
  37. // REMEMBER: strdup considered harmful!
  38. namespace FileUtil
  39. {
  40. // Remove any ending forward slashes from directory paths
  41. // Modifies argument.
  42. static void StripTailDirSlashes(std::string &fname)
  43. {
  44. if (fname.length() > 1)
  45. {
  46. size_t i = fname.length() - 1;
  47. while (fname[i] == DIR_SEP_CHR)
  48. fname[i--] = '\0';
  49. }
  50. return;
  51. }
  52. // Returns true if file filename exists
  53. bool Exists(const std::string &filename)
  54. {
  55. struct stat64 file_info;
  56. std::string copy(filename);
  57. StripTailDirSlashes(copy);
  58. #ifdef _WIN32
  59. int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info);
  60. #else
  61. int result = stat64(copy.c_str(), &file_info);
  62. #endif
  63. return (result == 0);
  64. }
  65. // Returns true if filename is a directory
  66. bool IsDirectory(const std::string &filename)
  67. {
  68. struct stat64 file_info;
  69. std::string copy(filename);
  70. StripTailDirSlashes(copy);
  71. #ifdef _WIN32
  72. int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info);
  73. #else
  74. int result = stat64(copy.c_str(), &file_info);
  75. #endif
  76. if (result < 0) {
  77. LOG_WARNING(Common_Filesystem, "stat failed on %s: %s",
  78. filename.c_str(), GetLastErrorMsg());
  79. return false;
  80. }
  81. return S_ISDIR(file_info.st_mode);
  82. }
  83. // Deletes a given filename, return true on success
  84. // Doesn't supports deleting a directory
  85. bool Delete(const std::string &filename)
  86. {
  87. LOG_INFO(Common_Filesystem, "file %s", filename.c_str());
  88. // Return true because we care about the file no
  89. // being there, not the actual delete.
  90. if (!Exists(filename))
  91. {
  92. LOG_WARNING(Common_Filesystem, "%s does not exist", filename.c_str());
  93. return true;
  94. }
  95. // We can't delete a directory
  96. if (IsDirectory(filename))
  97. {
  98. LOG_ERROR(Common_Filesystem, "Failed: %s is a directory", filename.c_str());
  99. return false;
  100. }
  101. #ifdef _WIN32
  102. if (!DeleteFile(Common::UTF8ToTStr(filename).c_str()))
  103. {
  104. LOG_ERROR(Common_Filesystem, "DeleteFile failed on %s: %s",
  105. filename.c_str(), GetLastErrorMsg());
  106. return false;
  107. }
  108. #else
  109. if (unlink(filename.c_str()) == -1) {
  110. LOG_ERROR(Common_Filesystem, "unlink failed on %s: %s",
  111. filename.c_str(), GetLastErrorMsg());
  112. return false;
  113. }
  114. #endif
  115. return true;
  116. }
  117. // Returns true if successful, or path already exists.
  118. bool CreateDir(const std::string &path)
  119. {
  120. LOG_TRACE(Common_Filesystem, "directory %s", path.c_str());
  121. #ifdef _WIN32
  122. if (::CreateDirectory(Common::UTF8ToTStr(path).c_str(), nullptr))
  123. return true;
  124. DWORD error = GetLastError();
  125. if (error == ERROR_ALREADY_EXISTS)
  126. {
  127. LOG_WARNING(Common_Filesystem, "CreateDirectory failed on %s: already exists", path.c_str());
  128. return true;
  129. }
  130. LOG_ERROR(Common_Filesystem, "CreateDirectory failed on %s: %i", path.c_str(), error);
  131. return false;
  132. #else
  133. if (mkdir(path.c_str(), 0755) == 0)
  134. return true;
  135. int err = errno;
  136. if (err == EEXIST)
  137. {
  138. LOG_WARNING(Common_Filesystem, "mkdir failed on %s: already exists", path.c_str());
  139. return true;
  140. }
  141. LOG_ERROR(Common_Filesystem, "mkdir failed on %s: %s", path.c_str(), strerror(err));
  142. return false;
  143. #endif
  144. }
  145. // Creates the full path of fullPath returns true on success
  146. bool CreateFullPath(const std::string &fullPath)
  147. {
  148. int panicCounter = 100;
  149. LOG_TRACE(Common_Filesystem, "path %s", fullPath.c_str());
  150. if (FileUtil::Exists(fullPath))
  151. {
  152. LOG_WARNING(Common_Filesystem, "path exists %s", fullPath.c_str());
  153. return true;
  154. }
  155. size_t position = 0;
  156. while (true)
  157. {
  158. // Find next sub path
  159. position = fullPath.find(DIR_SEP_CHR, position);
  160. // we're done, yay!
  161. if (position == fullPath.npos)
  162. return true;
  163. // Include the '/' so the first call is CreateDir("/") rather than CreateDir("")
  164. std::string const subPath(fullPath.substr(0, position + 1));
  165. if (!FileUtil::IsDirectory(subPath) && !FileUtil::CreateDir(subPath)) {
  166. LOG_ERROR(Common, "CreateFullPath: directory creation failed");
  167. return false;
  168. }
  169. // A safety check
  170. panicCounter--;
  171. if (panicCounter <= 0)
  172. {
  173. LOG_ERROR(Common, "CreateFullPath: directory structure is too deep");
  174. return false;
  175. }
  176. position++;
  177. }
  178. }
  179. // Deletes a directory filename, returns true on success
  180. bool DeleteDir(const std::string &filename)
  181. {
  182. LOG_INFO(Common_Filesystem, "directory %s", filename.c_str());
  183. // check if a directory
  184. if (!FileUtil::IsDirectory(filename))
  185. {
  186. LOG_ERROR(Common_Filesystem, "Not a directory %s", filename.c_str());
  187. return false;
  188. }
  189. #ifdef _WIN32
  190. if (::RemoveDirectory(Common::UTF8ToTStr(filename).c_str()))
  191. return true;
  192. #else
  193. if (rmdir(filename.c_str()) == 0)
  194. return true;
  195. #endif
  196. LOG_ERROR(Common_Filesystem, "failed %s: %s", filename.c_str(), GetLastErrorMsg());
  197. return false;
  198. }
  199. // renames file srcFilename to destFilename, returns true on success
  200. bool Rename(const std::string &srcFilename, const std::string &destFilename)
  201. {
  202. LOG_TRACE(Common_Filesystem, "%s --> %s",
  203. srcFilename.c_str(), destFilename.c_str());
  204. if (rename(srcFilename.c_str(), destFilename.c_str()) == 0)
  205. return true;
  206. LOG_ERROR(Common_Filesystem, "failed %s --> %s: %s",
  207. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  208. return false;
  209. }
  210. // copies file srcFilename to destFilename, returns true on success
  211. bool Copy(const std::string &srcFilename, const std::string &destFilename)
  212. {
  213. LOG_TRACE(Common_Filesystem, "%s --> %s",
  214. srcFilename.c_str(), destFilename.c_str());
  215. #ifdef _WIN32
  216. if (CopyFile(Common::UTF8ToTStr(srcFilename).c_str(), Common::UTF8ToTStr(destFilename).c_str(), FALSE))
  217. return true;
  218. LOG_ERROR(Common_Filesystem, "failed %s --> %s: %s",
  219. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  220. return false;
  221. #else
  222. // buffer size
  223. #define BSIZE 1024
  224. char buffer[BSIZE];
  225. // Open input file
  226. FILE *input = fopen(srcFilename.c_str(), "rb");
  227. if (!input)
  228. {
  229. LOG_ERROR(Common_Filesystem, "opening input failed %s --> %s: %s",
  230. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  231. return false;
  232. }
  233. // open output file
  234. FILE *output = fopen(destFilename.c_str(), "wb");
  235. if (!output)
  236. {
  237. fclose(input);
  238. LOG_ERROR(Common_Filesystem, "opening output failed %s --> %s: %s",
  239. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  240. return false;
  241. }
  242. // copy loop
  243. while (!feof(input))
  244. {
  245. // read input
  246. int rnum = fread(buffer, sizeof(char), BSIZE, input);
  247. if (rnum != BSIZE)
  248. {
  249. if (ferror(input) != 0)
  250. {
  251. LOG_ERROR(Common_Filesystem,
  252. "failed reading from source, %s --> %s: %s",
  253. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  254. goto bail;
  255. }
  256. }
  257. // write output
  258. int wnum = fwrite(buffer, sizeof(char), rnum, output);
  259. if (wnum != rnum)
  260. {
  261. LOG_ERROR(Common_Filesystem,
  262. "failed writing to output, %s --> %s: %s",
  263. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  264. goto bail;
  265. }
  266. }
  267. // close files
  268. fclose(input);
  269. fclose(output);
  270. return true;
  271. bail:
  272. if (input)
  273. fclose(input);
  274. if (output)
  275. fclose(output);
  276. return false;
  277. #endif
  278. }
  279. // Returns the size of filename (64bit)
  280. u64 GetSize(const std::string &filename)
  281. {
  282. if (!Exists(filename))
  283. {
  284. LOG_ERROR(Common_Filesystem, "failed %s: No such file", filename.c_str());
  285. return 0;
  286. }
  287. if (IsDirectory(filename))
  288. {
  289. LOG_ERROR(Common_Filesystem, "failed %s: is a directory", filename.c_str());
  290. return 0;
  291. }
  292. struct stat64 buf;
  293. #ifdef _WIN32
  294. if (_tstat64(Common::UTF8ToTStr(filename).c_str(), &buf) == 0)
  295. #else
  296. if (stat64(filename.c_str(), &buf) == 0)
  297. #endif
  298. {
  299. LOG_TRACE(Common_Filesystem, "%s: %lld",
  300. filename.c_str(), (long long)buf.st_size);
  301. return buf.st_size;
  302. }
  303. LOG_ERROR(Common_Filesystem, "Stat failed %s: %s",
  304. filename.c_str(), GetLastErrorMsg());
  305. return 0;
  306. }
  307. // Overloaded GetSize, accepts file descriptor
  308. u64 GetSize(const int fd)
  309. {
  310. struct stat64 buf;
  311. if (fstat64(fd, &buf) != 0) {
  312. LOG_ERROR(Common_Filesystem, "GetSize: stat failed %i: %s",
  313. fd, GetLastErrorMsg());
  314. return 0;
  315. }
  316. return buf.st_size;
  317. }
  318. // Overloaded GetSize, accepts FILE*
  319. u64 GetSize(FILE *f)
  320. {
  321. // can't use off_t here because it can be 32-bit
  322. u64 pos = ftello(f);
  323. if (fseeko(f, 0, SEEK_END) != 0) {
  324. LOG_ERROR(Common_Filesystem, "GetSize: seek failed %p: %s",
  325. f, GetLastErrorMsg());
  326. return 0;
  327. }
  328. u64 size = ftello(f);
  329. if ((size != pos) && (fseeko(f, pos, SEEK_SET) != 0)) {
  330. LOG_ERROR(Common_Filesystem, "GetSize: seek failed %p: %s",
  331. f, GetLastErrorMsg());
  332. return 0;
  333. }
  334. return size;
  335. }
  336. // creates an empty file filename, returns true on success
  337. bool CreateEmptyFile(const std::string &filename)
  338. {
  339. LOG_TRACE(Common_Filesystem, "%s", filename.c_str());
  340. if (!FileUtil::IOFile(filename, "wb"))
  341. {
  342. LOG_ERROR(Common_Filesystem, "failed %s: %s",
  343. filename.c_str(), GetLastErrorMsg());
  344. return false;
  345. }
  346. return true;
  347. }
  348. // Scans the directory tree gets, starting from _Directory and adds the
  349. // results into parentEntry. Returns the number of files+directories found
  350. u32 ScanDirectoryTree(const std::string &directory, FSTEntry& parentEntry)
  351. {
  352. LOG_TRACE(Common_Filesystem, "directory %s", directory.c_str());
  353. // How many files + directories we found
  354. u32 foundEntries = 0;
  355. #ifdef _WIN32
  356. // Find the first file in the directory.
  357. WIN32_FIND_DATA ffd;
  358. HANDLE hFind = FindFirstFile(Common::UTF8ToTStr(directory + "\\*").c_str(), &ffd);
  359. if (hFind == INVALID_HANDLE_VALUE)
  360. {
  361. FindClose(hFind);
  362. return foundEntries;
  363. }
  364. // windows loop
  365. do
  366. {
  367. FSTEntry entry;
  368. const std::string virtualName(Common::TStrToUTF8(ffd.cFileName));
  369. #else
  370. struct dirent dirent, *result = nullptr;
  371. DIR *dirp = opendir(directory.c_str());
  372. if (!dirp)
  373. return 0;
  374. // non windows loop
  375. while (!readdir_r(dirp, &dirent, &result) && result)
  376. {
  377. FSTEntry entry;
  378. const std::string virtualName(result->d_name);
  379. #endif
  380. // check for "." and ".."
  381. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  382. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  383. (virtualName[2] == '\0')))
  384. continue;
  385. entry.virtualName = virtualName;
  386. entry.physicalName = directory;
  387. entry.physicalName += DIR_SEP + entry.virtualName;
  388. if (IsDirectory(entry.physicalName.c_str()))
  389. {
  390. entry.isDirectory = true;
  391. // is a directory, lets go inside
  392. entry.size = ScanDirectoryTree(entry.physicalName, entry);
  393. foundEntries += (u32)entry.size;
  394. }
  395. else
  396. { // is a file
  397. entry.isDirectory = false;
  398. entry.size = GetSize(entry.physicalName.c_str());
  399. }
  400. ++foundEntries;
  401. // Push into the tree
  402. parentEntry.children.push_back(entry);
  403. #ifdef _WIN32
  404. } while (FindNextFile(hFind, &ffd) != 0);
  405. FindClose(hFind);
  406. #else
  407. }
  408. closedir(dirp);
  409. #endif
  410. // Return number of entries found.
  411. return foundEntries;
  412. }
  413. // Deletes the given directory and anything under it. Returns true on success.
  414. bool DeleteDirRecursively(const std::string &directory)
  415. {
  416. LOG_TRACE(Common_Filesystem, "%s", directory.c_str());
  417. #ifdef _WIN32
  418. // Find the first file in the directory.
  419. WIN32_FIND_DATA ffd;
  420. HANDLE hFind = FindFirstFile(Common::UTF8ToTStr(directory + "\\*").c_str(), &ffd);
  421. if (hFind == INVALID_HANDLE_VALUE)
  422. {
  423. FindClose(hFind);
  424. return false;
  425. }
  426. // windows loop
  427. do
  428. {
  429. const std::string virtualName(Common::TStrToUTF8(ffd.cFileName));
  430. #else
  431. struct dirent dirent, *result = nullptr;
  432. DIR *dirp = opendir(directory.c_str());
  433. if (!dirp)
  434. return false;
  435. // non windows loop
  436. while (!readdir_r(dirp, &dirent, &result) && result)
  437. {
  438. const std::string virtualName = result->d_name;
  439. #endif
  440. // check for "." and ".."
  441. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  442. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  443. (virtualName[2] == '\0')))
  444. continue;
  445. std::string newPath = directory + DIR_SEP_CHR + virtualName;
  446. if (IsDirectory(newPath))
  447. {
  448. if (!DeleteDirRecursively(newPath))
  449. {
  450. #ifndef _WIN32
  451. closedir(dirp);
  452. #endif
  453. return false;
  454. }
  455. }
  456. else
  457. {
  458. if (!FileUtil::Delete(newPath))
  459. {
  460. #ifndef _WIN32
  461. closedir(dirp);
  462. #endif
  463. return false;
  464. }
  465. }
  466. #ifdef _WIN32
  467. } while (FindNextFile(hFind, &ffd) != 0);
  468. FindClose(hFind);
  469. #else
  470. }
  471. closedir(dirp);
  472. #endif
  473. FileUtil::DeleteDir(directory);
  474. return true;
  475. }
  476. // Create directory and copy contents (does not overwrite existing files)
  477. void CopyDir(const std::string &source_path, const std::string &dest_path)
  478. {
  479. #ifndef _WIN32
  480. if (source_path == dest_path) return;
  481. if (!FileUtil::Exists(source_path)) return;
  482. if (!FileUtil::Exists(dest_path)) FileUtil::CreateFullPath(dest_path);
  483. struct dirent dirent, *result = nullptr;
  484. DIR *dirp = opendir(source_path.c_str());
  485. if (!dirp) return;
  486. while (!readdir_r(dirp, &dirent, &result) && result)
  487. {
  488. const std::string virtualName(result->d_name);
  489. // check for "." and ".."
  490. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  491. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  492. (virtualName[2] == '\0')))
  493. continue;
  494. std::string source, dest;
  495. source = source_path + virtualName;
  496. dest = dest_path + virtualName;
  497. if (IsDirectory(source))
  498. {
  499. source += '/';
  500. dest += '/';
  501. if (!FileUtil::Exists(dest)) FileUtil::CreateFullPath(dest);
  502. CopyDir(source, dest);
  503. }
  504. else if (!FileUtil::Exists(dest)) FileUtil::Copy(source, dest);
  505. }
  506. closedir(dirp);
  507. #endif
  508. }
  509. // Returns the current directory
  510. std::string GetCurrentDir()
  511. {
  512. char *dir;
  513. // Get the current working directory (getcwd uses malloc)
  514. if (!(dir = getcwd(nullptr, 0))) {
  515. LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: %s",
  516. GetLastErrorMsg());
  517. return nullptr;
  518. }
  519. std::string strDir = dir;
  520. free(dir);
  521. return strDir;
  522. }
  523. // Sets the current directory to the given directory
  524. bool SetCurrentDir(const std::string &directory)
  525. {
  526. return chdir(directory.c_str()) == 0;
  527. }
  528. #if defined(__APPLE__)
  529. std::string GetBundleDirectory()
  530. {
  531. CFURLRef BundleRef;
  532. char AppBundlePath[MAXPATHLEN];
  533. // Get the main bundle for the app
  534. BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  535. CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
  536. CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
  537. CFRelease(BundleRef);
  538. CFRelease(BundlePath);
  539. return AppBundlePath;
  540. }
  541. #endif
  542. #ifdef _WIN32
  543. std::string& GetExeDirectory()
  544. {
  545. static std::string exe_path;
  546. if (exe_path.empty())
  547. {
  548. TCHAR tchar_exe_path[2048];
  549. GetModuleFileName(nullptr, tchar_exe_path, 2048);
  550. exe_path = Common::TStrToUTF8(tchar_exe_path);
  551. exe_path = exe_path.substr(0, exe_path.find_last_of('\\'));
  552. }
  553. return exe_path;
  554. }
  555. #else
  556. /**
  557. * @return The user’s home directory on POSIX systems
  558. */
  559. static const std::string& GetHomeDirectory() {
  560. static std::string home_path;
  561. if (home_path.empty()) {
  562. const char* envvar = getenv("HOME");
  563. if (envvar) {
  564. home_path = envvar;
  565. } else {
  566. auto pw = getpwuid(getuid());
  567. ASSERT_MSG(pw, "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");
  568. home_path = pw->pw_dir;
  569. }
  570. }
  571. return home_path;
  572. }
  573. /**
  574. * Follows the XDG Base Directory Specification to get a directory path
  575. * @param envvar The XDG environment variable to get the value from
  576. * @return The directory path
  577. * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  578. */
  579. static const std::string GetUserDirectory(const std::string& envvar) {
  580. const char* directory = getenv(envvar.c_str());
  581. std::string user_dir;
  582. if (directory) {
  583. user_dir = directory;
  584. } else {
  585. std::string subdirectory;
  586. if (envvar == "XDG_DATA_HOME")
  587. subdirectory = DIR_SEP ".local" DIR_SEP "share";
  588. else if (envvar == "XDG_CONFIG_HOME")
  589. subdirectory = DIR_SEP ".config";
  590. else if (envvar == "XDG_CACHE_HOME")
  591. subdirectory = DIR_SEP ".cache";
  592. else
  593. ASSERT_MSG(false, "Unknown XDG variable %s.", envvar.c_str());
  594. user_dir = GetHomeDirectory() + subdirectory;
  595. }
  596. ASSERT_MSG(!user_dir.empty(), "User directory %s musn’t be empty.", envvar.c_str());
  597. ASSERT_MSG(user_dir[0] == '/', "User directory %s must be absolute.", envvar.c_str());
  598. return user_dir;
  599. }
  600. #endif
  601. std::string GetSysDirectory()
  602. {
  603. std::string sysDir;
  604. #if defined (__APPLE__)
  605. sysDir = GetBundleDirectory();
  606. sysDir += DIR_SEP;
  607. sysDir += SYSDATA_DIR;
  608. #else
  609. sysDir = SYSDATA_DIR;
  610. #endif
  611. sysDir += DIR_SEP;
  612. LOG_DEBUG(Common_Filesystem, "Setting to %s:", sysDir.c_str());
  613. return sysDir;
  614. }
  615. // Returns a string with a Citra data dir or file in the user's home
  616. // directory. To be used in "multi-user" mode (that is, installed).
  617. const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath)
  618. {
  619. static std::string paths[NUM_PATH_INDICES];
  620. // Set up all paths and files on the first run
  621. if (paths[D_USER_IDX].empty())
  622. {
  623. #ifdef _WIN32
  624. paths[D_USER_IDX] = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
  625. paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
  626. paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
  627. #else
  628. if (FileUtil::Exists(ROOT_DIR DIR_SEP USERDATA_DIR)) {
  629. paths[D_USER_IDX] = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
  630. paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
  631. paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
  632. } else {
  633. std::string data_dir = GetUserDirectory("XDG_DATA_HOME");
  634. std::string config_dir = GetUserDirectory("XDG_CONFIG_HOME");
  635. std::string cache_dir = GetUserDirectory("XDG_CACHE_HOME");
  636. paths[D_USER_IDX] = data_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
  637. paths[D_CONFIG_IDX] = config_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
  638. paths[D_CACHE_IDX] = cache_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
  639. }
  640. #endif
  641. paths[D_GAMECONFIG_IDX] = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
  642. paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
  643. paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
  644. paths[D_NAND_IDX] = paths[D_USER_IDX] + NAND_DIR DIR_SEP;
  645. paths[D_SYSDATA_IDX] = paths[D_USER_IDX] + SYSDATA_DIR DIR_SEP;
  646. paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
  647. paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
  648. paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
  649. paths[D_SCREENSHOTS_IDX] = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
  650. paths[D_DUMP_IDX] = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
  651. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  652. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  653. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  654. paths[D_LOGS_IDX] = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
  655. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  656. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  657. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  658. }
  659. if (!newPath.empty())
  660. {
  661. if (!FileUtil::IsDirectory(newPath))
  662. {
  663. LOG_ERROR(Common_Filesystem, "Invalid path specified %s", newPath.c_str());
  664. return paths[DirIDX];
  665. }
  666. else
  667. {
  668. paths[DirIDX] = newPath;
  669. }
  670. switch (DirIDX)
  671. {
  672. case D_ROOT_IDX:
  673. paths[D_USER_IDX] = paths[D_ROOT_IDX] + DIR_SEP;
  674. paths[D_SYSCONF_IDX] = paths[D_USER_IDX] + SYSCONF_DIR + DIR_SEP;
  675. paths[F_SYSCONF_IDX] = paths[D_SYSCONF_IDX] + SYSCONF;
  676. break;
  677. case D_USER_IDX:
  678. paths[D_USER_IDX] = paths[D_ROOT_IDX] + DIR_SEP;
  679. paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
  680. paths[D_GAMECONFIG_IDX] = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
  681. paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
  682. paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
  683. paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
  684. paths[D_NAND_IDX] = paths[D_USER_IDX] + NAND_DIR DIR_SEP;
  685. paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
  686. paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
  687. paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
  688. paths[D_SCREENSHOTS_IDX] = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
  689. paths[D_DUMP_IDX] = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
  690. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  691. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  692. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  693. paths[D_LOGS_IDX] = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
  694. paths[D_SYSCONF_IDX] = paths[D_USER_IDX] + SYSCONF_DIR DIR_SEP;
  695. paths[F_EMUCONFIG_IDX] = paths[D_CONFIG_IDX] + EMU_CONFIG;
  696. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  697. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  698. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  699. break;
  700. case D_CONFIG_IDX:
  701. paths[F_EMUCONFIG_IDX] = paths[D_CONFIG_IDX] + EMU_CONFIG;
  702. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  703. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  704. break;
  705. case D_DUMP_IDX:
  706. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  707. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  708. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  709. break;
  710. case D_LOGS_IDX:
  711. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  712. }
  713. }
  714. return paths[DirIDX];
  715. }
  716. size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename)
  717. {
  718. return FileUtil::IOFile(filename, text_file ? "w" : "wb").WriteBytes(str.data(), str.size());
  719. }
  720. size_t ReadFileToString(bool text_file, const char *filename, std::string &str)
  721. {
  722. FileUtil::IOFile file(filename, text_file ? "r" : "rb");
  723. auto const f = file.GetHandle();
  724. if (!f)
  725. return false;
  726. str.resize(static_cast<u32>(GetSize(f)));
  727. return file.ReadArray(&str[0], str.size());
  728. }
  729. /**
  730. * Splits the filename into 8.3 format
  731. * Loosely implemented following https://en.wikipedia.org/wiki/8.3_filename
  732. * @param filename The normal filename to use
  733. * @param short_name A 9-char array in which the short name will be written
  734. * @param extension A 4-char array in which the extension will be written
  735. */
  736. void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
  737. std::array<char, 4>& extension) {
  738. const std::string forbidden_characters = ".\"/\\[]:;=, ";
  739. // On a FAT32 partition, 8.3 names are stored as a 11 bytes array, filled with spaces.
  740. short_name = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
  741. extension = {' ', ' ', ' ', '\0'};
  742. std::string::size_type point = filename.rfind('.');
  743. if (point == filename.size() - 1)
  744. point = filename.rfind('.', point);
  745. // Get short name.
  746. int j = 0;
  747. for (char letter : filename.substr(0, point)) {
  748. if (forbidden_characters.find(letter, 0) != std::string::npos)
  749. continue;
  750. if (j == 8) {
  751. // TODO(Link Mauve): also do that for filenames containing a space.
  752. // TODO(Link Mauve): handle multiple files having the same short name.
  753. short_name[6] = '~';
  754. short_name[7] = '1';
  755. break;
  756. }
  757. short_name[j++] = toupper(letter);
  758. }
  759. // Get extension.
  760. if (point != std::string::npos) {
  761. j = 0;
  762. for (char letter : filename.substr(point + 1, 3))
  763. extension[j++] = toupper(letter);
  764. }
  765. }
  766. IOFile::IOFile()
  767. : m_file(nullptr), m_good(true)
  768. {}
  769. IOFile::IOFile(std::FILE* file)
  770. : m_file(file), m_good(true)
  771. {}
  772. IOFile::IOFile(const std::string& filename, const char openmode[])
  773. : m_file(nullptr), m_good(true)
  774. {
  775. Open(filename, openmode);
  776. }
  777. IOFile::~IOFile()
  778. {
  779. Close();
  780. }
  781. IOFile::IOFile(IOFile&& other)
  782. : m_file(nullptr), m_good(true)
  783. {
  784. Swap(other);
  785. }
  786. IOFile& IOFile::operator=(IOFile&& other)
  787. {
  788. Swap(other);
  789. return *this;
  790. }
  791. void IOFile::Swap(IOFile& other)
  792. {
  793. std::swap(m_file, other.m_file);
  794. std::swap(m_good, other.m_good);
  795. }
  796. bool IOFile::Open(const std::string& filename, const char openmode[])
  797. {
  798. Close();
  799. #ifdef _WIN32
  800. _tfopen_s(&m_file, Common::UTF8ToTStr(filename).c_str(), Common::UTF8ToTStr(openmode).c_str());
  801. #else
  802. m_file = fopen(filename.c_str(), openmode);
  803. #endif
  804. m_good = IsOpen();
  805. return m_good;
  806. }
  807. bool IOFile::Close()
  808. {
  809. if (!IsOpen() || 0 != std::fclose(m_file))
  810. m_good = false;
  811. m_file = nullptr;
  812. return m_good;
  813. }
  814. std::FILE* IOFile::ReleaseHandle()
  815. {
  816. std::FILE* const ret = m_file;
  817. m_file = nullptr;
  818. return ret;
  819. }
  820. void IOFile::SetHandle(std::FILE* file)
  821. {
  822. Close();
  823. Clear();
  824. m_file = file;
  825. }
  826. u64 IOFile::GetSize()
  827. {
  828. if (IsOpen())
  829. return FileUtil::GetSize(m_file);
  830. else
  831. return 0;
  832. }
  833. bool IOFile::Seek(s64 off, int origin)
  834. {
  835. if (!IsOpen() || 0 != fseeko(m_file, off, origin))
  836. m_good = false;
  837. return m_good;
  838. }
  839. u64 IOFile::Tell()
  840. {
  841. if (IsOpen())
  842. return ftello(m_file);
  843. else
  844. return -1;
  845. }
  846. bool IOFile::Flush()
  847. {
  848. if (!IsOpen() || 0 != std::fflush(m_file))
  849. m_good = false;
  850. return m_good;
  851. }
  852. bool IOFile::Resize(u64 size)
  853. {
  854. if (!IsOpen() || 0 !=
  855. #ifdef _WIN32
  856. // ector: _chsize sucks, not 64-bit safe
  857. // F|RES: changed to _chsize_s. i think it is 64-bit safe
  858. _chsize_s(_fileno(m_file), size)
  859. #else
  860. // TODO: handle 64bit and growing
  861. ftruncate(fileno(m_file), size)
  862. #endif
  863. )
  864. m_good = false;
  865. return m_good;
  866. }
  867. } // namespace