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.

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