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.

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