BsPath.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. #pragma once
  2. #include "BsPrerequisitesUtil.h"
  3. #include "BsUtil.h"
  4. namespace BansheeEngine
  5. {
  6. /**
  7. * @brief Class for storing and manipulating file paths. Paths may be parsed
  8. * from and to raw strings according to various platform specific path
  9. * types.
  10. *
  11. * @note In order to allow the system to easily distinguish between file and directory
  12. * paths, try to ensure that all directory paths end with a separator (\ or / depending
  13. * on platform). System won't fail if you don't but it will be easier to misuse.
  14. */
  15. class BS_UTILITY_EXPORT Path
  16. {
  17. public:
  18. enum class PathType
  19. {
  20. Windows,
  21. Unix,
  22. Default
  23. };
  24. public:
  25. Path();
  26. /**
  27. * @brief Constructs a path by parsing the provided path string.
  28. * Throws exception if provided path is not valid.
  29. *
  30. * @param type If set to default path will be parsed according to the
  31. * rules of the platform the application is being compiled to.
  32. * Otherwise it will be parsed according to provided type.
  33. */
  34. Path(const WString& pathStr, PathType type = PathType::Default);
  35. /**
  36. * @brief Constructs a path by parsing the provided path string.
  37. * Throws exception if provided path is not valid.
  38. *
  39. * @param type If set to default path will be parsed according to the
  40. * rules of the platform the application is being compiled to.
  41. * Otherwise it will be parsed according to provided type.
  42. */
  43. Path(const String& pathStr, PathType type = PathType::Default);
  44. /**
  45. * @brief Constructs a path by parsing the provided path null terminated string.
  46. * Throws exception if provided path is not valid.
  47. *
  48. * @param type If set to default path will be parsed according to the
  49. * rules of the platform the application is being compiled to.
  50. * Otherwise it will be parsed according to provided type.
  51. */
  52. Path(wchar_t* pathStr, PathType type = PathType::Default);
  53. /**
  54. * @brief Constructs a path by parsing the provided path null terminated string.
  55. * Throws exception if provided path is not valid.
  56. *
  57. * @param type If set to default path will be parsed according to the
  58. * rules of the platform the application is being compiled to.
  59. * Otherwise it will be parsed according to provided type.
  60. */
  61. Path(const char* pathStr, PathType type = PathType::Default);
  62. Path(const Path& other);
  63. /**
  64. * @brief Assigns a path by parsing the provided path string. Path will be
  65. * parsed according to the rules of the platform the application is
  66. * being compiled to.
  67. */
  68. Path& operator= (const WString& pathStr);
  69. /**
  70. * @brief Assigns a path by parsing the provided path string. Path will be
  71. * parsed according to the rules of the platform the application is
  72. * being compiled to.
  73. */
  74. Path& operator= (const String& pathStr);
  75. /**
  76. * @brief Assigns a path by parsing the provided path null terminated string.
  77. * Path will be parsed according to the rules of the platform the
  78. * application is being compiled to.
  79. */
  80. Path& operator= (const wchar_t* pathStr);
  81. /**
  82. * @brief Assigns a path by parsing the provided path null terminated string.
  83. * Path will be parsed according to the rules of the platform the
  84. * application is being compiled to.
  85. */
  86. Path& operator= (const char* pathStr);
  87. Path& operator= (const Path& path);
  88. /**
  89. * @brief Compares two paths and returns true if they match. Comparison is
  90. * case insensitive and paths will be compared as-is, without canonization.
  91. */
  92. bool operator== (const Path& path) const { return equals(path); }
  93. /**
  94. * @brief Compares two paths and returns true if they don't match. Comparison is
  95. * case insensitive and paths will be compared as-is, without canonization.
  96. */
  97. bool operator!= (const Path& path) const { return !equals(path); }
  98. /**
  99. * @brief Gets a directory name with the specified index from the path.
  100. */
  101. const WString& operator[] (UINT32 idx) const { return getWDirectory(idx); }
  102. /**
  103. * @brief Swap internal data with another Path object.
  104. */
  105. void swap(Path& path);
  106. /**
  107. * @brief Create a path from another Path object.
  108. */
  109. void assign(const Path& path);
  110. /**
  111. * @brief Constructs a path by parsing the provided path string.
  112. * Throws exception if provided path is not valid.
  113. *
  114. * @param type If set to default path will be parsed according to the
  115. * rules of the platform the application is being compiled to.
  116. * Otherwise it will be parsed according to provided type.
  117. */
  118. void assign(const WString& pathStr, PathType type = PathType::Default);
  119. /**
  120. * @brief Constructs a path by parsing the provided path string.
  121. * Throws exception if provided path is not valid.
  122. *
  123. * @param type If set to default path will be parsed according to the
  124. * rules of the platform the application is being compiled to.
  125. * Otherwise it will be parsed according to provided type.
  126. */
  127. void assign(const String& pathStr, PathType type = PathType::Default);
  128. /**
  129. * @brief Constructs a path by parsing the provided path null terminated string.
  130. * Throws exception if provided path is not valid.
  131. *
  132. * @param type If set to default path will be parsed according to the
  133. * rules of the platform the application is being compiled to.
  134. * Otherwise it will be parsed according to provided type.
  135. */
  136. void assign(const wchar_t* pathStr, PathType type = PathType::Default);
  137. /**
  138. * @brief Constructs a path by parsing the provided path null terminated string.
  139. * Throws exception if provided path is not valid.
  140. *
  141. * @param type If set to default path will be parsed according to the
  142. * rules of the platform the application is being compiled to.
  143. * Otherwise it will be parsed according to provided type.
  144. */
  145. void assign(const char* pathStr, PathType type = PathType::Default);
  146. /**
  147. * @brief Converts the path in a string according to platform path rules.
  148. *
  149. * @type If set to default path will be parsed according to the
  150. * rules of the platform the application is being compiled to.
  151. * Otherwise it will be parsed according to provided type.
  152. */
  153. WString toWString(PathType type = PathType::Default) const;
  154. /**
  155. * @brief Converts the path in a string according to platform path rules.
  156. *
  157. * @type If set to default path will be parsed according to the
  158. * rules of the platform the application is being compiled to.
  159. * Otherwise it will be parsed according to provided type.
  160. */
  161. String toString(PathType type = PathType::Default) const;
  162. /**
  163. * @brief Checks is the path a directory (contains no file-name).
  164. */
  165. bool isDirectory() const { return mFilename.empty(); }
  166. /**
  167. * @brief Checks does the path point to a file.
  168. */
  169. bool isFile() const { return !mFilename.empty(); }
  170. /**
  171. * @brief Checks is the contained path absolute.
  172. */
  173. bool isAbsolute() const { return mIsAbsolute; }
  174. /**
  175. * @brief Returns parent path. If current path points to a file
  176. * the parent path will be the folder where the file is located.
  177. * Or if it contains a directory the parent will be the parent directory.
  178. * If no parent exists, same path will be returned.
  179. */
  180. Path getParent() const;
  181. /**
  182. * @brief Returns an absolute path by appending the current path to the provided base.
  183. * If path was already absolute no changes are made and copy of current path
  184. * is returned.
  185. * If base is not absolute, then the returned path will be made relative to base,
  186. * but will not be absolute.
  187. */
  188. Path getAbsolute(const Path& base) const;
  189. /**
  190. * @brief Returns a relative path by making the current path relative to the provided base.
  191. * Base must be a part of the current path. If base is not a part
  192. * of the path no changes are made and a copy of the current path
  193. * is returned.
  194. */
  195. Path getRelative(const Path& base) const;
  196. /**
  197. * @brief Returns the path as a path to directory. If path was pointing
  198. * to a file, the filename is removed, otherwise no changes are made
  199. * and exact copy is returned.
  200. */
  201. Path getDirectory() const;
  202. /**
  203. * @brief Makes the path the parent of the current path. If current path points to a file
  204. * the parent path will be the folder where the file is located.
  205. * Or if it contains a directory the parent will be the parent directory.
  206. * If no parent exists, same path will be returned.
  207. */
  208. Path& makeParent();
  209. /**
  210. * @brief Makes the current path absolute by appending it to base.
  211. * If path was already absolute no changes are made and copy of current path
  212. * is returned.
  213. * If base is not absolute, then the returned path will be made relative to base,
  214. * but will not be absolute.
  215. */
  216. Path& makeAbsolute(const Path& base);
  217. /**
  218. * @brief Makes the current path relative to the provided base.
  219. * Base must be a part of the current path. If base is not a part
  220. * of the path no changes are made and a copy of the current path
  221. * is returned.
  222. */
  223. Path& makeRelative(const Path& base);
  224. /**
  225. * @brief Appends another path to the end of this path.
  226. */
  227. Path& append(const Path& path);
  228. /**
  229. * @brief Checks if the current path contains the provided path.
  230. * Comparison is case insensitive and paths will be compared
  231. * as-is, without canonization.
  232. */
  233. bool includes(const Path& child) const;
  234. /**
  235. * @brief Compares two paths and returns true if they match. Comparison is
  236. * case insensitive and paths will be compared as-is, without canonization.
  237. */
  238. bool equals(const Path& other) const;
  239. /**
  240. * @brief Change or set the filename in the path.
  241. */
  242. void setFilename(const WString& filename) { mFilename = filename; }
  243. /**
  244. * @brief Change or set the filename in the path.
  245. */
  246. void setFilename(const String& filename) { mFilename = BansheeEngine::toWString(filename); }
  247. /**
  248. * @brief Change or set the base name in the path. Base name changes the
  249. * filename by changing its base to the provided value but keeping extension intact.
  250. */
  251. void setBasename(const WString& basename);
  252. /**
  253. * @brief Change or set the base name in the path. Base name changes the
  254. * filename by changing its base to the provided value but keeping extension intact.
  255. */
  256. void setBasename(const String& basename);
  257. /**
  258. * @brief Change or set the extension of the filename in the path.
  259. */
  260. void setExtension(const WString& extension);
  261. /**
  262. * @brief Change or set the extension of the filename in the path.
  263. */
  264. void setExtension(const String& extension);
  265. /**
  266. * @brief Returns a filename in the path.
  267. *
  268. * @param extension If true, returned filename will contain an extension.
  269. */
  270. WString getWFilename(bool extension = true) const;
  271. /**
  272. * @brief Returns a filename in the path.
  273. *
  274. * @param extension If true, returned filename will contain an extension.
  275. */
  276. String getFilename(bool extension = true) const;
  277. /**
  278. * @brief Returns file extension with the leading ".".
  279. */
  280. WString getWExtension() const;
  281. /**
  282. * @brief Returns file extension with the leading ".".
  283. */
  284. String getExtension() const;
  285. /**
  286. * @brief Gets the number of directories in the path.
  287. */
  288. UINT32 getNumDirectories() const { return (UINT32)mDirectories.size(); }
  289. /**
  290. * @brief Gets a directory name with the specified index from the path.
  291. */
  292. const WString& getWDirectory(UINT32 idx) const;
  293. /**
  294. * @brief Gets a directory name with the specified index from the path.
  295. */
  296. String getDirectory(UINT32 idx) const;
  297. /**
  298. * @brief Returns path device (e.g. drive, volume, etc.) if one exists in the path.
  299. */
  300. const WString& getWDevice() const { return mDevice; }
  301. /**
  302. * @brief Returns path device (e.g. drive, volume, etc.) if one exists in the path.
  303. */
  304. String getDevice() const { return BansheeEngine::toString(mDevice); }
  305. /**
  306. * @brief Returns path node (e.g. network name) if one exists in the path.
  307. */
  308. const WString& getWNode() const { return mNode; }
  309. /**
  310. * @brief Returns path node (e.g. network name) if one exists in the path.
  311. */
  312. String getNode() const { return BansheeEngine::toString(mNode); }
  313. /**
  314. * @brief Gets last element in the path, filename if it exists, otherwise the last directory.
  315. * If no directories exist returns device or node.
  316. *
  317. * @param type Determines format of node or device, in case they are returned. When default,
  318. * format for the active platform will be used, otherwise the format defined
  319. * by the parameter will be used.
  320. */
  321. WString getWTail(PathType type = PathType::Default) const;
  322. /**
  323. * @brief Gets last element in the path, filename if it exists, otherwise the last directory.
  324. * If no directories exist returns device or node.
  325. *
  326. * @param type Determines format of node or device, in case they are returned. When default,
  327. * format for the active platform will be used, otherwise the format defined
  328. * by the parameter will be used.
  329. */
  330. String getTail(PathType type = PathType::Default) const;
  331. /**
  332. * @brief Clears the path to nothing.
  333. */
  334. void clear();
  335. /**
  336. * @brief Returns true if no path has been set.
  337. */
  338. bool isEmpty() const { return mDirectories.empty() && mFilename.empty() && mDevice.empty() && mNode.empty(); }
  339. /**
  340. * @brief Compares two path elements (i.e. filenames, directory names, etc.)
  341. */
  342. static bool comparePathElem(const WString& left, const WString& right);
  343. static const Path BLANK;
  344. private:
  345. /**
  346. * @brief Constructs a path by parsing the provided raw string data.
  347. * Throws exception if provided path is not valid.
  348. *
  349. * @param type If set to default path will be parsed according to the
  350. * rules of the platform the application is being compiled to.
  351. * Otherwise it will be parsed according to provided type.
  352. */
  353. void assign(const wchar_t* pathStr, UINT32 numChars, PathType type = PathType::Default);
  354. /**
  355. * @brief Constructs a path by parsing the provided raw string data.
  356. * Throws exception if provided path is not valid.
  357. *
  358. * @param type If set to default path will be parsed according to the
  359. * rules of the platform the application is being compiled to.
  360. * Otherwise it will be parsed according to provided type.
  361. */
  362. void assign(const char* pathStr, UINT32 numChars, PathType type = PathType::Default);
  363. /**
  364. * @brief Parses a Windows path and stores the parsed data internally.
  365. * Throws an exception if parsing fails.
  366. */
  367. template<class T>
  368. void parseWindows(const T* pathStr, UINT32 numChars)
  369. {
  370. clear();
  371. UINT32 idx = 0;
  372. BasicStringStream<T> tempStream;
  373. if (idx < numChars)
  374. {
  375. if (pathStr[idx] == '\\' || pathStr[idx] == '/')
  376. {
  377. mIsAbsolute = true;
  378. idx++;
  379. }
  380. }
  381. if (idx < numChars)
  382. {
  383. // Path starts with a node, a drive letter or is relative
  384. if (mIsAbsolute && pathStr[idx] == '\\' || pathStr[idx] == '/') // Node
  385. {
  386. idx++;
  387. tempStream.str(BasicString<T>());
  388. tempStream.clear();
  389. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  390. tempStream << pathStr[idx++];
  391. setNode(tempStream.str());
  392. if (idx < numChars)
  393. idx++;
  394. }
  395. else // A drive letter or not absolute
  396. {
  397. T drive = pathStr[idx];
  398. idx++;
  399. if (idx < numChars && pathStr[idx] == ':')
  400. {
  401. if (mIsAbsolute || !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')))
  402. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  403. mIsAbsolute = true;
  404. setDevice(BansheeEngine::toWString(drive));
  405. idx++;
  406. if (idx >= numChars || (pathStr[idx] != '\\' && pathStr[idx] != '/'))
  407. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  408. idx++;
  409. }
  410. else
  411. idx--;
  412. }
  413. while (idx < numChars)
  414. {
  415. tempStream.str(BasicString<T>());
  416. tempStream.clear();
  417. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  418. {
  419. tempStream << pathStr[idx];
  420. idx++;
  421. }
  422. if (idx < numChars)
  423. pushDirectory(tempStream.str());
  424. else
  425. setFilename(tempStream.str());
  426. idx++;
  427. }
  428. }
  429. }
  430. /**
  431. * @brief Parses a Unix path and stores the parsed data internally.
  432. * Throws an exception if parsing fails.
  433. */
  434. template<class T>
  435. void parseUnix(const T* pathStr, UINT32 numChars)
  436. {
  437. clear();
  438. UINT32 idx = 0;
  439. BasicStringStream<T> tempStream;
  440. if (idx < numChars)
  441. {
  442. if (pathStr[idx] == '/')
  443. {
  444. mIsAbsolute = true;
  445. idx++;
  446. }
  447. else if (pathStr[idx] == '~')
  448. {
  449. idx++;
  450. if (idx >= numChars || pathStr[idx] == '/')
  451. {
  452. pushDirectory(BansheeEngine::toWString('~'));
  453. mIsAbsolute = true;
  454. }
  455. else
  456. idx--;
  457. }
  458. while (idx < numChars)
  459. {
  460. tempStream.str(BasicString<T>());
  461. tempStream.clear();
  462. while (idx < numChars && pathStr[idx] != '/')
  463. {
  464. tempStream << pathStr[idx];
  465. idx++;
  466. }
  467. if (idx < numChars)
  468. {
  469. if (mDirectories.empty())
  470. {
  471. BasicString<T> deviceStr = tempStream.str();
  472. if (!deviceStr.empty() && *(deviceStr.rbegin()) == ':')
  473. {
  474. setDevice(deviceStr.substr(0, deviceStr.length() - 1));
  475. mIsAbsolute = true;
  476. }
  477. else
  478. {
  479. pushDirectory(deviceStr);
  480. }
  481. }
  482. else
  483. {
  484. pushDirectory(tempStream.str());
  485. }
  486. }
  487. else
  488. {
  489. setFilename(tempStream.str());
  490. }
  491. idx++;
  492. }
  493. }
  494. }
  495. void setNode(const WString& node) { mNode = node; }
  496. void setNode(const String& node) { mNode = BansheeEngine::toWString(node); }
  497. void setDevice(const WString& device) { mDevice = device; }
  498. void setDevice(const String& device) { mDevice = BansheeEngine::toWString(device); }
  499. /**
  500. * @brief Build a Windows path string from internal path data.
  501. */
  502. WString buildWindows() const;
  503. /**
  504. * @brief Build a Unix path string from internal path data.
  505. */
  506. WString buildUnix() const;
  507. /**
  508. * @brief Add new directory to the end of the path.
  509. */
  510. void pushDirectory(const WString& dir);
  511. /**
  512. * @brief Add new directory to the end of the path.
  513. */
  514. void pushDirectory(const String& dir);
  515. /**
  516. * @brief Helper method that throws invalid path exception.
  517. */
  518. void throwInvalidPathException(const WString& path) const;
  519. /**
  520. * @brief Helper method that throws invalid path exception.
  521. */
  522. void throwInvalidPathException(const String& path) const;
  523. private:
  524. friend struct RTTIPlainType<Path>; // For serialization
  525. friend struct ::std::hash<BansheeEngine::Path>;
  526. Vector<WString> mDirectories;
  527. WString mDevice;
  528. WString mFilename;
  529. WString mNode;
  530. bool mIsAbsolute;
  531. };
  532. /**
  533. * @brief RTTIPlainType specialization for Path that allows paths be serialized as
  534. * value types.
  535. *
  536. * @see RTTIPlainType
  537. */
  538. template<> struct RTTIPlainType<Path>
  539. {
  540. enum { id = TID_Path }; enum { hasDynamicSize = 1 };
  541. static void toMemory(const Path& data, char* memory)
  542. {
  543. UINT32 size = getDynamicSize(data);
  544. memcpy(memory, &size, sizeof(UINT32));
  545. memory += sizeof(UINT32);
  546. memory = rttiWriteElem(data.mDevice, memory);
  547. memory = rttiWriteElem(data.mNode, memory);
  548. memory = rttiWriteElem(data.mFilename, memory);
  549. memory = rttiWriteElem(data.mIsAbsolute, memory);
  550. memory = rttiWriteElem(data.mDirectories, memory);
  551. }
  552. static UINT32 fromMemory(Path& data, char* memory)
  553. {
  554. UINT32 size;
  555. memcpy(&size, memory, sizeof(UINT32));
  556. memory += sizeof(UINT32);
  557. memory = rttiReadElem(data.mDevice, memory);
  558. memory = rttiReadElem(data.mNode, memory);
  559. memory = rttiReadElem(data.mFilename, memory);
  560. memory = rttiReadElem(data.mIsAbsolute, memory);
  561. memory = rttiReadElem(data.mDirectories, memory);
  562. return size;
  563. }
  564. static UINT32 getDynamicSize(const Path& data)
  565. {
  566. UINT64 dataSize = rttiGetElemSize(data.mDevice) + rttiGetElemSize(data.mNode) + rttiGetElemSize(data.mFilename) +
  567. rttiGetElemSize(data.mIsAbsolute) + rttiGetElemSize(data.mDirectories) + sizeof(UINT32);
  568. #if BS_DEBUG_MODE
  569. if (dataSize > std::numeric_limits<UINT32>::max())
  570. {
  571. __string_throwDataOverflowException();
  572. }
  573. #endif
  574. return (UINT32)dataSize;
  575. }
  576. };
  577. }
  578. /**
  579. * @brief Hash value generator for Path.
  580. */
  581. template<>
  582. struct std::hash<BansheeEngine::Path>
  583. {
  584. size_t operator()(const BansheeEngine::Path& path) const
  585. {
  586. size_t hash = 0;
  587. BansheeEngine::hash_combine(hash, path.mFilename);
  588. BansheeEngine::hash_combine(hash, path.mDevice);
  589. BansheeEngine::hash_combine(hash, path.mNode);
  590. for (auto& dir : path.mDirectories)
  591. BansheeEngine::hash_combine(hash, dir);
  592. return hash;
  593. }
  594. };