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.

1756 lines
50KB

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