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.

1690 lines
50KB

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