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.

1685 lines
50KB

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