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.

436 lines
15KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. @interface FileChooserControllerClass : UIDocumentPickerViewController
  19. - (void) setParent: (FileChooser::Native*) ptr;
  20. @end
  21. @interface FileChooserDelegateClass : NSObject<UIDocumentPickerDelegate>
  22. - (id) initWithOwner: (FileChooser::Native*) owner;
  23. @end
  24. namespace juce
  25. {
  26. #if ! (defined (__IPHONE_16_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_16_0)
  27. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  28. #define JUCE_DEPRECATION_IGNORED 1
  29. #endif
  30. class FileChooser::Native : public FileChooser::Pimpl,
  31. public Component,
  32. public AsyncUpdater,
  33. public std::enable_shared_from_this<Native>
  34. {
  35. public:
  36. static std::shared_ptr<Native> make (FileChooser& fileChooser, int flags)
  37. {
  38. std::shared_ptr<Native> result { new Native (fileChooser, flags) };
  39. /* Must be called after forming a shared_ptr to an instance of this class.
  40. Note that we can't call this directly inside the class constructor, because
  41. the owning shared_ptr might not yet exist.
  42. */
  43. [result->controller.get() setParent: result.get()];
  44. return result;
  45. }
  46. ~Native() override
  47. {
  48. exitModalState (0);
  49. }
  50. void launch() override
  51. {
  52. jassert (shared_from_this() != nullptr);
  53. /* Normally, when deleteWhenDismissed is true, the modal component manger will keep a copy of a raw pointer
  54. to our component and delete it when the modal state has ended. However, this is incompatible with
  55. our class being tracked by shared_ptr as it will force delete our class regardless of the current
  56. reference count. On the other hand, it's important that the modal manager keeps a reference as it can
  57. sometimes be the only reference to our class.
  58. To do this, we set deleteWhenDismissed to false so that the modal component manager does not delete
  59. our class. Instead, we pass in a lambda which captures a shared_ptr to ourselves to increase the
  60. reference count while the component is modal.
  61. */
  62. enterModalState (true,
  63. ModalCallbackFunction::create ([_self = shared_from_this()] (int) {}),
  64. false);
  65. }
  66. void runModally() override
  67. {
  68. #if JUCE_MODAL_LOOPS_PERMITTED
  69. launch();
  70. runModalLoop();
  71. #else
  72. jassertfalse;
  73. #endif
  74. }
  75. void parentHierarchyChanged() override
  76. {
  77. auto* newPeer = dynamic_cast<UIViewComponentPeer*> (getPeer());
  78. if (peer != newPeer)
  79. {
  80. peer = newPeer;
  81. if (peer != nullptr)
  82. {
  83. if (auto* parentController = peer->controller)
  84. [parentController showViewController: controller.get() sender: parentController];
  85. peer->toFront (false);
  86. }
  87. }
  88. }
  89. void handleAsyncUpdate() override
  90. {
  91. pickerWasCancelled();
  92. }
  93. //==============================================================================
  94. void didPickDocumentsAtURLs (NSArray<NSURL*>* urls)
  95. {
  96. cancelPendingUpdate();
  97. const auto isWriting = controller.get().documentPickerMode == UIDocumentPickerModeExportToService
  98. || controller.get().documentPickerMode == UIDocumentPickerModeMoveToService;
  99. const auto accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
  100. auto* fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
  101. auto* intents = [[[NSMutableArray alloc] init] autorelease];
  102. for (NSURL* url in urls)
  103. {
  104. auto* fileAccessIntent = isWriting
  105. ? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
  106. : [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
  107. [intents addObject: fileAccessIntent];
  108. }
  109. [fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
  110. {
  111. if (err != nil)
  112. {
  113. [[maybe_unused]] auto desc = [err localizedDescription];
  114. jassertfalse;
  115. return;
  116. }
  117. Array<URL> result;
  118. for (NSURL* url in urls)
  119. {
  120. [url startAccessingSecurityScopedResource];
  121. NSError* error = nil;
  122. auto* bookmark = [url bookmarkDataWithOptions: 0
  123. includingResourceValuesForKeys: nil
  124. relativeToURL: nil
  125. error: &error];
  126. [bookmark retain];
  127. [url stopAccessingSecurityScopedResource];
  128. URL juceUrl (nsStringToJuce ([url absoluteString]));
  129. if (error == nil)
  130. {
  131. setURLBookmark (juceUrl, (void*) bookmark);
  132. }
  133. else
  134. {
  135. [[maybe_unused]] auto desc = [error localizedDescription];
  136. jassertfalse;
  137. }
  138. result.add (std::move (juceUrl));
  139. }
  140. passResultsToInitiator (std::move (result));
  141. }];
  142. }
  143. void didPickDocumentAtURL (NSURL* url)
  144. {
  145. didPickDocumentsAtURLs (@[url]);
  146. }
  147. void pickerWasCancelled()
  148. {
  149. passResultsToInitiator ({});
  150. }
  151. private:
  152. Native (FileChooser& fileChooser, int flags)
  153. : owner (fileChooser)
  154. {
  155. delegate.reset ([[FileChooserDelegateClass alloc] initWithOwner: this]);
  156. String firstFileExtension;
  157. auto utTypeArray = createNSArrayFromStringArray (getUTTypesForWildcards (owner.filters, firstFileExtension));
  158. if ((flags & FileBrowserComponent::saveMode) != 0)
  159. {
  160. auto currentFileOrDirectory = owner.startingFile;
  161. UIDocumentPickerMode pickerMode = currentFileOrDirectory.existsAsFile()
  162. ? UIDocumentPickerModeExportToService
  163. : UIDocumentPickerModeMoveToService;
  164. if (! currentFileOrDirectory.existsAsFile())
  165. {
  166. auto filename = getFilename (currentFileOrDirectory, firstFileExtension);
  167. auto tmpDirectory = File::createTempFile ("JUCE-filepath");
  168. if (tmpDirectory.createDirectory().wasOk())
  169. {
  170. currentFileOrDirectory = tmpDirectory.getChildFile (filename);
  171. currentFileOrDirectory.replaceWithText ("");
  172. }
  173. else
  174. {
  175. // Temporary directory creation failed! You need to specify a
  176. // path you have write access to. Saving will not work for
  177. // current path.
  178. jassertfalse;
  179. }
  180. }
  181. auto url = [[NSURL alloc] initFileURLWithPath: juceStringToNS (currentFileOrDirectory.getFullPathName())];
  182. controller.reset ([[FileChooserControllerClass alloc] initWithURL: url inMode: pickerMode]);
  183. [url release];
  184. }
  185. else
  186. {
  187. controller.reset ([[FileChooserControllerClass alloc] initWithDocumentTypes: utTypeArray inMode: UIDocumentPickerModeOpen]);
  188. if (@available (iOS 11.0, *))
  189. [controller.get() setAllowsMultipleSelection: (flags & FileBrowserComponent::canSelectMultipleItems) != 0];
  190. }
  191. [controller.get() setDelegate: delegate.get()];
  192. [controller.get() setModalTransitionStyle: UIModalTransitionStyleCrossDissolve];
  193. setOpaque (false);
  194. if (fileChooser.parent != nullptr)
  195. {
  196. [controller.get() setModalPresentationStyle: UIModalPresentationFullScreen];
  197. auto chooserBounds = fileChooser.parent->getBounds();
  198. setBounds (chooserBounds);
  199. setAlwaysOnTop (true);
  200. fileChooser.parent->addAndMakeVisible (this);
  201. }
  202. else
  203. {
  204. if (SystemStats::isRunningInAppExtensionSandbox())
  205. {
  206. // Opening a native top-level window in an AUv3 is not allowed (sandboxing). You need to specify a
  207. // parent component (for example your editor) to parent the native file chooser window. To do this
  208. // specify a parent component in the FileChooser's constructor!
  209. jassertfalse;
  210. return;
  211. }
  212. auto chooserBounds = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  213. setBounds (chooserBounds);
  214. setAlwaysOnTop (true);
  215. setVisible (true);
  216. addToDesktop (0);
  217. }
  218. }
  219. void passResultsToInitiator (Array<URL> urls)
  220. {
  221. cancelPendingUpdate();
  222. exitModalState (0);
  223. // If the caller attempts to show a platform-native dialog box inside the results callback (e.g. in the DialogsDemo)
  224. // then the original peer must already have focus. Otherwise, there's a danger that either the invisible FileChooser
  225. // components will display the popup, locking the application, or maybe no component will have focus, and the
  226. // dialog won't show at all.
  227. for (auto i = 0; i < ComponentPeer::getNumPeers(); ++i)
  228. if (auto* p = ComponentPeer::getPeer (i))
  229. if (p != getPeer())
  230. if (auto* view = (UIView*) p->getNativeHandle())
  231. if ([view becomeFirstResponder] && [view isFirstResponder])
  232. break;
  233. // Calling owner.finished will delete this Pimpl instance, so don't call any more member functions here!
  234. owner.finished (std::move (urls));
  235. }
  236. //==============================================================================
  237. static StringArray getUTTypesForWildcards (const String& filterWildcards, String& firstExtension)
  238. {
  239. auto filters = StringArray::fromTokens (filterWildcards, ";", "");
  240. StringArray result;
  241. firstExtension = {};
  242. if (! filters.contains ("*") && filters.size() > 0)
  243. {
  244. for (auto filter : filters)
  245. {
  246. if (filter.isEmpty())
  247. continue;
  248. // iOS only supports file extension wild cards
  249. jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
  250. auto fileExtension = filter.fromLastOccurrenceOf (".", false, false);
  251. CFUniquePtr<CFStringRef> fileExtensionCF (fileExtension.toCFString());
  252. if (firstExtension.isEmpty())
  253. firstExtension = fileExtension;
  254. if (auto tag = CFUniquePtr<CFStringRef> (UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF.get(), nullptr)))
  255. result.add (String::fromCFString (tag.get()));
  256. }
  257. }
  258. else
  259. {
  260. result.add ("public.data");
  261. }
  262. return result;
  263. }
  264. static String getFilename (const File& path, const String& fallbackExtension)
  265. {
  266. auto filename = path.getFileNameWithoutExtension();
  267. auto extension = path.getFileExtension().substring (1);
  268. if (filename.isEmpty())
  269. filename = "Untitled";
  270. if (extension.isEmpty())
  271. extension = fallbackExtension;
  272. if (extension.isNotEmpty())
  273. filename += "." + extension;
  274. return filename;
  275. }
  276. //==============================================================================
  277. FileChooser& owner;
  278. NSUniquePtr<NSObject<UIDocumentPickerDelegate>> delegate;
  279. NSUniquePtr<FileChooserControllerClass> controller;
  280. UIViewComponentPeer* peer = nullptr;
  281. //==============================================================================
  282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  283. };
  284. //==============================================================================
  285. bool FileChooser::isPlatformDialogAvailable()
  286. {
  287. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  288. return false;
  289. #else
  290. return true;
  291. #endif
  292. }
  293. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  294. FilePreviewComponent*)
  295. {
  296. return Native::make (owner, flags);
  297. }
  298. #if JUCE_DEPRECATION_IGNORED
  299. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  300. #endif
  301. } // namespace juce
  302. @implementation FileChooserControllerClass
  303. {
  304. std::weak_ptr<FileChooser::Native> ptr;
  305. }
  306. - (void) setParent: (FileChooser::Native*) parent
  307. {
  308. jassert (parent != nullptr);
  309. jassert (parent->shared_from_this() != nullptr);
  310. ptr = parent->weak_from_this();
  311. }
  312. - (void) viewDidDisappear: (BOOL) animated
  313. {
  314. [super viewDidDisappear: animated];
  315. if (auto nativeParent = ptr.lock())
  316. nativeParent->triggerAsyncUpdate();
  317. }
  318. @end
  319. @implementation FileChooserDelegateClass
  320. {
  321. FileChooser::Native* owner;
  322. }
  323. - (id) initWithOwner: (FileChooser::Native*) o
  324. {
  325. self = [super init];
  326. owner = o;
  327. return self;
  328. }
  329. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-implementations")
  330. - (void) documentPicker: (UIDocumentPickerViewController*) controller didPickDocumentAtURL: (NSURL*) url
  331. {
  332. if (owner != nullptr)
  333. owner->didPickDocumentAtURL (url);
  334. }
  335. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  336. - (void) documentPicker: (UIDocumentPickerViewController*) controller didPickDocumentsAtURLs: (NSArray<NSURL*>*) urls
  337. {
  338. if (owner != nullptr)
  339. owner->didPickDocumentsAtURLs (urls);
  340. }
  341. - (void) documentPickerWasCancelled: (UIDocumentPickerViewController*) controller
  342. {
  343. if (owner != nullptr)
  344. owner->pickerWasCancelled();
  345. }
  346. @end