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.

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