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.

1097 lines
36KB

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