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.

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