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.

1087 lines
36KB

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