BsPath.h 21 KB

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