file_util.cpp 28 KB

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