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.

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