BsPath.h 21 KB

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