The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1094 lines
35KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. File::File (const String& fullPathName)
  19. : fullPath (parseAbsolutePath (fullPathName))
  20. {
  21. }
  22. File File::createFileWithoutCheckingPath (const String& path)
  23. {
  24. File f;
  25. f.fullPath = path;
  26. return f;
  27. }
  28. File::File (const File& other)
  29. : fullPath (other.fullPath)
  30. {
  31. }
  32. File& File::operator= (const String& newPath)
  33. {
  34. fullPath = parseAbsolutePath (newPath);
  35. return *this;
  36. }
  37. File& File::operator= (const File& other)
  38. {
  39. fullPath = other.fullPath;
  40. return *this;
  41. }
  42. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  43. File::File (File&& other) noexcept
  44. : fullPath (static_cast <String&&> (other.fullPath))
  45. {
  46. }
  47. File& File::operator= (File&& other) noexcept
  48. {
  49. fullPath = static_cast <String&&> (other.fullPath);
  50. return *this;
  51. }
  52. #endif
  53. const File File::nonexistent;
  54. //==============================================================================
  55. String File::parseAbsolutePath (const String& p)
  56. {
  57. if (p.isEmpty())
  58. return String::empty;
  59. #if JUCE_WINDOWS
  60. // Windows..
  61. String path (p.replaceCharacter ('/', '\\'));
  62. if (path.startsWithChar (separator))
  63. {
  64. if (path[1] != separator)
  65. {
  66. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  67. If you're trying to parse a string that may be either a relative path or an absolute path,
  68. you MUST provide a context against which the partial path can be evaluated - you can do
  69. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  70. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  71. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  72. */
  73. jassertfalse;
  74. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  75. }
  76. }
  77. else if (! path.containsChar (':'))
  78. {
  79. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  80. If you're trying to parse a string that may be either a relative path or an absolute path,
  81. you MUST provide a context against which the partial path can be evaluated - you can do
  82. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  83. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  84. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  85. */
  86. jassertfalse;
  87. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  88. }
  89. #else
  90. // Mac or Linux..
  91. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  92. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  93. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  94. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  95. String path (p);
  96. if (path.startsWithChar ('~'))
  97. {
  98. if (path[1] == separator || path[1] == 0)
  99. {
  100. // expand a name of the form "~/abc"
  101. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  102. + path.substring (1);
  103. }
  104. else
  105. {
  106. // expand a name of type "~dave/abc"
  107. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  108. struct passwd* const pw = getpwnam (userName.toUTF8());
  109. if (pw != nullptr)
  110. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  111. }
  112. }
  113. else if (! path.startsWithChar (separator))
  114. {
  115. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  116. If you're trying to parse a string that may be either a relative path or an absolute path,
  117. you MUST provide a context against which the partial path can be evaluated - you can do
  118. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  119. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  120. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  121. */
  122. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  123. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  124. }
  125. #endif
  126. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  127. path = path.dropLastCharacters (1);
  128. return path;
  129. }
  130. String File::addTrailingSeparator (const String& path)
  131. {
  132. return path.endsWithChar (separator) ? path
  133. : path + separator;
  134. }
  135. //==============================================================================
  136. #if JUCE_LINUX
  137. #define NAMES_ARE_CASE_SENSITIVE 1
  138. #endif
  139. bool File::areFileNamesCaseSensitive()
  140. {
  141. #if NAMES_ARE_CASE_SENSITIVE
  142. return true;
  143. #else
  144. return false;
  145. #endif
  146. }
  147. bool File::operator== (const File& other) const
  148. {
  149. #if NAMES_ARE_CASE_SENSITIVE
  150. return fullPath == other.fullPath;
  151. #else
  152. return fullPath.equalsIgnoreCase (other.fullPath);
  153. #endif
  154. }
  155. bool File::operator!= (const File& other) const
  156. {
  157. return ! operator== (other);
  158. }
  159. bool File::operator< (const File& other) const
  160. {
  161. #if NAMES_ARE_CASE_SENSITIVE
  162. return fullPath < other.fullPath;
  163. #else
  164. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  165. #endif
  166. }
  167. bool File::operator> (const File& other) const
  168. {
  169. #if NAMES_ARE_CASE_SENSITIVE
  170. return fullPath > other.fullPath;
  171. #else
  172. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  173. #endif
  174. }
  175. //==============================================================================
  176. bool File::setReadOnly (const bool shouldBeReadOnly,
  177. const bool applyRecursively) const
  178. {
  179. bool worked = true;
  180. if (applyRecursively && isDirectory())
  181. {
  182. Array <File> subFiles;
  183. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  184. for (int i = subFiles.size(); --i >= 0;)
  185. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  186. }
  187. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  188. }
  189. bool File::deleteRecursively() const
  190. {
  191. bool worked = true;
  192. if (isDirectory())
  193. {
  194. Array<File> subFiles;
  195. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  196. for (int i = subFiles.size(); --i >= 0;)
  197. worked = subFiles.getReference(i).deleteRecursively() && worked;
  198. }
  199. return deleteFile() && worked;
  200. }
  201. bool File::moveFileTo (const File& newFile) const
  202. {
  203. if (newFile.fullPath == fullPath)
  204. return true;
  205. #if ! NAMES_ARE_CASE_SENSITIVE
  206. if (*this != newFile)
  207. #endif
  208. if (! newFile.deleteFile())
  209. return false;
  210. return moveInternal (newFile);
  211. }
  212. bool File::copyFileTo (const File& newFile) const
  213. {
  214. return (*this == newFile)
  215. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  216. }
  217. bool File::copyDirectoryTo (const File& newDirectory) const
  218. {
  219. if (isDirectory() && newDirectory.createDirectory())
  220. {
  221. Array<File> subFiles;
  222. findChildFiles (subFiles, File::findFiles, false);
  223. int i;
  224. for (i = 0; i < subFiles.size(); ++i)
  225. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  226. return false;
  227. subFiles.clear();
  228. findChildFiles (subFiles, File::findDirectories, false);
  229. for (i = 0; i < subFiles.size(); ++i)
  230. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  231. return false;
  232. return true;
  233. }
  234. return false;
  235. }
  236. //==============================================================================
  237. String File::getPathUpToLastSlash() const
  238. {
  239. const int lastSlash = fullPath.lastIndexOfChar (separator);
  240. if (lastSlash > 0)
  241. return fullPath.substring (0, lastSlash);
  242. else if (lastSlash == 0)
  243. return separatorString;
  244. else
  245. return fullPath;
  246. }
  247. File File::getParentDirectory() const
  248. {
  249. File f;
  250. f.fullPath = getPathUpToLastSlash();
  251. return f;
  252. }
  253. //==============================================================================
  254. String File::getFileName() const
  255. {
  256. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  257. }
  258. int File::hashCode() const
  259. {
  260. return fullPath.hashCode();
  261. }
  262. int64 File::hashCode64() const
  263. {
  264. return fullPath.hashCode64();
  265. }
  266. String File::getFileNameWithoutExtension() const
  267. {
  268. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  269. const int lastDot = fullPath.lastIndexOfChar ('.');
  270. if (lastDot > lastSlash)
  271. return fullPath.substring (lastSlash, lastDot);
  272. else
  273. return fullPath.substring (lastSlash);
  274. }
  275. bool File::isAChildOf (const File& potentialParent) const
  276. {
  277. if (potentialParent == File::nonexistent)
  278. return false;
  279. const String ourPath (getPathUpToLastSlash());
  280. #if NAMES_ARE_CASE_SENSITIVE
  281. if (potentialParent.fullPath == ourPath)
  282. #else
  283. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  284. #endif
  285. {
  286. return true;
  287. }
  288. else if (potentialParent.fullPath.length() >= ourPath.length())
  289. {
  290. return false;
  291. }
  292. else
  293. {
  294. return getParentDirectory().isAChildOf (potentialParent);
  295. }
  296. }
  297. //==============================================================================
  298. bool File::isAbsolutePath (const String& path)
  299. {
  300. return path.startsWithChar (separator)
  301. #if JUCE_WINDOWS
  302. || (path.isNotEmpty() && path[1] == ':');
  303. #else
  304. || path.startsWithChar ('~');
  305. #endif
  306. }
  307. File File::getChildFile (String relativePath) const
  308. {
  309. if (isAbsolutePath (relativePath))
  310. return File (relativePath);
  311. String path (fullPath);
  312. // It's relative, so remove any ../ or ./ bits at the start..
  313. if (relativePath[0] == '.')
  314. {
  315. #if JUCE_WINDOWS
  316. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  317. #else
  318. relativePath = relativePath.trimStart();
  319. #endif
  320. while (relativePath[0] == '.')
  321. {
  322. if (relativePath[1] == '.')
  323. {
  324. if (relativePath[2] == 0 || relativePath[2] == separator)
  325. {
  326. const int lastSlash = path.lastIndexOfChar (separator);
  327. if (lastSlash >= 0)
  328. path = path.substring (0, lastSlash);
  329. relativePath = relativePath.substring (3);
  330. }
  331. else
  332. {
  333. break;
  334. }
  335. }
  336. else if (relativePath[1] == separator)
  337. {
  338. relativePath = relativePath.substring (2);
  339. }
  340. else
  341. {
  342. break;
  343. }
  344. }
  345. }
  346. return File (addTrailingSeparator (path) + relativePath);
  347. }
  348. File File::getSiblingFile (const String& fileName) const
  349. {
  350. return getParentDirectory().getChildFile (fileName);
  351. }
  352. //==============================================================================
  353. String File::descriptionOfSizeInBytes (const int64 bytes)
  354. {
  355. if (bytes == 1) return "1 byte";
  356. else if (bytes < 1024) return String (bytes) + " bytes";
  357. else if (bytes < 1024 * 1024) return String (bytes / 1024.0, 1) + " KB";
  358. else if (bytes < 1024 * 1024 * 1024) return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  359. else return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  360. }
  361. //==============================================================================
  362. Result File::create() const
  363. {
  364. if (exists())
  365. return Result::ok();
  366. const File parentDir (getParentDirectory());
  367. if (parentDir == *this)
  368. return Result::fail ("Cannot create parent directory");
  369. Result r (parentDir.createDirectory());
  370. if (r.wasOk())
  371. {
  372. FileOutputStream fo (*this, 8);
  373. r = fo.getStatus();
  374. }
  375. return r;
  376. }
  377. Result File::createDirectory() const
  378. {
  379. if (isDirectory())
  380. return Result::ok();
  381. const File parentDir (getParentDirectory());
  382. if (parentDir == *this)
  383. return Result::fail ("Cannot create parent directory");
  384. Result r (parentDir.createDirectory());
  385. if (r.wasOk())
  386. r = createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  387. return r;
  388. }
  389. //==============================================================================
  390. Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); }
  391. Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); }
  392. Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); }
  393. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  394. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  395. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  396. //==============================================================================
  397. bool File::loadFileAsData (MemoryBlock& destBlock) const
  398. {
  399. if (! existsAsFile())
  400. return false;
  401. FileInputStream in (*this);
  402. return in.openedOk() && getSize() == in.readIntoMemoryBlock (destBlock);
  403. }
  404. String File::loadFileAsString() const
  405. {
  406. if (! existsAsFile())
  407. return String::empty;
  408. FileInputStream in (*this);
  409. return in.openedOk() ? in.readEntireStreamAsString()
  410. : String::empty;
  411. }
  412. void File::readLines (StringArray& destLines) const
  413. {
  414. destLines.addLines (loadFileAsString());
  415. }
  416. //==============================================================================
  417. int File::findChildFiles (Array<File>& results,
  418. const int whatToLookFor,
  419. const bool searchRecursively,
  420. const String& wildCardPattern) const
  421. {
  422. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  423. int total = 0;
  424. while (di.next())
  425. {
  426. results.add (di.getFile());
  427. ++total;
  428. }
  429. return total;
  430. }
  431. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  432. {
  433. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  434. int total = 0;
  435. while (di.next())
  436. ++total;
  437. return total;
  438. }
  439. bool File::containsSubDirectories() const
  440. {
  441. if (isDirectory())
  442. {
  443. DirectoryIterator di (*this, false, "*", findDirectories);
  444. return di.next();
  445. }
  446. return false;
  447. }
  448. //==============================================================================
  449. File File::getNonexistentChildFile (const String& prefix_,
  450. const String& suffix,
  451. bool putNumbersInBrackets) const
  452. {
  453. File f (getChildFile (prefix_ + suffix));
  454. if (f.exists())
  455. {
  456. int num = 2;
  457. String prefix (prefix_);
  458. // remove any bracketed numbers that may already be on the end..
  459. if (prefix.trim().endsWithChar (')'))
  460. {
  461. putNumbersInBrackets = true;
  462. const int openBracks = prefix.lastIndexOfChar ('(');
  463. const int closeBracks = prefix.lastIndexOfChar (')');
  464. if (openBracks > 0
  465. && closeBracks > openBracks
  466. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  467. {
  468. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  469. prefix = prefix.substring (0, openBracks);
  470. }
  471. }
  472. // also use brackets if it ends in a digit.
  473. putNumbersInBrackets = putNumbersInBrackets
  474. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  475. do
  476. {
  477. String newName (prefix);
  478. if (putNumbersInBrackets)
  479. newName << '(' << num++ << ')';
  480. else
  481. newName << num++;
  482. f = getChildFile (newName + suffix);
  483. } while (f.exists());
  484. }
  485. return f;
  486. }
  487. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  488. {
  489. if (exists())
  490. return getParentDirectory()
  491. .getNonexistentChildFile (getFileNameWithoutExtension(),
  492. getFileExtension(),
  493. putNumbersInBrackets);
  494. return *this;
  495. }
  496. //==============================================================================
  497. String File::getFileExtension() const
  498. {
  499. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  500. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  501. return fullPath.substring (indexOfDot);
  502. return String::empty;
  503. }
  504. bool File::hasFileExtension (const String& possibleSuffix) const
  505. {
  506. if (possibleSuffix.isEmpty())
  507. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  508. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  509. if (semicolon >= 0)
  510. {
  511. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  512. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  513. }
  514. else
  515. {
  516. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  517. {
  518. if (possibleSuffix.startsWithChar ('.'))
  519. return true;
  520. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  521. if (dotPos >= 0)
  522. return fullPath [dotPos] == '.';
  523. }
  524. }
  525. return false;
  526. }
  527. File File::withFileExtension (const String& newExtension) const
  528. {
  529. if (fullPath.isEmpty())
  530. return File::nonexistent;
  531. String filePart (getFileName());
  532. int i = filePart.lastIndexOfChar ('.');
  533. if (i >= 0)
  534. filePart = filePart.substring (0, i);
  535. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  536. filePart << '.';
  537. return getSiblingFile (filePart + newExtension);
  538. }
  539. //==============================================================================
  540. bool File::startAsProcess (const String& parameters) const
  541. {
  542. return exists() && Process::openDocument (fullPath, parameters);
  543. }
  544. //==============================================================================
  545. FileInputStream* File::createInputStream() const
  546. {
  547. if (existsAsFile())
  548. return new FileInputStream (*this);
  549. return nullptr;
  550. }
  551. FileOutputStream* File::createOutputStream (const int bufferSize) const
  552. {
  553. ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  554. return out->failedToOpen() ? nullptr
  555. : out.release();
  556. }
  557. //==============================================================================
  558. bool File::appendData (const void* const dataToAppend,
  559. const int numberOfBytes) const
  560. {
  561. if (numberOfBytes <= 0)
  562. return true;
  563. FileOutputStream out (*this, 8192);
  564. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  565. }
  566. bool File::replaceWithData (const void* const dataToWrite,
  567. const int numberOfBytes) const
  568. {
  569. jassert (numberOfBytes >= 0); // a negative number of bytes??
  570. if (numberOfBytes <= 0)
  571. return deleteFile();
  572. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  573. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  574. return tempFile.overwriteTargetFileWithTemporary();
  575. }
  576. bool File::appendText (const String& text,
  577. const bool asUnicode,
  578. const bool writeUnicodeHeaderBytes) const
  579. {
  580. FileOutputStream out (*this);
  581. if (out.failedToOpen())
  582. return false;
  583. out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
  584. return true;
  585. }
  586. bool File::replaceWithText (const String& textToWrite,
  587. const bool asUnicode,
  588. const bool writeUnicodeHeaderBytes) const
  589. {
  590. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  591. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  592. return tempFile.overwriteTargetFileWithTemporary();
  593. }
  594. bool File::hasIdenticalContentTo (const File& other) const
  595. {
  596. if (other == *this)
  597. return true;
  598. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  599. {
  600. FileInputStream in1 (*this), in2 (other);
  601. if (in1.openedOk() && in2.openedOk())
  602. {
  603. const int bufferSize = 4096;
  604. HeapBlock <char> buffer1 (bufferSize), buffer2 (bufferSize);
  605. for (;;)
  606. {
  607. const int num1 = in1.read (buffer1, bufferSize);
  608. const int num2 = in2.read (buffer2, bufferSize);
  609. if (num1 != num2)
  610. break;
  611. if (num1 <= 0)
  612. return true;
  613. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  614. break;
  615. }
  616. }
  617. }
  618. return false;
  619. }
  620. //==============================================================================
  621. String File::createLegalPathName (const String& original)
  622. {
  623. String s (original);
  624. String start;
  625. if (s[1] == ':')
  626. {
  627. start = s.substring (0, 2);
  628. s = s.substring (2);
  629. }
  630. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  631. .substring (0, 1024);
  632. }
  633. String File::createLegalFileName (const String& original)
  634. {
  635. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  636. const int maxLength = 128; // only the length of the filename, not the whole path
  637. const int len = s.length();
  638. if (len > maxLength)
  639. {
  640. const int lastDot = s.lastIndexOfChar ('.');
  641. if (lastDot > jmax (0, len - 12))
  642. {
  643. s = s.substring (0, maxLength - (len - lastDot))
  644. + s.substring (lastDot);
  645. }
  646. else
  647. {
  648. s = s.substring (0, maxLength);
  649. }
  650. }
  651. return s;
  652. }
  653. //==============================================================================
  654. static int countNumberOfSeparators (String::CharPointerType s)
  655. {
  656. int num = 0;
  657. for (;;)
  658. {
  659. const juce_wchar c = s.getAndAdvance();
  660. if (c == 0)
  661. break;
  662. if (c == File::separator)
  663. ++num;
  664. }
  665. return num;
  666. }
  667. String File::getRelativePathFrom (const File& dir) const
  668. {
  669. String thisPath (fullPath);
  670. while (thisPath.endsWithChar (separator))
  671. thisPath = thisPath.dropLastCharacters (1);
  672. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  673. : dir.fullPath));
  674. int commonBitLength = 0;
  675. String::CharPointerType thisPathAfterCommon (thisPath.getCharPointer());
  676. String::CharPointerType dirPathAfterCommon (dirPath.getCharPointer());
  677. {
  678. String::CharPointerType thisPathIter (thisPath.getCharPointer());
  679. String::CharPointerType dirPathIter (dirPath.getCharPointer());
  680. for (int i = 0;;)
  681. {
  682. const juce_wchar c1 = thisPathIter.getAndAdvance();
  683. const juce_wchar c2 = dirPathIter.getAndAdvance();
  684. #if NAMES_ARE_CASE_SENSITIVE
  685. if (c1 != c2
  686. #else
  687. if ((c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
  688. #endif
  689. || c1 == 0)
  690. break;
  691. ++i;
  692. if (c1 == separator)
  693. {
  694. thisPathAfterCommon = thisPathIter;
  695. dirPathAfterCommon = dirPathIter;
  696. commonBitLength = i;
  697. }
  698. }
  699. }
  700. // if the only common bit is the root, then just return the full path..
  701. if (commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == separator))
  702. return fullPath;
  703. const int numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  704. if (numUpDirectoriesNeeded == 0)
  705. return thisPathAfterCommon;
  706. #if JUCE_WINDOWS
  707. String s (String::repeatedString ("..\\", numUpDirectoriesNeeded));
  708. #else
  709. String s (String::repeatedString ("../", numUpDirectoriesNeeded));
  710. #endif
  711. s.appendCharPointer (thisPathAfterCommon);
  712. return s;
  713. }
  714. //==============================================================================
  715. File File::createTempFile (const String& fileNameEnding)
  716. {
  717. const File tempFile (getSpecialLocation (tempDirectory)
  718. .getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
  719. .withFileExtension (fileNameEnding));
  720. if (tempFile.exists())
  721. return createTempFile (fileNameEnding);
  722. return tempFile;
  723. }
  724. //==============================================================================
  725. #if JUCE_UNIT_TESTS
  726. class FileTests : public UnitTest
  727. {
  728. public:
  729. FileTests() : UnitTest ("Files") {}
  730. void runTest()
  731. {
  732. beginTest ("Reading");
  733. const File home (File::getSpecialLocation (File::userHomeDirectory));
  734. const File temp (File::getSpecialLocation (File::tempDirectory));
  735. expect (! File::nonexistent.exists());
  736. expect (home.isDirectory());
  737. expect (home.exists());
  738. expect (! home.existsAsFile());
  739. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  740. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  741. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  742. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  743. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  744. expect (home.getVolumeTotalSize() > 1024 * 1024);
  745. expect (home.getBytesFreeOnVolume() > 0);
  746. expect (! home.isHidden());
  747. expect (home.isOnHardDisk());
  748. expect (! home.isOnCDRomDrive());
  749. expect (File::getCurrentWorkingDirectory().exists());
  750. expect (home.setAsCurrentWorkingDirectory());
  751. expect (File::getCurrentWorkingDirectory() == home);
  752. {
  753. Array<File> roots;
  754. File::findFileSystemRoots (roots);
  755. expect (roots.size() > 0);
  756. int numRootsExisting = 0;
  757. for (int i = 0; i < roots.size(); ++i)
  758. if (roots[i].exists())
  759. ++numRootsExisting;
  760. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  761. expect (numRootsExisting > 0);
  762. }
  763. beginTest ("Writing");
  764. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  765. expect (demoFolder.deleteRecursively());
  766. expect (demoFolder.createDirectory());
  767. expect (demoFolder.isDirectory());
  768. expect (demoFolder.getParentDirectory() == temp);
  769. expect (temp.isDirectory());
  770. {
  771. Array<File> files;
  772. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  773. expect (files.contains (demoFolder));
  774. }
  775. {
  776. Array<File> files;
  777. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  778. expect (files.contains (demoFolder));
  779. }
  780. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  781. expect (tempFile.getFileExtension() == ".txt");
  782. expect (tempFile.hasFileExtension (".txt"));
  783. expect (tempFile.hasFileExtension ("txt"));
  784. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  785. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("abc;xyz;foo"));
  786. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("xyz;foo"));
  787. expect (! tempFile.withFileExtension ("h").hasFileExtension ("bar;foo;xx"));
  788. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  789. expect (tempFile.hasWriteAccess());
  790. {
  791. FileOutputStream fo (tempFile);
  792. fo.write ("0123456789", 10);
  793. }
  794. expect (tempFile.exists());
  795. expect (tempFile.getSize() == 10);
  796. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  797. expectEquals (tempFile.loadFileAsString(), String ("0123456789"));
  798. expect (! demoFolder.containsSubDirectories());
  799. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  800. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  801. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  802. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  803. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  804. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  805. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  806. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  807. expect (demoFolder.containsSubDirectories());
  808. expect (tempFile.hasWriteAccess());
  809. tempFile.setReadOnly (true);
  810. expect (! tempFile.hasWriteAccess());
  811. tempFile.setReadOnly (false);
  812. expect (tempFile.hasWriteAccess());
  813. Time t (Time::getCurrentTime());
  814. tempFile.setLastModificationTime (t);
  815. Time t2 = tempFile.getLastModificationTime();
  816. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  817. {
  818. MemoryBlock mb;
  819. tempFile.loadFileAsData (mb);
  820. expect (mb.getSize() == 10);
  821. expect (mb[0] == '0');
  822. }
  823. {
  824. expect (tempFile.getSize() == 10);
  825. FileOutputStream fo (tempFile);
  826. expect (fo.openedOk());
  827. expect (fo.setPosition (7));
  828. expect (fo.truncate().wasOk());
  829. expect (tempFile.getSize() == 7);
  830. fo.write ("789", 3);
  831. fo.flush();
  832. expect (tempFile.getSize() == 10);
  833. }
  834. beginTest ("Memory-mapped files");
  835. {
  836. MemoryMappedFile mmf (tempFile, MemoryMappedFile::readOnly);
  837. expect (mmf.getSize() == 10);
  838. expect (mmf.getData() != nullptr);
  839. expect (memcmp (mmf.getData(), "0123456789", 10) == 0);
  840. }
  841. {
  842. const File tempFile2 (tempFile.getNonexistentSibling (false));
  843. expect (tempFile2.create());
  844. expect (tempFile2.appendData ("xxxxxxxxxx", 10));
  845. {
  846. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  847. expect (mmf.getSize() == 10);
  848. expect (mmf.getData() != nullptr);
  849. memcpy (mmf.getData(), "abcdefghij", 10);
  850. }
  851. {
  852. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  853. expect (mmf.getSize() == 10);
  854. expect (mmf.getData() != nullptr);
  855. expect (memcmp (mmf.getData(), "abcdefghij", 10) == 0);
  856. }
  857. expect (tempFile2.deleteFile());
  858. }
  859. beginTest ("More writing");
  860. expect (tempFile.appendData ("abcdefghij", 10));
  861. expect (tempFile.getSize() == 20);
  862. expect (tempFile.replaceWithData ("abcdefghij", 10));
  863. expect (tempFile.getSize() == 10);
  864. File tempFile2 (tempFile.getNonexistentSibling (false));
  865. expect (tempFile.copyFileTo (tempFile2));
  866. expect (tempFile2.exists());
  867. expect (tempFile2.hasIdenticalContentTo (tempFile));
  868. expect (tempFile.deleteFile());
  869. expect (! tempFile.exists());
  870. expect (tempFile2.moveFileTo (tempFile));
  871. expect (tempFile.exists());
  872. expect (! tempFile2.exists());
  873. expect (demoFolder.deleteRecursively());
  874. expect (! demoFolder.exists());
  875. }
  876. };
  877. static FileTests fileUnitTests;
  878. #endif