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.

1062 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) noexcept
  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. static int compareFilenames (const String& name1, const String& name2) noexcept
  148. {
  149. #if NAMES_ARE_CASE_SENSITIVE
  150. return name1.compare (name2);
  151. #else
  152. return name1.compareIgnoreCase (name2);
  153. #endif
  154. }
  155. bool File::operator== (const File& other) const { return compareFilenames (fullPath, other.fullPath) == 0; }
  156. bool File::operator!= (const File& other) const { return compareFilenames (fullPath, other.fullPath) != 0; }
  157. bool File::operator< (const File& other) const { return compareFilenames (fullPath, other.fullPath) < 0; }
  158. bool File::operator> (const File& other) const { return compareFilenames (fullPath, other.fullPath) > 0; }
  159. //==============================================================================
  160. bool File::setReadOnly (const bool shouldBeReadOnly,
  161. const bool applyRecursively) const
  162. {
  163. bool worked = true;
  164. if (applyRecursively && isDirectory())
  165. {
  166. Array <File> subFiles;
  167. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  168. for (int i = subFiles.size(); --i >= 0;)
  169. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  170. }
  171. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  172. }
  173. bool File::deleteRecursively() const
  174. {
  175. bool worked = true;
  176. if (isDirectory())
  177. {
  178. Array<File> subFiles;
  179. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  180. for (int i = subFiles.size(); --i >= 0;)
  181. worked = subFiles.getReference(i).deleteRecursively() && worked;
  182. }
  183. return deleteFile() && worked;
  184. }
  185. bool File::moveFileTo (const File& newFile) const
  186. {
  187. if (newFile.fullPath == fullPath)
  188. return true;
  189. #if ! NAMES_ARE_CASE_SENSITIVE
  190. if (*this != newFile)
  191. #endif
  192. if (! newFile.deleteFile())
  193. return false;
  194. return moveInternal (newFile);
  195. }
  196. bool File::copyFileTo (const File& newFile) const
  197. {
  198. return (*this == newFile)
  199. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  200. }
  201. bool File::copyDirectoryTo (const File& newDirectory) const
  202. {
  203. if (isDirectory() && newDirectory.createDirectory())
  204. {
  205. Array<File> subFiles;
  206. findChildFiles (subFiles, File::findFiles, false);
  207. for (int i = 0; i < subFiles.size(); ++i)
  208. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  209. return false;
  210. subFiles.clear();
  211. findChildFiles (subFiles, File::findDirectories, false);
  212. for (int i = 0; i < subFiles.size(); ++i)
  213. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  214. return false;
  215. return true;
  216. }
  217. return false;
  218. }
  219. //==============================================================================
  220. String File::getPathUpToLastSlash() const
  221. {
  222. const int lastSlash = fullPath.lastIndexOfChar (separator);
  223. if (lastSlash > 0)
  224. return fullPath.substring (0, lastSlash);
  225. else if (lastSlash == 0)
  226. return separatorString;
  227. else
  228. return fullPath;
  229. }
  230. File File::getParentDirectory() const
  231. {
  232. File f;
  233. f.fullPath = getPathUpToLastSlash();
  234. return f;
  235. }
  236. //==============================================================================
  237. String File::getFileName() const
  238. {
  239. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  240. }
  241. String File::getFileNameWithoutExtension() const
  242. {
  243. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  244. const int lastDot = fullPath.lastIndexOfChar ('.');
  245. if (lastDot > lastSlash)
  246. return fullPath.substring (lastSlash, lastDot);
  247. else
  248. return fullPath.substring (lastSlash);
  249. }
  250. bool File::isAChildOf (const File& potentialParent) const
  251. {
  252. if (potentialParent == File::nonexistent)
  253. return false;
  254. const String ourPath (getPathUpToLastSlash());
  255. if (compareFilenames (potentialParent.fullPath, ourPath) == 0)
  256. return true;
  257. if (potentialParent.fullPath.length() >= ourPath.length())
  258. return false;
  259. return getParentDirectory().isAChildOf (potentialParent);
  260. }
  261. int File::hashCode() const { return fullPath.hashCode(); }
  262. int64 File::hashCode64() const { return fullPath.hashCode64(); }
  263. //==============================================================================
  264. bool File::isAbsolutePath (const String& path)
  265. {
  266. return path.startsWithChar (separator)
  267. #if JUCE_WINDOWS
  268. || (path.isNotEmpty() && path[1] == ':');
  269. #else
  270. || path.startsWithChar ('~');
  271. #endif
  272. }
  273. File File::getChildFile (String relativePath) const
  274. {
  275. if (isAbsolutePath (relativePath))
  276. return File (relativePath);
  277. String path (fullPath);
  278. // It's relative, so remove any ../ or ./ bits at the start..
  279. if (relativePath[0] == '.')
  280. {
  281. #if JUCE_WINDOWS
  282. relativePath = relativePath.replaceCharacter ('/', '\\');
  283. #endif
  284. while (relativePath[0] == '.')
  285. {
  286. const juce_wchar secondChar = relativePath[1];
  287. if (secondChar == '.')
  288. {
  289. const juce_wchar thirdChar = relativePath[2];
  290. if (thirdChar == 0 || thirdChar == separator)
  291. {
  292. const int lastSlash = path.lastIndexOfChar (separator);
  293. if (lastSlash >= 0)
  294. path = path.substring (0, lastSlash);
  295. relativePath = relativePath.substring (3);
  296. }
  297. else
  298. {
  299. break;
  300. }
  301. }
  302. else if (secondChar == separator)
  303. {
  304. relativePath = relativePath.substring (2);
  305. }
  306. else
  307. {
  308. break;
  309. }
  310. }
  311. }
  312. return File (addTrailingSeparator (path) + relativePath);
  313. }
  314. File File::getSiblingFile (const String& fileName) const
  315. {
  316. return getParentDirectory().getChildFile (fileName);
  317. }
  318. //==============================================================================
  319. String File::descriptionOfSizeInBytes (const int64 bytes)
  320. {
  321. const char* suffix;
  322. double divisor = 0;
  323. if (bytes == 1) { suffix = " byte"; }
  324. else if (bytes < 1024) { suffix = " bytes"; }
  325. else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
  326. else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
  327. else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
  328. return (divisor > 0 ? String (bytes / divisor, 1) : String (bytes)) + suffix;
  329. }
  330. //==============================================================================
  331. Result File::create() const
  332. {
  333. if (exists())
  334. return Result::ok();
  335. const File parentDir (getParentDirectory());
  336. if (parentDir == *this)
  337. return Result::fail ("Cannot create parent directory");
  338. Result r (parentDir.createDirectory());
  339. if (r.wasOk())
  340. {
  341. FileOutputStream fo (*this, 8);
  342. r = fo.getStatus();
  343. }
  344. return r;
  345. }
  346. Result File::createDirectory() const
  347. {
  348. if (isDirectory())
  349. return Result::ok();
  350. const File parentDir (getParentDirectory());
  351. if (parentDir == *this)
  352. return Result::fail ("Cannot create parent directory");
  353. Result r (parentDir.createDirectory());
  354. if (r.wasOk())
  355. r = createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  356. return r;
  357. }
  358. //==============================================================================
  359. Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); }
  360. Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); }
  361. Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); }
  362. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  363. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  364. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  365. //==============================================================================
  366. bool File::loadFileAsData (MemoryBlock& destBlock) const
  367. {
  368. if (! existsAsFile())
  369. return false;
  370. FileInputStream in (*this);
  371. return in.openedOk() && getSize() == in.readIntoMemoryBlock (destBlock);
  372. }
  373. String File::loadFileAsString() const
  374. {
  375. if (! existsAsFile())
  376. return String::empty;
  377. FileInputStream in (*this);
  378. return in.openedOk() ? in.readEntireStreamAsString()
  379. : String::empty;
  380. }
  381. void File::readLines (StringArray& destLines) const
  382. {
  383. destLines.addLines (loadFileAsString());
  384. }
  385. //==============================================================================
  386. int File::findChildFiles (Array<File>& results,
  387. const int whatToLookFor,
  388. const bool searchRecursively,
  389. const String& wildCardPattern) const
  390. {
  391. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  392. int total = 0;
  393. while (di.next())
  394. {
  395. results.add (di.getFile());
  396. ++total;
  397. }
  398. return total;
  399. }
  400. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  401. {
  402. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  403. int total = 0;
  404. while (di.next())
  405. ++total;
  406. return total;
  407. }
  408. bool File::containsSubDirectories() const
  409. {
  410. if (! isDirectory())
  411. return false;
  412. DirectoryIterator di (*this, false, "*", findDirectories);
  413. return di.next();
  414. }
  415. //==============================================================================
  416. File File::getNonexistentChildFile (const String& suggestedPrefix,
  417. const String& suffix,
  418. bool putNumbersInBrackets) const
  419. {
  420. File f (getChildFile (suggestedPrefix + suffix));
  421. if (f.exists())
  422. {
  423. int number = 1;
  424. String prefix (suggestedPrefix);
  425. // remove any bracketed numbers that may already be on the end..
  426. if (prefix.trim().endsWithChar (')'))
  427. {
  428. putNumbersInBrackets = true;
  429. const int openBracks = prefix.lastIndexOfChar ('(');
  430. const int closeBracks = prefix.lastIndexOfChar (')');
  431. if (openBracks > 0
  432. && closeBracks > openBracks
  433. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  434. {
  435. number = prefix.substring (openBracks + 1, closeBracks).getIntValue();
  436. prefix = prefix.substring (0, openBracks);
  437. }
  438. }
  439. // also use brackets if it ends in a digit.
  440. putNumbersInBrackets = putNumbersInBrackets
  441. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  442. do
  443. {
  444. String newName (prefix);
  445. if (putNumbersInBrackets)
  446. newName << '(' << ++number << ')';
  447. else
  448. newName << ++number;
  449. f = getChildFile (newName + suffix);
  450. } while (f.exists());
  451. }
  452. return f;
  453. }
  454. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  455. {
  456. if (! exists())
  457. return *this;
  458. return getParentDirectory().getNonexistentChildFile (getFileNameWithoutExtension(),
  459. getFileExtension(),
  460. putNumbersInBrackets);
  461. }
  462. //==============================================================================
  463. String File::getFileExtension() const
  464. {
  465. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  466. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  467. return fullPath.substring (indexOfDot);
  468. return String::empty;
  469. }
  470. bool File::hasFileExtension (const String& possibleSuffix) const
  471. {
  472. if (possibleSuffix.isEmpty())
  473. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  474. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  475. if (semicolon >= 0)
  476. {
  477. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  478. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  479. }
  480. else
  481. {
  482. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  483. {
  484. if (possibleSuffix.startsWithChar ('.'))
  485. return true;
  486. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  487. if (dotPos >= 0)
  488. return fullPath [dotPos] == '.';
  489. }
  490. }
  491. return false;
  492. }
  493. File File::withFileExtension (const String& newExtension) const
  494. {
  495. if (fullPath.isEmpty())
  496. return File::nonexistent;
  497. String filePart (getFileName());
  498. const int i = filePart.lastIndexOfChar ('.');
  499. if (i >= 0)
  500. filePart = filePart.substring (0, i);
  501. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  502. filePart << '.';
  503. return getSiblingFile (filePart + newExtension);
  504. }
  505. //==============================================================================
  506. bool File::startAsProcess (const String& parameters) const
  507. {
  508. return exists() && Process::openDocument (fullPath, parameters);
  509. }
  510. //==============================================================================
  511. FileInputStream* File::createInputStream() const
  512. {
  513. if (existsAsFile())
  514. return new FileInputStream (*this);
  515. return nullptr;
  516. }
  517. FileOutputStream* File::createOutputStream (const int bufferSize) const
  518. {
  519. ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  520. return out->failedToOpen() ? nullptr
  521. : out.release();
  522. }
  523. //==============================================================================
  524. bool File::appendData (const void* const dataToAppend,
  525. const int numberOfBytes) const
  526. {
  527. if (numberOfBytes <= 0)
  528. return true;
  529. FileOutputStream out (*this, 8192);
  530. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  531. }
  532. bool File::replaceWithData (const void* const dataToWrite,
  533. const int numberOfBytes) const
  534. {
  535. jassert (numberOfBytes >= 0); // a negative number of bytes??
  536. if (numberOfBytes <= 0)
  537. return deleteFile();
  538. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  539. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  540. return tempFile.overwriteTargetFileWithTemporary();
  541. }
  542. bool File::appendText (const String& text,
  543. const bool asUnicode,
  544. const bool writeUnicodeHeaderBytes) const
  545. {
  546. FileOutputStream out (*this);
  547. if (out.failedToOpen())
  548. return false;
  549. out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
  550. return true;
  551. }
  552. bool File::replaceWithText (const String& textToWrite,
  553. const bool asUnicode,
  554. const bool writeUnicodeHeaderBytes) const
  555. {
  556. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  557. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  558. return tempFile.overwriteTargetFileWithTemporary();
  559. }
  560. bool File::hasIdenticalContentTo (const File& other) const
  561. {
  562. if (other == *this)
  563. return true;
  564. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  565. {
  566. FileInputStream in1 (*this), in2 (other);
  567. if (in1.openedOk() && in2.openedOk())
  568. {
  569. const int bufferSize = 4096;
  570. HeapBlock <char> buffer1 (bufferSize), buffer2 (bufferSize);
  571. for (;;)
  572. {
  573. const int num1 = in1.read (buffer1, bufferSize);
  574. const int num2 = in2.read (buffer2, bufferSize);
  575. if (num1 != num2)
  576. break;
  577. if (num1 <= 0)
  578. return true;
  579. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  580. break;
  581. }
  582. }
  583. }
  584. return false;
  585. }
  586. //==============================================================================
  587. String File::createLegalPathName (const String& original)
  588. {
  589. String s (original);
  590. String start;
  591. if (s[1] == ':')
  592. {
  593. start = s.substring (0, 2);
  594. s = s.substring (2);
  595. }
  596. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  597. .substring (0, 1024);
  598. }
  599. String File::createLegalFileName (const String& original)
  600. {
  601. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  602. const int maxLength = 128; // only the length of the filename, not the whole path
  603. const int len = s.length();
  604. if (len > maxLength)
  605. {
  606. const int lastDot = s.lastIndexOfChar ('.');
  607. if (lastDot > jmax (0, len - 12))
  608. {
  609. s = s.substring (0, maxLength - (len - lastDot))
  610. + s.substring (lastDot);
  611. }
  612. else
  613. {
  614. s = s.substring (0, maxLength);
  615. }
  616. }
  617. return s;
  618. }
  619. //==============================================================================
  620. static int countNumberOfSeparators (String::CharPointerType s)
  621. {
  622. int num = 0;
  623. for (;;)
  624. {
  625. const juce_wchar c = s.getAndAdvance();
  626. if (c == 0)
  627. break;
  628. if (c == File::separator)
  629. ++num;
  630. }
  631. return num;
  632. }
  633. String File::getRelativePathFrom (const File& dir) const
  634. {
  635. String thisPath (fullPath);
  636. while (thisPath.endsWithChar (separator))
  637. thisPath = thisPath.dropLastCharacters (1);
  638. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  639. : dir.fullPath));
  640. int commonBitLength = 0;
  641. String::CharPointerType thisPathAfterCommon (thisPath.getCharPointer());
  642. String::CharPointerType dirPathAfterCommon (dirPath.getCharPointer());
  643. {
  644. String::CharPointerType thisPathIter (thisPath.getCharPointer());
  645. String::CharPointerType dirPathIter (dirPath.getCharPointer());
  646. for (int i = 0;;)
  647. {
  648. const juce_wchar c1 = thisPathIter.getAndAdvance();
  649. const juce_wchar c2 = dirPathIter.getAndAdvance();
  650. #if NAMES_ARE_CASE_SENSITIVE
  651. if (c1 != c2
  652. #else
  653. if ((c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
  654. #endif
  655. || c1 == 0)
  656. break;
  657. ++i;
  658. if (c1 == separator)
  659. {
  660. thisPathAfterCommon = thisPathIter;
  661. dirPathAfterCommon = dirPathIter;
  662. commonBitLength = i;
  663. }
  664. }
  665. }
  666. // if the only common bit is the root, then just return the full path..
  667. if (commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == separator))
  668. return fullPath;
  669. const int numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  670. if (numUpDirectoriesNeeded == 0)
  671. return thisPathAfterCommon;
  672. #if JUCE_WINDOWS
  673. String s (String::repeatedString ("..\\", numUpDirectoriesNeeded));
  674. #else
  675. String s (String::repeatedString ("../", numUpDirectoriesNeeded));
  676. #endif
  677. s.appendCharPointer (thisPathAfterCommon);
  678. return s;
  679. }
  680. //==============================================================================
  681. File File::createTempFile (const String& fileNameEnding)
  682. {
  683. const File tempFile (getSpecialLocation (tempDirectory)
  684. .getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
  685. .withFileExtension (fileNameEnding));
  686. if (tempFile.exists())
  687. return createTempFile (fileNameEnding);
  688. return tempFile;
  689. }
  690. //==============================================================================
  691. #if JUCE_UNIT_TESTS
  692. class FileTests : public UnitTest
  693. {
  694. public:
  695. FileTests() : UnitTest ("Files") {}
  696. void runTest()
  697. {
  698. beginTest ("Reading");
  699. const File home (File::getSpecialLocation (File::userHomeDirectory));
  700. const File temp (File::getSpecialLocation (File::tempDirectory));
  701. expect (! File::nonexistent.exists());
  702. expect (home.isDirectory());
  703. expect (home.exists());
  704. expect (! home.existsAsFile());
  705. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  706. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  707. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  708. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  709. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  710. expect (home.getVolumeTotalSize() > 1024 * 1024);
  711. expect (home.getBytesFreeOnVolume() > 0);
  712. expect (! home.isHidden());
  713. expect (home.isOnHardDisk());
  714. expect (! home.isOnCDRomDrive());
  715. expect (File::getCurrentWorkingDirectory().exists());
  716. expect (home.setAsCurrentWorkingDirectory());
  717. expect (File::getCurrentWorkingDirectory() == home);
  718. {
  719. Array<File> roots;
  720. File::findFileSystemRoots (roots);
  721. expect (roots.size() > 0);
  722. int numRootsExisting = 0;
  723. for (int i = 0; i < roots.size(); ++i)
  724. if (roots[i].exists())
  725. ++numRootsExisting;
  726. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  727. expect (numRootsExisting > 0);
  728. }
  729. beginTest ("Writing");
  730. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  731. expect (demoFolder.deleteRecursively());
  732. expect (demoFolder.createDirectory());
  733. expect (demoFolder.isDirectory());
  734. expect (demoFolder.getParentDirectory() == temp);
  735. expect (temp.isDirectory());
  736. {
  737. Array<File> files;
  738. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  739. expect (files.contains (demoFolder));
  740. }
  741. {
  742. Array<File> files;
  743. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  744. expect (files.contains (demoFolder));
  745. }
  746. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  747. expect (tempFile.getFileExtension() == ".txt");
  748. expect (tempFile.hasFileExtension (".txt"));
  749. expect (tempFile.hasFileExtension ("txt"));
  750. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  751. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("abc;xyz;foo"));
  752. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("xyz;foo"));
  753. expect (! tempFile.withFileExtension ("h").hasFileExtension ("bar;foo;xx"));
  754. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  755. expect (tempFile.hasWriteAccess());
  756. {
  757. FileOutputStream fo (tempFile);
  758. fo.write ("0123456789", 10);
  759. }
  760. expect (tempFile.exists());
  761. expect (tempFile.getSize() == 10);
  762. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  763. expectEquals (tempFile.loadFileAsString(), String ("0123456789"));
  764. expect (! demoFolder.containsSubDirectories());
  765. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  766. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  767. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  768. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  769. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  770. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  771. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  772. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  773. expect (demoFolder.containsSubDirectories());
  774. expect (tempFile.hasWriteAccess());
  775. tempFile.setReadOnly (true);
  776. expect (! tempFile.hasWriteAccess());
  777. tempFile.setReadOnly (false);
  778. expect (tempFile.hasWriteAccess());
  779. Time t (Time::getCurrentTime());
  780. tempFile.setLastModificationTime (t);
  781. Time t2 = tempFile.getLastModificationTime();
  782. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  783. {
  784. MemoryBlock mb;
  785. tempFile.loadFileAsData (mb);
  786. expect (mb.getSize() == 10);
  787. expect (mb[0] == '0');
  788. }
  789. {
  790. expect (tempFile.getSize() == 10);
  791. FileOutputStream fo (tempFile);
  792. expect (fo.openedOk());
  793. expect (fo.setPosition (7));
  794. expect (fo.truncate().wasOk());
  795. expect (tempFile.getSize() == 7);
  796. fo.write ("789", 3);
  797. fo.flush();
  798. expect (tempFile.getSize() == 10);
  799. }
  800. beginTest ("Memory-mapped files");
  801. {
  802. MemoryMappedFile mmf (tempFile, MemoryMappedFile::readOnly);
  803. expect (mmf.getSize() == 10);
  804. expect (mmf.getData() != nullptr);
  805. expect (memcmp (mmf.getData(), "0123456789", 10) == 0);
  806. }
  807. {
  808. const File tempFile2 (tempFile.getNonexistentSibling (false));
  809. expect (tempFile2.create());
  810. expect (tempFile2.appendData ("xxxxxxxxxx", 10));
  811. {
  812. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  813. expect (mmf.getSize() == 10);
  814. expect (mmf.getData() != nullptr);
  815. memcpy (mmf.getData(), "abcdefghij", 10);
  816. }
  817. {
  818. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  819. expect (mmf.getSize() == 10);
  820. expect (mmf.getData() != nullptr);
  821. expect (memcmp (mmf.getData(), "abcdefghij", 10) == 0);
  822. }
  823. expect (tempFile2.deleteFile());
  824. }
  825. beginTest ("More writing");
  826. expect (tempFile.appendData ("abcdefghij", 10));
  827. expect (tempFile.getSize() == 20);
  828. expect (tempFile.replaceWithData ("abcdefghij", 10));
  829. expect (tempFile.getSize() == 10);
  830. File tempFile2 (tempFile.getNonexistentSibling (false));
  831. expect (tempFile.copyFileTo (tempFile2));
  832. expect (tempFile2.exists());
  833. expect (tempFile2.hasIdenticalContentTo (tempFile));
  834. expect (tempFile.deleteFile());
  835. expect (! tempFile.exists());
  836. expect (tempFile2.moveFileTo (tempFile));
  837. expect (tempFile.exists());
  838. expect (! tempFile2.exists());
  839. expect (demoFolder.deleteRecursively());
  840. expect (! demoFolder.exists());
  841. }
  842. };
  843. static FileTests fileUnitTests;
  844. #endif