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.

File.cpp 49KB

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