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.

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