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.

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