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.

1705 lines
49KB

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