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.

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