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.

1698 lines
49KB

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