VCMIDirs.cpp 18 KB

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