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.

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