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.

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