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.

1214 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. File::File (const String& fullPathName)
  20. : fullPath (parseAbsolutePath (fullPathName))
  21. {
  22. }
  23. File File::createFileWithoutCheckingPath (const String& path) noexcept
  24. {
  25. File f;
  26. f.fullPath = path;
  27. return f;
  28. }
  29. File::File (const File& other)
  30. : fullPath (other.fullPath)
  31. {
  32. }
  33. File& File::operator= (const String& newPath)
  34. {
  35. fullPath = parseAbsolutePath (newPath);
  36. return *this;
  37. }
  38. File& File::operator= (const File& other)
  39. {
  40. fullPath = other.fullPath;
  41. return *this;
  42. }
  43. File::File (File&& other) noexcept
  44. : fullPath (static_cast<String&&> (other.fullPath))
  45. {
  46. }
  47. File& File::operator= (File&& other) noexcept
  48. {
  49. fullPath = static_cast<String&&> (other.fullPath);
  50. return *this;
  51. }
  52. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  53. const File File::nonexistent;
  54. #endif
  55. //==============================================================================
  56. static String removeEllipsis (const String& path)
  57. {
  58. // This will quickly find both /../ and /./ at the expense of a minor
  59. // false-positive performance hit when path elements end in a dot.
  60. #if JUCE_WINDOWS
  61. if (path.contains (".\\"))
  62. #else
  63. if (path.contains ("./"))
  64. #endif
  65. {
  66. StringArray toks;
  67. toks.addTokens (path, File::getSeparatorString(), {});
  68. bool anythingChanged = false;
  69. for (int i = 1; i < toks.size(); ++i)
  70. {
  71. auto& t = toks[i];
  72. if (t == ".." && toks[i - 1] != "..")
  73. {
  74. anythingChanged = true;
  75. toks.removeRange (i - 1, 2);
  76. i = jmax (0, i - 2);
  77. }
  78. else if (t == ".")
  79. {
  80. anythingChanged = true;
  81. toks.remove (i--);
  82. }
  83. }
  84. if (anythingChanged)
  85. return toks.joinIntoString (File::getSeparatorString());
  86. }
  87. return path;
  88. }
  89. bool File::isRoot() const
  90. {
  91. return fullPath.isNotEmpty() && *this == getParentDirectory();
  92. }
  93. String File::parseAbsolutePath (const String& p)
  94. {
  95. if (p.isEmpty())
  96. return {};
  97. #if JUCE_WINDOWS
  98. // Windows..
  99. auto path = removeEllipsis (p.replaceCharacter ('/', '\\'));
  100. if (path.startsWithChar (getSeparatorChar()))
  101. {
  102. if (path[1] != getSeparatorChar())
  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. auto path = removeEllipsis (p);
  134. if (path.startsWithChar ('~'))
  135. {
  136. if (path[1] == getSeparatorChar() || 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. auto userName = path.substring (1).upToFirstOccurrenceOf ("/", false, false);
  146. if (auto* pw = getpwnam (userName.toUTF8()))
  147. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  148. }
  149. }
  150. else if (! path.startsWithChar (getSeparatorChar()))
  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 (getSeparatorChar()) && path != getSeparatorString()) // 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 (getSeparatorChar()) ? path
  178. : path + getSeparatorChar();
  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 (auto& f : subFiles)
  214. worked = f.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 (auto& f : subFiles)
  230. worked = f.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 (auto& f : subFiles)
  270. if (! f.copyFileTo (newDirectory.getChildFile (f.getFileName())))
  271. return false;
  272. subFiles.clear();
  273. findChildFiles (subFiles, File::findDirectories, false);
  274. for (auto& f : subFiles)
  275. if (! f.copyDirectoryTo (newDirectory.getChildFile (f.getFileName())))
  276. return false;
  277. return true;
  278. }
  279. return false;
  280. }
  281. //==============================================================================
  282. String File::getPathUpToLastSlash() const
  283. {
  284. auto lastSlash = fullPath.lastIndexOfChar (getSeparatorChar());
  285. if (lastSlash > 0)
  286. return fullPath.substring (0, lastSlash);
  287. if (lastSlash == 0)
  288. return getSeparatorString();
  289. return fullPath;
  290. }
  291. File File::getParentDirectory() const
  292. {
  293. return createFileWithoutCheckingPath (getPathUpToLastSlash());
  294. }
  295. //==============================================================================
  296. String File::getFileName() const
  297. {
  298. return fullPath.substring (fullPath.lastIndexOfChar (getSeparatorChar()) + 1);
  299. }
  300. String File::getFileNameWithoutExtension() const
  301. {
  302. auto lastSlash = fullPath.lastIndexOfChar (getSeparatorChar()) + 1;
  303. auto lastDot = fullPath.lastIndexOfChar ('.');
  304. if (lastDot > lastSlash)
  305. return fullPath.substring (lastSlash, lastDot);
  306. return fullPath.substring (lastSlash);
  307. }
  308. bool File::isAChildOf (const File& potentialParent) const
  309. {
  310. if (potentialParent.fullPath.isEmpty())
  311. return false;
  312. auto ourPath = getPathUpToLastSlash();
  313. if (compareFilenames (potentialParent.fullPath, ourPath) == 0)
  314. return true;
  315. if (potentialParent.fullPath.length() >= ourPath.length())
  316. return false;
  317. return getParentDirectory().isAChildOf (potentialParent);
  318. }
  319. int File::hashCode() const { return fullPath.hashCode(); }
  320. int64 File::hashCode64() const { return fullPath.hashCode64(); }
  321. //==============================================================================
  322. bool File::isAbsolutePath (StringRef path)
  323. {
  324. auto firstChar = *(path.text);
  325. return firstChar == getSeparatorChar()
  326. #if JUCE_WINDOWS
  327. || (firstChar != 0 && path.text[1] == ':');
  328. #else
  329. || firstChar == '~';
  330. #endif
  331. }
  332. File File::getChildFile (StringRef relativePath) const
  333. {
  334. auto r = relativePath.text;
  335. if (isAbsolutePath (r))
  336. return File (String (r));
  337. #if JUCE_WINDOWS
  338. if (r.indexOf ((juce_wchar) '/') >= 0)
  339. return getChildFile (String (r).replaceCharacter ('/', '\\'));
  340. #endif
  341. auto path = fullPath;
  342. auto separatorChar = getSeparatorChar();
  343. while (*r == '.')
  344. {
  345. auto lastPos = r;
  346. auto secondChar = *++r;
  347. if (secondChar == '.') // remove "../"
  348. {
  349. auto thirdChar = *++r;
  350. if (thirdChar == separatorChar || thirdChar == 0)
  351. {
  352. auto lastSlash = path.lastIndexOfChar (separatorChar);
  353. if (lastSlash >= 0)
  354. path = path.substring (0, lastSlash);
  355. while (*r == separatorChar) // ignore duplicate slashes
  356. ++r;
  357. }
  358. else
  359. {
  360. r = lastPos;
  361. break;
  362. }
  363. }
  364. else if (secondChar == separatorChar || secondChar == 0) // remove "./"
  365. {
  366. while (*r == separatorChar) // ignore duplicate slashes
  367. ++r;
  368. }
  369. else
  370. {
  371. r = lastPos;
  372. break;
  373. }
  374. }
  375. path = addTrailingSeparator (path);
  376. path.appendCharPointer (r);
  377. return File (path);
  378. }
  379. File File::getSiblingFile (StringRef fileName) const
  380. {
  381. return getParentDirectory().getChildFile (fileName);
  382. }
  383. //==============================================================================
  384. String File::descriptionOfSizeInBytes (const int64 bytes)
  385. {
  386. const char* suffix;
  387. double divisor = 0;
  388. if (bytes == 1) { suffix = " byte"; }
  389. else if (bytes < 1024) { suffix = " bytes"; }
  390. else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
  391. else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
  392. else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
  393. return (divisor > 0 ? String (bytes / divisor, 1) : String (bytes)) + suffix;
  394. }
  395. //==============================================================================
  396. Result File::create() const
  397. {
  398. if (exists())
  399. return Result::ok();
  400. auto parentDir = getParentDirectory();
  401. if (parentDir == *this)
  402. return Result::fail ("Cannot create parent directory");
  403. auto r = parentDir.createDirectory();
  404. if (r.wasOk())
  405. {
  406. FileOutputStream fo (*this, 8);
  407. r = fo.getStatus();
  408. }
  409. return r;
  410. }
  411. Result File::createDirectory() const
  412. {
  413. if (isDirectory())
  414. return Result::ok();
  415. auto parentDir = getParentDirectory();
  416. if (parentDir == *this)
  417. return Result::fail ("Cannot create parent directory");
  418. auto r = parentDir.createDirectory();
  419. if (r.wasOk())
  420. r = createDirectoryInternal (fullPath.trimCharactersAtEnd (getSeparatorString()));
  421. return r;
  422. }
  423. //==============================================================================
  424. Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); }
  425. Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); }
  426. Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); }
  427. bool File::setLastModificationTime (Time t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  428. bool File::setLastAccessTime (Time t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  429. bool File::setCreationTime (Time t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  430. //==============================================================================
  431. bool File::loadFileAsData (MemoryBlock& destBlock) const
  432. {
  433. if (! existsAsFile())
  434. return false;
  435. FileInputStream in (*this);
  436. return in.openedOk() && getSize() == (int64) in.readIntoMemoryBlock (destBlock);
  437. }
  438. String File::loadFileAsString() const
  439. {
  440. if (! existsAsFile())
  441. return {};
  442. FileInputStream in (*this);
  443. return in.openedOk() ? in.readEntireStreamAsString()
  444. : String();
  445. }
  446. void File::readLines (StringArray& destLines) const
  447. {
  448. destLines.addLines (loadFileAsString());
  449. }
  450. //==============================================================================
  451. int File::findChildFiles (Array<File>& results,
  452. const int whatToLookFor,
  453. const bool searchRecursively,
  454. const String& wildCardPattern) const
  455. {
  456. int total = 0;
  457. for (DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor); di.next();)
  458. {
  459. results.add (di.getFile());
  460. ++total;
  461. }
  462. return total;
  463. }
  464. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  465. {
  466. int total = 0;
  467. for (DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor); di.next();)
  468. ++total;
  469. return total;
  470. }
  471. bool File::containsSubDirectories() const
  472. {
  473. if (! isDirectory())
  474. return false;
  475. DirectoryIterator di (*this, false, "*", findDirectories);
  476. return di.next();
  477. }
  478. //==============================================================================
  479. File File::getNonexistentChildFile (const String& suggestedPrefix,
  480. const String& suffix,
  481. bool putNumbersInBrackets) const
  482. {
  483. auto f = getChildFile (suggestedPrefix + suffix);
  484. if (f.exists())
  485. {
  486. int number = 1;
  487. auto prefix = suggestedPrefix;
  488. // remove any bracketed numbers that may already be on the end..
  489. if (prefix.trim().endsWithChar (')'))
  490. {
  491. putNumbersInBrackets = true;
  492. auto openBracks = prefix.lastIndexOfChar ('(');
  493. auto closeBracks = prefix.lastIndexOfChar (')');
  494. if (openBracks > 0
  495. && closeBracks > openBracks
  496. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  497. {
  498. number = prefix.substring (openBracks + 1, closeBracks).getIntValue();
  499. prefix = prefix.substring (0, openBracks);
  500. }
  501. }
  502. do
  503. {
  504. auto newName = prefix;
  505. if (putNumbersInBrackets)
  506. {
  507. newName << '(' << ++number << ')';
  508. }
  509. else
  510. {
  511. if (CharacterFunctions::isDigit (prefix.getLastCharacter()))
  512. newName << '_'; // pad with an underscore if the name already ends in a digit
  513. newName << ++number;
  514. }
  515. f = getChildFile (newName + suffix);
  516. } while (f.exists());
  517. }
  518. return f;
  519. }
  520. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  521. {
  522. if (! exists())
  523. return *this;
  524. return getParentDirectory().getNonexistentChildFile (getFileNameWithoutExtension(),
  525. getFileExtension(),
  526. putNumbersInBrackets);
  527. }
  528. //==============================================================================
  529. String File::getFileExtension() const
  530. {
  531. auto indexOfDot = fullPath.lastIndexOfChar ('.');
  532. if (indexOfDot > fullPath.lastIndexOfChar (getSeparatorChar()))
  533. return fullPath.substring (indexOfDot);
  534. return {};
  535. }
  536. bool File::hasFileExtension (StringRef possibleSuffix) const
  537. {
  538. if (possibleSuffix.isEmpty())
  539. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (getSeparatorChar());
  540. auto semicolon = possibleSuffix.text.indexOf ((juce_wchar) ';');
  541. if (semicolon >= 0)
  542. return hasFileExtension (String (possibleSuffix.text).substring (0, semicolon).trimEnd())
  543. || hasFileExtension ((possibleSuffix.text + (semicolon + 1)).findEndOfWhitespace());
  544. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  545. {
  546. if (possibleSuffix.text[0] == '.')
  547. return true;
  548. auto dotPos = fullPath.length() - possibleSuffix.length() - 1;
  549. if (dotPos >= 0)
  550. return fullPath[dotPos] == '.';
  551. }
  552. return false;
  553. }
  554. File File::withFileExtension (StringRef newExtension) const
  555. {
  556. if (fullPath.isEmpty())
  557. return {};
  558. auto filePart = getFileName();
  559. auto lastDot = filePart.lastIndexOfChar ('.');
  560. if (lastDot >= 0)
  561. filePart = filePart.substring (0, lastDot);
  562. if (newExtension.isNotEmpty() && newExtension.text[0] != '.')
  563. filePart << '.';
  564. return getSiblingFile (filePart + newExtension);
  565. }
  566. //==============================================================================
  567. bool File::startAsProcess (const String& parameters) const
  568. {
  569. return exists() && Process::openDocument (fullPath, parameters);
  570. }
  571. //==============================================================================
  572. FileInputStream* File::createInputStream() const
  573. {
  574. ScopedPointer<FileInputStream> fin (new FileInputStream (*this));
  575. if (fin->openedOk())
  576. return fin.release();
  577. return nullptr;
  578. }
  579. FileOutputStream* File::createOutputStream (size_t bufferSize) const
  580. {
  581. ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  582. return out->failedToOpen() ? nullptr
  583. : out.release();
  584. }
  585. //==============================================================================
  586. bool File::appendData (const void* const dataToAppend,
  587. const size_t numberOfBytes) const
  588. {
  589. jassert (((ssize_t) numberOfBytes) >= 0);
  590. if (numberOfBytes == 0)
  591. return true;
  592. FileOutputStream out (*this, 8192);
  593. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  594. }
  595. bool File::replaceWithData (const void* const dataToWrite,
  596. const size_t numberOfBytes) const
  597. {
  598. if (numberOfBytes == 0)
  599. return deleteFile();
  600. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  601. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  602. return tempFile.overwriteTargetFileWithTemporary();
  603. }
  604. bool File::appendText (const String& text,
  605. const bool asUnicode,
  606. const bool writeUnicodeHeaderBytes) const
  607. {
  608. FileOutputStream out (*this);
  609. if (out.failedToOpen())
  610. return false;
  611. return out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
  612. }
  613. bool File::replaceWithText (const String& textToWrite,
  614. const bool asUnicode,
  615. const bool writeUnicodeHeaderBytes) const
  616. {
  617. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  618. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  619. return tempFile.overwriteTargetFileWithTemporary();
  620. }
  621. bool File::hasIdenticalContentTo (const File& other) const
  622. {
  623. if (other == *this)
  624. return true;
  625. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  626. {
  627. FileInputStream in1 (*this), in2 (other);
  628. if (in1.openedOk() && in2.openedOk())
  629. {
  630. const int bufferSize = 4096;
  631. HeapBlock<char> buffer1 (bufferSize), buffer2 (bufferSize);
  632. for (;;)
  633. {
  634. auto num1 = in1.read (buffer1, bufferSize);
  635. auto num2 = in2.read (buffer2, bufferSize);
  636. if (num1 != num2)
  637. break;
  638. if (num1 <= 0)
  639. return true;
  640. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  641. break;
  642. }
  643. }
  644. }
  645. return false;
  646. }
  647. //==============================================================================
  648. String File::createLegalPathName (const String& original)
  649. {
  650. auto s = original;
  651. String start;
  652. if (s.isNotEmpty() && s[1] == ':')
  653. {
  654. start = s.substring (0, 2);
  655. s = s.substring (2);
  656. }
  657. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  658. .substring (0, 1024);
  659. }
  660. String File::createLegalFileName (const String& original)
  661. {
  662. auto s = original.removeCharacters ("\"#@,;:<>*^|?\\/");
  663. const int maxLength = 128; // only the length of the filename, not the whole path
  664. auto len = s.length();
  665. if (len > maxLength)
  666. {
  667. auto lastDot = s.lastIndexOfChar ('.');
  668. if (lastDot > jmax (0, len - 12))
  669. {
  670. s = s.substring (0, maxLength - (len - lastDot))
  671. + s.substring (lastDot);
  672. }
  673. else
  674. {
  675. s = s.substring (0, maxLength);
  676. }
  677. }
  678. return s;
  679. }
  680. //==============================================================================
  681. static int countNumberOfSeparators (String::CharPointerType s)
  682. {
  683. int num = 0;
  684. for (;;)
  685. {
  686. auto c = s.getAndAdvance();
  687. if (c == 0)
  688. break;
  689. if (c == File::getSeparatorChar())
  690. ++num;
  691. }
  692. return num;
  693. }
  694. String File::getRelativePathFrom (const File& dir) const
  695. {
  696. if (dir == *this)
  697. return ".";
  698. auto thisPath = fullPath;
  699. while (thisPath.endsWithChar (getSeparatorChar()))
  700. thisPath = thisPath.dropLastCharacters (1);
  701. auto dirPath = addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  702. : dir.fullPath);
  703. int commonBitLength = 0;
  704. auto thisPathAfterCommon = thisPath.getCharPointer();
  705. auto dirPathAfterCommon = dirPath.getCharPointer();
  706. {
  707. auto thisPathIter = thisPath.getCharPointer();
  708. auto dirPathIter = dirPath.getCharPointer();
  709. for (int i = 0;;)
  710. {
  711. auto c1 = thisPathIter.getAndAdvance();
  712. auto 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 == getSeparatorChar())
  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] == getSeparatorChar()))
  731. return fullPath;
  732. auto numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  733. if (numUpDirectoriesNeeded == 0)
  734. return thisPathAfterCommon;
  735. #if JUCE_WINDOWS
  736. auto s = String::repeatedString ("..\\", numUpDirectoriesNeeded);
  737. #else
  738. auto s = String::repeatedString ("../", numUpDirectoriesNeeded);
  739. #endif
  740. s.appendCharPointer (thisPathAfterCommon);
  741. return s;
  742. }
  743. //==============================================================================
  744. File File::createTempFile (StringRef fileNameEnding)
  745. {
  746. auto 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. : range (0, file.getSize())
  787. {
  788. openInternal (file, mode, exclusive);
  789. }
  790. MemoryMappedFile::MemoryMappedFile (const File& file, const Range<int64>& fileRange, AccessMode mode, bool exclusive)
  791. : range (fileRange.getIntersectionWith (Range<int64> (0, file.getSize())))
  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", "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::getSeparatorString() + tempFile.getFileName());
  888. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::getSeparatorString() + ".." + File::getSeparatorString() + 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
  967. } // namespace juce