VCMIDirs.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * VCMIDirs.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "VCMIDirs.h"
  12. namespace bfs = boost::filesystem;
  13. bfs::path IVCMIDirs::userSavePath() const { return userDataPath() / "Saves"; }
  14. void IVCMIDirs::init()
  15. {
  16. // TODO: Log errors
  17. bfs::create_directories(userDataPath());
  18. bfs::create_directories(userCachePath());
  19. bfs::create_directories(userConfigPath());
  20. bfs::create_directories(userSavePath());
  21. }
  22. #ifdef VCMI_WINDOWS
  23. #ifdef __MINGW32__
  24. #define _WIN32_IE 0x0500
  25. #ifndef CSIDL_MYDOCUMENTS
  26. #define CSIDL_MYDOCUMENTS CSIDL_PERSONAL
  27. #endif
  28. #endif // __MINGW32__
  29. #include <windows.h>
  30. #include <shlobj.h>
  31. #include <shellapi.h>
  32. // Generates script file named _temp.bat in 'to' directory and runs it
  33. // Script will:
  34. // - Wait util 'exeName' ends.
  35. // - Copy all files from 'from' to 'to'
  36. // - Ask user to replace files existed in 'to'.
  37. // - Run 'exeName'
  38. // - Delete itself.
  39. bool StartBatchCopyDataProgram(
  40. const bfs::path& from, const bfs::path& to, const bfs::path& exeName,
  41. const bfs::path& currentPath = bfs::current_path())
  42. {
  43. static const char base[] =
  44. "@echo off" "\n"
  45. "echo Preparing to move VCMI data system." "\n"
  46. ":CLIENT_RUNNING_LOOP" "\n"
  47. "TASKLIST | FIND /I %1% > nul" "\n"
  48. "IF ERRORLEVEL 1 (" "\n"
  49. "GOTO CLIENT_NOT_RUNNING" "\n"
  50. ") ELSE (" "\n"
  51. "echo %1% is still running..." "\n"
  52. "echo Waiting until process ends..." "\n"
  53. "ping 1.1.1.1 -n 1 -w 3000 > nul" "\n" // Sleep ~3 seconds. I love Windows :)
  54. "goto :CLIENT_RUNNING_LOOP" "\n"
  55. ")" "\n"
  56. ":CLIENT_NOT_RUNNING" "\n"
  57. "echo %1% turned off..." "\n"
  58. "echo Attempt to move datas." "\n"
  59. "echo From: %2%" "\n"
  60. "echo To: %4%" "\n"
  61. "echo Please resolve any conflicts..." "\n"
  62. "move /-Y %3% %4%" "\n" // Move all files from %3% to %4%.
  63. // /-Y ask what to do when file exists in %4%
  64. ":REMOVE_OLD_DIR" "\n"
  65. "rd %2% || rem" "\n" // Remove empty directory. Sets error flag if fail.
  66. "IF ERRORLEVEL 145 (" "\n" // Directory not empty
  67. "echo Directory %2% is not empty." "\n"
  68. "echo Please move rest of files manually now." "\n"
  69. "pause" "\n" // Press any key to continue...
  70. "goto REMOVE_OLD_DIR" "\n"
  71. ")" "\n"
  72. "echo Game data updated succefully." "\n"
  73. "echo Please update your shortcuts." "\n"
  74. "echo Press any key to start a game . . ." "\n"
  75. "pause > nul" "\n"
  76. "%5%" "\n"
  77. "del \"%%~f0\"&exit" "\n" // Script deletes itself
  78. ;
  79. const auto startGameString =
  80. bfs::equivalent(currentPath, from) ?
  81. (boost::format("start \"\" %1%") % (to / exeName)) : // Start game in new path.
  82. (boost::format("start \"\" /D %1% %2%") % currentPath % (to / exeName)); // Start game in 'currentPath"
  83. const bfs::path bathFilename = to / "_temp.bat";
  84. bfs::ofstream bathFile(bathFilename, bfs::ofstream::trunc | bfs::ofstream::out);
  85. if (!bathFile.is_open())
  86. return false;
  87. bathFile << (boost::format(base) % exeName % from % (from / "*.*") % to % startGameString.str()).str();
  88. bathFile.close();
  89. std::system(("start \"Updating VCMI datas\" /D \"" + to.string() + "\" \"" + bathFilename.string() + '\"').c_str());
  90. // start won't block std::system
  91. // /D start bat in other directory insteand of current directory.
  92. return true;
  93. }
  94. class VCMIDirsWIN32 final : public IVCMIDirs
  95. {
  96. public:
  97. boost::filesystem::path userDataPath() const override;
  98. boost::filesystem::path userCachePath() const override;
  99. boost::filesystem::path userConfigPath() const override;
  100. std::vector<boost::filesystem::path> dataPaths() const override;
  101. boost::filesystem::path clientPath() const override;
  102. boost::filesystem::path serverPath() const override;
  103. boost::filesystem::path libraryPath() const override;
  104. boost::filesystem::path binaryPath() const override;
  105. std::string libraryName(const std::string& basename) const override;
  106. std::string genHelpString() const override;
  107. void init() override;
  108. protected:
  109. boost::filesystem::path oldUserDataPath() const;
  110. boost::filesystem::path oldUserSavePath() const;
  111. };
  112. void VCMIDirsWIN32::init()
  113. {
  114. // Call base (init dirs)
  115. IVCMIDirs::init();
  116. // Moves one directory (from) contents to another directory (to)
  117. // Shows user the "moving file dialog" and ask to resolve conflits.
  118. // If necessary updates current directory.
  119. auto moveDirIfExists = [](const bfs::path& from, const bfs::path& to) -> bool
  120. {
  121. if (!bfs::is_directory(from))
  122. return true; // Nothing to do here. Flies away.
  123. if (bfs::is_empty(from))
  124. {
  125. if (bfs::current_path() == from)
  126. bfs::current_path(to);
  127. bfs::remove(from);
  128. return true; // Nothing to do here. Flies away.
  129. }
  130. if (!bfs::is_directory(to))
  131. {
  132. // IVCMIDirs::init() should create all destination directories.
  133. // TODO: Log fact, that we shouldn't be here.
  134. bfs::create_directories(to);
  135. }
  136. // Why the hell path strings should be end with double null :/
  137. auto makeDoubleNulled = [](const bfs::path& path) -> std::unique_ptr<wchar_t[]>
  138. {
  139. const std::wstring& pathStr = path.native();
  140. std::unique_ptr<wchar_t[]> result(new wchar_t[pathStr.length() + 2]);
  141. size_t i = 0;
  142. for (const wchar_t ch : pathStr)
  143. result[i++] = ch;
  144. result[i++] = L'\0';
  145. result[i++] = L'\0';
  146. return result;
  147. };
  148. auto fromDNulled = makeDoubleNulled(from / L"*.*");
  149. auto toDNulled = makeDoubleNulled(to);
  150. SHFILEOPSTRUCTW fileOp;
  151. fileOp.hwnd = GetConsoleWindow();
  152. fileOp.wFunc = FO_MOVE;
  153. fileOp.pFrom = fromDNulled.get();
  154. fileOp.pTo = toDNulled.get();
  155. fileOp.fFlags = 0;
  156. fileOp.hNameMappings = nullptr;
  157. fileOp.lpszProgressTitle = nullptr;
  158. const int errorCode = SHFileOperationW(&fileOp);
  159. if (errorCode != 0) // TODO: Log error. User should try to move files.
  160. return false;
  161. else if (fileOp.fAnyOperationsAborted) // TODO: Log warn. User aborted operation. User should move files.
  162. return false;
  163. else if (!bfs::is_empty(from)) // TODO: Log warn. Some files not moved. User should try to move files.
  164. return false;
  165. if (bfs::current_path() == from)
  166. bfs::current_path(to);
  167. // TODO: Log fact that we moved files succefully.
  168. bfs::remove(from);
  169. return true;
  170. };
  171. // Retrieves the fully qualified path for the file that contains the specified module.
  172. // The module must have been loaded by the current process.
  173. // If this parameter is nullptr, retrieves the path of the executable file of the current process.
  174. auto getModulePath = [](HMODULE hModule) -> bfs::path
  175. {
  176. wchar_t exePathW[MAX_PATH];
  177. DWORD nSize = GetModuleFileNameW(hModule, exePathW, MAX_PATH);
  178. DWORD error = GetLastError();
  179. // WARN: Windows XP don't set ERROR_INSUFFICIENT_BUFFER error.
  180. if (nSize != 0 && error != ERROR_INSUFFICIENT_BUFFER)
  181. return bfs::path(std::wstring(exePathW, nSize));
  182. // TODO: Error handling
  183. return bfs::path();
  184. };
  185. // Moves one directory contents to another directory
  186. // Shows user the "moving file dialog" and ask to resolve conflicts.
  187. // It takes into account that 'from' path can contain current executable.
  188. // If necessary closes program and starts update script.
  189. auto advancedMoveDirIfExists = [getModulePath, moveDirIfExists](const bfs::path& from, const bfs::path& to) -> bool
  190. {
  191. const bfs::path executablePath = getModulePath(nullptr);
  192. // VCMI cann't determine executable path.
  193. // Use standard way to move directory and exit function.
  194. if (executablePath.empty())
  195. return moveDirIfExists(from, to);
  196. const bfs::path executableName = executablePath.filename();
  197. // Current executabl isn't in 'from' path.
  198. // Use standard way to move directory and exit function.
  199. if (!bfs::equivalent(executablePath, from / executableName))
  200. return moveDirIfExists(from, to);
  201. // Try standard way to move directory.
  202. // I don't know how other systems, but Windows 8.1 allow to move running executable.
  203. if (moveDirIfExists(from, to))
  204. return true;
  205. // Start copying script and exit program.
  206. if (StartBatchCopyDataProgram(from, to, executableName))
  207. exit(ERROR_SUCCESS);
  208. // Everything failed :C
  209. return false;
  210. };
  211. moveDirIfExists(oldUserSavePath(), userSavePath());
  212. advancedMoveDirIfExists(oldUserDataPath(), userDataPath());
  213. }
  214. bfs::path VCMIDirsWIN32::userDataPath() const
  215. {
  216. wchar_t profileDir[MAX_PATH];
  217. if (SHGetSpecialFolderPathW(nullptr, profileDir, CSIDL_MYDOCUMENTS, FALSE) != FALSE)
  218. return bfs::path(profileDir) / "My Games\\vcmi";
  219. return ".";
  220. }
  221. bfs::path VCMIDirsWIN32::oldUserDataPath() const
  222. {
  223. wchar_t profileDir[MAX_PATH];
  224. if (SHGetSpecialFolderPathW(nullptr, profileDir, CSIDL_PROFILE, FALSE) == FALSE) // WinAPI way failed
  225. {
  226. #if defined(_MSC_VER) && _MSC_VER >= 1700
  227. wchar_t* buffer;
  228. size_t bufferSize;
  229. errno_t result = _wdupenv_s(&buffer, &bufferSize, L"userprofile");
  230. if (result == 0)
  231. {
  232. bfs::path result(std::wstring(buffer, bufferSize));
  233. free(buffer);
  234. return result;
  235. }
  236. #else
  237. const char* profileDirA;
  238. if ((profileDirA = std::getenv("userprofile"))) // STL way succeed
  239. return bfs::path(profileDirA) / "vcmi";
  240. #endif
  241. else
  242. return "."; // Every thing failed, return current directory.
  243. }
  244. else
  245. return bfs::path(profileDir) / "vcmi";
  246. //return dataPaths()[0] ???;
  247. }
  248. bfs::path VCMIDirsWIN32::oldUserSavePath() const { return userDataPath() / "Games"; }
  249. bfs::path VCMIDirsWIN32::userCachePath() const { return userDataPath(); }
  250. bfs::path VCMIDirsWIN32::userConfigPath() const { return userDataPath() / "config"; }
  251. std::vector<bfs::path> VCMIDirsWIN32::dataPaths() const
  252. {
  253. return std::vector<bfs::path>(1, bfs::path("."));
  254. }
  255. bfs::path VCMIDirsWIN32::clientPath() const { return binaryPath() / "VCMI_client.exe"; }
  256. bfs::path VCMIDirsWIN32::serverPath() const { return binaryPath() / "VCMI_server.exe"; }
  257. bfs::path VCMIDirsWIN32::libraryPath() const { return "."; }
  258. bfs::path VCMIDirsWIN32::binaryPath() const { return "."; }
  259. std::string VCMIDirsWIN32::genHelpString() const
  260. {
  261. std::vector<std::string> tempVec;
  262. for (const bfs::path& path : dataPaths())
  263. tempVec.push_back(path.string());
  264. std::string gdStringA = boost::algorithm::join(tempVec, ";");
  265. return
  266. " game data: " + gdStringA + "\n"
  267. " libraries: " + libraryPath().string() + "\n"
  268. " server: " + serverPath().string() + "\n"
  269. "\n"
  270. " user data: " + userDataPath().string() + "\n"
  271. " user cache: " + userCachePath().string() + "\n"
  272. " user config: " + userConfigPath().string() + "\n"
  273. " user saves: " + userSavePath().string() + "\n"; // Should end without new-line?
  274. }
  275. std::string VCMIDirsWIN32::libraryName(const std::string& basename) const { return basename + ".dll"; }
  276. #elif defined(VCMI_UNIX)
  277. class IVCMIDirsUNIX : public IVCMIDirs
  278. {
  279. public:
  280. boost::filesystem::path clientPath() const override;
  281. boost::filesystem::path serverPath() const override;
  282. std::string genHelpString() const override;
  283. };
  284. bfs::path IVCMIDirsUNIX::clientPath() const { return binaryPath() / "vcmiclient"; }
  285. bfs::path IVCMIDirsUNIX::serverPath() const { return binaryPath() / "vcmiserver"; }
  286. std::string IVCMIDirsUNIX::genHelpString() const
  287. {
  288. std::vector<std::string> tempVec;
  289. for (const bfs::path& path : dataPaths())
  290. tempVec.push_back(path.string());
  291. std::string gdStringA = boost::algorithm::join(tempVec, ":");
  292. return
  293. " game data: " + gdStringA + "\n"
  294. " libraries: " + libraryPath().string() + "\n"
  295. " server: " + serverPath().string() + "\n"
  296. "\n"
  297. " user data: " + userDataPath().string() + "\n"
  298. " user cache: " + userCachePath().string() + "\n"
  299. " user config: " + userConfigPath().string() + "\n"
  300. " user saves: " + userSavePath().string() + "\n"; // Should end without new-line?
  301. }
  302. #ifdef VCMI_APPLE
  303. class VCMIDirsOSX final : public IVCMIDirsUNIX
  304. {
  305. public:
  306. boost::filesystem::path userDataPath() const override;
  307. boost::filesystem::path userCachePath() const override;
  308. boost::filesystem::path userConfigPath() const override;
  309. std::vector<boost::filesystem::path> dataPaths() const override;
  310. boost::filesystem::path libraryPath() const override;
  311. boost::filesystem::path binaryPath() const override;
  312. std::string libraryName(const std::string& basename) const override;
  313. void init() override;
  314. };
  315. void VCMIDirsOSX::init()
  316. {
  317. // Call base (init dirs)
  318. IVCMIDirsUNIX::init();
  319. auto moveDirIfExists = [](const bfs::path& from, const bfs::path& to)
  320. {
  321. if (!bfs::is_directory(from))
  322. return; // Nothing to do here. Flies away.
  323. if (bfs::is_empty(from))
  324. {
  325. bfs::remove(from);
  326. return; // Nothing to do here. Flies away.
  327. }
  328. if (!bfs::is_directory(to))
  329. {
  330. // IVCMIDirs::init() should create all destination directories.
  331. // TODO: Log fact, that we shouldn't be here.
  332. bfs::create_directories(to);
  333. }
  334. for (bfs::directory_iterator file(from); file != bfs::directory_iterator(); ++file)
  335. {
  336. const boost::filesystem::path& srcFilePath = file->path();
  337. const boost::filesystem::path dstFilePath = to / srcFilePath.filename();
  338. // TODO: Aplication should ask user what to do when file exists:
  339. // replace/ignore/stop process/replace all/ignore all
  340. if (!boost::filesystem::exists(dstFilePath))
  341. bfs::rename(srcFilePath, dstFilePath);
  342. }
  343. if (!bfs::is_empty(from)); // TODO: Log warn. Some files not moved. User should try to move files.
  344. else
  345. bfs::remove(from);
  346. };
  347. moveDirIfExists(userDataPath() / "Games", userSavePath());
  348. }
  349. bfs::path VCMIDirsOSX::userDataPath() const
  350. {
  351. // This is Cocoa code that should be normally used to get path to Application Support folder but can't use it here for now...
  352. // NSArray* urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
  353. // UserPath = path([urls[0] path] + "/vcmi").string();
  354. // ...so here goes a bit of hardcode instead
  355. const char* homeDir = getenv("HOME"); // Should be std::getenv?
  356. if (homeDir == nullptr)
  357. homeDir = ".";
  358. return bfs::path(homeDir) / "Library" / "Application Support" / "vcmi";
  359. }
  360. bfs::path VCMIDirsOSX::userCachePath() const { return userDataPath(); }
  361. bfs::path VCMIDirsOSX::userConfigPath() const { return userDataPath() / "config"; }
  362. std::vector<bfs::path> VCMIDirsOSX::dataPaths() const
  363. {
  364. return std::vector<bfs::path>(1, "../Data");
  365. }
  366. bfs::path VCMIDirsOSX::libraryPath() const { return "."; }
  367. bfs::path VCMIDirsOSX::binaryPath() const { return "."; }
  368. std::string VCMIDirsOSX::libraryName(const std::string& basename) const { return "lib" + basename + ".dylib"; }
  369. #elif defined(VCMI_XDG)
  370. class VCMIDirsXDG : public IVCMIDirsUNIX
  371. {
  372. public:
  373. boost::filesystem::path userDataPath() const override;
  374. boost::filesystem::path userCachePath() const override;
  375. boost::filesystem::path userConfigPath() const override;
  376. std::vector<boost::filesystem::path> dataPaths() const override;
  377. boost::filesystem::path libraryPath() const override;
  378. boost::filesystem::path binaryPath() const override;
  379. std::string libraryName(const std::string& basename) const override;
  380. };
  381. bfs::path VCMIDirsXDG::userDataPath() const
  382. {
  383. // $XDG_DATA_HOME, default: $HOME/.local/share
  384. const char* homeDir;
  385. if ((homeDir = getenv("XDG_DATA_HOME")))
  386. return homeDir;
  387. else if ((homeDir = getenv("HOME")))
  388. return bfs::path(homeDir) / ".local" / "share" / "vcmi";
  389. else
  390. return ".";
  391. }
  392. bfs::path VCMIDirsXDG::userCachePath() const
  393. {
  394. // $XDG_CACHE_HOME, default: $HOME/.cache
  395. const char* tempResult;
  396. if ((tempResult = getenv("XDG_CACHE_HOME")))
  397. return bfs::path(tempResult) / "vcmi";
  398. else if ((tempResult = getenv("HOME")))
  399. return bfs::path(tempResult) / ".cache" / "vcmi";
  400. else
  401. return ".";
  402. }
  403. bfs::path VCMIDirsXDG::userConfigPath() const
  404. {
  405. // $XDG_CONFIG_HOME, default: $HOME/.config
  406. const char* tempResult;
  407. if ((tempResult = getenv("XDG_CONFIG_HOME")))
  408. return bfs::path(tempResult) / "vcmi";
  409. else if ((tempResult = getenv("HOME")))
  410. return bfs::path(tempResult) / ".config" / "vcmi";
  411. else
  412. return ".";
  413. }
  414. std::vector<bfs::path> VCMIDirsXDG::dataPaths() const
  415. {
  416. // $XDG_DATA_DIRS, default: /usr/local/share/:/usr/share/
  417. // construct list in reverse.
  418. // in specification first directory has highest priority
  419. // in vcmi fs last directory has highest priority
  420. std::vector<bfs::path> ret;
  421. const char* tempResult;
  422. ret.push_back(M_DATA_DIR);
  423. if ((tempResult = getenv("XDG_DATA_DIRS")) != nullptr)
  424. {
  425. std::string dataDirsEnv = tempResult;
  426. std::vector<std::string> dataDirs;
  427. boost::split(dataDirs, dataDirsEnv, boost::is_any_of(":"));
  428. for (auto & entry : boost::adaptors::reverse(dataDirs))
  429. ret.push_back(entry + "/vcmi");
  430. }
  431. else
  432. {
  433. ret.push_back("/usr/share/");
  434. ret.push_back("/usr/local/share/");
  435. }
  436. return ret;
  437. }
  438. bfs::path VCMIDirsXDG::libraryPath() const { return M_LIB_DIR; }
  439. bfs::path VCMIDirsXDG::binaryPath() const { return M_BIN_DIR; }
  440. std::string VCMIDirsXDG::libraryName(const std::string& basename) const { return "lib" + basename + ".so"; }
  441. #ifdef VCMI_ANDROID
  442. class VCMIDirsAndroid : public VCMIDirsXDG
  443. {
  444. public:
  445. boost::filesystem::path userDataPath() const override;
  446. boost::filesystem::path userCachePath() const override;
  447. boost::filesystem::path userConfigPath() const override;
  448. std::vector<boost::filesystem::path> dataPaths() const override;
  449. };
  450. // on Android HOME will be set to something like /sdcard/data/Android/is.xyz.vcmi/files/
  451. bfs::path VCMIDirsAndroid::userDataPath() const { return getenv("HOME"); }
  452. bfs::path VCMIDirsAndroid::userCachePath() const { return userDataPath() / "cache"; }
  453. bfs::path VCMIDirsAndroid::userConfigPath() const { return userDataPath() / "config"; }
  454. std::vector<bfs::path> VCMIDirsAndroid::dataPaths() const
  455. {
  456. return std::vector<bfs::path>(1, userDataPath());
  457. }
  458. #endif // VCMI_ANDROID
  459. #endif // VCMI_APPLE, VCMI_XDG
  460. #endif // VCMI_WINDOWS, VCMI_UNIX
  461. // Getters for interfaces are separated for clarity.
  462. namespace VCMIDirs
  463. {
  464. const IVCMIDirs& get()
  465. {
  466. #ifdef VCMI_WINDOWS
  467. static VCMIDirsWIN32 singleton;
  468. #elif defined(VCMI_ANDROID)
  469. static VCMIDirsAndroid singleton;
  470. #elif defined(VCMI_XDG)
  471. static VCMIDirsXDG singleton;
  472. #elif defined(VCMI_APPLE)
  473. static VCMIDirsOSX singleton;
  474. #endif
  475. static bool initialized = false;
  476. if (!initialized)
  477. {
  478. #ifndef VCMI_ANDROID
  479. std::locale::global(boost::locale::generator().generate("en_US.UTF-8"));
  480. #endif
  481. boost::filesystem::path::imbue(std::locale());
  482. singleton.init();
  483. initialized = true;
  484. }
  485. return singleton;
  486. }
  487. }