The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1046 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. #pragma once
  18. //==============================================================================
  19. /**
  20. Represents a local file or directory.
  21. This class encapsulates the absolute pathname of a file or directory, and
  22. has methods for finding out about the file and changing its properties.
  23. To read or write to the file, there are methods for returning an input or
  24. output stream.
  25. @see FileInputStream, FileOutputStream
  26. */
  27. class JUCE_API File
  28. {
  29. public:
  30. //==============================================================================
  31. /** Creates an (invalid) file object.
  32. The file is initially set to an empty path, so getFullPathName() will return
  33. an empty string.
  34. You can use its operator= method to point it at a proper file.
  35. */
  36. File() noexcept {}
  37. /** Creates a file from an absolute path.
  38. If the path supplied is a relative path, it is taken to be relative
  39. to the current working directory (see File::getCurrentWorkingDirectory()),
  40. but this isn't a recommended way of creating a file, because you
  41. never know what the CWD is going to be.
  42. On the Mac/Linux, the path can include "~" notation for referring to
  43. user home directories.
  44. */
  45. File (const String& absolutePath);
  46. /** Creates a copy of another file object. */
  47. File (const File&);
  48. /** Destructor. */
  49. ~File() noexcept {}
  50. /** Sets the file based on an absolute pathname.
  51. If the path supplied is a relative path, it is taken to be relative
  52. to the current working directory (see File::getCurrentWorkingDirectory()),
  53. but this isn't a recommended way of creating a file, because you
  54. never know what the CWD is going to be.
  55. On the Mac/Linux, the path can include "~" notation for referring to
  56. user home directories.
  57. */
  58. File& operator= (const String& newAbsolutePath);
  59. /** Copies from another file object. */
  60. File& operator= (const File& otherFile);
  61. /** Move constructor */
  62. File (File&&) noexcept;
  63. /** Move assignment operator */
  64. File& operator= (File&&) noexcept;
  65. //==============================================================================
  66. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  67. /** This static constant is used for referring to an 'invalid' file.
  68. Bear in mind that you should avoid this kind of static variable, and always prefer
  69. to use File() or {} if you need a default-constructed File object.
  70. */
  71. static const File nonexistent;
  72. #endif
  73. //==============================================================================
  74. /** Checks whether the file actually exists.
  75. @returns true if the file exists, either as a file or a directory.
  76. @see existsAsFile, isDirectory
  77. */
  78. bool exists() const;
  79. /** Checks whether the file exists and is a file rather than a directory.
  80. @returns true only if this is a real file, false if it's a directory
  81. or doesn't exist
  82. @see exists, isDirectory
  83. */
  84. bool existsAsFile() const;
  85. /** Checks whether the file is a directory that exists.
  86. @returns true only if the file is a directory which actually exists, so
  87. false if it's a file or doesn't exist at all
  88. @see exists, existsAsFile
  89. */
  90. bool isDirectory() const;
  91. /** Checks whether the path of this file represents the root of a file system,
  92. irrespective of its existance.
  93. This will return true for "C:", "D:", etc on Windows and "/" on other
  94. platforms.
  95. */
  96. bool isRoot() const;
  97. /** Returns the size of the file in bytes.
  98. @returns the number of bytes in the file, or 0 if it doesn't exist.
  99. */
  100. int64 getSize() const;
  101. /** Utility function to convert a file size in bytes to a neat string description.
  102. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  103. 2000000 would produce "2 MB", etc.
  104. */
  105. static String descriptionOfSizeInBytes (int64 bytes);
  106. //==============================================================================
  107. /** Returns the complete, absolute path of this file.
  108. This includes the filename and all its parent folders. On Windows it'll
  109. also include the drive letter prefix; on Mac or Linux it'll be a complete
  110. path starting from the root folder.
  111. If you just want the file's name, you should use getFileName() or
  112. getFileNameWithoutExtension().
  113. @see getFileName, getRelativePathFrom
  114. */
  115. const String& getFullPathName() const noexcept { return fullPath; }
  116. /** Returns the last section of the pathname.
  117. Returns just the final part of the path - e.g. if the whole path
  118. is "/moose/fish/foo.txt" this will return "foo.txt".
  119. For a directory, it returns the final part of the path - e.g. for the
  120. directory "/moose/fish" it'll return "fish".
  121. If the filename begins with a dot, it'll return the whole filename, e.g. for
  122. "/moose/.fish", it'll return ".fish"
  123. @see getFullPathName, getFileNameWithoutExtension
  124. */
  125. String getFileName() const;
  126. /** Creates a relative path that refers to a file relatively to a given directory.
  127. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  128. would return "../../foo.txt".
  129. If it's not possible to navigate from one file to the other, an absolute
  130. path is returned. If the paths are invalid, an empty string may also be
  131. returned.
  132. @param directoryToBeRelativeTo the directory which the resultant string will
  133. be relative to. If this is actually a file rather than
  134. a directory, its parent directory will be used instead.
  135. If it doesn't exist, it's assumed to be a directory.
  136. @see getChildFile, isAbsolutePath
  137. */
  138. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  139. //==============================================================================
  140. /** Returns the file's extension.
  141. Returns the file extension of this file, also including the dot.
  142. e.g. "/moose/fish/foo.txt" would return ".txt"
  143. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  144. */
  145. String getFileExtension() const;
  146. /** Checks whether the file has a given extension.
  147. @param extensionToTest the extension to look for - it doesn't matter whether or
  148. not this string has a dot at the start, so ".wav" and "wav"
  149. will have the same effect. To compare with multiple extensions, this
  150. parameter can contain multiple strings, separated by semi-colons -
  151. so, for example: hasFileExtension (".jpeg;png;gif") would return
  152. true if the file has any of those three extensions.
  153. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  154. */
  155. bool hasFileExtension (StringRef extensionToTest) const;
  156. /** Returns a version of this file with a different file extension.
  157. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  158. @param newExtension the new extension, either with or without a dot at the start (this
  159. doesn't make any difference). To get remove a file's extension altogether,
  160. pass an empty string into this function.
  161. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  162. */
  163. File withFileExtension (StringRef newExtension) const;
  164. /** Returns the last part of the filename, without its file extension.
  165. e.g. for "/moose/fish/foo.txt" this will return "foo".
  166. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  167. */
  168. String getFileNameWithoutExtension() const;
  169. //==============================================================================
  170. /** Returns a 32-bit hash-code that identifies this file.
  171. This is based on the filename. Obviously it's possible, although unlikely, that
  172. two files will have the same hash-code.
  173. */
  174. int hashCode() const;
  175. /** Returns a 64-bit hash-code that identifies this file.
  176. This is based on the filename. Obviously it's possible, although unlikely, that
  177. two files will have the same hash-code.
  178. */
  179. int64 hashCode64() const;
  180. //==============================================================================
  181. /** Returns a file that represents a relative (or absolute) sub-path of the current one.
  182. This will find a child file or directory of the current object.
  183. e.g.
  184. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  185. File ("/moose/fish").getChildFile ("haddock/foo.txt") will produce "/moose/fish/haddock/foo.txt".
  186. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  187. If the string is actually an absolute path, it will be treated as such, e.g.
  188. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  189. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  190. */
  191. File getChildFile (StringRef relativeOrAbsolutePath) const;
  192. /** Returns a file which is in the same directory as this one.
  193. This is equivalent to getParentDirectory().getChildFile (name).
  194. @see getChildFile, getParentDirectory
  195. */
  196. File getSiblingFile (StringRef siblingFileName) const;
  197. //==============================================================================
  198. /** Returns the directory that contains this file or directory.
  199. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  200. */
  201. File getParentDirectory() const;
  202. /** Checks whether a file is somewhere inside a directory.
  203. Returns true if this file is somewhere inside a subdirectory of the directory
  204. that is passed in. Neither file actually has to exist, because the function
  205. just checks the paths for similarities.
  206. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  207. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  208. */
  209. bool isAChildOf (const File& potentialParentDirectory) const;
  210. //==============================================================================
  211. /** Chooses a filename relative to this one that doesn't already exist.
  212. If this file is a directory, this will return a child file of this
  213. directory that doesn't exist, by adding numbers to a prefix and suffix until
  214. it finds one that isn't already there.
  215. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  216. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  217. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  218. @param prefix the string to use for the filename before the number
  219. @param suffix the string to add to the filename after the number
  220. @param putNumbersInBrackets if true, this will create filenames in the
  221. format "prefix(number)suffix", if false, it will leave the
  222. brackets out.
  223. */
  224. File getNonexistentChildFile (const String& prefix,
  225. const String& suffix,
  226. bool putNumbersInBrackets = true) const;
  227. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  228. If this file doesn't exist, this will just return itself, otherwise it
  229. will return an appropriate sibling that doesn't exist, e.g. if a file
  230. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  231. @param putNumbersInBrackets whether to add brackets around the numbers that
  232. get appended to the new filename.
  233. */
  234. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  235. //==============================================================================
  236. /** Compares the pathnames for two files. */
  237. bool operator== (const File&) const;
  238. /** Compares the pathnames for two files. */
  239. bool operator!= (const File&) const;
  240. /** Compares the pathnames for two files. */
  241. bool operator< (const File&) const;
  242. /** Compares the pathnames for two files. */
  243. bool operator> (const File&) const;
  244. //==============================================================================
  245. /** Checks whether a file can be created or written to.
  246. @returns true if it's possible to create and write to this file. If the file
  247. doesn't already exist, this will check its parent directory to
  248. see if writing is allowed.
  249. @see setReadOnly
  250. */
  251. bool hasWriteAccess() const;
  252. /** Changes the write-permission of a file or directory.
  253. @param shouldBeReadOnly whether to add or remove write-permission
  254. @param applyRecursively if the file is a directory and this is true, it will
  255. recurse through all the subfolders changing the permissions
  256. of all files
  257. @returns true if it manages to change the file's permissions.
  258. @see hasWriteAccess
  259. */
  260. bool setReadOnly (bool shouldBeReadOnly,
  261. bool applyRecursively = false) const;
  262. /** Changes the execute-permissions of a file.
  263. @param shouldBeExecutable whether to add or remove execute-permission
  264. @returns true if it manages to change the file's permissions.
  265. */
  266. bool setExecutePermission (bool shouldBeExecutable) const;
  267. /** Returns true if this file is a hidden or system file.
  268. The criteria for deciding whether a file is hidden are platform-dependent.
  269. */
  270. bool isHidden() const;
  271. /** Returns a unique identifier for the file, if one is available.
  272. Depending on the OS and file-system, this may be a unix inode number or
  273. a win32 file identifier, or 0 if it fails to find one. The number will
  274. be unique on the filesystem, but not globally.
  275. */
  276. uint64 getFileIdentifier() const;
  277. //==============================================================================
  278. /** Returns the last modification time of this file.
  279. @returns the time, or an invalid time if the file doesn't exist.
  280. @see setLastModificationTime, getLastAccessTime, getCreationTime
  281. */
  282. Time getLastModificationTime() const;
  283. /** Returns the last time this file was accessed.
  284. @returns the time, or an invalid time if the file doesn't exist.
  285. @see setLastAccessTime, getLastModificationTime, getCreationTime
  286. */
  287. Time getLastAccessTime() const;
  288. /** Returns the time that this file was created.
  289. @returns the time, or an invalid time if the file doesn't exist.
  290. @see getLastModificationTime, getLastAccessTime
  291. */
  292. Time getCreationTime() const;
  293. /** Changes the modification time for this file.
  294. @param newTime the time to apply to the file
  295. @returns true if it manages to change the file's time.
  296. @see getLastModificationTime, setLastAccessTime, setCreationTime
  297. */
  298. bool setLastModificationTime (Time newTime) const;
  299. /** Changes the last-access time for this file.
  300. @param newTime the time to apply to the file
  301. @returns true if it manages to change the file's time.
  302. @see getLastAccessTime, setLastModificationTime, setCreationTime
  303. */
  304. bool setLastAccessTime (Time newTime) const;
  305. /** Changes the creation date for this file.
  306. @param newTime the time to apply to the file
  307. @returns true if it manages to change the file's time.
  308. @see getCreationTime, setLastModificationTime, setLastAccessTime
  309. */
  310. bool setCreationTime (Time newTime) const;
  311. /** If possible, this will try to create a version string for the given file.
  312. The OS may be able to look at the file and give a version for it - e.g. with
  313. executables, bundles, dlls, etc. If no version is available, this will
  314. return an empty string.
  315. */
  316. String getVersion() const;
  317. //==============================================================================
  318. /** Creates an empty file if it doesn't already exist.
  319. If the file that this object refers to doesn't exist, this will create a file
  320. of zero size.
  321. If it already exists or is a directory, this method will do nothing.
  322. If the parent directories of the File do not exist then this method will
  323. recursively create the parent directories.
  324. @returns a result to indicate whether the file was created successfully,
  325. or an error message if it failed.
  326. @see createDirectory
  327. */
  328. Result create() const;
  329. /** Creates a new directory for this filename.
  330. This will try to create the file as a directory, and will also create
  331. any parent directories it needs in order to complete the operation.
  332. @returns a result to indicate whether the directory was created successfully, or
  333. an error message if it failed.
  334. @see create
  335. */
  336. Result createDirectory() const;
  337. /** Deletes a file.
  338. If this file is actually a directory, it may not be deleted correctly if it
  339. contains files. See deleteRecursively() as a better way of deleting directories.
  340. @returns true if the file has been successfully deleted (or if it didn't exist to
  341. begin with).
  342. @see deleteRecursively
  343. */
  344. bool deleteFile() const;
  345. /** Deletes a file or directory and all its subdirectories.
  346. If this file is a directory, this will try to delete it and all its subfolders. If
  347. it's just a file, it will just try to delete the file.
  348. @returns true if the file and all its subfolders have been successfully deleted
  349. (or if it didn't exist to begin with).
  350. @see deleteFile
  351. */
  352. bool deleteRecursively() const;
  353. /** Moves this file or folder to the trash.
  354. @returns true if the operation succeeded. It could fail if the trash is full, or
  355. if the file is write-protected, so you should check the return value
  356. and act appropriately.
  357. */
  358. bool moveToTrash() const;
  359. /** Moves or renames a file.
  360. Tries to move a file to a different location.
  361. If the target file already exists, this will attempt to delete it first, and
  362. will fail if this can't be done.
  363. Note that the destination file isn't the directory to put it in, it's the actual
  364. filename that you want the new file to have.
  365. Also note that on some OSes (e.g. Windows), moving files between different
  366. volumes may not be possible.
  367. @returns true if the operation succeeds
  368. */
  369. bool moveFileTo (const File& targetLocation) const;
  370. /** Copies a file.
  371. Tries to copy a file to a different location.
  372. If the target file already exists, this will attempt to delete it first, and
  373. will fail if this can't be done.
  374. @returns true if the operation succeeds
  375. */
  376. bool copyFileTo (const File& targetLocation) const;
  377. /** Replaces a file.
  378. Replace the file in the given location, assuming the replaced files identity.
  379. Depending on the file system this will preserve file attributes such as
  380. creation date, short file name, etc.
  381. If replacement succeeds the original file is deleted.
  382. @returns true if the operation succeeds
  383. */
  384. bool replaceFileIn (const File& targetLocation) const;
  385. /** Copies a directory.
  386. Tries to copy an entire directory, recursively.
  387. If this file isn't a directory or if any target files can't be created, this
  388. will return false.
  389. @param newDirectory the directory that this one should be copied to. Note that this
  390. is the name of the actual directory to create, not the directory
  391. into which the new one should be placed, so there must be enough
  392. write privileges to create it if it doesn't exist. Any files inside
  393. it will be overwritten by similarly named ones that are copied.
  394. */
  395. bool copyDirectoryTo (const File& newDirectory) const;
  396. //==============================================================================
  397. /** Used in file searching, to specify whether to return files, directories, or both.
  398. */
  399. enum TypesOfFileToFind
  400. {
  401. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  402. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  403. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  404. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  405. };
  406. /** Searches inside a directory for files matching a wildcard pattern.
  407. Assuming that this file is a directory, this method will search it
  408. for either files or subdirectories whose names match a filename pattern.
  409. @param results an array to which File objects will be added for the
  410. files that the search comes up with
  411. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  412. return files, directories, or both. If the ignoreHiddenFiles flag
  413. is also added to this value, hidden files won't be returned
  414. @param searchRecursively if true, all subdirectories will be recursed into to do
  415. an exhaustive search
  416. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  417. @returns the number of results that have been found
  418. @see getNumberOfChildFiles, DirectoryIterator
  419. */
  420. int findChildFiles (Array<File>& results,
  421. int whatToLookFor,
  422. bool searchRecursively,
  423. const String& wildCardPattern = "*") const;
  424. /** Searches inside a directory and counts how many files match a wildcard pattern.
  425. Assuming that this file is a directory, this method will search it
  426. for either files or subdirectories whose names match a filename pattern,
  427. and will return the number of matches found.
  428. This isn't a recursive call, and will only search this directory, not
  429. its children.
  430. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  431. count files, directories, or both. If the ignoreHiddenFiles flag
  432. is also added to this value, hidden files won't be counted
  433. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  434. @returns the number of matches found
  435. @see findChildFiles, DirectoryIterator
  436. */
  437. int getNumberOfChildFiles (int whatToLookFor,
  438. const String& wildCardPattern = "*") const;
  439. /** Returns true if this file is a directory that contains one or more subdirectories.
  440. @see isDirectory, findChildFiles
  441. */
  442. bool containsSubDirectories() const;
  443. //==============================================================================
  444. /** Creates a stream to read from this file.
  445. @returns a stream that will read from this file (initially positioned at the
  446. start of the file), or nullptr if the file can't be opened for some reason
  447. @see createOutputStream, loadFileAsData
  448. */
  449. FileInputStream* createInputStream() const;
  450. /** Creates a stream to write to this file.
  451. If the file exists, the stream that is returned will be positioned ready for
  452. writing at the end of the file, so you might want to use deleteFile() first
  453. to write to an empty file.
  454. @returns a stream that will write to this file (initially positioned at the
  455. end of the file), or nullptr if the file can't be opened for some reason
  456. @see createInputStream, appendData, appendText
  457. */
  458. FileOutputStream* createOutputStream (size_t bufferSize = 0x8000) const;
  459. //==============================================================================
  460. /** Loads a file's contents into memory as a block of binary data.
  461. Of course, trying to load a very large file into memory will blow up, so
  462. it's better to check first.
  463. @param result the data block to which the file's contents should be appended - note
  464. that if the memory block might already contain some data, you
  465. might want to clear it first
  466. @returns true if the file could all be read into memory
  467. */
  468. bool loadFileAsData (MemoryBlock& result) const;
  469. /** Reads a file into memory as a string.
  470. Attempts to load the entire file as a zero-terminated string.
  471. This makes use of InputStream::readEntireStreamAsString, which can
  472. read either UTF-16 or UTF-8 file formats.
  473. */
  474. String loadFileAsString() const;
  475. /** Reads the contents of this file as text and splits it into lines, which are
  476. appended to the given StringArray.
  477. */
  478. void readLines (StringArray& destLines) const;
  479. //==============================================================================
  480. /** Appends a block of binary data to the end of the file.
  481. This will try to write the given buffer to the end of the file.
  482. @returns false if it can't write to the file for some reason
  483. */
  484. bool appendData (const void* dataToAppend,
  485. size_t numberOfBytes) const;
  486. /** Replaces this file's contents with a given block of data.
  487. This will delete the file and replace it with the given data.
  488. A nice feature of this method is that it's safe - instead of deleting
  489. the file first and then re-writing it, it creates a new temporary file,
  490. writes the data to that, and then moves the new file to replace the existing
  491. file. This means that if the power gets pulled out or something crashes,
  492. you're a lot less likely to end up with a corrupted or unfinished file..
  493. Returns true if the operation succeeds, or false if it fails.
  494. @see appendText
  495. */
  496. bool replaceWithData (const void* dataToWrite,
  497. size_t numberOfBytes) const;
  498. /** Appends a string to the end of the file.
  499. This will try to append a text string to the file, as either 16-bit unicode
  500. or 8-bit characters in the default system encoding.
  501. It can also write the 'ff fe' unicode header bytes before the text to indicate
  502. the endianness of the file.
  503. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  504. @see replaceWithText
  505. */
  506. bool appendText (const String& textToAppend,
  507. bool asUnicode = false,
  508. bool writeUnicodeHeaderBytes = false) const;
  509. /** Replaces this file's contents with a given text string.
  510. This will delete the file and replace it with the given text.
  511. A nice feature of this method is that it's safe - instead of deleting
  512. the file first and then re-writing it, it creates a new temporary file,
  513. writes the text to that, and then moves the new file to replace the existing
  514. file. This means that if the power gets pulled out or something crashes,
  515. you're a lot less likely to end up with an empty file..
  516. For an explanation of the parameters here, see the appendText() method.
  517. Returns true if the operation succeeds, or false if it fails.
  518. @see appendText
  519. */
  520. bool replaceWithText (const String& textToWrite,
  521. bool asUnicode = false,
  522. bool writeUnicodeHeaderBytes = false) const;
  523. /** Attempts to scan the contents of this file and compare it to another file, returning
  524. true if this is possible and they match byte-for-byte.
  525. */
  526. bool hasIdenticalContentTo (const File& other) const;
  527. //==============================================================================
  528. /** Creates a set of files to represent each file root.
  529. e.g. on Windows this will create files for "c:\", "d:\" etc according
  530. to which ones are available. On the Mac/Linux, this will probably
  531. just add a single entry for "/".
  532. */
  533. static void findFileSystemRoots (Array<File>& results);
  534. /** Finds the name of the drive on which this file lives.
  535. @returns the volume label of the drive, or an empty string if this isn't possible
  536. */
  537. String getVolumeLabel() const;
  538. /** Returns the serial number of the volume on which this file lives.
  539. @returns the serial number, or zero if there's a problem doing this
  540. */
  541. int getVolumeSerialNumber() const;
  542. /** Returns the number of bytes free on the drive that this file lives on.
  543. @returns the number of bytes free, or 0 if there's a problem finding this out
  544. @see getVolumeTotalSize
  545. */
  546. int64 getBytesFreeOnVolume() const;
  547. /** Returns the total size of the drive that contains this file.
  548. @returns the total number of bytes that the volume can hold
  549. @see getBytesFreeOnVolume
  550. */
  551. int64 getVolumeTotalSize() const;
  552. /** Returns true if this file is on a CD or DVD drive. */
  553. bool isOnCDRomDrive() const;
  554. /** Returns true if this file is on a hard disk.
  555. This will fail if it's a network drive, but will still be true for
  556. removable hard-disks.
  557. */
  558. bool isOnHardDisk() const;
  559. /** Returns true if this file is on a removable disk drive.
  560. This might be a usb-drive, a CD-rom, or maybe a network drive.
  561. */
  562. bool isOnRemovableDrive() const;
  563. //==============================================================================
  564. /** Launches the file as a process.
  565. - if the file is executable, this will run it.
  566. - if it's a document of some kind, it will launch the document with its
  567. default viewer application.
  568. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  569. @see revealToUser
  570. */
  571. bool startAsProcess (const String& parameters = String()) const;
  572. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  573. @see startAsProcess
  574. */
  575. void revealToUser() const;
  576. //==============================================================================
  577. /** A set of types of location that can be passed to the getSpecialLocation() method.
  578. */
  579. enum SpecialLocationType
  580. {
  581. /** The user's home folder. This is the same as using File ("~"). */
  582. userHomeDirectory,
  583. /** The user's default documents folder. On Windows, this might be the user's
  584. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  585. doesn't tend to have one of these, so it might just return their home folder.
  586. */
  587. userDocumentsDirectory,
  588. /** The folder that contains the user's desktop objects. */
  589. userDesktopDirectory,
  590. /** The most likely place where a user might store their music files. */
  591. userMusicDirectory,
  592. /** The most likely place where a user might store their movie files. */
  593. userMoviesDirectory,
  594. /** The most likely place where a user might store their picture files. */
  595. userPicturesDirectory,
  596. /** The folder in which applications store their persistent user-specific settings.
  597. On Windows, this might be "\Documents and Settings\username\Application Data".
  598. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  599. always create your own sub-folder to put them in, to avoid making a mess.
  600. On GNU/Linux it is "~/.config".
  601. */
  602. userApplicationDataDirectory,
  603. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  604. of the computer, rather than just the current user.
  605. On the Mac it'll be "/Library", on Windows, it could be something like
  606. "\Documents and Settings\All Users\Application Data".
  607. On GNU/Linux it is "/opt".
  608. Depending on the setup, this folder may be read-only.
  609. */
  610. commonApplicationDataDirectory,
  611. /** A place to put documents which are shared by all users of the machine.
  612. On Windows this may be somewhere like "C:\Users\Public\Documents", on OSX it
  613. will be something like "/Users/Shared". Other OSes may have no such concept
  614. though, so be careful.
  615. */
  616. commonDocumentsDirectory,
  617. /** The folder that should be used for temporary files.
  618. Always delete them when you're finished, to keep the user's computer tidy!
  619. */
  620. tempDirectory,
  621. /** Returns this application's executable file.
  622. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  623. host app.
  624. On the mac this will return the unix binary, not the package folder - see
  625. currentApplicationFile for that.
  626. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  627. file link, invokedExecutableFile will return the name of the link.
  628. */
  629. currentExecutableFile,
  630. /** Returns this application's location.
  631. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  632. host app.
  633. On the mac this will return the package folder (if it's in one), not the unix binary
  634. that's inside it - compare with currentExecutableFile.
  635. */
  636. currentApplicationFile,
  637. /** Returns the file that was invoked to launch this executable.
  638. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  639. will return the name of the link that was used, whereas currentExecutableFile will return
  640. the actual location of the target executable.
  641. */
  642. invokedExecutableFile,
  643. /** In a plugin, this will return the path of the host executable. */
  644. hostApplicationPath,
  645. #if JUCE_WINDOWS
  646. /** On a Windows machine, returns the location of the Windows/System32 folder. */
  647. windowsSystemDirectory,
  648. #endif
  649. /** The directory in which applications normally get installed.
  650. So on windows, this would be something like "C:\Program Files", on the
  651. Mac "/Applications", or "/usr" on linux.
  652. */
  653. globalApplicationsDirectory,
  654. #if JUCE_WINDOWS
  655. /** On a Windows machine, returns the directory in which 32 bit applications
  656. normally get installed. On a 64 bit machine this would be something like
  657. "C:\Program Files (x86)", whereas for 32 bit machines this would match
  658. globalApplicationsDirectory and be something like "C:\Program Files".
  659. @see globalApplicationsDirectory
  660. */
  661. globalApplicationsDirectoryX86
  662. #endif
  663. };
  664. /** Finds the location of a special type of file or directory, such as a home folder or
  665. documents folder.
  666. @see SpecialLocationType
  667. */
  668. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  669. //==============================================================================
  670. /** Returns a temporary file in the system's temp directory.
  671. This will try to return the name of a non-existent temp file.
  672. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  673. */
  674. static File createTempFile (StringRef fileNameEnding);
  675. //==============================================================================
  676. /** Returns the current working directory.
  677. @see setAsCurrentWorkingDirectory
  678. */
  679. static File getCurrentWorkingDirectory();
  680. /** Sets the current working directory to be this file.
  681. For this to work the file must point to a valid directory.
  682. @returns true if the current directory has been changed.
  683. @see getCurrentWorkingDirectory
  684. */
  685. bool setAsCurrentWorkingDirectory() const;
  686. //==============================================================================
  687. /** The system-specific file separator character.
  688. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  689. */
  690. static const juce_wchar separator;
  691. /** The system-specific file separator character, as a string.
  692. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  693. */
  694. static const String separatorString;
  695. //==============================================================================
  696. /** Returns a version of a filename with any illegal characters removed.
  697. This will return a copy of the given string after removing characters
  698. that are not allowed in a legal filename, and possibly shortening the
  699. string if it's too long.
  700. Because this will remove slashes, don't use it on an absolute pathname - use
  701. createLegalPathName() for that.
  702. @see createLegalPathName
  703. */
  704. static String createLegalFileName (const String& fileNameToFix);
  705. /** Returns a version of a path with any illegal characters removed.
  706. Similar to createLegalFileName(), but this won't remove slashes, so can
  707. be used on a complete pathname.
  708. @see createLegalFileName
  709. */
  710. static String createLegalPathName (const String& pathNameToFix);
  711. /** Indicates whether filenames are case-sensitive on the current operating system. */
  712. static bool areFileNamesCaseSensitive();
  713. /** Returns true if the string seems to be a fully-specified absolute path. */
  714. static bool isAbsolutePath (StringRef path);
  715. /** Creates a file that simply contains this string, without doing the sanity-checking
  716. that the normal constructors do.
  717. Best to avoid this unless you really know what you're doing.
  718. */
  719. static File createFileWithoutCheckingPath (const String& absolutePath) noexcept;
  720. /** Adds a separator character to the end of a path if it doesn't already have one. */
  721. static String addTrailingSeparator (const String& path);
  722. //==============================================================================
  723. /** Tries to create a symbolic link and returns a boolean to indicate success */
  724. bool createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const;
  725. /** Returns true if this file is a link or alias that can be followed using getLinkedTarget(). */
  726. bool isSymbolicLink() const;
  727. /** If this file is a link or alias, this returns the file that it points to.
  728. If the file isn't actually link, it'll just return itself.
  729. */
  730. File getLinkedTarget() const;
  731. #if JUCE_WINDOWS
  732. /** Windows ONLY - Creates a win32 .LNK shortcut file that links to this file. */
  733. bool createShortcut (const String& description, const File& linkFileToCreate) const;
  734. /** Windows ONLY - Returns true if this is a win32 .LNK file. */
  735. bool isShortcut() const;
  736. #endif
  737. //==============================================================================
  738. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  739. /** OSX ONLY - Finds the OSType of a file from the its resources. */
  740. OSType getMacOSType() const;
  741. /** OSX ONLY - Returns true if this file is actually a bundle. */
  742. bool isBundle() const;
  743. #endif
  744. #if JUCE_MAC || DOXYGEN
  745. /** OSX ONLY - Adds this file to the OSX dock */
  746. void addToDock() const;
  747. #endif
  748. //==============================================================================
  749. struct NaturalFileComparator
  750. {
  751. NaturalFileComparator (bool shouldPutFoldersFirst) noexcept : foldersFirst (shouldPutFoldersFirst) {}
  752. int compareElements (const File& firstFile, const File& secondFile) const
  753. {
  754. if (foldersFirst && (firstFile.isDirectory() != secondFile.isDirectory()))
  755. return firstFile.isDirectory() ? -1 : 1;
  756. #if NAMES_ARE_CASE_SENSITIVE
  757. return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), true);
  758. #else
  759. return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), false);
  760. #endif
  761. }
  762. bool foldersFirst;
  763. };
  764. private:
  765. //==============================================================================
  766. String fullPath;
  767. static String parseAbsolutePath (const String&);
  768. String getPathUpToLastSlash() const;
  769. Result createDirectoryInternal (const String&) const;
  770. bool copyInternal (const File&) const;
  771. bool moveInternal (const File&) const;
  772. bool replaceInternal (const File&) const;
  773. bool setFileTimesInternal (int64 m, int64 a, int64 c) const;
  774. void getFileTimesInternal (int64& m, int64& a, int64& c) const;
  775. bool setFileReadOnlyInternal (bool) const;
  776. bool setFileExecutableInternal (bool) const;
  777. };