file_util.cpp 29 KB

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