Audio plugin host https://kx.studio/carla
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.

1704 lines
51KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. File::File (const String& fullPathName)
  24. : fullPath (parseAbsolutePath (fullPathName))
  25. {
  26. }
  27. File File::createFileWithoutCheckingPath (const String& path) noexcept
  28. {
  29. File f;
  30. f.fullPath = path;
  31. return f;
  32. }
  33. File::File (const File& other)
  34. : fullPath (other.fullPath)
  35. {
  36. }
  37. File& File::operator= (const String& newPath)
  38. {
  39. fullPath = parseAbsolutePath (newPath);
  40. return *this;
  41. }
  42. File& File::operator= (const File& other)
  43. {
  44. fullPath = other.fullPath;
  45. return *this;
  46. }
  47. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  48. File::File (File&& other) noexcept
  49. : fullPath (static_cast<String&&> (other.fullPath))
  50. {
  51. }
  52. File& File::operator= (File&& other) noexcept
  53. {
  54. fullPath = static_cast<String&&> (other.fullPath);
  55. return *this;
  56. }
  57. #endif
  58. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  59. const File File::nonexistent;
  60. #endif
  61. //==============================================================================
  62. static String removeEllipsis (const String& path)
  63. {
  64. // This will quickly find both /../ and /./ at the expense of a minor
  65. // false-positive performance hit when path elements end in a dot.
  66. #ifdef CARLA_OS_WIN
  67. if (path.contains (".\\"))
  68. #else
  69. if (path.contains ("./"))
  70. #endif
  71. {
  72. StringArray toks;
  73. toks.addTokens (path, File::separatorString, StringRef());
  74. bool anythingChanged = false;
  75. for (int i = 1; i < toks.size(); ++i)
  76. {
  77. const String& t = toks[i];
  78. if (t == ".." && toks[i - 1] != "..")
  79. {
  80. anythingChanged = true;
  81. toks.removeRange (i - 1, 2);
  82. i = jmax (0, i - 2);
  83. }
  84. else if (t == ".")
  85. {
  86. anythingChanged = true;
  87. toks.remove (i--);
  88. }
  89. }
  90. if (anythingChanged)
  91. return toks.joinIntoString (File::separatorString);
  92. }
  93. return path;
  94. }
  95. String File::parseAbsolutePath (const String& p)
  96. {
  97. if (p.isEmpty())
  98. return String();
  99. #ifdef CARLA_OS_WIN
  100. // Windows..
  101. String path (removeEllipsis (p.replaceCharacter ('/', '\\')));
  102. if (path.startsWithChar (separator))
  103. {
  104. if (path[1] != separator)
  105. {
  106. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  107. If you're trying to parse a string that may be either a relative path or an absolute path,
  108. you MUST provide a context against which the partial path can be evaluated - you can do
  109. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  110. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  111. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  112. */
  113. jassertfalse;
  114. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  115. }
  116. }
  117. else if (! path.containsChar (':'))
  118. {
  119. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  120. If you're trying to parse a string that may be either a relative path or an absolute path,
  121. you MUST provide a context against which the partial path can be evaluated - you can do
  122. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  123. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  124. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  125. */
  126. jassertfalse;
  127. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  128. }
  129. #else
  130. // Mac or Linux..
  131. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  132. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  133. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  134. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  135. String path (removeEllipsis (p));
  136. if (path.startsWithChar ('~'))
  137. {
  138. if (path[1] == separator || path[1] == 0)
  139. {
  140. // expand a name of the form "~/abc"
  141. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  142. + path.substring (1);
  143. }
  144. else
  145. {
  146. // expand a name of type "~dave/abc"
  147. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  148. if (struct passwd* const pw = getpwnam (userName.toUTF8()))
  149. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  150. }
  151. }
  152. else if (! path.startsWithChar (separator))
  153. {
  154. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  155. if (! (path.startsWith ("./") || path.startsWith ("../")))
  156. {
  157. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  158. If you're trying to parse a string that may be either a relative path or an absolute path,
  159. you MUST provide a context against which the partial path can be evaluated - you can do
  160. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  161. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  162. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  163. */
  164. jassertfalse;
  165. #if JUCE_LOG_ASSERTIONS
  166. Logger::writeToLog ("Illegal absolute path: " + path);
  167. #endif
  168. }
  169. #endif
  170. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  171. }
  172. #endif
  173. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  174. path = path.dropLastCharacters (1);
  175. return path;
  176. }
  177. String File::addTrailingSeparator (const String& path)
  178. {
  179. return path.endsWithChar (separator) ? path
  180. : path + separator;
  181. }
  182. //==============================================================================
  183. #if JUCE_LINUX
  184. #define NAMES_ARE_CASE_SENSITIVE 1
  185. #endif
  186. bool File::areFileNamesCaseSensitive()
  187. {
  188. #if NAMES_ARE_CASE_SENSITIVE
  189. return true;
  190. #else
  191. return false;
  192. #endif
  193. }
  194. static int compareFilenames (const String& name1, const String& name2) noexcept
  195. {
  196. #if NAMES_ARE_CASE_SENSITIVE
  197. return name1.compare (name2);
  198. #else
  199. return name1.compareIgnoreCase (name2);
  200. #endif
  201. }
  202. bool File::operator== (const File& other) const { return compareFilenames (fullPath, other.fullPath) == 0; }
  203. bool File::operator!= (const File& other) const { return compareFilenames (fullPath, other.fullPath) != 0; }
  204. bool File::operator< (const File& other) const { return compareFilenames (fullPath, other.fullPath) < 0; }
  205. bool File::operator> (const File& other) const { return compareFilenames (fullPath, other.fullPath) > 0; }
  206. //==============================================================================
  207. bool File::deleteRecursively() const
  208. {
  209. bool worked = true;
  210. if (isDirectory())
  211. {
  212. Array<File> subFiles;
  213. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  214. for (int i = subFiles.size(); --i >= 0;)
  215. worked = subFiles.getReference(i).deleteRecursively() && worked;
  216. }
  217. return deleteFile() && worked;
  218. }
  219. bool File::moveFileTo (const File& newFile) const
  220. {
  221. if (newFile.fullPath == fullPath)
  222. return true;
  223. if (! exists())
  224. return false;
  225. #if ! NAMES_ARE_CASE_SENSITIVE
  226. if (*this != newFile)
  227. #endif
  228. if (! newFile.deleteFile())
  229. return false;
  230. return moveInternal (newFile);
  231. }
  232. bool File::copyFileTo (const File& newFile) const
  233. {
  234. return (*this == newFile)
  235. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  236. }
  237. bool File::replaceFileIn (const File& newFile) const
  238. {
  239. if (newFile.fullPath == fullPath)
  240. return true;
  241. if (! newFile.exists())
  242. return moveFileTo (newFile);
  243. if (! replaceInternal (newFile))
  244. return false;
  245. deleteFile();
  246. return true;
  247. }
  248. bool File::copyDirectoryTo (const File& newDirectory) const
  249. {
  250. if (isDirectory() && newDirectory.createDirectory())
  251. {
  252. Array<File> subFiles;
  253. findChildFiles (subFiles, File::findFiles, false);
  254. for (int i = 0; i < subFiles.size(); ++i)
  255. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  256. return false;
  257. subFiles.clear();
  258. findChildFiles (subFiles, File::findDirectories, false);
  259. for (int i = 0; i < subFiles.size(); ++i)
  260. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  261. return false;
  262. return true;
  263. }
  264. return false;
  265. }
  266. //==============================================================================
  267. String File::getPathUpToLastSlash() const
  268. {
  269. const int lastSlash = fullPath.lastIndexOfChar (separator);
  270. if (lastSlash > 0)
  271. return fullPath.substring (0, lastSlash);
  272. if (lastSlash == 0)
  273. return separatorString;
  274. return fullPath;
  275. }
  276. File File::getParentDirectory() const
  277. {
  278. File f;
  279. f.fullPath = getPathUpToLastSlash();
  280. return f;
  281. }
  282. //==============================================================================
  283. String File::getFileName() const
  284. {
  285. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  286. }
  287. String File::getFileNameWithoutExtension() const
  288. {
  289. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  290. const int lastDot = fullPath.lastIndexOfChar ('.');
  291. if (lastDot > lastSlash)
  292. return fullPath.substring (lastSlash, lastDot);
  293. return fullPath.substring (lastSlash);
  294. }
  295. bool File::isAChildOf (const File& potentialParent) const
  296. {
  297. if (potentialParent.fullPath.isEmpty())
  298. return false;
  299. const String ourPath (getPathUpToLastSlash());
  300. if (compareFilenames (potentialParent.fullPath, ourPath) == 0)
  301. return true;
  302. if (potentialParent.fullPath.length() >= ourPath.length())
  303. return false;
  304. return getParentDirectory().isAChildOf (potentialParent);
  305. }
  306. int File::hashCode() const { return fullPath.hashCode(); }
  307. int64 File::hashCode64() const { return fullPath.hashCode64(); }
  308. //==============================================================================
  309. bool File::isAbsolutePath (StringRef path)
  310. {
  311. const juce_wchar firstChar = *(path.text);
  312. return firstChar == separator
  313. #ifdef CARLA_OS_WIN
  314. || (firstChar != 0 && path.text[1] == ':');
  315. #else
  316. || firstChar == '~';
  317. #endif
  318. }
  319. File File::getChildFile (StringRef relativePath) const
  320. {
  321. String::CharPointerType r = relativePath.text;
  322. if (isAbsolutePath (r))
  323. return File (String (r));
  324. #ifdef CARLA_OS_WIN
  325. if (r.indexOf ((juce_wchar) '/') >= 0)
  326. return getChildFile (String (r).replaceCharacter ('/', '\\'));
  327. #endif
  328. String path (fullPath);
  329. while (*r == '.')
  330. {
  331. String::CharPointerType lastPos = r;
  332. const juce_wchar secondChar = *++r;
  333. if (secondChar == '.') // remove "../"
  334. {
  335. const juce_wchar thirdChar = *++r;
  336. if (thirdChar == separator || thirdChar == 0)
  337. {
  338. const int lastSlash = path.lastIndexOfChar (separator);
  339. if (lastSlash >= 0)
  340. path = path.substring (0, lastSlash);
  341. while (*r == separator) // ignore duplicate slashes
  342. ++r;
  343. }
  344. else
  345. {
  346. r = lastPos;
  347. break;
  348. }
  349. }
  350. else if (secondChar == separator || secondChar == 0) // remove "./"
  351. {
  352. while (*r == separator) // ignore duplicate slashes
  353. ++r;
  354. }
  355. else
  356. {
  357. r = lastPos;
  358. break;
  359. }
  360. }
  361. path = addTrailingSeparator (path);
  362. path.appendCharPointer (r);
  363. return File (path);
  364. }
  365. File File::getSiblingFile (StringRef fileName) const
  366. {
  367. return getParentDirectory().getChildFile (fileName);
  368. }
  369. //==============================================================================
  370. String File::descriptionOfSizeInBytes (const int64 bytes)
  371. {
  372. const char* suffix;
  373. double divisor = 0;
  374. if (bytes == 1) { suffix = " byte"; }
  375. else if (bytes < 1024) { suffix = " bytes"; }
  376. else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
  377. else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
  378. else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
  379. return (divisor > 0 ? String (bytes / divisor, 1) : String (bytes)) + suffix;
  380. }
  381. //==============================================================================
  382. Result File::create() const
  383. {
  384. if (exists())
  385. return Result::ok();
  386. const File parentDir (getParentDirectory());
  387. if (parentDir == *this)
  388. return Result::fail ("Cannot create parent directory");
  389. Result r (parentDir.createDirectory());
  390. if (r.wasOk())
  391. {
  392. FileOutputStream fo (*this, 8);
  393. r = fo.getStatus();
  394. }
  395. return r;
  396. }
  397. Result File::createDirectory() const
  398. {
  399. if (isDirectory())
  400. return Result::ok();
  401. const File parentDir (getParentDirectory());
  402. if (parentDir == *this)
  403. return Result::fail ("Cannot create parent directory");
  404. Result r (parentDir.createDirectory());
  405. if (r.wasOk())
  406. r = createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  407. return r;
  408. }
  409. //==============================================================================
  410. bool File::loadFileAsData (MemoryBlock& destBlock) const
  411. {
  412. if (! existsAsFile())
  413. return false;
  414. FileInputStream in (*this);
  415. return in.openedOk() && getSize() == (int64) in.readIntoMemoryBlock (destBlock);
  416. }
  417. String File::loadFileAsString() const
  418. {
  419. if (! existsAsFile())
  420. return String();
  421. FileInputStream in (*this);
  422. return in.openedOk() ? in.readEntireStreamAsString()
  423. : String();
  424. }
  425. void File::readLines (StringArray& destLines) const
  426. {
  427. destLines.addLines (loadFileAsString());
  428. }
  429. //==============================================================================
  430. int File::findChildFiles (Array<File>& results,
  431. const int whatToLookFor,
  432. const bool searchRecursively,
  433. const String& wildCardPattern) const
  434. {
  435. int total = 0;
  436. for (DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor); di.next();)
  437. {
  438. results.add (di.getFile());
  439. ++total;
  440. }
  441. return total;
  442. }
  443. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  444. {
  445. int total = 0;
  446. for (DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor); di.next();)
  447. ++total;
  448. return total;
  449. }
  450. bool File::containsSubDirectories() const
  451. {
  452. if (! isDirectory())
  453. return false;
  454. DirectoryIterator di (*this, false, "*", findDirectories);
  455. return di.next();
  456. }
  457. //==============================================================================
  458. File File::getNonexistentChildFile (const String& suggestedPrefix,
  459. const String& suffix,
  460. bool putNumbersInBrackets) const
  461. {
  462. File f (getChildFile (suggestedPrefix + suffix));
  463. if (f.exists())
  464. {
  465. int number = 1;
  466. String prefix (suggestedPrefix);
  467. // remove any bracketed numbers that may already be on the end..
  468. if (prefix.trim().endsWithChar (')'))
  469. {
  470. putNumbersInBrackets = true;
  471. const int openBracks = prefix.lastIndexOfChar ('(');
  472. const int closeBracks = prefix.lastIndexOfChar (')');
  473. if (openBracks > 0
  474. && closeBracks > openBracks
  475. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  476. {
  477. number = prefix.substring (openBracks + 1, closeBracks).getIntValue();
  478. prefix = prefix.substring (0, openBracks);
  479. }
  480. }
  481. do
  482. {
  483. String newName (prefix);
  484. if (putNumbersInBrackets)
  485. {
  486. newName << '(' << ++number << ')';
  487. }
  488. else
  489. {
  490. if (CharacterFunctions::isDigit (prefix.getLastCharacter()))
  491. newName << '_'; // pad with an underscore if the name already ends in a digit
  492. newName << ++number;
  493. }
  494. f = getChildFile (newName + suffix);
  495. } while (f.exists());
  496. }
  497. return f;
  498. }
  499. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  500. {
  501. if (! exists())
  502. return *this;
  503. return getParentDirectory().getNonexistentChildFile (getFileNameWithoutExtension(),
  504. getFileExtension(),
  505. putNumbersInBrackets);
  506. }
  507. //==============================================================================
  508. String File::getFileExtension() const
  509. {
  510. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  511. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  512. return fullPath.substring (indexOfDot);
  513. return String();
  514. }
  515. bool File::hasFileExtension (StringRef possibleSuffix) const
  516. {
  517. if (possibleSuffix.isEmpty())
  518. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  519. const int semicolon = possibleSuffix.text.indexOf ((juce_wchar) ';');
  520. if (semicolon >= 0)
  521. return hasFileExtension (String (possibleSuffix.text).substring (0, semicolon).trimEnd())
  522. || hasFileExtension ((possibleSuffix.text + (semicolon + 1)).findEndOfWhitespace());
  523. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  524. {
  525. if (possibleSuffix.text[0] == '.')
  526. return true;
  527. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  528. if (dotPos >= 0)
  529. return fullPath [dotPos] == '.';
  530. }
  531. return false;
  532. }
  533. File File::withFileExtension (StringRef newExtension) const
  534. {
  535. if (fullPath.isEmpty())
  536. return File();
  537. String filePart (getFileName());
  538. const int i = filePart.lastIndexOfChar ('.');
  539. if (i >= 0)
  540. filePart = filePart.substring (0, i);
  541. if (newExtension.isNotEmpty() && newExtension.text[0] != '.')
  542. filePart << '.';
  543. return getSiblingFile (filePart + newExtension);
  544. }
  545. //==============================================================================
  546. FileInputStream* File::createInputStream() const
  547. {
  548. ScopedPointer<FileInputStream> fin (new FileInputStream (*this));
  549. if (fin->openedOk())
  550. return fin.release();
  551. return nullptr;
  552. }
  553. FileOutputStream* File::createOutputStream (const size_t bufferSize) const
  554. {
  555. ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  556. return out->failedToOpen() ? nullptr
  557. : out.release();
  558. }
  559. //==============================================================================
  560. bool File::appendData (const void* const dataToAppend,
  561. const size_t numberOfBytes) const
  562. {
  563. jassert (((ssize_t) numberOfBytes) >= 0);
  564. if (numberOfBytes == 0)
  565. return true;
  566. FileOutputStream out (*this, 8192);
  567. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  568. }
  569. bool File::replaceWithData (const void* const dataToWrite,
  570. const size_t numberOfBytes) const
  571. {
  572. if (numberOfBytes == 0)
  573. return deleteFile();
  574. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  575. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  576. return tempFile.overwriteTargetFileWithTemporary();
  577. }
  578. bool File::appendText (const String& text,
  579. const bool asUnicode,
  580. const bool writeUnicodeHeaderBytes) const
  581. {
  582. FileOutputStream out (*this);
  583. if (out.failedToOpen())
  584. return false;
  585. out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
  586. return true;
  587. }
  588. bool File::replaceWithText (const String& textToWrite,
  589. const bool asUnicode,
  590. const bool writeUnicodeHeaderBytes) const
  591. {
  592. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  593. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  594. return tempFile.overwriteTargetFileWithTemporary();
  595. }
  596. bool File::hasIdenticalContentTo (const File& other) const
  597. {
  598. if (other == *this)
  599. return true;
  600. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  601. {
  602. FileInputStream in1 (*this), in2 (other);
  603. if (in1.openedOk() && in2.openedOk())
  604. {
  605. const int bufferSize = 4096;
  606. HeapBlock<char> buffer1 (bufferSize), buffer2 (bufferSize);
  607. for (;;)
  608. {
  609. const int num1 = in1.read (buffer1, bufferSize);
  610. const int num2 = in2.read (buffer2, bufferSize);
  611. if (num1 != num2)
  612. break;
  613. if (num1 <= 0)
  614. return true;
  615. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  616. break;
  617. }
  618. }
  619. }
  620. return false;
  621. }
  622. //==============================================================================
  623. String File::createLegalPathName (const String& original)
  624. {
  625. String s (original);
  626. String start;
  627. if (s.isNotEmpty() && s[1] == ':')
  628. {
  629. start = s.substring (0, 2);
  630. s = s.substring (2);
  631. }
  632. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  633. .substring (0, 1024);
  634. }
  635. String File::createLegalFileName (const String& original)
  636. {
  637. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  638. const int maxLength = 128; // only the length of the filename, not the whole path
  639. const int len = s.length();
  640. if (len > maxLength)
  641. {
  642. const int lastDot = s.lastIndexOfChar ('.');
  643. if (lastDot > jmax (0, len - 12))
  644. {
  645. s = s.substring (0, maxLength - (len - lastDot))
  646. + s.substring (lastDot);
  647. }
  648. else
  649. {
  650. s = s.substring (0, maxLength);
  651. }
  652. }
  653. return s;
  654. }
  655. //==============================================================================
  656. static int countNumberOfSeparators (String::CharPointerType s)
  657. {
  658. int num = 0;
  659. for (;;)
  660. {
  661. const juce_wchar c = s.getAndAdvance();
  662. if (c == 0)
  663. break;
  664. if (c == File::separator)
  665. ++num;
  666. }
  667. return num;
  668. }
  669. String File::getRelativePathFrom (const File& dir) const
  670. {
  671. String thisPath (fullPath);
  672. while (thisPath.endsWithChar (separator))
  673. thisPath = thisPath.dropLastCharacters (1);
  674. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  675. : dir.fullPath));
  676. int commonBitLength = 0;
  677. String::CharPointerType thisPathAfterCommon (thisPath.getCharPointer());
  678. String::CharPointerType dirPathAfterCommon (dirPath.getCharPointer());
  679. {
  680. String::CharPointerType thisPathIter (thisPath.getCharPointer());
  681. String::CharPointerType dirPathIter (dirPath.getCharPointer());
  682. for (int i = 0;;)
  683. {
  684. const juce_wchar c1 = thisPathIter.getAndAdvance();
  685. const juce_wchar c2 = dirPathIter.getAndAdvance();
  686. #if NAMES_ARE_CASE_SENSITIVE
  687. if (c1 != c2
  688. #else
  689. if ((c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
  690. #endif
  691. || c1 == 0)
  692. break;
  693. ++i;
  694. if (c1 == separator)
  695. {
  696. thisPathAfterCommon = thisPathIter;
  697. dirPathAfterCommon = dirPathIter;
  698. commonBitLength = i;
  699. }
  700. }
  701. }
  702. // if the only common bit is the root, then just return the full path..
  703. if (commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == separator))
  704. return fullPath;
  705. const int numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  706. if (numUpDirectoriesNeeded == 0)
  707. return thisPathAfterCommon;
  708. #ifdef CARLA_OS_WIN
  709. String s (String::repeatedString ("..\\", numUpDirectoriesNeeded));
  710. #else
  711. String s (String::repeatedString ("../", numUpDirectoriesNeeded));
  712. #endif
  713. s.appendCharPointer (thisPathAfterCommon);
  714. return s;
  715. }
  716. //==============================================================================
  717. File File::createTempFile (StringRef fileNameEnding)
  718. {
  719. const File tempFile (getSpecialLocation (tempDirectory)
  720. .getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
  721. .withFileExtension (fileNameEnding));
  722. if (tempFile.exists())
  723. return createTempFile (fileNameEnding);
  724. return tempFile;
  725. }
  726. bool File::createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const
  727. {
  728. if (linkFileToCreate.exists())
  729. {
  730. if (! linkFileToCreate.isSymbolicLink())
  731. {
  732. // user has specified an existing file / directory as the link
  733. // this is bad! the user could end up unintentionally destroying data
  734. jassertfalse;
  735. return false;
  736. }
  737. if (overwriteExisting)
  738. linkFileToCreate.deleteFile();
  739. }
  740. #if JUCE_MAC || JUCE_LINUX
  741. // one common reason for getting an error here is that the file already exists
  742. if (symlink (fullPath.toRawUTF8(), linkFileToCreate.getFullPathName().toRawUTF8()) == -1)
  743. {
  744. jassertfalse;
  745. return false;
  746. }
  747. return true;
  748. #elif JUCE_MSVC
  749. return CreateSymbolicLink (linkFileToCreate.getFullPathName().toUTF8(),
  750. fullPath.toUTF8(),
  751. isDirectory() ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0) != FALSE;
  752. #else
  753. jassertfalse; // symbolic links not supported on this platform!
  754. return false;
  755. #endif
  756. }
  757. #if 0
  758. //=====================================================================================================================
  759. MemoryMappedFile::MemoryMappedFile (const File& file, MemoryMappedFile::AccessMode mode, bool exclusive)
  760. : address (nullptr), range (0, file.getSize()), fileHandle (0)
  761. {
  762. openInternal (file, mode, exclusive);
  763. }
  764. MemoryMappedFile::MemoryMappedFile (const File& file, const Range<int64>& fileRange, AccessMode mode, bool exclusive)
  765. : address (nullptr), range (fileRange.getIntersectionWith (Range<int64> (0, file.getSize()))), fileHandle (0)
  766. {
  767. openInternal (file, mode, exclusive);
  768. }
  769. #endif
  770. //=====================================================================================================================
  771. #ifdef CARLA_OS_WIN
  772. namespace WindowsFileHelpers
  773. {
  774. DWORD getAtts (const String& path)
  775. {
  776. return GetFileAttributes (path.toUTF8());
  777. }
  778. int64 fileTimeToTime (const FILETIME* const ft)
  779. {
  780. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  781. return (int64) ((reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - 116444736000000000LL) / 10000);
  782. }
  783. File getSpecialFolderPath (int type)
  784. {
  785. CHAR path [MAX_PATH + 256];
  786. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  787. return File (String (path));
  788. return File();
  789. }
  790. File getModuleFileName (HINSTANCE moduleHandle)
  791. {
  792. CHAR dest [MAX_PATH + 256];
  793. dest[0] = 0;
  794. GetModuleFileName (moduleHandle, dest, (DWORD) numElementsInArray (dest));
  795. return File (String (dest));
  796. }
  797. }
  798. const juce_wchar File::separator = '\\';
  799. const String File::separatorString ("\\");
  800. bool File::isDirectory() const
  801. {
  802. const DWORD attr = WindowsFileHelpers::getAtts (fullPath);
  803. return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0 && attr != INVALID_FILE_ATTRIBUTES;
  804. }
  805. bool File::exists() const
  806. {
  807. return fullPath.isNotEmpty()
  808. && WindowsFileHelpers::getAtts (fullPath) != INVALID_FILE_ATTRIBUTES;
  809. }
  810. bool File::existsAsFile() const
  811. {
  812. return fullPath.isNotEmpty()
  813. && (WindowsFileHelpers::getAtts (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  814. }
  815. bool File::hasWriteAccess() const
  816. {
  817. if (fullPath.isEmpty())
  818. return true;
  819. const DWORD attr = WindowsFileHelpers::getAtts (fullPath);
  820. // NB: According to MS, the FILE_ATTRIBUTE_READONLY attribute doesn't work for
  821. // folders, and can be incorrectly set for some special folders, so we'll just say
  822. // that folders are always writable.
  823. return attr == INVALID_FILE_ATTRIBUTES
  824. || (attr & FILE_ATTRIBUTE_DIRECTORY) != 0
  825. || (attr & FILE_ATTRIBUTE_READONLY) == 0;
  826. }
  827. int64 File::getSize() const
  828. {
  829. WIN32_FILE_ATTRIBUTE_DATA attributes;
  830. if (GetFileAttributesEx (fullPath.toUTF8(), GetFileExInfoStandard, &attributes))
  831. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  832. return 0;
  833. }
  834. bool File::deleteFile() const
  835. {
  836. if (! exists())
  837. return true;
  838. return isDirectory() ? RemoveDirectory (fullPath.toUTF8()) != 0
  839. : DeleteFile (fullPath.toUTF8()) != 0;
  840. }
  841. bool File::copyInternal (const File& dest) const
  842. {
  843. return CopyFile (fullPath.toUTF8(), dest.getFullPathName().toUTF8(), false) != 0;
  844. }
  845. bool File::moveInternal (const File& dest) const
  846. {
  847. return MoveFile (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) != 0;
  848. }
  849. bool File::replaceInternal (const File& dest) const
  850. {
  851. void* lpExclude = 0;
  852. void* lpReserved = 0;
  853. return ReplaceFile (dest.getFullPathName().toUTF8(), fullPath.toUTF8(),
  854. 0, REPLACEFILE_IGNORE_MERGE_ERRORS, lpExclude, lpReserved) != 0;
  855. }
  856. Result File::createDirectoryInternal (const String& fileName) const
  857. {
  858. return CreateDirectory (fileName.toUTF8(), 0) ? Result::ok()
  859. : getResultForLastError();
  860. }
  861. File File::getCurrentWorkingDirectory()
  862. {
  863. CHAR dest [MAX_PATH + 256];
  864. dest[0] = 0;
  865. GetCurrentDirectory ((DWORD) numElementsInArray (dest), dest);
  866. return File (String (dest));
  867. }
  868. bool File::isSymbolicLink() const
  869. {
  870. return (GetFileAttributes (fullPath.toUTF8()) & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
  871. }
  872. File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  873. {
  874. int csidlType = 0;
  875. switch (type)
  876. {
  877. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  878. case tempDirectory:
  879. {
  880. CHAR dest [2048];
  881. dest[0] = 0;
  882. GetTempPath ((DWORD) numElementsInArray (dest), dest);
  883. return File (String (dest));
  884. }
  885. case windowsSystemDirectory:
  886. {
  887. CHAR dest [2048];
  888. dest[0] = 0;
  889. GetSystemDirectory (dest, (UINT) numElementsInArray (dest));
  890. return File (String (dest));
  891. }
  892. case currentExecutableFile:
  893. case currentApplicationFile:
  894. return WindowsFileHelpers::getModuleFileName ((HINSTANCE) Process::getCurrentModuleInstanceHandle());
  895. case hostApplicationPath:
  896. return WindowsFileHelpers::getModuleFileName (0);
  897. default:
  898. jassertfalse; // unknown type?
  899. return File();
  900. }
  901. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  902. }
  903. //=====================================================================================================================
  904. class DirectoryIterator::NativeIterator::Pimpl
  905. {
  906. public:
  907. Pimpl (const File& directory, const String& wildCard)
  908. : directoryWithWildCard (directory.getFullPathName().isNotEmpty() ? File::addTrailingSeparator (directory.getFullPathName()) + wildCard : String()),
  909. handle (INVALID_HANDLE_VALUE)
  910. {
  911. }
  912. ~Pimpl()
  913. {
  914. if (handle != INVALID_HANDLE_VALUE)
  915. FindClose (handle);
  916. }
  917. bool next (String& filenameFound,
  918. bool* const isDir, bool* const isHidden, int64* const fileSize,
  919. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  920. {
  921. using namespace WindowsFileHelpers;
  922. WIN32_FIND_DATA findData;
  923. if (handle == INVALID_HANDLE_VALUE)
  924. {
  925. handle = FindFirstFile (directoryWithWildCard.toUTF8(), &findData);
  926. if (handle == INVALID_HANDLE_VALUE)
  927. return false;
  928. }
  929. else
  930. {
  931. if (FindNextFile (handle, &findData) == 0)
  932. return false;
  933. }
  934. filenameFound = findData.cFileName;
  935. if (isDir != nullptr) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  936. if (isHidden != nullptr) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  937. if (isReadOnly != nullptr) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  938. if (fileSize != nullptr) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  939. if (modTime != nullptr) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  940. if (creationTime != nullptr) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  941. return true;
  942. }
  943. private:
  944. const String directoryWithWildCard;
  945. HANDLE handle;
  946. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  947. };
  948. #else
  949. //=====================================================================================================================
  950. namespace
  951. {
  952. #if CARLA_OS_MAC
  953. typedef struct stat juce_statStruct;
  954. #define JUCE_STAT stat
  955. #else
  956. typedef struct stat64 juce_statStruct;
  957. #define JUCE_STAT stat64
  958. #endif
  959. bool juce_stat (const String& fileName, juce_statStruct& info)
  960. {
  961. return fileName.isNotEmpty()
  962. && JUCE_STAT (fileName.toUTF8(), &info) == 0;
  963. }
  964. #if CARLA_OS_MAC
  965. static int64 getCreationTime (const juce_statStruct& s) noexcept { return (int64) s.st_birthtime; }
  966. #else
  967. static int64 getCreationTime (const juce_statStruct& s) noexcept { return (int64) s.st_ctime; }
  968. #endif
  969. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  970. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  971. {
  972. if (isDir != nullptr || fileSize != nullptr || modTime != nullptr || creationTime != nullptr)
  973. {
  974. juce_statStruct info;
  975. const bool statOk = juce_stat (path, info);
  976. if (isDir != nullptr) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  977. if (fileSize != nullptr) *fileSize = statOk ? (int64) info.st_size : 0;
  978. if (modTime != nullptr) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  979. if (creationTime != nullptr) *creationTime = Time (statOk ? getCreationTime (info) * 1000 : 0);
  980. }
  981. if (isReadOnly != nullptr)
  982. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  983. }
  984. Result getResultForReturnValue (int value)
  985. {
  986. return value == -1 ? getResultForErrno() : Result::ok();
  987. }
  988. }
  989. const juce_wchar File::separator = '/';
  990. const String File::separatorString ("/");
  991. bool File::isDirectory() const
  992. {
  993. juce_statStruct info;
  994. return fullPath.isNotEmpty()
  995. && (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  996. }
  997. bool File::exists() const
  998. {
  999. return fullPath.isNotEmpty()
  1000. && access (fullPath.toUTF8(), F_OK) == 0;
  1001. }
  1002. bool File::existsAsFile() const
  1003. {
  1004. return exists() && ! isDirectory();
  1005. }
  1006. bool File::hasWriteAccess() const
  1007. {
  1008. if (exists())
  1009. return access (fullPath.toUTF8(), W_OK) == 0;
  1010. if ((! isDirectory()) && fullPath.containsChar (separator))
  1011. return getParentDirectory().hasWriteAccess();
  1012. return false;
  1013. }
  1014. int64 File::getSize() const
  1015. {
  1016. juce_statStruct info;
  1017. return juce_stat (fullPath, info) ? info.st_size : 0;
  1018. }
  1019. bool File::deleteFile() const
  1020. {
  1021. if (! exists() && ! isSymbolicLink())
  1022. return true;
  1023. if (isDirectory())
  1024. return rmdir (fullPath.toUTF8()) == 0;
  1025. return remove (fullPath.toUTF8()) == 0;
  1026. }
  1027. bool File::moveInternal (const File& dest) const
  1028. {
  1029. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  1030. return true;
  1031. if (hasWriteAccess() && copyInternal (dest))
  1032. {
  1033. if (deleteFile())
  1034. return true;
  1035. dest.deleteFile();
  1036. }
  1037. return false;
  1038. }
  1039. bool File::replaceInternal (const File& dest) const
  1040. {
  1041. return moveInternal (dest);
  1042. }
  1043. Result File::createDirectoryInternal (const String& fileName) const
  1044. {
  1045. return getResultForReturnValue (mkdir (fileName.toUTF8(), 0777));
  1046. }
  1047. File File::getCurrentWorkingDirectory()
  1048. {
  1049. HeapBlock<char> heapBuffer;
  1050. char localBuffer [1024];
  1051. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  1052. size_t bufferSize = 4096;
  1053. while (cwd == nullptr && errno == ERANGE)
  1054. {
  1055. heapBuffer.malloc (bufferSize);
  1056. cwd = getcwd (heapBuffer, bufferSize - 1);
  1057. bufferSize += 1024;
  1058. }
  1059. return File (CharPointer_UTF8 (cwd));
  1060. }
  1061. File juce_getExecutableFile();
  1062. File juce_getExecutableFile()
  1063. {
  1064. struct DLAddrReader
  1065. {
  1066. static String getFilename()
  1067. {
  1068. Dl_info exeInfo;
  1069. void* localSymbol = (void*) juce_getExecutableFile;
  1070. dladdr (localSymbol, &exeInfo);
  1071. const CharPointer_UTF8 filename (exeInfo.dli_fname);
  1072. // if the filename is absolute simply return it
  1073. if (File::isAbsolutePath (filename))
  1074. return filename;
  1075. // if the filename is relative construct from CWD
  1076. if (filename[0] == '.')
  1077. return File::getCurrentWorkingDirectory().getChildFile (filename).getFullPathName();
  1078. // filename is abstract, look up in PATH
  1079. if (const char* const envpath = ::getenv ("PATH"))
  1080. {
  1081. StringArray paths (StringArray::fromTokens (envpath, ":", ""));
  1082. for (int i=paths.size(); --i>=0;)
  1083. {
  1084. const File filepath (File (paths[i]).getChildFile (filename));
  1085. if (filepath.existsAsFile())
  1086. return filepath.getFullPathName();
  1087. }
  1088. }
  1089. // if we reach this, we failed to find ourselves...
  1090. jassertfalse;
  1091. return filename;
  1092. }
  1093. };
  1094. static String filename (DLAddrReader::getFilename());
  1095. return filename;
  1096. }
  1097. #ifdef CARLA_OS_MAC
  1098. static NSString* getFileLink (const String& path)
  1099. {
  1100. return [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (path) error: nil];
  1101. }
  1102. bool File::isSymbolicLink() const
  1103. {
  1104. return getFileLink (fullPath) != nil;
  1105. }
  1106. File File::getLinkedTarget() const
  1107. {
  1108. if (NSString* dest = getFileLink (fullPath))
  1109. return getSiblingFile (nsStringToJuce (dest));
  1110. return *this;
  1111. }
  1112. bool File::copyInternal (const File& dest) const
  1113. {
  1114. JUCE_AUTORELEASEPOOL
  1115. {
  1116. NSFileManager* fm = [NSFileManager defaultManager];
  1117. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  1118. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1119. && [fm copyItemAtPath: juceStringToNS (fullPath)
  1120. toPath: juceStringToNS (dest.getFullPathName())
  1121. error: nil];
  1122. #else
  1123. && [fm copyPath: juceStringToNS (fullPath)
  1124. toPath: juceStringToNS (dest.getFullPathName())
  1125. handler: nil];
  1126. #endif
  1127. }
  1128. }
  1129. File File::getSpecialLocation (const SpecialLocationType type)
  1130. {
  1131. JUCE_AUTORELEASEPOOL
  1132. {
  1133. String resultPath;
  1134. switch (type)
  1135. {
  1136. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  1137. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  1138. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  1139. case tempDirectory:
  1140. {
  1141. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  1142. tmp.createDirectory();
  1143. return File (tmp.getFullPathName());
  1144. }
  1145. case userMusicDirectory: resultPath = "~/Music"; break;
  1146. case userMoviesDirectory: resultPath = "~/Movies"; break;
  1147. case userPicturesDirectory: resultPath = "~/Pictures"; break;
  1148. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  1149. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  1150. case commonDocumentsDirectory: resultPath = "/Users/Shared"; break;
  1151. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  1152. case invokedExecutableFile:
  1153. if (juce_argv != nullptr && juce_argc > 0)
  1154. return File::getCurrentWorkingDirectory().getChildFile (CharPointer_UTF8 (juce_argv[0]));
  1155. // deliberate fall-through...
  1156. case currentExecutableFile:
  1157. return juce_getExecutableFile();
  1158. case currentApplicationFile:
  1159. {
  1160. const File exe (juce_getExecutableFile());
  1161. const File parent (exe.getParentDirectory());
  1162. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  1163. ? parent.getParentDirectory().getParentDirectory()
  1164. : exe;
  1165. }
  1166. case hostApplicationPath:
  1167. {
  1168. unsigned int size = 8192;
  1169. HeapBlock<char> buffer;
  1170. buffer.calloc (size + 8);
  1171. _NSGetExecutablePath (buffer.getData(), &size);
  1172. return File (String::fromUTF8 (buffer, (int) size));
  1173. }
  1174. default:
  1175. jassertfalse; // unknown type?
  1176. break;
  1177. }
  1178. if (resultPath.isNotEmpty())
  1179. return File (resultPath.convertToPrecomposedUnicode());
  1180. }
  1181. return File();
  1182. }
  1183. //==============================================================================
  1184. class DirectoryIterator::NativeIterator::Pimpl
  1185. {
  1186. public:
  1187. Pimpl (const File& directory, const String& wildCard_)
  1188. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  1189. wildCard (wildCard_),
  1190. enumerator (nil)
  1191. {
  1192. JUCE_AUTORELEASEPOOL
  1193. {
  1194. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  1195. }
  1196. }
  1197. ~Pimpl()
  1198. {
  1199. [enumerator release];
  1200. }
  1201. bool next (String& filenameFound,
  1202. bool* const isDir, bool* const isHidden, int64* const fileSize,
  1203. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  1204. {
  1205. JUCE_AUTORELEASEPOOL
  1206. {
  1207. const char* wildcardUTF8 = nullptr;
  1208. for (;;)
  1209. {
  1210. NSString* file;
  1211. if (enumerator == nil || (file = [enumerator nextObject]) == nil)
  1212. return false;
  1213. [enumerator skipDescendents];
  1214. filenameFound = nsStringToJuce (file).convertToPrecomposedUnicode();
  1215. if (wildcardUTF8 == nullptr)
  1216. wildcardUTF8 = wildCard.toUTF8();
  1217. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  1218. continue;
  1219. const String fullPath (parentDir + filenameFound);
  1220. updateStatInfoForFile (fullPath, isDir, fileSize, modTime, creationTime, isReadOnly);
  1221. if (isHidden != nullptr)
  1222. *isHidden = MacFileHelpers::isHiddenFile (fullPath);
  1223. return true;
  1224. }
  1225. }
  1226. }
  1227. private:
  1228. String parentDir, wildCard;
  1229. NSDirectoryEnumerator* enumerator;
  1230. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  1231. };
  1232. #else
  1233. static String getLinkedFile (const String& file)
  1234. {
  1235. HeapBlock<char> buffer (8194);
  1236. const int numBytes = (int) readlink (file.toRawUTF8(), buffer, 8192);
  1237. return String::fromUTF8 (buffer, jmax (0, numBytes));
  1238. }
  1239. bool File::isSymbolicLink() const
  1240. {
  1241. return getLinkedFile (getFullPathName()).isNotEmpty();
  1242. }
  1243. File File::getLinkedTarget() const
  1244. {
  1245. String f (getLinkedFile (getFullPathName()));
  1246. if (f.isNotEmpty())
  1247. return getSiblingFile (f);
  1248. return *this;
  1249. }
  1250. bool File::copyInternal (const File& dest) const
  1251. {
  1252. FileInputStream in (*this);
  1253. if (dest.deleteFile())
  1254. {
  1255. {
  1256. FileOutputStream out (dest);
  1257. if (out.failedToOpen())
  1258. return false;
  1259. if (out.writeFromInputStream (in, -1) == getSize())
  1260. return true;
  1261. }
  1262. dest.deleteFile();
  1263. }
  1264. return false;
  1265. }
  1266. File File::getSpecialLocation (const SpecialLocationType type)
  1267. {
  1268. switch (type)
  1269. {
  1270. case userHomeDirectory:
  1271. {
  1272. if (const char* homeDir = getenv ("HOME"))
  1273. return File (CharPointer_UTF8 (homeDir));
  1274. if (struct passwd* const pw = getpwuid (getuid()))
  1275. return File (CharPointer_UTF8 (pw->pw_dir));
  1276. return File();
  1277. }
  1278. case tempDirectory:
  1279. {
  1280. File tmp ("/var/tmp");
  1281. if (! tmp.isDirectory())
  1282. {
  1283. tmp = "/tmp";
  1284. if (! tmp.isDirectory())
  1285. tmp = File::getCurrentWorkingDirectory();
  1286. }
  1287. return tmp;
  1288. }
  1289. case currentExecutableFile:
  1290. case currentApplicationFile:
  1291. return juce_getExecutableFile();
  1292. case hostApplicationPath:
  1293. {
  1294. const File f ("/proc/self/exe");
  1295. return f.isSymbolicLink() ? f.getLinkedTarget() : juce_getExecutableFile();
  1296. }
  1297. default:
  1298. jassertfalse; // unknown type?
  1299. break;
  1300. }
  1301. return File();
  1302. }
  1303. //==============================================================================
  1304. class DirectoryIterator::NativeIterator::Pimpl
  1305. {
  1306. public:
  1307. Pimpl (const File& directory, const String& wc)
  1308. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  1309. wildCard (wc), dir (opendir (directory.getFullPathName().toUTF8()))
  1310. {
  1311. }
  1312. ~Pimpl()
  1313. {
  1314. if (dir != nullptr)
  1315. closedir (dir);
  1316. }
  1317. bool next (String& filenameFound,
  1318. bool* const isDir, bool* const isHidden, int64* const fileSize,
  1319. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  1320. {
  1321. if (dir != nullptr)
  1322. {
  1323. const char* wildcardUTF8 = nullptr;
  1324. for (;;)
  1325. {
  1326. struct dirent* const de = readdir (dir);
  1327. if (de == nullptr)
  1328. break;
  1329. if (wildcardUTF8 == nullptr)
  1330. wildcardUTF8 = wildCard.toUTF8();
  1331. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  1332. {
  1333. filenameFound = CharPointer_UTF8 (de->d_name);
  1334. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  1335. if (isHidden != nullptr)
  1336. *isHidden = filenameFound.startsWithChar ('.');
  1337. return true;
  1338. }
  1339. }
  1340. }
  1341. return false;
  1342. }
  1343. private:
  1344. String parentDir, wildCard;
  1345. DIR* dir;
  1346. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  1347. };
  1348. #endif
  1349. #endif
  1350. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCardStr)
  1351. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCardStr))
  1352. {
  1353. }
  1354. DirectoryIterator::NativeIterator::~NativeIterator() {}
  1355. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  1356. bool* isDir, bool* isHidden, int64* fileSize,
  1357. Time* modTime, Time* creationTime, bool* isReadOnly)
  1358. {
  1359. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  1360. }