PathUtil.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. // Description : Utility functions to simplify working with paths.
  9. #ifndef CRYINCLUDE_EDITOR_UTIL_PATHUTIL_H
  10. #define CRYINCLUDE_EDITOR_UTIL_PATHUTIL_H
  11. #pragma once
  12. #include <CryPath.h>
  13. #if defined(AZ_PLATFORM_WINDOWS)
  14. #include <shlwapi.h>
  15. #endif
  16. #include <Include/EditorCoreAPI.h>
  17. #include <AzCore/IO/SystemFile.h> // for max path
  18. #include <AzCore/std/string/string.h>
  19. #include <AzFramework/StringFunc/StringFunc.h>
  20. #include <QRegularExpression>
  21. #include <QDir>
  22. class QString;
  23. class QStringList;
  24. namespace Path
  25. {
  26. //! creates an absolute path from a relative game path, used for saving game files.
  27. //! Example: Libs/Some/tokens.xml to c:/game/engine/GameName/Mods/ModName/Libs/Some/tokens.xml
  28. //! If you're not working on a mod, it will return it with the game folder prepended.
  29. //! This is the function you should use at all times to convert an asset ID to a full writable editor path.
  30. EDITOR_CORE_API AZStd::string MakeModPathFromGamePath(const char* input);
  31. //! Get the data folder where assets should be saved.
  32. //! if we're working on a mod, will return the mod's root (absolute path, with no slash at the end)
  33. //! if not, will return the default game root (absolute path, with no slash at the end)
  34. //! always returns a full path
  35. EDITOR_CORE_API AZStd::string GetEditingGameDataFolder();
  36. //! Set the current mod NAME for editing purposes. After doing this the above functions will take this into account
  37. //! name only, please!
  38. EDITOR_CORE_API void SetModName(const char* input);
  39. //! converts path to lowercase given the cvar for ed_lowercasepaths
  40. inline QString CaselessPaths(const QString& strPath)
  41. {
  42. ICVar* pCvar = gEnv->pConsole->GetCVar("ed_lowercasepaths");
  43. if (pCvar)
  44. {
  45. int uselowercase = pCvar->GetIVal();
  46. if (uselowercase)
  47. {
  48. QString str = strPath;
  49. str = str.toLower();
  50. return str;
  51. }
  52. }
  53. return strPath;
  54. }
  55. //! Split path into segments
  56. //! @param filepath [IN] path
  57. inline QStringList SplitIntoSegments(const QString& path)
  58. {
  59. return path.split(QRegularExpression(QStringLiteral(R"([\\/])")), Qt::SkipEmptyParts);
  60. }
  61. //! Extract extension from full specified file path.
  62. inline QString GetExt(const QString& filepath)
  63. {
  64. char ext[_MAX_EXT];
  65. #ifdef AZ_COMPILER_MSVC
  66. _splitpath_s(filepath.toUtf8().data(), 0, 0, 0, 0, 0, 0, ext, AZ_ARRAY_SIZE(ext));
  67. #else
  68. _splitpath(filepath.toUtf8().data(), 0, 0, 0, ext);
  69. #endif
  70. if (ext[0] == '.')
  71. {
  72. return ext + 1;
  73. }
  74. return ext;
  75. }
  76. //! Extract path from full specified file path.
  77. inline QString GetPath(const QString& filepath)
  78. {
  79. char path_buffer[_MAX_PATH];
  80. char drive[_MAX_DRIVE];
  81. char dir[_MAX_DIR];
  82. #ifdef AZ_COMPILER_MSVC
  83. _splitpath_s(filepath.toUtf8().data(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), 0, 0, 0, 0);
  84. _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
  85. #else
  86. _splitpath(filepath.toUtf8().data(), drive, dir, 0, 0);
  87. _makepath(path_buffer, drive, dir, 0, 0);
  88. #endif
  89. return CaselessPaths(path_buffer);
  90. }
  91. //! Extract file name with extension from full specified file path.
  92. inline QString GetFile(const QString& filepath)
  93. {
  94. char path_buffer[_MAX_PATH];
  95. char fname[_MAX_FNAME];
  96. char ext[_MAX_EXT];
  97. #ifdef AZ_COMPILER_MSVC
  98. _splitpath_s(filepath.toUtf8().data(), 0, 0, 0, 0, fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
  99. _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), 0, 0, fname, ext);
  100. #else
  101. _splitpath(filepath.toUtf8().data(), 0, 0, fname, ext);
  102. _makepath(path_buffer, 0, 0, fname, ext);
  103. #endif
  104. return CaselessPaths(path_buffer);
  105. }
  106. //! Extract file name without extension from full specified file path.
  107. inline QString GetFileName(const QString& filepath)
  108. {
  109. char fname[_MAX_FNAME];
  110. #ifdef AZ_COMPILER_MSVC
  111. _splitpath_s(filepath.toUtf8().data(), 0, 0, 0, 0, fname, AZ_ARRAY_SIZE(fname), 0, 0);
  112. #else
  113. _splitpath(filepath.toUtf8().data(), 0, 0, fname, 0);
  114. #endif
  115. return fname;
  116. }
  117. inline bool EndsWithSlash(QString path)
  118. {
  119. return (path.endsWith(QStringLiteral("\\")) || path.endsWith(QStringLiteral("/")));
  120. }
  121. template<size_t size>
  122. inline bool EndsWithSlash(AZStd::fixed_string<size>* path)
  123. {
  124. if ((!path) || (path->empty()))
  125. {
  126. return false;
  127. }
  128. if (
  129. ((*path)[path->size() - 1] != '\\') ||
  130. ((*path)[path->size() - 1] != '/')
  131. )
  132. {
  133. return true;
  134. }
  135. return false;
  136. }
  137. //! add a backslash if needed
  138. inline QString AddBackslash(QString path)
  139. {
  140. if (path.isEmpty() || EndsWithSlash(path))
  141. {
  142. return path;
  143. }
  144. return CaselessPaths(path + "\\");
  145. }
  146. //! add a slash if needed
  147. inline QString AddSlash(const QString& path)
  148. {
  149. if (path.isEmpty() || EndsWithSlash(path))
  150. {
  151. return path;
  152. }
  153. return CaselessPaths(path + "/");
  154. }
  155. template<size_t size>
  156. inline void AddBackslash(AZStd::fixed_string<size>* path)
  157. {
  158. if (path->empty())
  159. {
  160. return;
  161. }
  162. if (!EndsWithSlash(path))
  163. {
  164. (*path) += '\\';
  165. }
  166. }
  167. template<size_t size>
  168. inline void AddSlash(AZStd::fixed_string<size>* path)
  169. {
  170. if (path->empty())
  171. {
  172. return;
  173. }
  174. if (!EndsWithSlash(path))
  175. {
  176. (*path) += '/';
  177. }
  178. }
  179. inline QString AddPathSlash(const QString& path)
  180. {
  181. #if defined(AZ_PLATFORM_WINDOWS)
  182. return AddBackslash(path);
  183. #else
  184. return AddSlash(path);
  185. #endif
  186. }
  187. //! Replace extension for given file.
  188. inline QString ReplaceExtension(const QString& filepath, const QString& ext)
  189. {
  190. AZStd::string newPath = filepath.toUtf8().data();
  191. AzFramework::StringFunc::Path::ReplaceExtension(newPath, ext.toUtf8().data());
  192. QString returnString(newPath.c_str());
  193. return CaselessPaths(returnString);
  194. }
  195. //! Replace extension for given file.
  196. inline QString RemoveExtension(const QString& filepath)
  197. {
  198. char path_buffer[_MAX_PATH];
  199. char drive[_MAX_DRIVE];
  200. char dir[_MAX_DIR];
  201. char fname[_MAX_FNAME];
  202. #ifdef AZ_COMPILER_MSVC
  203. _splitpath_s(filepath.toUtf8().data(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), 0, 0);
  204. _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, fname, 0);
  205. #else
  206. _splitpath(filepath.toUtf8().data(), drive, dir, fname, 0);
  207. _makepath(path_buffer, drive, dir, fname, 0);
  208. #endif
  209. return path_buffer;
  210. }
  211. //! Makes a fully specified file path from path and file name.
  212. inline QString Make(const QString& dir, const QString& filename, const QString& ext)
  213. {
  214. char path_buffer[_MAX_PATH];
  215. #ifdef AZ_COMPILER_MSVC
  216. _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), nullptr, dir.toUtf8().data(), filename.toUtf8().data(), ext.toUtf8().data());
  217. #else
  218. _makepath(path_buffer, nullptr, dir.toUtf8().data(), filename.toUtf8().data(), ext.toUtf8().data());
  219. #endif
  220. return CaselessPaths(path_buffer);
  221. }
  222. //////////////////////////////////////////////////////////////////////////
  223. EDITOR_CORE_API QString GetRelativePath(const QString& fullPath, bool bRelativeToGameFolder = false);
  224. //////////////////////////////////////////////////////////////////////////
  225. // Description:
  226. // given the assetID of a produced asset, constructs the full path to the SOURCE ASSET that was used to produce it.
  227. // Ex. Objects/box.dds will be converted to C:\Test\Game\Objects\box.tif (or bmp or whatever)
  228. EDITOR_CORE_API QString GamePathToFullPath(const QString& path);
  229. //////////////////////////////////////////////////////////////////////////
  230. inline QString FullPathToGamePath(const QString& path)
  231. {
  232. return CaselessPaths(GetRelativePath(path, true));
  233. }
  234. inline AZStd::string FullPathToGamePath(const char* path)
  235. {
  236. return CaselessPaths(GetRelativePath(path, true)).toUtf8().data();
  237. }
  238. QString FullPathToLevelPath(const QString& path);
  239. //////////////////////////////////////////////////////////////////////////
  240. // Description:
  241. // Turn any path into an asset ID.
  242. inline QString MakeGamePath(const QString& path)
  243. {
  244. QString fullpath = Path::GamePathToFullPath(path);
  245. // if its in a mod, we still want the 'asset id' of it.
  246. QString dataFolder = Path::AddPathSlash(QString(Path::GetEditingGameDataFolder().c_str()));
  247. if (fullpath.length() > dataFolder.length() && QString::compare(fullpath, dataFolder, Qt::CaseInsensitive) == 0)
  248. {
  249. fullpath = fullpath.right(fullpath.length() - dataFolder.length());
  250. fullpath.replace('\\', '/'); // Slashes use for game files.
  251. return fullpath;
  252. }
  253. fullpath = GetRelativePath(path, true);
  254. if (fullpath.isEmpty())
  255. {
  256. fullpath = path;
  257. }
  258. fullpath.replace('\\', '/'); // Slashes use for game files.
  259. return CaselessPaths(fullpath);
  260. }
  261. inline QString GetAudioLocalizationFolder(bool returnAbsolutePath)
  262. {
  263. // Omit the trailing slash!
  264. QString sLocalizationFolder(QString(PathUtil::GetLocalizationFolder().c_str()).left(static_cast<int>(PathUtil::GetLocalizationFolder().size()) - 1));
  265. if (!sLocalizationFolder.isEmpty())
  266. {
  267. sLocalizationFolder = returnAbsolutePath ? (QString(Path::GetEditingGameDataFolder().c_str()) + "/" + sLocalizationFolder + "/dialog/") : sLocalizationFolder + "/dialog/";
  268. }
  269. else
  270. {
  271. gEnv->pSystem->Warning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, VALIDATOR_FLAG_AUDIO, 0, "The localization folder is not set! Please make sure it is by checking the setting of cvar \"sys_localization_folder\"!");
  272. }
  273. return sLocalizationFolder;
  274. }
  275. //! Returns the aliased path to the user Sandbox folder
  276. EDITOR_CORE_API QString GetUserSandboxFolder();
  277. //! Returns the resolved, non-aliased path to the user Sandbox folder
  278. EDITOR_CORE_API QString GetResolvedUserSandboxFolder();
  279. //! Convert a path to the uniform form.
  280. EDITOR_CORE_API QString ToUnixPath(const QString& strPath, bool bCallCaselessPath = true);
  281. //! Makes a fully specified file path from path and file name.
  282. EDITOR_CORE_API QString Make(const QString& path, const QString& file);
  283. // This had to be created because _splitpath is too dumb about console drives.
  284. EDITOR_CORE_API void SplitPath(const QString& rstrFullPathFilename, QString& rstrDriveLetter, QString& rstrDirectory, QString& rstrFilename, QString& rstrExtension);
  285. // Requires a path from Splithpath: no drive letter and backslash at the end.
  286. EDITOR_CORE_API void GetDirectoryQueue(const QString& rstrSourceDirectory, QStringList& rcstrDirectoryTree);
  287. // Converts all slashes to backslashes so MS things won't complain.
  288. EDITOR_CORE_API void ConvertSlashToBackSlash(QString& rstrStringToConvert);
  289. // Converts backslashes into forward slashes.
  290. EDITOR_CORE_API void ConvertBackSlashToSlash(QString& rstrStringToConvert);
  291. // Surrounds a string with quotes if necessary. This is useful for calling other programs.
  292. EDITOR_CORE_API void SurroundWithQuotes(QString& rstrSurroundString);
  293. // Gets the temporary directory path (which may not exist).
  294. EDITOR_CORE_API QString GetWindowsTempDirectory();
  295. // This function returns the full path used to run the editor.
  296. EDITOR_CORE_API QString GetExecutableFullPath();
  297. // This function returns the engine's root path
  298. EDITOR_CORE_API QString GetEngineRootPath();
  299. // This function replaces the filename from a path, keeping extension and directory/drive path.
  300. // WARNING: do not use the same variable in the last parameter and in any of the others.
  301. EDITOR_CORE_API QString& ReplaceFilename(const QString& strFilepath, const QString& strFilename, QString& strOutputFilename, bool bCallCaselessPath = true);
  302. //! \return true if the given path is a folder and not a file
  303. EDITOR_CORE_API bool IsFolder(const char* pPath);
  304. EDITOR_CORE_API void ConvertSlashToBackSlash(QString& str);
  305. EDITOR_CORE_API void ConvertBackSlashToSlash(QString& str);
  306. EDITOR_CORE_API QString RemoveBackslash(QString path);
  307. /*
  308. * Returns the complete path of the subdirectories in parts inside of path. If
  309. * one of the parts already exists but in different upper and lower case, the resulting
  310. * path will contain that one. Note that the directory is not created!
  311. */
  312. EDITOR_CORE_API QString SubDirectoryCaseInsensitive(const QString& path, const QStringList& parts);
  313. };
  314. inline QString operator /(const QString& first, const QString& second)
  315. {
  316. return Path::Make(first, second);
  317. }
  318. #endif // CRYINCLUDE_EDITOR_UTIL_PATHUTIL_H