file_util.cpp 29 KB

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