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.

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