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.

1704 lines
50KB

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