BsPath.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. void setExtension(const WString& extension);
  259. /**
  260. * @brief Change or set the extension of the filename in the path.
  261. */
  262. void setExtension(const String& extension);
  263. /**
  264. * @brief Returns a filename in the path.
  265. *
  266. * @param extension If true, returned filename will contain an extension.
  267. */
  268. WString getWFilename(bool extension = true) const;
  269. /**
  270. * @brief Returns a filename in the path.
  271. *
  272. * @param extension If true, returned filename will contain an extension.
  273. */
  274. String getFilename(bool extension = true) const;
  275. /**
  276. * @brief Returns file extension with the leading ".".
  277. */
  278. WString getWExtension() const;
  279. /**
  280. * @brief Returns file extension with the leading ".".
  281. */
  282. String getExtension() const;
  283. /**
  284. * @brief Gets the number of directories in the path.
  285. */
  286. UINT32 getNumDirectories() const { return (UINT32)mDirectories.size(); }
  287. /**
  288. * @brief Gets a directory name with the specified index from the path.
  289. */
  290. const WString& getWDirectory(UINT32 idx) const;
  291. /**
  292. * @brief Gets a directory name with the specified index from the path.
  293. */
  294. String getDirectory(UINT32 idx) const;
  295. /**
  296. * @brief Returns path device (e.g. drive, volume, etc.) if one exists in the path.
  297. */
  298. const WString& getWDevice() const { return mDevice; }
  299. /**
  300. * @brief Returns path device (e.g. drive, volume, etc.) if one exists in the path.
  301. */
  302. String getDevice() const { return BansheeEngine::toString(mDevice); }
  303. /**
  304. * @brief Returns path node (e.g. network name) if one exists in the path.
  305. */
  306. const WString& getWNode() const { return mNode; }
  307. /**
  308. * @brief Returns path node (e.g. network name) if one exists in the path.
  309. */
  310. String getNode() const { return BansheeEngine::toString(mNode); }
  311. /**
  312. * @brief Gets last element in the path, filename if it exists, otherwise the last directory.
  313. * If no directories exist returns device or node.
  314. *
  315. * @param type Determines format of node or device, in case they are returned. When default,
  316. * format for the active platform will be used, otherwise the format defined
  317. * by the parameter will be used.
  318. */
  319. WString getWTail(PathType type = PathType::Default) const;
  320. /**
  321. * @brief Gets last element in the path, filename if it exists, otherwise the last directory.
  322. * If no directories exist returns device or node.
  323. *
  324. * @param type Determines format of node or device, in case they are returned. When default,
  325. * format for the active platform will be used, otherwise the format defined
  326. * by the parameter will be used.
  327. */
  328. String getTail(PathType type = PathType::Default) const;
  329. /**
  330. * @brief Clears the path to nothing.
  331. */
  332. void clear();
  333. /**
  334. * @brief Returns true if no path has been set.
  335. */
  336. bool isEmpty() const { return mDirectories.empty() && mFilename.empty() && mDevice.empty() && mNode.empty(); }
  337. /**
  338. * @brief Compares two path elements (i.e. filenames, directory names, etc.)
  339. */
  340. static bool comparePathElem(const WString& left, const WString& right);
  341. static const Path BLANK;
  342. private:
  343. /**
  344. * @brief Constructs a path by parsing the provided raw string data.
  345. * Throws exception if provided path is not valid.
  346. *
  347. * @param type If set to default path will be parsed according to the
  348. * rules of the platform the application is being compiled to.
  349. * Otherwise it will be parsed according to provided type.
  350. */
  351. void assign(const wchar_t* pathStr, UINT32 numChars, PathType type = PathType::Default);
  352. /**
  353. * @brief Constructs a path by parsing the provided raw string data.
  354. * Throws exception if provided path is not valid.
  355. *
  356. * @param type If set to default path will be parsed according to the
  357. * rules of the platform the application is being compiled to.
  358. * Otherwise it will be parsed according to provided type.
  359. */
  360. void assign(const char* pathStr, UINT32 numChars, PathType type = PathType::Default);
  361. /**
  362. * @brief Parses a Windows path and stores the parsed data internally.
  363. * Throws an exception if parsing fails.
  364. */
  365. template<class T>
  366. void parseWindows(const T* pathStr, UINT32 numChars)
  367. {
  368. clear();
  369. UINT32 idx = 0;
  370. BasicStringStream<T> tempStream;
  371. if (idx < numChars)
  372. {
  373. if (pathStr[idx] == '\\' || pathStr[idx] == '/')
  374. {
  375. mIsAbsolute = true;
  376. idx++;
  377. }
  378. }
  379. if (idx < numChars)
  380. {
  381. // Path starts with a node, a drive letter or is relative
  382. if (mIsAbsolute && pathStr[idx] == '\\' || pathStr[idx] == '/') // Node
  383. {
  384. idx++;
  385. tempStream.str(BasicString<T>());
  386. tempStream.clear();
  387. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  388. tempStream << pathStr[idx++];
  389. setNode(tempStream.str());
  390. if (idx < numChars)
  391. idx++;
  392. }
  393. else // A drive letter or not absolute
  394. {
  395. T drive = pathStr[idx];
  396. idx++;
  397. if (idx < numChars && pathStr[idx] == ':')
  398. {
  399. if (mIsAbsolute || !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')))
  400. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  401. mIsAbsolute = true;
  402. setDevice(BansheeEngine::toWString(drive));
  403. idx++;
  404. if (idx >= numChars || (pathStr[idx] != '\\' && pathStr[idx] != '/'))
  405. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  406. idx++;
  407. }
  408. else
  409. idx--;
  410. }
  411. while (idx < numChars)
  412. {
  413. tempStream.str(BasicString<T>());
  414. tempStream.clear();
  415. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  416. {
  417. tempStream << pathStr[idx];
  418. idx++;
  419. }
  420. if (idx < numChars)
  421. pushDirectory(tempStream.str());
  422. else
  423. setFilename(tempStream.str());
  424. idx++;
  425. }
  426. }
  427. }
  428. /**
  429. * @brief Parses a Unix path and stores the parsed data internally.
  430. * Throws an exception if parsing fails.
  431. */
  432. template<class T>
  433. void parseUnix(const T* pathStr, UINT32 numChars)
  434. {
  435. clear();
  436. UINT32 idx = 0;
  437. BasicStringStream<T> tempStream;
  438. if (idx < numChars)
  439. {
  440. if (pathStr[idx] == '/')
  441. {
  442. mIsAbsolute = true;
  443. idx++;
  444. }
  445. else if (pathStr[idx] == '~')
  446. {
  447. idx++;
  448. if (idx >= numChars || pathStr[idx] == '/')
  449. {
  450. pushDirectory(BansheeEngine::toWString('~'));
  451. mIsAbsolute = true;
  452. }
  453. else
  454. idx--;
  455. }
  456. while (idx < numChars)
  457. {
  458. tempStream.str(BasicString<T>());
  459. tempStream.clear();
  460. while (idx < numChars && pathStr[idx] != '/')
  461. {
  462. tempStream << pathStr[idx];
  463. idx++;
  464. }
  465. if (idx < numChars)
  466. {
  467. if (mDirectories.empty())
  468. {
  469. BasicString<T> deviceStr = tempStream.str();
  470. if (!deviceStr.empty() && *(deviceStr.rbegin()) == ':')
  471. {
  472. setDevice(deviceStr.substr(0, deviceStr.length() - 1));
  473. mIsAbsolute = true;
  474. }
  475. else
  476. {
  477. pushDirectory(deviceStr);
  478. }
  479. }
  480. else
  481. {
  482. pushDirectory(tempStream.str());
  483. }
  484. }
  485. else
  486. {
  487. setFilename(tempStream.str());
  488. }
  489. idx++;
  490. }
  491. }
  492. }
  493. void setNode(const WString& node) { mNode = node; }
  494. void setNode(const String& node) { mNode = BansheeEngine::toWString(node); }
  495. void setDevice(const WString& device) { mDevice = device; }
  496. void setDevice(const String& device) { mDevice = BansheeEngine::toWString(device); }
  497. /**
  498. * @brief Build a Windows path string from internal path data.
  499. */
  500. WString buildWindows() const;
  501. /**
  502. * @brief Build a Unix path string from internal path data.
  503. */
  504. WString buildUnix() const;
  505. /**
  506. * @brief Add new directory to the end of the path.
  507. */
  508. void pushDirectory(const WString& dir);
  509. /**
  510. * @brief Add new directory to the end of the path.
  511. */
  512. void pushDirectory(const String& dir);
  513. /**
  514. * @brief Helper method that throws invalid path exception.
  515. */
  516. void throwInvalidPathException(const WString& path) const;
  517. /**
  518. * @brief Helper method that throws invalid path exception.
  519. */
  520. void throwInvalidPathException(const String& path) const;
  521. private:
  522. friend struct RTTIPlainType<Path>; // For serialization
  523. friend struct ::std::hash<BansheeEngine::Path>;
  524. Vector<WString> mDirectories;
  525. WString mDevice;
  526. WString mFilename;
  527. WString mNode;
  528. bool mIsAbsolute;
  529. };
  530. /**
  531. * @brief RTTIPlainType specialization for Path that allows paths be serialized as
  532. * value types.
  533. *
  534. * @see RTTIPlainType
  535. */
  536. template<> struct RTTIPlainType<Path>
  537. {
  538. enum { id = TID_Path }; enum { hasDynamicSize = 1 };
  539. static void toMemory(const Path& data, char* memory)
  540. {
  541. UINT32 size = getDynamicSize(data);
  542. memcpy(memory, &size, sizeof(UINT32));
  543. memory += sizeof(UINT32);
  544. memory = rttiWriteElem(data.mDevice, memory);
  545. memory = rttiWriteElem(data.mNode, memory);
  546. memory = rttiWriteElem(data.mFilename, memory);
  547. memory = rttiWriteElem(data.mIsAbsolute, memory);
  548. memory = rttiWriteElem(data.mDirectories, memory);
  549. }
  550. static UINT32 fromMemory(Path& data, char* memory)
  551. {
  552. UINT32 size;
  553. memcpy(&size, memory, sizeof(UINT32));
  554. memory += sizeof(UINT32);
  555. memory = rttiReadElem(data.mDevice, memory);
  556. memory = rttiReadElem(data.mNode, memory);
  557. memory = rttiReadElem(data.mFilename, memory);
  558. memory = rttiReadElem(data.mIsAbsolute, memory);
  559. memory = rttiReadElem(data.mDirectories, memory);
  560. return size;
  561. }
  562. static UINT32 getDynamicSize(const Path& data)
  563. {
  564. UINT64 dataSize = rttiGetElemSize(data.mDevice) + rttiGetElemSize(data.mNode) + rttiGetElemSize(data.mFilename) +
  565. rttiGetElemSize(data.mIsAbsolute) + rttiGetElemSize(data.mDirectories) + sizeof(UINT32);
  566. #if BS_DEBUG_MODE
  567. if (dataSize > std::numeric_limits<UINT32>::max())
  568. {
  569. __string_throwDataOverflowException();
  570. }
  571. #endif
  572. return (UINT32)dataSize;
  573. }
  574. };
  575. }
  576. /**
  577. * @brief Hash value generator for Path.
  578. */
  579. template<>
  580. struct std::hash<BansheeEngine::Path>
  581. {
  582. size_t operator()(const BansheeEngine::Path& path) const
  583. {
  584. size_t hash = 0;
  585. BansheeEngine::hash_combine(hash, path.mFilename);
  586. BansheeEngine::hash_combine(hash, path.mDevice);
  587. BansheeEngine::hash_combine(hash, path.mNode);
  588. for (auto& dir : path.mDirectories)
  589. BansheeEngine::hash_combine(hash, dir);
  590. return hash;
  591. }
  592. };