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.

1717 lines
52KB

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