BsPath.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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 Compares two path elements (i.e. filenames, directory names, etc.)
  343. */
  344. static bool comparePathElem(const WString& left, const WString& right);
  345. static const Path BLANK;
  346. private:
  347. /**
  348. * @brief Constructs a path by parsing the provided raw string data.
  349. * Throws exception if provided path is not valid.
  350. *
  351. * @param type If set to default path will be parsed according to the
  352. * rules of the platform the application is being compiled to.
  353. * Otherwise it will be parsed according to provided type.
  354. */
  355. void assign(const wchar_t* pathStr, UINT32 numChars, PathType type = PathType::Default);
  356. /**
  357. * @brief Constructs a path by parsing the provided raw string data.
  358. * Throws exception if provided path is not valid.
  359. *
  360. * @param type If set to default path will be parsed according to the
  361. * rules of the platform the application is being compiled to.
  362. * Otherwise it will be parsed according to provided type.
  363. */
  364. void assign(const char* pathStr, UINT32 numChars, PathType type = PathType::Default);
  365. /**
  366. * @brief Parses a Windows path and stores the parsed data internally.
  367. * Throws an exception if parsing fails.
  368. */
  369. template<class T>
  370. void parseWindows(const T* pathStr, UINT32 numChars)
  371. {
  372. clear();
  373. UINT32 idx = 0;
  374. BasicStringStream<T> tempStream;
  375. if (idx < numChars)
  376. {
  377. if (pathStr[idx] == '\\' || pathStr[idx] == '/')
  378. {
  379. mIsAbsolute = true;
  380. idx++;
  381. }
  382. }
  383. if (idx < numChars)
  384. {
  385. // Path starts with a node, a drive letter or is relative
  386. if (mIsAbsolute && pathStr[idx] == '\\' || pathStr[idx] == '/') // Node
  387. {
  388. idx++;
  389. tempStream.str(BasicString<T>());
  390. tempStream.clear();
  391. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  392. tempStream << pathStr[idx++];
  393. setNode(tempStream.str());
  394. if (idx < numChars)
  395. idx++;
  396. }
  397. else // A drive letter or not absolute
  398. {
  399. T drive = pathStr[idx];
  400. idx++;
  401. if (idx < numChars && pathStr[idx] == ':')
  402. {
  403. if (mIsAbsolute || !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')))
  404. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  405. mIsAbsolute = true;
  406. setDevice(BansheeEngine::toWString(drive));
  407. idx++;
  408. if (idx >= numChars || (pathStr[idx] != '\\' && pathStr[idx] != '/'))
  409. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  410. idx++;
  411. }
  412. else
  413. idx--;
  414. }
  415. while (idx < numChars)
  416. {
  417. tempStream.str(BasicString<T>());
  418. tempStream.clear();
  419. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  420. {
  421. tempStream << pathStr[idx];
  422. idx++;
  423. }
  424. if (idx < numChars)
  425. pushDirectory(tempStream.str());
  426. else
  427. setFilename(tempStream.str());
  428. idx++;
  429. }
  430. }
  431. }
  432. /**
  433. * @brief Parses a Unix path and stores the parsed data internally.
  434. * Throws an exception if parsing fails.
  435. */
  436. template<class T>
  437. void parseUnix(const T* pathStr, UINT32 numChars)
  438. {
  439. clear();
  440. UINT32 idx = 0;
  441. BasicStringStream<T> tempStream;
  442. if (idx < numChars)
  443. {
  444. if (pathStr[idx] == '/')
  445. {
  446. mIsAbsolute = true;
  447. idx++;
  448. }
  449. else if (pathStr[idx] == '~')
  450. {
  451. idx++;
  452. if (idx >= numChars || pathStr[idx] == '/')
  453. {
  454. pushDirectory(BansheeEngine::toWString('~'));
  455. mIsAbsolute = true;
  456. }
  457. else
  458. idx--;
  459. }
  460. while (idx < numChars)
  461. {
  462. tempStream.str(BasicString<T>());
  463. tempStream.clear();
  464. while (idx < numChars && pathStr[idx] != '/')
  465. {
  466. tempStream << pathStr[idx];
  467. idx++;
  468. }
  469. if (idx < numChars)
  470. {
  471. if (mDirectories.empty())
  472. {
  473. BasicString<T> deviceStr = tempStream.str();
  474. if (!deviceStr.empty() && *(deviceStr.rbegin()) == ':')
  475. {
  476. setDevice(deviceStr.substr(0, deviceStr.length() - 1));
  477. mIsAbsolute = true;
  478. }
  479. else
  480. {
  481. pushDirectory(deviceStr);
  482. }
  483. }
  484. else
  485. {
  486. pushDirectory(tempStream.str());
  487. }
  488. }
  489. else
  490. {
  491. setFilename(tempStream.str());
  492. }
  493. idx++;
  494. }
  495. }
  496. }
  497. void setNode(const WString& node) { mNode = node; }
  498. void setNode(const String& node) { mNode = BansheeEngine::toWString(node); }
  499. void setDevice(const WString& device) { mDevice = device; }
  500. void setDevice(const String& device) { mDevice = BansheeEngine::toWString(device); }
  501. /**
  502. * @brief Build a Windows path string from internal path data.
  503. */
  504. WString buildWindows() const;
  505. /**
  506. * @brief Build a Unix path string from internal path data.
  507. */
  508. WString buildUnix() const;
  509. /**
  510. * @brief Add new directory to the end of the path.
  511. */
  512. void pushDirectory(const WString& dir);
  513. /**
  514. * @brief Add new directory to the end of the path.
  515. */
  516. void pushDirectory(const String& dir);
  517. /**
  518. * @brief Helper method that throws invalid path exception.
  519. */
  520. void throwInvalidPathException(const WString& path) const;
  521. /**
  522. * @brief Helper method that throws invalid path exception.
  523. */
  524. void throwInvalidPathException(const String& path) const;
  525. private:
  526. friend struct RTTIPlainType<Path>; // For serialization
  527. friend struct ::std::hash<BansheeEngine::Path>;
  528. Vector<WString> mDirectories;
  529. WString mDevice;
  530. WString mFilename;
  531. WString mNode;
  532. bool mIsAbsolute;
  533. };
  534. /**
  535. * @brief RTTIPlainType specialization for Path that allows paths be serialized as
  536. * value types.
  537. *
  538. * @see RTTIPlainType
  539. */
  540. template<> struct RTTIPlainType<Path>
  541. {
  542. enum { id = TID_Path }; enum { hasDynamicSize = 1 };
  543. static void toMemory(const Path& data, char* memory)
  544. {
  545. UINT32 size = getDynamicSize(data);
  546. memcpy(memory, &size, sizeof(UINT32));
  547. memory += sizeof(UINT32);
  548. memory = rttiWriteElem(data.mDevice, memory);
  549. memory = rttiWriteElem(data.mNode, memory);
  550. memory = rttiWriteElem(data.mFilename, memory);
  551. memory = rttiWriteElem(data.mIsAbsolute, memory);
  552. memory = rttiWriteElem(data.mDirectories, memory);
  553. }
  554. static UINT32 fromMemory(Path& data, char* memory)
  555. {
  556. UINT32 size;
  557. memcpy(&size, memory, sizeof(UINT32));
  558. memory += sizeof(UINT32);
  559. memory = rttiReadElem(data.mDevice, memory);
  560. memory = rttiReadElem(data.mNode, memory);
  561. memory = rttiReadElem(data.mFilename, memory);
  562. memory = rttiReadElem(data.mIsAbsolute, memory);
  563. memory = rttiReadElem(data.mDirectories, memory);
  564. return size;
  565. }
  566. static UINT32 getDynamicSize(const Path& data)
  567. {
  568. UINT64 dataSize = rttiGetElemSize(data.mDevice) + rttiGetElemSize(data.mNode) + rttiGetElemSize(data.mFilename) +
  569. rttiGetElemSize(data.mIsAbsolute) + rttiGetElemSize(data.mDirectories) + sizeof(UINT32);
  570. #if BS_DEBUG_MODE
  571. if (dataSize > std::numeric_limits<UINT32>::max())
  572. {
  573. __string_throwDataOverflowException();
  574. }
  575. #endif
  576. return (UINT32)dataSize;
  577. }
  578. };
  579. }
  580. /**
  581. * @brief Hash value generator for Path.
  582. */
  583. template<>
  584. struct std::hash<BansheeEngine::Path>
  585. {
  586. size_t operator()(const BansheeEngine::Path& path) const
  587. {
  588. size_t hash = 0;
  589. BansheeEngine::hash_combine(hash, path.mFilename);
  590. BansheeEngine::hash_combine(hash, path.mDevice);
  591. BansheeEngine::hash_combine(hash, path.mNode);
  592. for (auto& dir : path.mDirectories)
  593. BansheeEngine::hash_combine(hash, dir);
  594. return hash;
  595. }
  596. };