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.

1712 lines
51KB

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