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.

1731 lines
50KB

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