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