VCMIDirs.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. #ifdef VCMI_IOS
  13. #include "iOS_utils.h"
  14. #elif defined(VCMI_ANDROID)
  15. #include "CAndroidVMHelper.h"
  16. #endif
  17. VCMI_LIB_NAMESPACE_BEGIN
  18. namespace bfs = boost::filesystem;
  19. bfs::path IVCMIDirs::userLogsPath() const { return userCachePath(); }
  20. bfs::path IVCMIDirs::userSavePath() const { return userDataPath() / "Saves"; }
  21. bfs::path IVCMIDirs::userExtractedPath() const { return userCachePath() / "extracted"; }
  22. bfs::path IVCMIDirs::fullLibraryPath(const std::string &desiredFolder, const std::string &baseLibName) const
  23. {
  24. return libraryPath() / desiredFolder / libraryName(baseLibName);
  25. }
  26. std::string IVCMIDirs::genHelpString() const
  27. {
  28. std::vector<std::string> tempVec;
  29. for (const bfs::path & path : dataPaths())
  30. tempVec.push_back(path.string());
  31. const auto gdStringA = boost::algorithm::join(tempVec, ":");
  32. return
  33. " game data: " + gdStringA + "\n"
  34. " libraries: " + libraryPath().string() + "\n"
  35. " server: " + serverPath().string() + "\n"
  36. "\n"
  37. " user data: " + userDataPath().string() + "\n"
  38. " user cache: " + userCachePath().string() + "\n"
  39. " user config: " + userConfigPath().string() + "\n"
  40. " user logs: " + userLogsPath().string() + "\n"
  41. " user saves: " + userSavePath().string() + "\n"
  42. " user extracted: " + userExtractedPath().string() + "\n";
  43. }
  44. void IVCMIDirs::init()
  45. {
  46. // TODO: Log errors
  47. bfs::create_directories(userDataPath());
  48. bfs::create_directories(userCachePath());
  49. bfs::create_directories(userConfigPath());
  50. bfs::create_directories(userLogsPath());
  51. bfs::create_directories(userSavePath());
  52. }
  53. #ifdef VCMI_WINDOWS
  54. #ifdef __MINGW32__
  55. #define _WIN32_IE 0x0500
  56. #ifndef CSIDL_MYDOCUMENTS
  57. #define CSIDL_MYDOCUMENTS CSIDL_PERSONAL
  58. #endif
  59. #endif // __MINGW32__
  60. #include <windows.h>
  61. #include <shlobj.h>
  62. #include <shellapi.h>
  63. // Generates script file named _temp.bat in 'to' directory and runs it
  64. // Script will:
  65. // - Wait util 'exeName' ends.
  66. // - Copy all files from 'from' to 'to'
  67. // - Ask user to replace files existed in 'to'.
  68. // - Run 'exeName'
  69. // - Delete itself.
  70. bool StartBatchCopyDataProgram(
  71. const bfs::path& from, const bfs::path& to, const bfs::path& exeName,
  72. const bfs::path& currentPath = bfs::current_path())
  73. {
  74. static const char base[] =
  75. "@echo off" "\n"
  76. "echo Preparing to move VCMI data system." "\n"
  77. ":CLIENT_RUNNING_LOOP" "\n"
  78. "TASKLIST | FIND /I %1% > nul" "\n"
  79. "IF ERRORLEVEL 1 (" "\n"
  80. "GOTO CLIENT_NOT_RUNNING" "\n"
  81. ") ELSE (" "\n"
  82. "echo %1% is still running..." "\n"
  83. "echo Waiting until process ends..." "\n"
  84. "ping 1.1.1.1 -n 1 -w 3000 > nul" "\n" // Sleep ~3 seconds. I love Windows :)
  85. "goto :CLIENT_RUNNING_LOOP" "\n"
  86. ")" "\n"
  87. ":CLIENT_NOT_RUNNING" "\n"
  88. "echo %1% turned off..." "\n"
  89. "echo Attempt to move data." "\n"
  90. "echo From: %2%" "\n"
  91. "echo To: %4%" "\n"
  92. "echo Please resolve any conflicts..." "\n"
  93. "move /-Y %3% %4%" "\n" // Move all files from %3% to %4%.
  94. // /-Y ask what to do when file exists in %4%
  95. ":REMOVE_OLD_DIR" "\n"
  96. "rd %2% || rem" "\n" // Remove empty directory. Sets error flag if fail.
  97. "IF ERRORLEVEL 145 (" "\n" // Directory not empty
  98. "echo Directory %2% is not empty." "\n"
  99. "echo Please move rest of files manually now." "\n"
  100. "pause" "\n" // Press any key to continue...
  101. "goto REMOVE_OLD_DIR" "\n"
  102. ")" "\n"
  103. "echo Game data updated successfully." "\n"
  104. "echo Please update your shortcuts." "\n"
  105. "echo Press any key to start a game . . ." "\n"
  106. "pause > nul" "\n"
  107. "%5%" "\n"
  108. "del \"%%~f0\"&exit" "\n" // Script deletes itself
  109. ;
  110. const auto startGameString =
  111. bfs::equivalent(currentPath, from) ?
  112. (boost::format("start \"\" %1%") % (to / exeName)) : // Start game in new path.
  113. (boost::format("start \"\" /D %1% %2%") % currentPath % (to / exeName)); // Start game in 'currentPath"
  114. const bfs::path bathFilename = to / "_temp.bat";
  115. bfs::ofstream bathFile(bathFilename, bfs::ofstream::trunc | bfs::ofstream::out);
  116. if (!bathFile.is_open())
  117. return false;
  118. bathFile << (boost::format(base) % exeName % from % (from / "*.*") % to % startGameString.str()).str();
  119. bathFile.close();
  120. std::system(("start \"Updating VCMI data\" /D \"" + to.string() + "\" \"" + bathFilename.string() + '\"').c_str());
  121. // start won't block std::system
  122. // /D start bat in other directory insteand of current directory.
  123. return true;
  124. }
  125. class VCMIDirsWIN32 final : public IVCMIDirs
  126. {
  127. public:
  128. bfs::path userDataPath() const override;
  129. bfs::path userCachePath() const override;
  130. bfs::path userConfigPath() const override;
  131. std::vector<bfs::path> dataPaths() const override;
  132. bfs::path clientPath() const override;
  133. bfs::path mapEditorPath() const override;
  134. bfs::path serverPath() const override;
  135. bfs::path libraryPath() const override;
  136. bfs::path binaryPath() const override;
  137. std::string libraryName(const std::string& basename) const override;
  138. void init() override;
  139. protected:
  140. bfs::path oldUserDataPath() const;
  141. bfs::path oldUserSavePath() const;
  142. };
  143. void VCMIDirsWIN32::init()
  144. {
  145. std::locale::global(boost::locale::generator().generate("en_US.UTF-8"));
  146. boost::filesystem::path::imbue(std::locale());
  147. // Call base (init dirs)
  148. IVCMIDirs::init();
  149. // Moves one directory (from) contents to another directory (to)
  150. // Shows user the "moving file dialog" and ask to resolve conflits.
  151. // If necessary updates current directory.
  152. auto moveDirIfExists = [](const bfs::path& from, const bfs::path& to) -> bool
  153. {
  154. if (!bfs::is_directory(from))
  155. return true; // Nothing to do here. Flies away.
  156. if (bfs::is_empty(from))
  157. {
  158. if (bfs::current_path() == from)
  159. bfs::current_path(to);
  160. bfs::remove(from);
  161. return true; // Nothing to do here. Flies away.
  162. }
  163. if (!bfs::is_directory(to))
  164. {
  165. // IVCMIDirs::init() should create all destination directories.
  166. // TODO: Log fact, that we shouldn't be here.
  167. bfs::create_directories(to);
  168. }
  169. // Why the hell path strings should be end with double null :/
  170. auto makeDoubleNulled = [](const bfs::path& path) -> std::unique_ptr<wchar_t[]>
  171. {
  172. const std::wstring& pathStr = path.native();
  173. std::unique_ptr<wchar_t[]> result(new wchar_t[pathStr.length() + 2]);
  174. size_t i = 0;
  175. for (const wchar_t ch : pathStr)
  176. result[i++] = ch;
  177. result[i++] = L'\0';
  178. result[i++] = L'\0';
  179. return result;
  180. };
  181. auto fromDNulled = makeDoubleNulled(from / L"*.*");
  182. auto toDNulled = makeDoubleNulled(to);
  183. SHFILEOPSTRUCTW fileOp;
  184. fileOp.hwnd = GetConsoleWindow();
  185. fileOp.wFunc = FO_MOVE;
  186. fileOp.pFrom = fromDNulled.get();
  187. fileOp.pTo = toDNulled.get();
  188. fileOp.fFlags = 0;
  189. fileOp.hNameMappings = nullptr;
  190. fileOp.lpszProgressTitle = nullptr;
  191. const int errorCode = SHFileOperationW(&fileOp);
  192. if (errorCode != 0) // TODO: Log error. User should try to move files.
  193. return false;
  194. else if (fileOp.fAnyOperationsAborted) // TODO: Log warn. User aborted operation. User should move files.
  195. return false;
  196. else if (!bfs::is_empty(from)) // TODO: Log warn. Some files not moved. User should try to move files.
  197. return false;
  198. if (bfs::current_path() == from)
  199. bfs::current_path(to);
  200. // TODO: Log fact that we moved files successfully.
  201. bfs::remove(from);
  202. return true;
  203. };
  204. // Retrieves the fully qualified path for the file that contains the specified module.
  205. // The module must have been loaded by the current process.
  206. // If this parameter is nullptr, retrieves the path of the executable file of the current process.
  207. auto getModulePath = [](HMODULE hModule) -> bfs::path
  208. {
  209. wchar_t exePathW[MAX_PATH];
  210. DWORD nSize = GetModuleFileNameW(hModule, exePathW, MAX_PATH);
  211. DWORD error = GetLastError();
  212. // WARN: Windows XP don't set ERROR_INSUFFICIENT_BUFFER error.
  213. if (nSize != 0 && error != ERROR_INSUFFICIENT_BUFFER)
  214. return bfs::path(std::wstring(exePathW, nSize));
  215. // TODO: Error handling
  216. return bfs::path();
  217. };
  218. // Moves one directory contents to another directory
  219. // Shows user the "moving file dialog" and ask to resolve conflicts.
  220. // It takes into account that 'from' path can contain current executable.
  221. // If necessary closes program and starts update script.
  222. auto advancedMoveDirIfExists = [getModulePath, moveDirIfExists](const bfs::path& from, const bfs::path& to) -> bool
  223. {
  224. const bfs::path executablePath = getModulePath(nullptr);
  225. // VCMI can't determine executable path.
  226. // Use standard way to move directory and exit function.
  227. if (executablePath.empty())
  228. return moveDirIfExists(from, to);
  229. const bfs::path executableName = executablePath.filename();
  230. // Current executabl isn't in 'from' path.
  231. // Use standard way to move directory and exit function.
  232. if (!bfs::equivalent(executablePath, from / executableName))
  233. return moveDirIfExists(from, to);
  234. // Try standard way to move directory.
  235. // I don't know how other systems, but Windows 8.1 allow to move running executable.
  236. if (moveDirIfExists(from, to))
  237. return true;
  238. // Start copying script and exit program.
  239. if (StartBatchCopyDataProgram(from, to, executableName))
  240. exit(ERROR_SUCCESS);
  241. // Everything failed :C
  242. return false;
  243. };
  244. moveDirIfExists(oldUserSavePath(), userSavePath());
  245. advancedMoveDirIfExists(oldUserDataPath(), userDataPath());
  246. }
  247. bfs::path VCMIDirsWIN32::userDataPath() const
  248. {
  249. wchar_t profileDir[MAX_PATH];
  250. if (SHGetSpecialFolderPathW(nullptr, profileDir, CSIDL_MYDOCUMENTS, FALSE) != FALSE)
  251. return bfs::path(profileDir) / "My Games" / "vcmi";
  252. return ".";
  253. }
  254. bfs::path VCMIDirsWIN32::oldUserDataPath() const
  255. {
  256. wchar_t profileDir[MAX_PATH];
  257. if (SHGetSpecialFolderPathW(nullptr, profileDir, CSIDL_PROFILE, FALSE) == FALSE) // WinAPI way failed
  258. {
  259. #if defined(_MSC_VER) && _MSC_VER >= 1700
  260. wchar_t* buffer;
  261. size_t bufferSize;
  262. errno_t result = _wdupenv_s(&buffer, &bufferSize, L"userprofile");
  263. if (result == 0)
  264. {
  265. bfs::path result(std::wstring(buffer, bufferSize));
  266. free(buffer);
  267. return result;
  268. }
  269. #else
  270. const char* profileDirA;
  271. if ((profileDirA = std::getenv("userprofile"))) // STL way succeed
  272. return bfs::path(profileDirA) / "vcmi";
  273. #endif
  274. else
  275. return "."; // Every thing failed, return current directory.
  276. }
  277. else
  278. return bfs::path(profileDir) / "vcmi";
  279. //return dataPaths()[0] ???;
  280. }
  281. bfs::path VCMIDirsWIN32::oldUserSavePath() const { return userDataPath() / "Games"; }
  282. bfs::path VCMIDirsWIN32::userCachePath() const { return userDataPath(); }
  283. bfs::path VCMIDirsWIN32::userConfigPath() const { return userDataPath() / "config"; }
  284. std::vector<bfs::path> VCMIDirsWIN32::dataPaths() const
  285. {
  286. return std::vector<bfs::path>(1, bfs::path("."));
  287. }
  288. bfs::path VCMIDirsWIN32::clientPath() const { return binaryPath() / "VCMI_client.exe"; }
  289. bfs::path VCMIDirsWIN32::mapEditorPath() const { return binaryPath() / "VCMI_mapeditor.exe"; }
  290. bfs::path VCMIDirsWIN32::serverPath() const { return binaryPath() / "VCMI_server.exe"; }
  291. bfs::path VCMIDirsWIN32::libraryPath() const { return "."; }
  292. bfs::path VCMIDirsWIN32::binaryPath() const { return "."; }
  293. std::string VCMIDirsWIN32::libraryName(const std::string& basename) const { return basename + ".dll"; }
  294. #elif defined(VCMI_UNIX)
  295. class IVCMIDirsUNIX : public IVCMIDirs
  296. {
  297. public:
  298. bfs::path clientPath() const override;
  299. bfs::path mapEditorPath() const override;
  300. bfs::path serverPath() const override;
  301. virtual bool developmentMode() const;
  302. };
  303. bool IVCMIDirsUNIX::developmentMode() const
  304. {
  305. // We want to be able to run VCMI from single directory. E.g to run from build output directory
  306. const bool hasConfigs = bfs::exists("config") && bfs::exists("Mods");
  307. const bool hasBinaries = bfs::exists("vcmiclient") || bfs::exists("vcmiserver") || bfs::exists("vcmilobby");
  308. return hasConfigs && hasBinaries;
  309. }
  310. bfs::path IVCMIDirsUNIX::clientPath() const { return binaryPath() / "vcmiclient"; }
  311. bfs::path IVCMIDirsUNIX::mapEditorPath() const { return binaryPath() / "vcmieditor"; }
  312. bfs::path IVCMIDirsUNIX::serverPath() const { return binaryPath() / "vcmiserver"; }
  313. #ifdef VCMI_APPLE
  314. class VCMIDirsApple : public IVCMIDirsUNIX
  315. {
  316. public:
  317. bfs::path userConfigPath() const override;
  318. std::string libraryName(const std::string& basename) const override;
  319. };
  320. bfs::path VCMIDirsApple::userConfigPath() const { return userDataPath() / "config"; }
  321. std::string VCMIDirsApple::libraryName(const std::string& basename) const { return "lib" + basename + ".dylib"; }
  322. #ifdef VCMI_IOS
  323. class VCMIDirsIOS final : public VCMIDirsApple
  324. {
  325. public:
  326. bfs::path userDataPath() const override;
  327. bfs::path userCachePath() const override;
  328. bfs::path userLogsPath() const override;
  329. std::vector<bfs::path> dataPaths() const override;
  330. bfs::path libraryPath() const override;
  331. bfs::path fullLibraryPath(const std::string & desiredFolder, const std::string & baseLibName) const override;
  332. bfs::path binaryPath() const override;
  333. };
  334. bfs::path VCMIDirsIOS::userDataPath() const { return {iOS_utils::documentsPath()}; }
  335. bfs::path VCMIDirsIOS::userCachePath() const { return {iOS_utils::cachesPath()}; }
  336. bfs::path VCMIDirsIOS::userLogsPath() const { return {iOS_utils::documentsPath()}; }
  337. std::vector<bfs::path> VCMIDirsIOS::dataPaths() const
  338. {
  339. std::vector<bfs::path> paths;
  340. paths.reserve(4);
  341. #ifdef VCMI_IOS_SIM
  342. paths.emplace_back(iOS_utils::hostApplicationSupportPath());
  343. #endif
  344. paths.emplace_back(userDataPath());
  345. paths.emplace_back(iOS_utils::documentsPath());
  346. paths.emplace_back(binaryPath());
  347. return paths;
  348. }
  349. bfs::path VCMIDirsIOS::fullLibraryPath(const std::string & desiredFolder, const std::string & baseLibName) const
  350. {
  351. // iOS has flat libs directory structure
  352. return libraryPath() / libraryName(baseLibName);
  353. }
  354. bfs::path VCMIDirsIOS::libraryPath() const { return {iOS_utils::frameworksPath()}; }
  355. bfs::path VCMIDirsIOS::binaryPath() const { return {iOS_utils::bundlePath()}; }
  356. #elif defined(VCMI_MAC)
  357. class VCMIDirsOSX final : public VCMIDirsApple
  358. {
  359. public:
  360. bfs::path userDataPath() const override;
  361. bfs::path userCachePath() const override;
  362. bfs::path userLogsPath() const override;
  363. std::vector<bfs::path> dataPaths() const override;
  364. bfs::path libraryPath() const override;
  365. bfs::path binaryPath() const override;
  366. void init() override;
  367. };
  368. void VCMIDirsOSX::init()
  369. {
  370. // Call base (init dirs)
  371. IVCMIDirsUNIX::init();
  372. auto moveDirIfExists = [](const bfs::path& from, const bfs::path& to)
  373. {
  374. if (!bfs::is_directory(from))
  375. return; // Nothing to do here. Flies away.
  376. if (bfs::is_empty(from))
  377. {
  378. bfs::remove(from);
  379. return; // Nothing to do here. Flies away.
  380. }
  381. if (!bfs::is_directory(to))
  382. {
  383. // IVCMIDirs::init() should create all destination directories.
  384. // TODO: Log fact, that we shouldn't be here.
  385. bfs::create_directories(to);
  386. }
  387. for (bfs::directory_iterator file(from); file != bfs::directory_iterator(); ++file)
  388. {
  389. const bfs::path& srcFilePath = file->path();
  390. const bfs::path dstFilePath = to / srcFilePath.filename();
  391. // TODO: Application should ask user what to do when file exists:
  392. // replace/ignore/stop process/replace all/ignore all
  393. if (!bfs::exists(dstFilePath))
  394. bfs::rename(srcFilePath, dstFilePath);
  395. }
  396. if (!bfs::is_empty(from)); // TODO: Log warn. Some files not moved. User should try to move files.
  397. else
  398. bfs::remove(from);
  399. };
  400. moveDirIfExists(userDataPath() / "Games", userSavePath());
  401. }
  402. bfs::path VCMIDirsOSX::userDataPath() const
  403. {
  404. // This is Cocoa code that should be normally used to get path to Application Support folder but can't use it here for now...
  405. // NSArray* urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
  406. // UserPath = path([urls[0] path] + "/vcmi").string();
  407. // ...so here goes a bit of hardcode instead
  408. const char* homeDir = getenv("HOME"); // Should be std::getenv?
  409. if (homeDir == nullptr)
  410. homeDir = ".";
  411. return bfs::path(homeDir) / "Library" / "Application Support" / "vcmi";
  412. }
  413. bfs::path VCMIDirsOSX::userCachePath() const { return userDataPath(); }
  414. bfs::path VCMIDirsOSX::userLogsPath() const
  415. {
  416. // TODO: use proper objc code from Foundation framework
  417. if(const auto homeDir = std::getenv("HOME"))
  418. return bfs::path{homeDir} / "Library" / "Logs" / "vcmi";
  419. return IVCMIDirsUNIX::userLogsPath();
  420. }
  421. std::vector<bfs::path> VCMIDirsOSX::dataPaths() const
  422. {
  423. std::vector<bfs::path> ret;
  424. //FIXME: need some proper codepath for detecting running from build output directory
  425. if(developmentMode())
  426. {
  427. ret.push_back(".");
  428. }
  429. else
  430. {
  431. ret.push_back("../Resources/Data");
  432. }
  433. return ret;
  434. }
  435. bfs::path VCMIDirsOSX::libraryPath() const { return "."; }
  436. bfs::path VCMIDirsOSX::binaryPath() const { return "."; }
  437. #endif // VCMI_IOS, VCMI_MAC
  438. #elif defined(VCMI_ANDROID)
  439. class VCMIDirsAndroid : public IVCMIDirsUNIX
  440. {
  441. std::string basePath;
  442. std::string internalPath;
  443. std::string nativePath;
  444. public:
  445. std::string libraryName(const std::string & basename) const override;
  446. bfs::path fullLibraryPath(const std::string & desiredFolder, const std::string & baseLibName) const override;
  447. bfs::path binaryPath() const override;
  448. bfs::path libraryPath() const override;
  449. bfs::path userDataPath() const override;
  450. bfs::path userCachePath() const override;
  451. bfs::path userConfigPath() const override;
  452. std::vector<bfs::path> dataPaths() const override;
  453. void init() override;
  454. };
  455. std::string VCMIDirsAndroid::libraryName(const std::string & basename) const { return "lib" + basename + ".so"; }
  456. bfs::path VCMIDirsAndroid::binaryPath() const { return "."; }
  457. bfs::path VCMIDirsAndroid::libraryPath() const { return nativePath; }
  458. bfs::path VCMIDirsAndroid::userDataPath() const { return basePath; }
  459. bfs::path VCMIDirsAndroid::userCachePath() const { return userDataPath() / "cache"; }
  460. bfs::path VCMIDirsAndroid::userConfigPath() const { return userDataPath() / "config"; }
  461. bfs::path VCMIDirsAndroid::fullLibraryPath(const std::string & desiredFolder, const std::string & baseLibName) const
  462. {
  463. // ignore passed folder (all libraries in android are dumped into a single folder)
  464. return libraryPath() / libraryName(baseLibName);
  465. }
  466. std::vector<bfs::path> VCMIDirsAndroid::dataPaths() const
  467. {
  468. return {
  469. internalPath,
  470. userDataPath(),
  471. };
  472. }
  473. void VCMIDirsAndroid::init()
  474. {
  475. // asks java code to retrieve needed paths from environment
  476. CAndroidVMHelper envHelper;
  477. basePath = envHelper.callStaticStringMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "dataRoot");
  478. internalPath = envHelper.callStaticStringMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "internalDataRoot");
  479. nativePath = envHelper.callStaticStringMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "nativePath");
  480. IVCMIDirsUNIX::init();
  481. }
  482. #elif defined(VCMI_PORTMASTER)
  483. class VCMIDirsPM : public IVCMIDirsUNIX
  484. {
  485. public:
  486. bfs::path userDataPath() const override;
  487. bfs::path userCachePath() const override;
  488. bfs::path userConfigPath() const override;
  489. std::vector<bfs::path> dataPaths() const override;
  490. bfs::path libraryPath() const override;
  491. bfs::path binaryPath() const override;
  492. std::string libraryName(const std::string& basename) const override;
  493. };
  494. bfs::path VCMIDirsPM::userDataPath() const
  495. {
  496. const char* homeDir;
  497. if((homeDir = getenv("PORTMASTER_HOME")))
  498. return bfs::path(homeDir) / "data";
  499. else
  500. return bfs::path(".") / "data";
  501. }
  502. bfs::path VCMIDirsPM::userCachePath() const
  503. {
  504. // $XDG_CACHE_HOME, default: $HOME/.cache
  505. const char * tempResult;
  506. if ((tempResult = getenv("PORTMASTER_HOME")))
  507. return bfs::path(tempResult) / "cache";
  508. else
  509. return bfs::path(".") / "cache";
  510. }
  511. bfs::path VCMIDirsPM::userConfigPath() const
  512. {
  513. // $XDG_CONFIG_HOME, default: $HOME/.config
  514. const char * tempResult;
  515. if ((tempResult = getenv("PORTMASTER_HOME")))
  516. return bfs::path(tempResult) / "save";
  517. else
  518. return bfs::path(".") / "save";
  519. }
  520. std::vector<bfs::path> VCMIDirsPM::dataPaths() const
  521. {
  522. // $XDG_DATA_DIRS, default: /usr/local/share/:/usr/share/
  523. // construct list in reverse.
  524. // in specification first directory has highest priority
  525. // in vcmi fs last directory has highest priority
  526. std::vector<bfs::path> ret;
  527. const char * tempResult;
  528. if ((tempResult = getenv("PORTMASTER_HOME")))
  529. {
  530. ret.push_back(bfs::path(tempResult) / "data");
  531. ret.push_back(bfs::path(tempResult));
  532. }
  533. ret.push_back(bfs::path(".") / "data");
  534. ret.push_back(bfs::path("."));
  535. return ret;
  536. }
  537. bfs::path VCMIDirsPM::libraryPath() const
  538. {
  539. const char * tempResult;
  540. if ((tempResult = getenv("PORTMASTER_HOME")))
  541. return bfs::path(tempResult) / "libs";
  542. else
  543. return M_LIB_DIR;
  544. }
  545. bfs::path VCMIDirsPM::binaryPath() const
  546. {
  547. const char * tempResult;
  548. if ((tempResult = getenv("PORTMASTER_HOME")))
  549. return bfs::path(tempResult) / "bin";
  550. else
  551. return M_BIN_DIR;
  552. }
  553. std::string VCMIDirsPM::libraryName(const std::string& basename) const { return "lib" + basename + ".so"; }
  554. #elif defined(VCMI_XDG)
  555. class VCMIDirsXDG : public IVCMIDirsUNIX
  556. {
  557. public:
  558. bfs::path userDataPath() const override;
  559. bfs::path userCachePath() const override;
  560. bfs::path userConfigPath() const override;
  561. std::vector<bfs::path> dataPaths() const override;
  562. bfs::path libraryPath() const override;
  563. bfs::path binaryPath() const override;
  564. std::string libraryName(const std::string& basename) const override;
  565. };
  566. bfs::path VCMIDirsXDG::userDataPath() const
  567. {
  568. // $XDG_DATA_HOME, default: $HOME/.local/share
  569. const char* homeDir;
  570. if((homeDir = getenv("XDG_DATA_HOME")))
  571. return bfs::path(homeDir) / "vcmi";
  572. else if((homeDir = getenv("HOME")))
  573. return bfs::path(homeDir) / ".local" / "share" / "vcmi";
  574. else
  575. return ".";
  576. }
  577. bfs::path VCMIDirsXDG::userCachePath() const
  578. {
  579. // $XDG_CACHE_HOME, default: $HOME/.cache
  580. const char * tempResult;
  581. if ((tempResult = getenv("XDG_CACHE_HOME")))
  582. return bfs::path(tempResult) / "vcmi";
  583. else if ((tempResult = getenv("HOME")))
  584. return bfs::path(tempResult) / ".cache" / "vcmi";
  585. else
  586. return ".";
  587. }
  588. bfs::path VCMIDirsXDG::userConfigPath() const
  589. {
  590. // $XDG_CONFIG_HOME, default: $HOME/.config
  591. const char * tempResult = getenv("XDG_CONFIG_HOME");
  592. if (tempResult)
  593. return bfs::path(tempResult) / "vcmi";
  594. tempResult = getenv("HOME");
  595. if (tempResult)
  596. return bfs::path(tempResult) / ".config" / "vcmi";
  597. return ".";
  598. }
  599. std::vector<bfs::path> VCMIDirsXDG::dataPaths() const
  600. {
  601. // $XDG_DATA_DIRS, default: /usr/local/share/:/usr/share/
  602. // construct list in reverse.
  603. // in specification first directory has highest priority
  604. // in vcmi fs last directory has highest priority
  605. std::vector<bfs::path> ret;
  606. if(developmentMode())
  607. {
  608. //For now we'll disable usage of system directories when VCMI running from bin directory
  609. ret.emplace_back(".");
  610. }
  611. else
  612. {
  613. ret.emplace_back(M_DATA_DIR);
  614. const char * tempResult;
  615. if((tempResult = getenv("XDG_DATA_DIRS")) != nullptr)
  616. {
  617. std::string dataDirsEnv = tempResult;
  618. std::vector<std::string> dataDirs;
  619. boost::split(dataDirs, dataDirsEnv, boost::is_any_of(":"));
  620. for (auto & entry : boost::adaptors::reverse(dataDirs))
  621. ret.push_back(bfs::path(entry) / "vcmi");
  622. }
  623. else
  624. {
  625. ret.push_back(bfs::path("/usr/share") / "vcmi");
  626. ret.push_back(bfs::path("/usr/local/share") / "vcmi");
  627. }
  628. // Debian and other distributions might want to use it while it's not part of XDG
  629. ret.push_back(bfs::path("/usr/share/games") / "vcmi");
  630. }
  631. return ret;
  632. }
  633. bfs::path VCMIDirsXDG::libraryPath() const
  634. {
  635. if(developmentMode())
  636. return ".";
  637. else
  638. return M_LIB_DIR;
  639. }
  640. bfs::path VCMIDirsXDG::binaryPath() const
  641. {
  642. if(developmentMode())
  643. return ".";
  644. else
  645. return M_BIN_DIR;
  646. }
  647. std::string VCMIDirsXDG::libraryName(const std::string& basename) const { return "lib" + basename + ".so"; }
  648. #endif // VCMI_APPLE, VCMI_ANDROID, VCMI_XDG
  649. #endif // VCMI_WINDOWS, VCMI_UNIX
  650. // Getters for interfaces are separated for clarity.
  651. namespace VCMIDirs
  652. {
  653. const IVCMIDirs& get()
  654. {
  655. #ifdef VCMI_WINDOWS
  656. static VCMIDirsWIN32 singleton;
  657. #elif defined(VCMI_ANDROID)
  658. static VCMIDirsAndroid singleton;
  659. #elif defined(VCMI_PORTMASTER)
  660. static VCMIDirsPM singleton;
  661. #elif defined(VCMI_XDG)
  662. static VCMIDirsXDG singleton;
  663. #elif defined(VCMI_MAC)
  664. static VCMIDirsOSX singleton;
  665. #elif defined(VCMI_IOS)
  666. static VCMIDirsIOS singleton;
  667. #endif
  668. static std::once_flag flag;
  669. std::call_once(flag, [] { singleton.init(); });
  670. return singleton;
  671. }
  672. }
  673. VCMI_LIB_NAMESPACE_END