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.

1206 lines
40KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. File::File (const String& fullPathName)
  22. : fullPath (parseAbsolutePath (fullPathName))
  23. {
  24. }
  25. File File::createFileWithoutCheckingPath (const String& path) noexcept
  26. {
  27. File f;
  28. f.fullPath = path;
  29. return f;
  30. }
  31. File::File (const File& other)
  32. : fullPath (other.fullPath)
  33. {
  34. }
  35. File& File::operator= (const String& newPath)
  36. {
  37. fullPath = parseAbsolutePath (newPath);
  38. return *this;
  39. }
  40. File& File::operator= (const File& other)
  41. {
  42. fullPath = other.fullPath;
  43. return *this;
  44. }
  45. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  46. File::File (File&& other) noexcept
  47. : fullPath (static_cast<String&&> (other.fullPath))
  48. {
  49. }
  50. File& File::operator= (File&& other) noexcept
  51. {
  52. fullPath = static_cast<String&&> (other.fullPath);
  53. return *this;
  54. }
  55. #endif
  56. #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. // also use brackets if it ends in a digit.
  504. putNumbersInBrackets = putNumbersInBrackets
  505. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  506. do
  507. {
  508. String newName (prefix);
  509. if (putNumbersInBrackets)
  510. newName << '(' << ++number << ')';
  511. else
  512. newName << ++number;
  513. f = getChildFile (newName + suffix);
  514. } while (f.exists());
  515. }
  516. return f;
  517. }
  518. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  519. {
  520. if (! exists())
  521. return *this;
  522. return getParentDirectory().getNonexistentChildFile (getFileNameWithoutExtension(),
  523. getFileExtension(),
  524. putNumbersInBrackets);
  525. }
  526. //==============================================================================
  527. String File::getFileExtension() const
  528. {
  529. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  530. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  531. return fullPath.substring (indexOfDot);
  532. return String();
  533. }
  534. bool File::hasFileExtension (StringRef possibleSuffix) const
  535. {
  536. if (possibleSuffix.isEmpty())
  537. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  538. const int semicolon = possibleSuffix.text.indexOf ((juce_wchar) ';');
  539. if (semicolon >= 0)
  540. return hasFileExtension (String (possibleSuffix.text).substring (0, semicolon).trimEnd())
  541. || hasFileExtension ((possibleSuffix.text + (semicolon + 1)).findEndOfWhitespace());
  542. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  543. {
  544. if (possibleSuffix.text[0] == '.')
  545. return true;
  546. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  547. if (dotPos >= 0)
  548. return fullPath [dotPos] == '.';
  549. }
  550. return false;
  551. }
  552. File File::withFileExtension (StringRef newExtension) const
  553. {
  554. if (fullPath.isEmpty())
  555. return File();
  556. String filePart (getFileName());
  557. const int i = filePart.lastIndexOfChar ('.');
  558. if (i >= 0)
  559. filePart = filePart.substring (0, i);
  560. if (newExtension.isNotEmpty() && newExtension.text[0] != '.')
  561. filePart << '.';
  562. return getSiblingFile (filePart + newExtension);
  563. }
  564. //==============================================================================
  565. bool File::startAsProcess (const String& parameters) const
  566. {
  567. return exists() && Process::openDocument (fullPath, parameters);
  568. }
  569. //==============================================================================
  570. FileInputStream* File::createInputStream() const
  571. {
  572. ScopedPointer<FileInputStream> fin (new FileInputStream (*this));
  573. if (fin->openedOk())
  574. return fin.release();
  575. return nullptr;
  576. }
  577. FileOutputStream* File::createOutputStream (const size_t bufferSize) const
  578. {
  579. ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  580. return out->failedToOpen() ? nullptr
  581. : out.release();
  582. }
  583. //==============================================================================
  584. bool File::appendData (const void* const dataToAppend,
  585. const size_t numberOfBytes) const
  586. {
  587. jassert (((ssize_t) numberOfBytes) >= 0);
  588. if (numberOfBytes == 0)
  589. return true;
  590. FileOutputStream out (*this, 8192);
  591. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  592. }
  593. bool File::replaceWithData (const void* const dataToWrite,
  594. const size_t numberOfBytes) const
  595. {
  596. if (numberOfBytes == 0)
  597. return deleteFile();
  598. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  599. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  600. return tempFile.overwriteTargetFileWithTemporary();
  601. }
  602. bool File::appendText (const String& text,
  603. const bool asUnicode,
  604. const bool writeUnicodeHeaderBytes) const
  605. {
  606. FileOutputStream out (*this);
  607. if (out.failedToOpen())
  608. return false;
  609. out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
  610. return true;
  611. }
  612. bool File::replaceWithText (const String& textToWrite,
  613. const bool asUnicode,
  614. const bool writeUnicodeHeaderBytes) const
  615. {
  616. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  617. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  618. return tempFile.overwriteTargetFileWithTemporary();
  619. }
  620. bool File::hasIdenticalContentTo (const File& other) const
  621. {
  622. if (other == *this)
  623. return true;
  624. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  625. {
  626. FileInputStream in1 (*this), in2 (other);
  627. if (in1.openedOk() && in2.openedOk())
  628. {
  629. const int bufferSize = 4096;
  630. HeapBlock<char> buffer1 (bufferSize), buffer2 (bufferSize);
  631. for (;;)
  632. {
  633. const int num1 = in1.read (buffer1, bufferSize);
  634. const int num2 = in2.read (buffer2, bufferSize);
  635. if (num1 != num2)
  636. break;
  637. if (num1 <= 0)
  638. return true;
  639. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  640. break;
  641. }
  642. }
  643. }
  644. return false;
  645. }
  646. //==============================================================================
  647. String File::createLegalPathName (const String& original)
  648. {
  649. String s (original);
  650. String start;
  651. if (s.isNotEmpty() && s[1] == ':')
  652. {
  653. start = s.substring (0, 2);
  654. s = s.substring (2);
  655. }
  656. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  657. .substring (0, 1024);
  658. }
  659. String File::createLegalFileName (const String& original)
  660. {
  661. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  662. const int maxLength = 128; // only the length of the filename, not the whole path
  663. const int len = s.length();
  664. if (len > maxLength)
  665. {
  666. const int lastDot = s.lastIndexOfChar ('.');
  667. if (lastDot > jmax (0, len - 12))
  668. {
  669. s = s.substring (0, maxLength - (len - lastDot))
  670. + s.substring (lastDot);
  671. }
  672. else
  673. {
  674. s = s.substring (0, maxLength);
  675. }
  676. }
  677. return s;
  678. }
  679. //==============================================================================
  680. static int countNumberOfSeparators (String::CharPointerType s)
  681. {
  682. int num = 0;
  683. for (;;)
  684. {
  685. const juce_wchar c = s.getAndAdvance();
  686. if (c == 0)
  687. break;
  688. if (c == File::separator)
  689. ++num;
  690. }
  691. return num;
  692. }
  693. String File::getRelativePathFrom (const File& dir) const
  694. {
  695. String thisPath (fullPath);
  696. while (thisPath.endsWithChar (separator))
  697. thisPath = thisPath.dropLastCharacters (1);
  698. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  699. : dir.fullPath));
  700. int commonBitLength = 0;
  701. String::CharPointerType thisPathAfterCommon (thisPath.getCharPointer());
  702. String::CharPointerType dirPathAfterCommon (dirPath.getCharPointer());
  703. {
  704. String::CharPointerType thisPathIter (thisPath.getCharPointer());
  705. String::CharPointerType dirPathIter (dirPath.getCharPointer());
  706. for (int i = 0;;)
  707. {
  708. const juce_wchar c1 = thisPathIter.getAndAdvance();
  709. const juce_wchar c2 = dirPathIter.getAndAdvance();
  710. #if NAMES_ARE_CASE_SENSITIVE
  711. if (c1 != c2
  712. #else
  713. if ((c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
  714. #endif
  715. || c1 == 0)
  716. break;
  717. ++i;
  718. if (c1 == separator)
  719. {
  720. thisPathAfterCommon = thisPathIter;
  721. dirPathAfterCommon = dirPathIter;
  722. commonBitLength = i;
  723. }
  724. }
  725. }
  726. // if the only common bit is the root, then just return the full path..
  727. if (commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == separator))
  728. return fullPath;
  729. const int numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  730. if (numUpDirectoriesNeeded == 0)
  731. return thisPathAfterCommon;
  732. #if JUCE_WINDOWS
  733. String s (String::repeatedString ("..\\", numUpDirectoriesNeeded));
  734. #else
  735. String s (String::repeatedString ("../", numUpDirectoriesNeeded));
  736. #endif
  737. s.appendCharPointer (thisPathAfterCommon);
  738. return s;
  739. }
  740. //==============================================================================
  741. File File::createTempFile (StringRef fileNameEnding)
  742. {
  743. const File tempFile (getSpecialLocation (tempDirectory)
  744. .getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
  745. .withFileExtension (fileNameEnding));
  746. if (tempFile.exists())
  747. return createTempFile (fileNameEnding);
  748. return tempFile;
  749. }
  750. bool File::createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const
  751. {
  752. if (linkFileToCreate.exists())
  753. {
  754. if (! linkFileToCreate.isSymbolicLink())
  755. {
  756. // user has specified an existing file / directory as the link
  757. // this is bad! the user could end up unintentionally destroying data
  758. jassertfalse;
  759. return false;
  760. }
  761. if (overwriteExisting)
  762. linkFileToCreate.deleteFile();
  763. }
  764. #if JUCE_MAC || JUCE_LINUX
  765. // one common reason for getting an error here is that the file already exists
  766. if (symlink (fullPath.toRawUTF8(), linkFileToCreate.getFullPathName().toRawUTF8()) == -1)
  767. {
  768. jassertfalse;
  769. return false;
  770. }
  771. return true;
  772. #elif JUCE_MSVC
  773. return CreateSymbolicLink (linkFileToCreate.getFullPathName().toWideCharPointer(),
  774. fullPath.toWideCharPointer(),
  775. isDirectory() ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0) != FALSE;
  776. #else
  777. jassertfalse; // symbolic links not supported on this platform!
  778. return false;
  779. #endif
  780. }
  781. //==============================================================================
  782. MemoryMappedFile::MemoryMappedFile (const File& file, MemoryMappedFile::AccessMode mode, bool exclusive)
  783. : address (nullptr), range (0, file.getSize()), fileHandle (0)
  784. {
  785. openInternal (file, mode, exclusive);
  786. }
  787. MemoryMappedFile::MemoryMappedFile (const File& file, const Range<int64>& fileRange, AccessMode mode, bool exclusive)
  788. : address (nullptr), range (fileRange.getIntersectionWith (Range<int64> (0, file.getSize()))), fileHandle (0)
  789. {
  790. openInternal (file, mode, exclusive);
  791. }
  792. //==============================================================================
  793. #if JUCE_UNIT_TESTS
  794. class FileTests : public UnitTest
  795. {
  796. public:
  797. FileTests() : UnitTest ("Files") {}
  798. void runTest() override
  799. {
  800. beginTest ("Reading");
  801. const File home (File::getSpecialLocation (File::userHomeDirectory));
  802. const File temp (File::getSpecialLocation (File::tempDirectory));
  803. expect (! File().exists());
  804. expect (! File().existsAsFile());
  805. expect (! File().isDirectory());
  806. #if ! JUCE_WINDOWS
  807. expect (File("/").isDirectory());
  808. #endif
  809. expect (home.isDirectory());
  810. expect (home.exists());
  811. expect (! home.existsAsFile());
  812. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  813. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  814. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  815. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  816. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  817. expect (home.getVolumeTotalSize() > 1024 * 1024);
  818. expect (home.getBytesFreeOnVolume() > 0);
  819. expect (! home.isHidden());
  820. expect (home.isOnHardDisk());
  821. expect (! home.isOnCDRomDrive());
  822. expect (File::getCurrentWorkingDirectory().exists());
  823. expect (home.setAsCurrentWorkingDirectory());
  824. expect (File::getCurrentWorkingDirectory() == home);
  825. {
  826. Array<File> roots;
  827. File::findFileSystemRoots (roots);
  828. expect (roots.size() > 0);
  829. int numRootsExisting = 0;
  830. for (int i = 0; i < roots.size(); ++i)
  831. if (roots[i].exists())
  832. ++numRootsExisting;
  833. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  834. expect (numRootsExisting > 0);
  835. }
  836. beginTest ("Writing");
  837. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  838. expect (demoFolder.deleteRecursively());
  839. expect (demoFolder.createDirectory());
  840. expect (demoFolder.isDirectory());
  841. expect (demoFolder.getParentDirectory() == temp);
  842. expect (temp.isDirectory());
  843. {
  844. Array<File> files;
  845. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  846. expect (files.contains (demoFolder));
  847. }
  848. {
  849. Array<File> files;
  850. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  851. expect (files.contains (demoFolder));
  852. }
  853. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  854. expect (tempFile.getFileExtension() == ".txt");
  855. expect (tempFile.hasFileExtension (".txt"));
  856. expect (tempFile.hasFileExtension ("txt"));
  857. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  858. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("abc;xyz;foo"));
  859. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("xyz;foo"));
  860. expect (! tempFile.withFileExtension ("h").hasFileExtension ("bar;foo;xx"));
  861. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  862. expect (tempFile.hasWriteAccess());
  863. expect (home.getChildFile (".") == home);
  864. expect (home.getChildFile ("..") == home.getParentDirectory());
  865. expect (home.getChildFile (".xyz").getFileName() == ".xyz");
  866. expect (home.getChildFile ("..xyz").getFileName() == "..xyz");
  867. expect (home.getChildFile ("...xyz").getFileName() == "...xyz");
  868. expect (home.getChildFile ("./xyz") == home.getChildFile ("xyz"));
  869. expect (home.getChildFile ("././xyz") == home.getChildFile ("xyz"));
  870. expect (home.getChildFile ("../xyz") == home.getParentDirectory().getChildFile ("xyz"));
  871. expect (home.getChildFile (".././xyz") == home.getParentDirectory().getChildFile ("xyz"));
  872. expect (home.getChildFile (".././xyz/./abc") == home.getParentDirectory().getChildFile ("xyz/abc"));
  873. expect (home.getChildFile ("./../xyz") == home.getParentDirectory().getChildFile ("xyz"));
  874. expect (home.getChildFile ("a1/a2/a3/./../../a4") == home.getChildFile ("a1/a4"));
  875. {
  876. FileOutputStream fo (tempFile);
  877. fo.write ("0123456789", 10);
  878. }
  879. expect (tempFile.exists());
  880. expect (tempFile.getSize() == 10);
  881. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  882. expectEquals (tempFile.loadFileAsString(), String ("0123456789"));
  883. expect (! demoFolder.containsSubDirectories());
  884. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  885. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  886. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  887. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  888. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  889. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  890. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  891. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  892. expect (demoFolder.containsSubDirectories());
  893. expect (tempFile.hasWriteAccess());
  894. tempFile.setReadOnly (true);
  895. expect (! tempFile.hasWriteAccess());
  896. tempFile.setReadOnly (false);
  897. expect (tempFile.hasWriteAccess());
  898. Time t (Time::getCurrentTime());
  899. tempFile.setLastModificationTime (t);
  900. Time t2 = tempFile.getLastModificationTime();
  901. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  902. {
  903. MemoryBlock mb;
  904. tempFile.loadFileAsData (mb);
  905. expect (mb.getSize() == 10);
  906. expect (mb[0] == '0');
  907. }
  908. {
  909. expect (tempFile.getSize() == 10);
  910. FileOutputStream fo (tempFile);
  911. expect (fo.openedOk());
  912. expect (fo.setPosition (7));
  913. expect (fo.truncate().wasOk());
  914. expect (tempFile.getSize() == 7);
  915. fo.write ("789", 3);
  916. fo.flush();
  917. expect (tempFile.getSize() == 10);
  918. }
  919. beginTest ("Memory-mapped files");
  920. {
  921. MemoryMappedFile mmf (tempFile, MemoryMappedFile::readOnly);
  922. expect (mmf.getSize() == 10);
  923. expect (mmf.getData() != nullptr);
  924. expect (memcmp (mmf.getData(), "0123456789", 10) == 0);
  925. }
  926. {
  927. const File tempFile2 (tempFile.getNonexistentSibling (false));
  928. expect (tempFile2.create());
  929. expect (tempFile2.appendData ("xxxxxxxxxx", 10));
  930. {
  931. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  932. expect (mmf.getSize() == 10);
  933. expect (mmf.getData() != nullptr);
  934. memcpy (mmf.getData(), "abcdefghij", 10);
  935. }
  936. {
  937. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  938. expect (mmf.getSize() == 10);
  939. expect (mmf.getData() != nullptr);
  940. expect (memcmp (mmf.getData(), "abcdefghij", 10) == 0);
  941. }
  942. expect (tempFile2.deleteFile());
  943. }
  944. beginTest ("More writing");
  945. expect (tempFile.appendData ("abcdefghij", 10));
  946. expect (tempFile.getSize() == 20);
  947. expect (tempFile.replaceWithData ("abcdefghij", 10));
  948. expect (tempFile.getSize() == 10);
  949. File tempFile2 (tempFile.getNonexistentSibling (false));
  950. expect (tempFile.copyFileTo (tempFile2));
  951. expect (tempFile2.exists());
  952. expect (tempFile2.hasIdenticalContentTo (tempFile));
  953. expect (tempFile.deleteFile());
  954. expect (! tempFile.exists());
  955. expect (tempFile2.moveFileTo (tempFile));
  956. expect (tempFile.exists());
  957. expect (! tempFile2.exists());
  958. expect (demoFolder.deleteRecursively());
  959. expect (! demoFolder.exists());
  960. }
  961. };
  962. static FileTests fileUnitTests;
  963. #endif