file_util.cpp 29 KB

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