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.

1718 lines
52KB

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