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 50KB

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