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.

1684 lines
50KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #include "File.h"
  21. #include "DirectoryIterator.h"
  22. #include "FileInputStream.h"
  23. #include "FileOutputStream.h"
  24. #include "TemporaryFile.h"
  25. #include "../maths/Random.h"
  26. #include "../misc/Time.h"
  27. #include "../text/StringArray.h"
  28. #include "CarlaJuceUtils.hpp"
  29. #ifdef CARLA_OS_WIN
  30. # include <shlobj.h>
  31. #else
  32. # include <dlfcn.h>
  33. # include <fcntl.h>
  34. # include <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 (const String& fullPathName)
  48. : fullPath (parseAbsolutePath (fullPathName))
  49. {
  50. }
  51. File File::createFileWithoutCheckingPath (const String& path) noexcept
  52. {
  53. File f;
  54. f.fullPath = path;
  55. return f;
  56. }
  57. File::File (const File& other)
  58. : fullPath (other.fullPath)
  59. {
  60. }
  61. File& File::operator= (const String& newPath)
  62. {
  63. fullPath = parseAbsolutePath (newPath);
  64. return *this;
  65. }
  66. File& File::operator= (const File& other)
  67. {
  68. fullPath = other.fullPath;
  69. return *this;
  70. }
  71. #if WATER_COMPILER_SUPPORTS_MOVE_SEMANTICS
  72. File::File (File&& other) noexcept
  73. : fullPath (static_cast<String&&> (other.fullPath))
  74. {
  75. }
  76. File& File::operator= (File&& other) noexcept
  77. {
  78. fullPath = static_cast<String&&> (other.fullPath);
  79. return *this;
  80. }
  81. #endif
  82. //==============================================================================
  83. static String removeEllipsis (const String& path)
  84. {
  85. // This will quickly find both /../ and /./ at the expense of a minor
  86. // false-positive performance hit when path elements end in a dot.
  87. #ifdef CARLA_OS_WIN
  88. if (path.contains (".\\"))
  89. #else
  90. if (path.contains ("./"))
  91. #endif
  92. {
  93. StringArray toks;
  94. toks.addTokens (path, File::separatorString, StringRef());
  95. bool anythingChanged = false;
  96. for (int i = 1; i < toks.size(); ++i)
  97. {
  98. const String& t = toks[i];
  99. if (t == ".." && toks[i - 1] != "..")
  100. {
  101. anythingChanged = true;
  102. toks.removeRange (i - 1, 2);
  103. i = jmax (0, i - 2);
  104. }
  105. else if (t == ".")
  106. {
  107. anythingChanged = true;
  108. toks.remove (i--);
  109. }
  110. }
  111. if (anythingChanged)
  112. return toks.joinIntoString (File::separatorString);
  113. }
  114. return path;
  115. }
  116. String File::parseAbsolutePath (const String& p)
  117. {
  118. if (p.isEmpty())
  119. return String();
  120. #ifdef CARLA_OS_WIN
  121. // Windows..
  122. String path (removeEllipsis (p.replaceCharacter ('/', '\\')));
  123. if (path.startsWithChar (separator))
  124. {
  125. if (path[1] != separator)
  126. {
  127. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  128. If you're trying to parse a string that may be either a relative path or an absolute path,
  129. you MUST provide a context against which the partial path can be evaluated - you can do
  130. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  131. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  132. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  133. */
  134. jassertfalse;
  135. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  136. }
  137. }
  138. else if (! path.containsChar (':'))
  139. {
  140. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  141. If you're trying to parse a string that may be either a relative path or an absolute path,
  142. you MUST provide a context against which the partial path can be evaluated - you can do
  143. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  144. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  145. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  146. */
  147. jassertfalse;
  148. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  149. }
  150. #else
  151. // Mac or Linux..
  152. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  153. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  154. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  155. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  156. String path (removeEllipsis (p));
  157. if (path.startsWithChar ('~'))
  158. {
  159. if (path[1] == separator || path[1] == 0)
  160. {
  161. // expand a name of the form "~/abc"
  162. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  163. + path.substring (1);
  164. }
  165. else
  166. {
  167. // expand a name of type "~dave/abc"
  168. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  169. if (struct passwd* const pw = getpwnam (userName.toUTF8()))
  170. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  171. }
  172. }
  173. else if (! path.startsWithChar (separator))
  174. {
  175. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  176. If you're trying to parse a string that may be either a relative path or an absolute path,
  177. you MUST provide a context against which the partial path can be evaluated - you can do
  178. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  179. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  180. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  181. */
  182. CARLA_SAFE_ASSERT_RETURN(path.startsWith ("./") || path.startsWith ("../"), String());
  183. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  184. }
  185. #endif
  186. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  187. path = path.dropLastCharacters (1);
  188. return path;
  189. }
  190. String File::addTrailingSeparator (const String& path)
  191. {
  192. return path.endsWithChar (separator) ? path
  193. : path + separator;
  194. }
  195. //==============================================================================
  196. #if ! (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  197. #define NAMES_ARE_CASE_SENSITIVE 1
  198. #endif
  199. bool File::areFileNamesCaseSensitive()
  200. {
  201. #if NAMES_ARE_CASE_SENSITIVE
  202. return true;
  203. #else
  204. return false;
  205. #endif
  206. }
  207. static int compareFilenames (const String& name1, const String& name2) noexcept
  208. {
  209. #if NAMES_ARE_CASE_SENSITIVE
  210. return name1.compare (name2);
  211. #else
  212. return name1.compareIgnoreCase (name2);
  213. #endif
  214. }
  215. bool File::operator== (const File& other) const { return compareFilenames (fullPath, other.fullPath) == 0; }
  216. bool File::operator!= (const File& other) const { return compareFilenames (fullPath, other.fullPath) != 0; }
  217. bool File::operator< (const File& other) const { return compareFilenames (fullPath, other.fullPath) < 0; }
  218. bool File::operator> (const File& other) const { return compareFilenames (fullPath, other.fullPath) > 0; }
  219. //==============================================================================
  220. bool File::deleteRecursively() const
  221. {
  222. bool worked = true;
  223. if (isDirectory())
  224. {
  225. Array<File> subFiles;
  226. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  227. for (int i = subFiles.size(); --i >= 0;)
  228. worked = subFiles.getReference(i).deleteRecursively() && worked;
  229. }
  230. return deleteFile() && worked;
  231. }
  232. bool File::moveFileTo (const File& newFile) const
  233. {
  234. if (newFile.fullPath == fullPath)
  235. return true;
  236. if (! exists())
  237. return false;
  238. #if ! NAMES_ARE_CASE_SENSITIVE
  239. if (*this != newFile)
  240. #endif
  241. if (! newFile.deleteFile())
  242. return false;
  243. return moveInternal (newFile);
  244. }
  245. bool File::copyFileTo (const File& newFile) const
  246. {
  247. return (*this == newFile)
  248. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  249. }
  250. bool File::replaceFileIn (const File& newFile) const
  251. {
  252. if (newFile.fullPath == fullPath)
  253. return true;
  254. if (! newFile.exists())
  255. return moveFileTo (newFile);
  256. if (! replaceInternal (newFile))
  257. return false;
  258. deleteFile();
  259. return true;
  260. }
  261. bool File::copyDirectoryTo (const File& newDirectory) const
  262. {
  263. if (isDirectory() && newDirectory.createDirectory())
  264. {
  265. Array<File> subFiles;
  266. findChildFiles (subFiles, File::findFiles, false);
  267. for (int i = 0; i < subFiles.size(); ++i)
  268. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  269. return false;
  270. subFiles.clear();
  271. findChildFiles (subFiles, File::findDirectories, false);
  272. for (int i = 0; i < subFiles.size(); ++i)
  273. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  274. return false;
  275. return true;
  276. }
  277. return false;
  278. }
  279. //==============================================================================
  280. String File::getPathUpToLastSlash() const
  281. {
  282. const int lastSlash = fullPath.lastIndexOfChar (separator);
  283. if (lastSlash > 0)
  284. return fullPath.substring (0, lastSlash);
  285. if (lastSlash == 0)
  286. return separatorString;
  287. return fullPath;
  288. }
  289. File File::getParentDirectory() const
  290. {
  291. File f;
  292. f.fullPath = getPathUpToLastSlash();
  293. return f;
  294. }
  295. //==============================================================================
  296. String File::getFileName() const
  297. {
  298. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  299. }
  300. String File::getFileNameWithoutExtension() const
  301. {
  302. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  303. const int lastDot = fullPath.lastIndexOfChar ('.');
  304. if (lastDot > lastSlash)
  305. return fullPath.substring (lastSlash, lastDot);
  306. return fullPath.substring (lastSlash);
  307. }
  308. bool File::isAChildOf (const File& potentialParent) const
  309. {
  310. if (potentialParent.fullPath.isEmpty())
  311. return false;
  312. const String ourPath (getPathUpToLastSlash());
  313. if (compareFilenames (potentialParent.fullPath, ourPath) == 0)
  314. return true;
  315. if (potentialParent.fullPath.length() >= ourPath.length())
  316. return false;
  317. return getParentDirectory().isAChildOf (potentialParent);
  318. }
  319. #if 0
  320. int File::hashCode() const { return fullPath.hashCode(); }
  321. int64 File::hashCode64() const { return fullPath.hashCode64(); }
  322. #endif
  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. ScopedPointer<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. ScopedPointer<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. jassert (((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. if (! linkFileToCreate.isSymbolicLink())
  747. {
  748. // user has specified an existing file / directory as the link
  749. // this is bad! the user could end up unintentionally destroying data
  750. jassertfalse;
  751. return false;
  752. }
  753. if (overwriteExisting)
  754. linkFileToCreate.deleteFile();
  755. }
  756. #ifndef CARLA_OS_WIN
  757. // one common reason for getting an error here is that the file already exists
  758. if (symlink (fullPath.toRawUTF8(), linkFileToCreate.getFullPathName().toRawUTF8()) == -1)
  759. {
  760. jassertfalse;
  761. return false;
  762. }
  763. return true;
  764. #elif _MSVC_VER
  765. return CreateSymbolicLink (linkFileToCreate.getFullPathName().toUTF8(),
  766. fullPath.toUTF8(),
  767. isDirectory() ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0) != FALSE;
  768. #else
  769. jassertfalse; // symbolic links not supported on this platform!
  770. return false;
  771. #endif
  772. }
  773. #if 0
  774. //=====================================================================================================================
  775. MemoryMappedFile::MemoryMappedFile (const File& file, MemoryMappedFile::AccessMode mode, bool exclusive)
  776. : address (nullptr), range (0, file.getSize()), fileHandle (0)
  777. {
  778. openInternal (file, mode, exclusive);
  779. }
  780. MemoryMappedFile::MemoryMappedFile (const File& file, const Range<int64>& fileRange, AccessMode mode, bool exclusive)
  781. : address (nullptr), range (fileRange.getIntersectionWith (Range<int64> (0, file.getSize()))), fileHandle (0)
  782. {
  783. openInternal (file, mode, exclusive);
  784. }
  785. #endif
  786. //=====================================================================================================================
  787. #ifdef CARLA_OS_WIN
  788. namespace WindowsFileHelpers
  789. {
  790. DWORD getAtts (const String& path)
  791. {
  792. return GetFileAttributes (path.toUTF8());
  793. }
  794. int64 fileTimeToTime (const FILETIME* const ft)
  795. {
  796. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  797. return (int64) ((reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - 116444736000000000LL) / 10000);
  798. }
  799. File getSpecialFolderPath (int type)
  800. {
  801. CHAR path [MAX_PATH + 256];
  802. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  803. return File (String (path));
  804. return File();
  805. }
  806. File getModuleFileName (HINSTANCE moduleHandle)
  807. {
  808. CHAR dest [MAX_PATH + 256];
  809. dest[0] = 0;
  810. GetModuleFileName (moduleHandle, dest, (DWORD) numElementsInArray (dest));
  811. return File (String (dest));
  812. }
  813. }
  814. const water_uchar File::separator = '\\';
  815. const String File::separatorString ("\\");
  816. bool File::isDirectory() const
  817. {
  818. const DWORD attr = WindowsFileHelpers::getAtts (fullPath);
  819. return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0 && attr != INVALID_FILE_ATTRIBUTES;
  820. }
  821. bool File::exists() const
  822. {
  823. return fullPath.isNotEmpty()
  824. && WindowsFileHelpers::getAtts (fullPath) != INVALID_FILE_ATTRIBUTES;
  825. }
  826. bool File::existsAsFile() const
  827. {
  828. return fullPath.isNotEmpty()
  829. && (WindowsFileHelpers::getAtts (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  830. }
  831. bool File::hasWriteAccess() const
  832. {
  833. if (fullPath.isEmpty())
  834. return true;
  835. const DWORD attr = WindowsFileHelpers::getAtts (fullPath);
  836. // NB: According to MS, the FILE_ATTRIBUTE_READONLY attribute doesn't work for
  837. // folders, and can be incorrectly set for some special folders, so we'll just say
  838. // that folders are always writable.
  839. return attr == INVALID_FILE_ATTRIBUTES
  840. || (attr & FILE_ATTRIBUTE_DIRECTORY) != 0
  841. || (attr & FILE_ATTRIBUTE_READONLY) == 0;
  842. }
  843. int64 File::getSize() const
  844. {
  845. WIN32_FILE_ATTRIBUTE_DATA attributes;
  846. if (GetFileAttributesEx (fullPath.toUTF8(), GetFileExInfoStandard, &attributes))
  847. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  848. return 0;
  849. }
  850. bool File::deleteFile() const
  851. {
  852. if (! exists())
  853. return true;
  854. return isDirectory() ? RemoveDirectory (fullPath.toUTF8()) != 0
  855. : DeleteFile (fullPath.toUTF8()) != 0;
  856. }
  857. bool File::copyInternal (const File& dest) const
  858. {
  859. return CopyFile (fullPath.toUTF8(), dest.getFullPathName().toUTF8(), false) != 0;
  860. }
  861. bool File::moveInternal (const File& dest) const
  862. {
  863. return MoveFile (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) != 0;
  864. }
  865. bool File::replaceInternal (const File& dest) const
  866. {
  867. void* lpExclude = 0;
  868. void* lpReserved = 0;
  869. return ReplaceFile (dest.getFullPathName().toUTF8(), fullPath.toUTF8(),
  870. 0, REPLACEFILE_IGNORE_MERGE_ERRORS, lpExclude, lpReserved) != 0;
  871. }
  872. Result File::createDirectoryInternal (const String& fileName) const
  873. {
  874. return CreateDirectory (fileName.toUTF8(), 0) ? Result::ok()
  875. : getResultForLastError();
  876. }
  877. File File::getCurrentWorkingDirectory()
  878. {
  879. CHAR dest [MAX_PATH + 256];
  880. dest[0] = 0;
  881. GetCurrentDirectory ((DWORD) numElementsInArray (dest), dest);
  882. return File (String (dest));
  883. }
  884. bool File::isSymbolicLink() const
  885. {
  886. return (GetFileAttributes (fullPath.toUTF8()) & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
  887. }
  888. File File::getSpecialLocation (const SpecialLocationType type)
  889. {
  890. int csidlType = 0;
  891. switch (type)
  892. {
  893. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  894. case tempDirectory:
  895. {
  896. CHAR dest [2048];
  897. dest[0] = 0;
  898. GetTempPath ((DWORD) numElementsInArray (dest), dest);
  899. return File (String (dest));
  900. }
  901. case currentExecutableFile:
  902. return WindowsFileHelpers::getModuleFileName (water_getCurrentModuleInstanceHandle());
  903. case hostApplicationPath:
  904. return WindowsFileHelpers::getModuleFileName (nullptr);
  905. default:
  906. jassertfalse; // unknown type?
  907. return File();
  908. }
  909. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  910. }
  911. //=====================================================================================================================
  912. class DirectoryIterator::NativeIterator::Pimpl
  913. {
  914. public:
  915. Pimpl (const File& directory, const String& wildCard)
  916. : directoryWithWildCard (directory.getFullPathName().isNotEmpty() ? File::addTrailingSeparator (directory.getFullPathName()) + wildCard : String()),
  917. handle (INVALID_HANDLE_VALUE)
  918. {
  919. }
  920. ~Pimpl()
  921. {
  922. if (handle != INVALID_HANDLE_VALUE)
  923. FindClose (handle);
  924. }
  925. bool next (String& filenameFound,
  926. bool* const isDir, int64* const fileSize,
  927. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  928. {
  929. using namespace WindowsFileHelpers;
  930. WIN32_FIND_DATA findData;
  931. if (handle == INVALID_HANDLE_VALUE)
  932. {
  933. handle = FindFirstFile (directoryWithWildCard.toUTF8(), &findData);
  934. if (handle == INVALID_HANDLE_VALUE)
  935. return false;
  936. }
  937. else
  938. {
  939. if (FindNextFile (handle, &findData) == 0)
  940. return false;
  941. }
  942. filenameFound = findData.cFileName;
  943. if (isDir != nullptr) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  944. if (isReadOnly != nullptr) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  945. if (fileSize != nullptr) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  946. if (modTime != nullptr) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  947. if (creationTime != nullptr) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  948. return true;
  949. }
  950. private:
  951. const String directoryWithWildCard;
  952. HANDLE handle;
  953. CARLA_DECLARE_NON_COPY_CLASS (Pimpl)
  954. };
  955. #else
  956. //=====================================================================================================================
  957. namespace
  958. {
  959. #ifdef CARLA_OS_LINUX
  960. typedef struct stat64 water_statStruct;
  961. #define WATER_STAT stat64
  962. #else
  963. typedef struct stat water_statStruct;
  964. #define WATER_STAT stat
  965. #endif
  966. bool water_stat (const String& fileName, water_statStruct& info)
  967. {
  968. return fileName.isNotEmpty()
  969. && WATER_STAT (fileName.toUTF8(), &info) == 0;
  970. }
  971. #if 0 //def CARLA_OS_MAC
  972. static int64 getCreationTime (const water_statStruct& s) noexcept { return (int64) s.st_birthtime; }
  973. #else
  974. static int64 getCreationTime (const water_statStruct& s) noexcept { return (int64) s.st_ctime; }
  975. #endif
  976. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  977. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  978. {
  979. if (isDir != nullptr || fileSize != nullptr || modTime != nullptr || creationTime != nullptr)
  980. {
  981. water_statStruct info;
  982. const bool statOk = water_stat (path, info);
  983. if (isDir != nullptr) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  984. if (fileSize != nullptr) *fileSize = statOk ? (int64) info.st_size : 0;
  985. if (modTime != nullptr) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  986. if (creationTime != nullptr) *creationTime = Time (statOk ? getCreationTime (info) * 1000 : 0);
  987. }
  988. if (isReadOnly != nullptr)
  989. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  990. }
  991. Result getResultForReturnValue (int value)
  992. {
  993. return value == -1 ? getResultForErrno() : Result::ok();
  994. }
  995. }
  996. const water_uchar File::separator = '/';
  997. const String File::separatorString ("/");
  998. bool File::isDirectory() const
  999. {
  1000. water_statStruct info;
  1001. return fullPath.isNotEmpty()
  1002. && (water_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  1003. }
  1004. bool File::exists() const
  1005. {
  1006. return fullPath.isNotEmpty()
  1007. && access (fullPath.toUTF8(), F_OK) == 0;
  1008. }
  1009. bool File::existsAsFile() const
  1010. {
  1011. return exists() && ! isDirectory();
  1012. }
  1013. bool File::hasWriteAccess() const
  1014. {
  1015. if (exists())
  1016. return access (fullPath.toUTF8(), W_OK) == 0;
  1017. if ((! isDirectory()) && fullPath.containsChar (separator))
  1018. return getParentDirectory().hasWriteAccess();
  1019. return false;
  1020. }
  1021. int64 File::getSize() const
  1022. {
  1023. water_statStruct info;
  1024. return water_stat (fullPath, info) ? info.st_size : 0;
  1025. }
  1026. bool File::deleteFile() const
  1027. {
  1028. if (! exists() && ! isSymbolicLink())
  1029. return true;
  1030. if (isDirectory())
  1031. return rmdir (fullPath.toUTF8()) == 0;
  1032. return remove (fullPath.toUTF8()) == 0;
  1033. }
  1034. bool File::moveInternal (const File& dest) const
  1035. {
  1036. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  1037. return true;
  1038. if (hasWriteAccess() && copyInternal (dest))
  1039. {
  1040. if (deleteFile())
  1041. return true;
  1042. dest.deleteFile();
  1043. }
  1044. return false;
  1045. }
  1046. bool File::replaceInternal (const File& dest) const
  1047. {
  1048. return moveInternal (dest);
  1049. }
  1050. Result File::createDirectoryInternal (const String& fileName) const
  1051. {
  1052. return getResultForReturnValue (mkdir (fileName.toUTF8(), 0777));
  1053. }
  1054. File File::getCurrentWorkingDirectory()
  1055. {
  1056. HeapBlock<char> heapBuffer;
  1057. char localBuffer [1024];
  1058. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  1059. size_t bufferSize = 4096;
  1060. while (cwd == nullptr && errno == ERANGE)
  1061. {
  1062. heapBuffer.malloc (bufferSize);
  1063. cwd = getcwd (heapBuffer, bufferSize - 1);
  1064. bufferSize += 1024;
  1065. }
  1066. return File (CharPointer_UTF8 (cwd));
  1067. }
  1068. File water_getExecutableFile();
  1069. File water_getExecutableFile()
  1070. {
  1071. struct DLAddrReader
  1072. {
  1073. static String getFilename()
  1074. {
  1075. Dl_info exeInfo;
  1076. void* localSymbol = (void*) water_getExecutableFile;
  1077. dladdr (localSymbol, &exeInfo);
  1078. const CharPointer_UTF8 filename (exeInfo.dli_fname);
  1079. // if the filename is absolute simply return it
  1080. if (File::isAbsolutePath (filename))
  1081. return filename;
  1082. // if the filename is relative construct from CWD
  1083. if (filename[0] == '.')
  1084. return File::getCurrentWorkingDirectory().getChildFile (filename).getFullPathName();
  1085. // filename is abstract, look up in PATH
  1086. if (const char* const envpath = ::getenv ("PATH"))
  1087. {
  1088. StringArray paths (StringArray::fromTokens (envpath, ":", ""));
  1089. for (int i=paths.size(); --i>=0;)
  1090. {
  1091. const File filepath (File (paths[i]).getChildFile (filename));
  1092. if (filepath.existsAsFile())
  1093. return filepath.getFullPathName();
  1094. }
  1095. }
  1096. // if we reach this, we failed to find ourselves...
  1097. jassertfalse;
  1098. return filename;
  1099. }
  1100. };
  1101. static String filename (DLAddrReader::getFilename());
  1102. return filename;
  1103. }
  1104. #ifdef CARLA_OS_MAC
  1105. static NSString* getFileLink (const String& path)
  1106. {
  1107. return [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: waterStringToNS (path) error: nil];
  1108. }
  1109. bool File::isSymbolicLink() const
  1110. {
  1111. // FIXME
  1112. return false;
  1113. //return getFileLink (fullPath) != nil;
  1114. }
  1115. File File::getLinkedTarget() const
  1116. {
  1117. if (NSString* dest = getFileLink (fullPath))
  1118. return getSiblingFile (nsStringToWater (dest));
  1119. return *this;
  1120. }
  1121. bool File::copyInternal (const File& dest) const
  1122. {
  1123. //@autoreleasepool
  1124. {
  1125. NSFileManager* fm = [NSFileManager defaultManager];
  1126. return [fm fileExistsAtPath: waterStringToNS (fullPath)]
  1127. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1128. && [fm copyItemAtPath: waterStringToNS (fullPath)
  1129. toPath: waterStringToNS (dest.getFullPathName())
  1130. error: nil];
  1131. #else
  1132. && [fm copyPath: waterStringToNS (fullPath)
  1133. toPath: waterStringToNS (dest.getFullPathName())
  1134. handler: nil];
  1135. #endif
  1136. }
  1137. }
  1138. File File::getSpecialLocation (const SpecialLocationType type)
  1139. {
  1140. //@autoreleasepool
  1141. {
  1142. String resultPath;
  1143. switch (type)
  1144. {
  1145. case userHomeDirectory: resultPath = nsStringToWater (NSHomeDirectory()); break;
  1146. case tempDirectory:
  1147. {
  1148. File tmp ("~/Library/Caches/" + water_getExecutableFile().getFileNameWithoutExtension());
  1149. tmp.createDirectory();
  1150. return File (tmp.getFullPathName());
  1151. }
  1152. case currentExecutableFile:
  1153. return water_getExecutableFile();
  1154. case hostApplicationPath:
  1155. {
  1156. unsigned int size = 8192;
  1157. HeapBlock<char> buffer;
  1158. buffer.calloc (size + 8);
  1159. _NSGetExecutablePath (buffer.getData(), &size);
  1160. return File (String::fromUTF8 (buffer, (int) size));
  1161. }
  1162. default:
  1163. jassertfalse; // unknown type?
  1164. break;
  1165. }
  1166. if (resultPath.isNotEmpty())
  1167. return File (resultPath.convertToPrecomposedUnicode());
  1168. }
  1169. return File();
  1170. }
  1171. //==============================================================================
  1172. class DirectoryIterator::NativeIterator::Pimpl
  1173. {
  1174. public:
  1175. Pimpl (const File& directory, const String& wildCard_)
  1176. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  1177. wildCard (wildCard_),
  1178. enumerator (nil)
  1179. {
  1180. //@autoreleasepool
  1181. {
  1182. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: waterStringToNS (directory.getFullPathName())] retain];
  1183. }
  1184. }
  1185. ~Pimpl()
  1186. {
  1187. [enumerator release];
  1188. }
  1189. bool next (String& filenameFound,
  1190. bool* const isDir, int64* const fileSize,
  1191. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  1192. {
  1193. //@autoreleasepool
  1194. {
  1195. const char* wildcardUTF8 = nullptr;
  1196. for (;;)
  1197. {
  1198. NSString* file;
  1199. if (enumerator == nil || (file = [enumerator nextObject]) == nil)
  1200. return false;
  1201. [enumerator skipDescendents];
  1202. filenameFound = nsStringToWater (file).convertToPrecomposedUnicode();
  1203. if (wildcardUTF8 == nullptr)
  1204. wildcardUTF8 = wildCard.toUTF8();
  1205. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  1206. continue;
  1207. const String fullPath (parentDir + filenameFound);
  1208. updateStatInfoForFile (fullPath, isDir, fileSize, modTime, creationTime, isReadOnly);
  1209. return true;
  1210. }
  1211. }
  1212. }
  1213. private:
  1214. String parentDir, wildCard;
  1215. NSDirectoryEnumerator* enumerator;
  1216. CARLA_DECLARE_NON_COPY_CLASS (Pimpl)
  1217. };
  1218. #else
  1219. static String getLinkedFile (const String& file)
  1220. {
  1221. HeapBlock<char> buffer;
  1222. CARLA_SAFE_ASSERT_RETURN(buffer.malloc(8194), String());
  1223. const int numBytes = (int) readlink (file.toRawUTF8(), buffer, 8192);
  1224. return String::fromUTF8 (buffer, jmax (0, numBytes));
  1225. }
  1226. bool File::isSymbolicLink() const
  1227. {
  1228. return getLinkedFile (getFullPathName()).isNotEmpty();
  1229. }
  1230. File File::getLinkedTarget() const
  1231. {
  1232. String f (getLinkedFile (getFullPathName()));
  1233. if (f.isNotEmpty())
  1234. return getSiblingFile (f);
  1235. return *this;
  1236. }
  1237. bool File::copyInternal (const File& dest) const
  1238. {
  1239. FileInputStream in (*this);
  1240. if (dest.deleteFile())
  1241. {
  1242. {
  1243. FileOutputStream out (dest);
  1244. if (out.failedToOpen())
  1245. return false;
  1246. if (out.writeFromInputStream (in, -1) == getSize())
  1247. return true;
  1248. }
  1249. dest.deleteFile();
  1250. }
  1251. return false;
  1252. }
  1253. File File::getSpecialLocation (const SpecialLocationType type)
  1254. {
  1255. switch (type)
  1256. {
  1257. case userHomeDirectory:
  1258. {
  1259. if (const char* homeDir = getenv ("HOME"))
  1260. return File (CharPointer_UTF8 (homeDir));
  1261. if (struct passwd* const pw = getpwuid (getuid()))
  1262. return File (CharPointer_UTF8 (pw->pw_dir));
  1263. return File();
  1264. }
  1265. case tempDirectory:
  1266. {
  1267. File tmp ("/var/tmp");
  1268. if (! tmp.isDirectory())
  1269. {
  1270. tmp = "/tmp";
  1271. if (! tmp.isDirectory())
  1272. tmp = File::getCurrentWorkingDirectory();
  1273. }
  1274. return tmp;
  1275. }
  1276. case currentExecutableFile:
  1277. return water_getExecutableFile();
  1278. case hostApplicationPath:
  1279. {
  1280. const File f ("/proc/self/exe");
  1281. return f.isSymbolicLink() ? f.getLinkedTarget() : water_getExecutableFile();
  1282. }
  1283. default:
  1284. jassertfalse; // unknown type?
  1285. break;
  1286. }
  1287. return File();
  1288. }
  1289. //==============================================================================
  1290. class DirectoryIterator::NativeIterator::Pimpl
  1291. {
  1292. public:
  1293. Pimpl (const File& directory, const String& wc)
  1294. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  1295. wildCard (wc), dir (opendir (directory.getFullPathName().toUTF8()))
  1296. {
  1297. }
  1298. ~Pimpl()
  1299. {
  1300. if (dir != nullptr)
  1301. closedir (dir);
  1302. }
  1303. bool next (String& filenameFound,
  1304. bool* const isDir, int64* const fileSize,
  1305. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  1306. {
  1307. if (dir != nullptr)
  1308. {
  1309. const char* wildcardUTF8 = nullptr;
  1310. for (;;)
  1311. {
  1312. struct dirent* const de = readdir (dir);
  1313. if (de == nullptr)
  1314. break;
  1315. if (wildcardUTF8 == nullptr)
  1316. wildcardUTF8 = wildCard.toUTF8();
  1317. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  1318. {
  1319. filenameFound = CharPointer_UTF8 (de->d_name);
  1320. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  1321. return true;
  1322. }
  1323. }
  1324. }
  1325. return false;
  1326. }
  1327. private:
  1328. String parentDir, wildCard;
  1329. DIR* dir;
  1330. CARLA_DECLARE_NON_COPY_CLASS (Pimpl)
  1331. };
  1332. #endif
  1333. #endif
  1334. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCardStr)
  1335. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCardStr))
  1336. {
  1337. }
  1338. DirectoryIterator::NativeIterator::~NativeIterator() {}
  1339. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  1340. bool* isDir, int64* fileSize,
  1341. Time* modTime, Time* creationTime, bool* isReadOnly)
  1342. {
  1343. return pimpl->next (filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  1344. }
  1345. }