Audio plugin host https://kx.studio/carla
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.

1211 lines
40KB

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