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.

389 lines
14KB

  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, UIAdaptivePresentationControllerDelegate>
  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. //==============================================================================
  31. class FileChooser::Native final : public FileChooser::Pimpl,
  32. public detail::NativeModalWrapperComponent,
  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. void launch() override
  47. {
  48. jassert (shared_from_this() != nullptr);
  49. /* Normally, when deleteWhenDismissed is true, the modal component manager will keep a copy of a raw pointer
  50. to our component and delete it when the modal state has ended. However, this is incompatible with
  51. our class being tracked by shared_ptr as it will force delete our class regardless of the current
  52. reference count. On the other hand, it's important that the modal manager keeps a reference as it can
  53. sometimes be the only reference to our class.
  54. To do this, we set deleteWhenDismissed to false so that the modal component manager does not delete
  55. our class. Instead, we pass in a lambda which captures a shared_ptr to ourselves to increase the
  56. reference count while the component is modal.
  57. */
  58. enterModalState (true,
  59. ModalCallbackFunction::create ([_self = shared_from_this()] (int) {}),
  60. false);
  61. }
  62. void runModally() override
  63. {
  64. #if JUCE_MODAL_LOOPS_PERMITTED
  65. launch();
  66. runModalLoop();
  67. #else
  68. jassertfalse;
  69. #endif
  70. }
  71. //==============================================================================
  72. void didPickDocumentsAtURLs (NSArray<NSURL*>* urls)
  73. {
  74. const auto isWriting = controller.get().documentPickerMode == UIDocumentPickerModeExportToService
  75. || controller.get().documentPickerMode == UIDocumentPickerModeMoveToService;
  76. const auto accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
  77. auto* fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
  78. auto* intents = [[[NSMutableArray alloc] init] autorelease];
  79. for (NSURL* url in urls)
  80. {
  81. auto* fileAccessIntent = isWriting
  82. ? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
  83. : [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
  84. [intents addObject: fileAccessIntent];
  85. }
  86. [fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
  87. {
  88. if (err != nil)
  89. {
  90. [[maybe_unused]] auto desc = [err localizedDescription];
  91. jassertfalse;
  92. return;
  93. }
  94. Array<URL> result;
  95. for (NSURL* url in urls)
  96. {
  97. [url startAccessingSecurityScopedResource];
  98. NSError* error = nil;
  99. auto* bookmark = [url bookmarkDataWithOptions: 0
  100. includingResourceValuesForKeys: nil
  101. relativeToURL: nil
  102. error: &error];
  103. [bookmark retain];
  104. [url stopAccessingSecurityScopedResource];
  105. URL juceUrl (nsStringToJuce ([url absoluteString]));
  106. if (error == nil)
  107. {
  108. setURLBookmark (juceUrl, (void*) bookmark);
  109. }
  110. else
  111. {
  112. [[maybe_unused]] auto desc = [error localizedDescription];
  113. jassertfalse;
  114. }
  115. result.add (std::move (juceUrl));
  116. }
  117. passResultsToInitiator (std::move (result));
  118. }];
  119. }
  120. void didPickDocumentAtURL (NSURL* url)
  121. {
  122. didPickDocumentsAtURLs (@[url]);
  123. }
  124. void pickerWasCancelled()
  125. {
  126. passResultsToInitiator ({});
  127. }
  128. private:
  129. UIViewController* getViewController() const override { return controller.get(); }
  130. Native (FileChooser& fileChooser, int flags)
  131. : owner (fileChooser)
  132. {
  133. delegate.reset ([[FileChooserDelegateClass alloc] initWithOwner: this]);
  134. const auto validExtensions = getValidExtensionsForWildcards (owner.filters);
  135. const auto utTypeArray = (flags & FileBrowserComponent::canSelectDirectories) != 0
  136. ? @[@"public.folder"]
  137. : createNSArrayFromStringArray (getUTTypesForExtensions (validExtensions));
  138. if ((flags & FileBrowserComponent::saveMode) != 0)
  139. {
  140. auto currentFileOrDirectory = owner.startingFile;
  141. UIDocumentPickerMode pickerMode = currentFileOrDirectory.existsAsFile()
  142. ? UIDocumentPickerModeExportToService
  143. : UIDocumentPickerModeMoveToService;
  144. if (! currentFileOrDirectory.existsAsFile())
  145. {
  146. const auto extension = validExtensions.isEmpty() ? String()
  147. : validExtensions.getReference (0);
  148. const auto filename = getFilename (currentFileOrDirectory, extension);
  149. const auto tmpDirectory = File::createTempFile ("JUCE-filepath");
  150. if (tmpDirectory.createDirectory().wasOk())
  151. {
  152. currentFileOrDirectory = tmpDirectory.getChildFile (filename);
  153. currentFileOrDirectory.replaceWithText ("");
  154. }
  155. else
  156. {
  157. // Temporary directory creation failed! You need to specify a
  158. // path you have write access to. Saving will not work for
  159. // current path.
  160. jassertfalse;
  161. }
  162. }
  163. auto url = [[NSURL alloc] initFileURLWithPath: juceStringToNS (currentFileOrDirectory.getFullPathName())];
  164. controller.reset ([[FileChooserControllerClass alloc] initWithURL: url inMode: pickerMode]);
  165. [url release];
  166. }
  167. else
  168. {
  169. controller.reset ([[FileChooserControllerClass alloc] initWithDocumentTypes: utTypeArray inMode: UIDocumentPickerModeOpen]);
  170. if (@available (iOS 11.0, *))
  171. [controller.get() setAllowsMultipleSelection: (flags & FileBrowserComponent::canSelectMultipleItems) != 0];
  172. }
  173. [controller.get() setDelegate: delegate.get()];
  174. if (auto* pc = [controller.get() presentationController])
  175. [pc setDelegate: delegate.get()];
  176. displayNativeWindowModally (fileChooser.parent);
  177. }
  178. void passResultsToInitiator (Array<URL> urls)
  179. {
  180. exitModalState (0);
  181. // If the caller attempts to show a platform-native dialog box inside the results callback (e.g. in the DialogsDemo)
  182. // then the original peer must already have focus. Otherwise, there's a danger that either the invisible FileChooser
  183. // components will display the popup, locking the application, or maybe no component will have focus, and the
  184. // dialog won't show at all.
  185. for (auto i = 0; i < ComponentPeer::getNumPeers(); ++i)
  186. if (auto* p = ComponentPeer::getPeer (i))
  187. if (p != getPeer())
  188. if (auto* view = (UIView*) p->getNativeHandle())
  189. if ([view becomeFirstResponder] && [view isFirstResponder])
  190. break;
  191. // Calling owner.finished will delete this Pimpl instance, so don't call any more member functions here!
  192. owner.finished (std::move (urls));
  193. }
  194. //==============================================================================
  195. static StringArray getValidExtensionsForWildcards (const String& filterWildcards)
  196. {
  197. const auto filters = StringArray::fromTokens (filterWildcards, ";", "");
  198. if (filters.contains ("*") || filters.isEmpty())
  199. return {};
  200. StringArray result;
  201. for (const auto& filter : filters)
  202. {
  203. if (filter.isEmpty())
  204. continue;
  205. // iOS only supports file extension wild cards
  206. jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
  207. result.add (filter.fromLastOccurrenceOf (".", false, false));
  208. }
  209. return result;
  210. }
  211. static StringArray getUTTypesForExtensions (const StringArray& extensions)
  212. {
  213. if (extensions.isEmpty())
  214. return { "public.data" };
  215. StringArray result;
  216. for (const auto& extension : extensions)
  217. {
  218. if (extension.isEmpty())
  219. continue;
  220. CFUniquePtr<CFStringRef> fileExtensionCF (extension.toCFString());
  221. if (const auto tag = CFUniquePtr<CFStringRef> (UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF.get(), nullptr)))
  222. result.add (String::fromCFString (tag.get()));
  223. }
  224. return result;
  225. }
  226. static String getFilename (const File& path, const String& fallbackExtension)
  227. {
  228. auto filename = path.getFileNameWithoutExtension();
  229. auto extension = path.getFileExtension().substring (1);
  230. if (filename.isEmpty())
  231. filename = "Untitled";
  232. if (extension.isEmpty())
  233. extension = fallbackExtension;
  234. if (extension.isNotEmpty())
  235. filename += "." + extension;
  236. return filename;
  237. }
  238. //==============================================================================
  239. FileChooser& owner;
  240. NSUniquePtr<NSObject<UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate>> delegate;
  241. NSUniquePtr<FileChooserControllerClass> controller;
  242. //==============================================================================
  243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  244. };
  245. //==============================================================================
  246. bool FileChooser::isPlatformDialogAvailable()
  247. {
  248. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  249. return false;
  250. #else
  251. return true;
  252. #endif
  253. }
  254. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  255. FilePreviewComponent*)
  256. {
  257. return Native::make (owner, flags);
  258. }
  259. #if JUCE_DEPRECATION_IGNORED
  260. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  261. #endif
  262. } // namespace juce
  263. @implementation FileChooserControllerClass
  264. {
  265. std::weak_ptr<FileChooser::Native> ptr;
  266. }
  267. - (void) setParent: (FileChooser::Native*) parent
  268. {
  269. jassert (parent != nullptr);
  270. jassert (parent->shared_from_this() != nullptr);
  271. ptr = parent->weak_from_this();
  272. }
  273. @end
  274. @implementation FileChooserDelegateClass
  275. {
  276. FileChooser::Native* owner;
  277. }
  278. - (id) initWithOwner: (FileChooser::Native*) o
  279. {
  280. self = [super init];
  281. owner = o;
  282. return self;
  283. }
  284. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-implementations")
  285. - (void) documentPicker: (UIDocumentPickerViewController*) controller didPickDocumentAtURL: (NSURL*) url
  286. {
  287. if (owner != nullptr)
  288. owner->didPickDocumentAtURL (url);
  289. }
  290. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  291. - (void) documentPicker: (UIDocumentPickerViewController*) controller didPickDocumentsAtURLs: (NSArray<NSURL*>*) urls
  292. {
  293. if (owner != nullptr)
  294. owner->didPickDocumentsAtURLs (urls);
  295. }
  296. - (void) documentPickerWasCancelled: (UIDocumentPickerViewController*) controller
  297. {
  298. if (owner != nullptr)
  299. owner->pickerWasCancelled();
  300. }
  301. - (void) presentationControllerDidDismiss: (UIPresentationController *) presentationController
  302. {
  303. if (owner != nullptr)
  304. owner->pickerWasCancelled();
  305. }
  306. @end