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.

1288 lines
43KB

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