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.

1154 lines
38KB

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