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.

477 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. Some information about a document.
  22. Each instance represents some information about the document at the point when the instance
  23. was created.
  24. Instance information is not updated automatically. If you think some file information may
  25. have changed, create a new instance.
  26. @tags{Core}
  27. */
  28. class AndroidDocumentInfo
  29. {
  30. public:
  31. AndroidDocumentInfo() = default;
  32. /** True if this file really exists. */
  33. bool exists() const { return isJuceFlagSet (flagExists); }
  34. /** True if this is a directory rather than a file. */
  35. bool isDirectory() const;
  36. /** True if this is a file rather than a directory. */
  37. bool isFile() const { return type.isNotEmpty() && ! isDirectory(); }
  38. /** True if this process has permission to read this file.
  39. If this returns true, and the AndroidDocument refers to a file rather than a directory,
  40. then AndroidDocument::createInputStream should work on this document.
  41. */
  42. bool canRead() const { return isJuceFlagSet (flagHasReadPermission) && type.isNotEmpty(); }
  43. /** True if this is a document that can be written, or a directory that can be modified.
  44. If this returns true, and the AndroidDocument refers to a file rather than a directory,
  45. then AndroidDocument::createOutputStream should work on this document.
  46. */
  47. bool canWrite() const
  48. {
  49. return isJuceFlagSet (flagHasWritePermission)
  50. && type.isNotEmpty()
  51. && (isNativeFlagSet (flagSupportsWrite)
  52. || isNativeFlagSet (flagSupportsDelete)
  53. || isNativeFlagSet (flagDirSupportsCreate));
  54. }
  55. /** True if this document can be removed completely from the filesystem. */
  56. bool canDelete() const { return isNativeFlagSet (flagSupportsDelete); }
  57. /** True if this is a directory and adding child documents is supported. */
  58. bool canCreateChildren() const { return isNativeFlagSet (flagDirSupportsCreate); }
  59. /** True if this document can be renamed. */
  60. bool canRename() const { return isNativeFlagSet (flagSupportsRename); }
  61. /** True if this document can be copied. */
  62. bool canCopy() const { return isNativeFlagSet (flagSupportsCopy); }
  63. /** True if this document can be moved. */
  64. bool canMove() const { return isNativeFlagSet (flagSupportsMove); }
  65. /** True if this document isn't a physical file on storage. */
  66. bool isVirtual() const { return isNativeFlagSet (flagVirtualDocument); }
  67. /** The user-facing name.
  68. This may or may not contain a file extension. For files identified by a URL, the MIME type
  69. is stored separately.
  70. */
  71. String getName() const { return name; }
  72. /** The MIME type of this document. */
  73. String getType() const { return isDirectory() ? String{} : type; }
  74. /** Timestamp when a document was last modified, in milliseconds since January 1, 1970 00:00:00.0 UTC.
  75. Use isLastModifiedValid() to determine whether or not the result of this
  76. function is valid.
  77. */
  78. int64 getLastModified() const { return isJuceFlagSet (flagValidModified) ? lastModified : 0; }
  79. /** True if the filesystem provided a modification time. */
  80. bool isLastModifiedValid() const { return isJuceFlagSet (flagValidModified); }
  81. /** The size of the document in bytes, if known.
  82. Use isSizeInBytesValid() to determine whether or not the result of this
  83. function is valid.
  84. */
  85. int64 getSizeInBytes() const { return isJuceFlagSet (flagValidSize) ? sizeInBytes : 0; }
  86. /** True if the filesystem provided a size in bytes. */
  87. bool isSizeInBytesValid() const { return isJuceFlagSet (flagValidSize); }
  88. /** @internal */
  89. class Args;
  90. private:
  91. explicit AndroidDocumentInfo (Args);
  92. bool isNativeFlagSet (int flag) const { return (nativeFlags & flag) != 0; }
  93. bool isJuceFlagSet (int flag) const { return (juceFlags & flag) != 0; }
  94. /* Native Android flags that might be set in the COLUMN_FLAGS for a particular document */
  95. enum
  96. {
  97. flagSupportsWrite = 0x0002,
  98. flagSupportsDelete = 0x0004,
  99. flagDirSupportsCreate = 0x0008,
  100. flagSupportsRename = 0x0040,
  101. flagSupportsCopy = 0x0080,
  102. flagSupportsMove = 0x0100,
  103. flagVirtualDocument = 0x0200,
  104. };
  105. /* Flags for other binary properties that aren't exposed in COLUMN_FLAGS */
  106. enum
  107. {
  108. flagExists = 1 << 0,
  109. flagValidModified = 1 << 1,
  110. flagValidSize = 1 << 2,
  111. flagHasReadPermission = 1 << 3,
  112. flagHasWritePermission = 1 << 4,
  113. };
  114. String name;
  115. String type;
  116. int64 lastModified = 0;
  117. int64 sizeInBytes = 0;
  118. int nativeFlags = 0, juceFlags = 0;
  119. };
  120. //==============================================================================
  121. /**
  122. Represents a permission granted to an application to read and/or write to a particular document
  123. or tree.
  124. This class also contains static methods to request, revoke, and query the permissions of your
  125. app. These functions are no-ops on all platforms other than Android.
  126. @tags{Core}
  127. */
  128. class AndroidDocumentPermission
  129. {
  130. public:
  131. /** The url of the document with persisted permissions. */
  132. URL getUrl() const { return url; }
  133. /** The time when the permissions were persisted, in milliseconds since January 1, 1970 00:00:00.0 UTC. */
  134. int64 getPersistedTime() const { return time; }
  135. /** True if the permission allows read access. */
  136. bool isReadPermission() const { return read; }
  137. /** True if the permission allows write access. */
  138. bool isWritePermission() const { return write; }
  139. /** Gives your app access to a particular document or tree, even after the device is rebooted.
  140. If you want to persist access to a folder selected through a native file chooser, make sure
  141. to pass the exact URL returned by the file picker. Do NOT call AndroidDocument::fromTree
  142. and then pass the result of getUrl to this function, as the resulting URL may differ from
  143. the result of the file picker.
  144. */
  145. static void takePersistentReadWriteAccess (const URL&);
  146. /** Revokes persistent access to a document or tree. */
  147. static void releasePersistentReadWriteAccess (const URL&);
  148. /** Returns all of the permissions that have previously been granted to the app, via
  149. takePersistentReadWriteAccess();
  150. */
  151. static std::vector<AndroidDocumentPermission> getPersistedPermissions();
  152. private:
  153. URL url;
  154. int64 time = 0;
  155. bool read = false, write = false;
  156. };
  157. //==============================================================================
  158. /**
  159. Provides access to a document on Android devices.
  160. In this context, a 'document' may be a file or a directory.
  161. The main purpose of this class is to provide access to files in shared storage on Android.
  162. On newer Android versions, such files cannot be accessed directly by a file path, and must
  163. instead be read and modified using a new URI-based DocumentsContract API.
  164. Example use-cases:
  165. - After showing the system open dialog to allow the user to open a file, pass the FileChooser's
  166. URL result to AndroidDocument::fromDocument. Then, you can use getInfo() to retrieve
  167. information about the file, and createInputStream to read from the file. Other functions allow
  168. moving, copying, and deleting the file.
  169. - Similarly to the 'open' use-case, you may use createOutputStream to write to a file, normally
  170. located using the system save dialog.
  171. - To allow reading or writing to a tree of files in shared storage, you can show the system
  172. open dialog in 'selects directories' mode, and pass the resulting URL to
  173. AndroidDocument::fromTree. Then, you can iterate the files in the directory, query them,
  174. and create new files. This is a good way to store multiple files that the user can access from
  175. other apps, and that will be persistent after uninstalling and reinstalling your app.
  176. Note that you probably do *not* need this class if your app only needs to access files in its
  177. own internal sandbox. juce::File instances should work as expected in that case.
  178. AndroidDocument is a bit like the DocumentFile class from the androidx extension library,
  179. in that it represents a single document, and is implemented using DocumentsContract functions.
  180. @tags{Core}
  181. */
  182. class AndroidDocument
  183. {
  184. public:
  185. /** Create a null document. */
  186. AndroidDocument();
  187. /** Create an AndroidDocument representing a file or directory at a particular path.
  188. This is provided for use on older API versions (lower than 19), or on other platforms, so
  189. that the same AndroidDocument API can be used regardless of the runtime platform version.
  190. If the runtime platform version is 19 or higher, and you wish to work with a URI obtained
  191. from a native file picker, use fromDocument() or fromTree() instead.
  192. If this function fails, hasValue() will return false on the returned document.
  193. */
  194. static AndroidDocument fromFile (const File& filePath);
  195. /** Create an AndroidDocument representing a single document.
  196. The argument should be a URL representing a document. Such URLs are returned by the system
  197. file-picker when it is not in folder-selection mode. If you pass a tree URL, this function
  198. will fail.
  199. This function may fail on Android devices with API level 18 or lower, and on non-Android
  200. platforms. If this function fails, hasValue() will return false on the returned document.
  201. If calling this function fails, you may want to retry creating an AndroidDocument
  202. with fromFile(), passing the result of URL::getLocalFile().
  203. */
  204. static AndroidDocument fromDocument (const URL& documentUrl);
  205. /** Create an AndroidDocument representing the root of a tree of files.
  206. The argument should be a URL representing a tree. Such URLs are returned by the system
  207. file-picker when it is in folder-selection mode. If you pass a URL referring to a document
  208. inside a tree, this will return a document referring to the root of the tree. If you pass
  209. a URL referring to a single file, this will fail.
  210. When targeting platform version 30 or later, access to the filesystem via file paths is
  211. heavily restricted, and access to shared storage must use a new URI-based system instead.
  212. At time of writing, apps uploaded to the Play Store must target API 30 or higher.
  213. If you want read/write access to a shared folder, you must:
  214. - Use a native FileChooser in canSelectDirectories mode, to allow the user to select a
  215. folder that your app can access. Your app will only have access to the contents of this
  216. directory; it cannot escape to the filesystem root. The system will not allow the user
  217. to grant access to certain locations, including filesystem roots and the Download folder.
  218. - Pass the URI that the user selected to fromTree(), and use the resulting AndroidDocument
  219. to read/write to the file system.
  220. This function may fail on Android devices with API level 20 or lower, and on non-Android
  221. platforms. If this function fails, hasValue() will return false on the returned document.
  222. */
  223. static AndroidDocument fromTree (const URL& treeUrl);
  224. AndroidDocument (const AndroidDocument&);
  225. AndroidDocument (AndroidDocument&&) noexcept;
  226. AndroidDocument& operator= (const AndroidDocument&);
  227. AndroidDocument& operator= (AndroidDocument&&) noexcept;
  228. ~AndroidDocument();
  229. /** True if the URLs of the two documents match. */
  230. bool operator== (const AndroidDocument&) const;
  231. /** False if the URLs of the two documents match. */
  232. bool operator!= (const AndroidDocument&) const;
  233. /** Attempts to delete this document, and returns true on success. */
  234. bool deleteDocument() const;
  235. /** Renames the document, and returns true on success.
  236. This may cause the document's URI and metadata to change, so ensure to invalidate any
  237. cached information about the document (URLs, AndroidDocumentInfo instances) after calling
  238. this function.
  239. */
  240. bool renameTo (const String& newDisplayName);
  241. /** Attempts to create a new nested document with a particular type and name.
  242. The type should be a standard MIME type string, e.g. "image/png", "text/plain".
  243. The file name doesn't need to contain an extension, as this information is passed via the
  244. type argument. If this document is File-based rather than URL-based, then an appropriate
  245. file extension will be chosen based on the MIME type.
  246. On failure, the returned AndroidDocument may be invalid, and will return false from hasValue().
  247. */
  248. AndroidDocument createChildDocumentWithTypeAndName (const String& type, const String& name) const;
  249. /** Attempts to create a new nested directory with a particular name.
  250. On failure, the returned AndroidDocument may be invalid, and will return false from hasValue().
  251. */
  252. AndroidDocument createChildDirectory (const String& name) const;
  253. /** True if this object actually refers to a document.
  254. If this function returns false, you *must not* call any function on this instance other
  255. than the special member functions to copy, move, and/or destruct the instance.
  256. */
  257. bool hasValue() const { return pimpl != nullptr; }
  258. /** Like hasValue(), but allows declaring AndroidDocument instances directly in 'if' statements. */
  259. explicit operator bool() const { return hasValue(); }
  260. /** Creates a stream for reading from this document. */
  261. std::unique_ptr<InputStream> createInputStream() const;
  262. /** Creates a stream for writing to this document. */
  263. std::unique_ptr<OutputStream> createOutputStream() const;
  264. /** Returns the content URL describing this document. */
  265. URL getUrl() const;
  266. /** Fetches information about this document. */
  267. AndroidDocumentInfo getInfo() const;
  268. /** Experimental: Attempts to copy this document to a new parent, and returns an AndroidDocument
  269. representing the copy.
  270. On failure, the returned AndroidDocument may be invalid, and will return false from hasValue().
  271. This function may fail if the document doesn't allow copying, and when using URI-based
  272. documents on devices with API level 23 or lower. On failure, the returned AndroidDocument
  273. will return false from hasValue(). In testing, copying was not supported on the Android
  274. emulator for API 24, 30, or 31, so there's a good chance this function won't work on real
  275. devices.
  276. @see AndroidDocumentInfo::canCopy
  277. */
  278. AndroidDocument copyDocumentToParentDocument (const AndroidDocument& target) const;
  279. /** Experimental: Attempts to move this document from one parent to another, and returns true on
  280. success.
  281. This may cause the document's URI and metadata to change, so ensure to invalidate any
  282. cached information about the document (URLs, AndroidDocumentInfo instances) after calling
  283. this function.
  284. This function may fail if the document doesn't allow moving, and when using URI-based
  285. documents on devices with API level 23 or lower.
  286. */
  287. bool moveDocumentFromParentToParent (const AndroidDocument& currentParent,
  288. const AndroidDocument& newParent);
  289. /** @internal */
  290. struct NativeInfo;
  291. /** @internal */
  292. NativeInfo getNativeInfo() const;
  293. private:
  294. struct Utils;
  295. class Pimpl;
  296. explicit AndroidDocument (std::unique_ptr<Pimpl>);
  297. void swap (AndroidDocument& other) noexcept { std::swap (other.pimpl, pimpl); }
  298. std::unique_ptr<Pimpl> pimpl;
  299. };
  300. //==============================================================================
  301. /**
  302. An iterator that visits child documents in a directory.
  303. Instances of this iterator can be created by calling makeRecursive() or
  304. makeNonRecursive(). The results of these functions can additionally be used
  305. in standard algorithms, and in range-for loops:
  306. @code
  307. AndroidDocument findFileWithName (const AndroidDocument& parent, const String& name)
  308. {
  309. for (const auto& child : AndroidDocumentIterator::makeNonRecursive (parent))
  310. if (child.getInfo().getName() == name)
  311. return child;
  312. return AndroidDocument();
  313. }
  314. std::vector<AndroidDocument> findAllChildrenRecursive (const AndroidDocument& parent)
  315. {
  316. std::vector<AndroidDocument> children;
  317. std::copy (AndroidDocumentIterator::makeRecursive (doc),
  318. AndroidDocumentIterator(),
  319. std::back_inserter (children));
  320. return children;
  321. }
  322. @endcode
  323. @tags{Core}
  324. */
  325. class AndroidDocumentIterator final
  326. {
  327. public:
  328. using difference_type = std::ptrdiff_t;
  329. using pointer = void;
  330. using iterator_category = std::input_iterator_tag;
  331. /** Create an iterator that will visit each item in this directory. */
  332. static AndroidDocumentIterator makeNonRecursive (const AndroidDocument&);
  333. /** Create an iterator that will visit each item in this directory, and all nested directories. */
  334. static AndroidDocumentIterator makeRecursive (const AndroidDocument&);
  335. /** Creates an end/sentinel iterator. */
  336. AndroidDocumentIterator() = default;
  337. bool operator== (const AndroidDocumentIterator& other) const noexcept { return pimpl == nullptr && other.pimpl == nullptr; }
  338. bool operator!= (const AndroidDocumentIterator& other) const noexcept { return ! operator== (other); }
  339. /** Returns the document to which this iterator points. */
  340. AndroidDocument operator*() const;
  341. /** Moves this iterator to the next position. */
  342. AndroidDocumentIterator& operator++();
  343. /** Allows this iterator to be used directly in a range-for. */
  344. AndroidDocumentIterator begin() const { return *this; }
  345. /** Allows this iterator to be used directly in a range-for. */
  346. AndroidDocumentIterator end() const { return AndroidDocumentIterator{}; }
  347. private:
  348. struct Utils;
  349. struct Pimpl;
  350. explicit AndroidDocumentIterator (std::unique_ptr<Pimpl>);
  351. std::shared_ptr<Pimpl> pimpl;
  352. };
  353. } // namespace juce