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.

406 lines
15KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. #if ! (defined (__IPHONE_16_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_16_0)
  16. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  17. #define JUCE_DEPRECATION_IGNORED 1
  18. #endif
  19. class FileChooser::Native : public FileChooser::Pimpl,
  20. public Component,
  21. private AsyncUpdater
  22. {
  23. public:
  24. Native (FileChooser& fileChooser, int flags)
  25. : owner (fileChooser)
  26. {
  27. static FileChooserDelegateClass delegateClass;
  28. delegate.reset ([delegateClass.createInstance() init]);
  29. FileChooserDelegateClass::setOwner (delegate.get(), this);
  30. static FileChooserControllerClass controllerClass;
  31. auto* controllerClassInstance = controllerClass.createInstance();
  32. String firstFileExtension;
  33. auto utTypeArray = createNSArrayFromStringArray (getUTTypesForWildcards (owner.filters, firstFileExtension));
  34. if ((flags & FileBrowserComponent::saveMode) != 0)
  35. {
  36. auto currentFileOrDirectory = owner.startingFile;
  37. UIDocumentPickerMode pickerMode = currentFileOrDirectory.existsAsFile()
  38. ? UIDocumentPickerModeExportToService
  39. : UIDocumentPickerModeMoveToService;
  40. if (! currentFileOrDirectory.existsAsFile())
  41. {
  42. auto filename = getFilename (currentFileOrDirectory, firstFileExtension);
  43. auto tmpDirectory = File::createTempFile ("JUCE-filepath");
  44. if (tmpDirectory.createDirectory().wasOk())
  45. {
  46. currentFileOrDirectory = tmpDirectory.getChildFile (filename);
  47. currentFileOrDirectory.replaceWithText ("");
  48. }
  49. else
  50. {
  51. // Temporary directory creation failed! You need to specify a
  52. // path you have write access to. Saving will not work for
  53. // current path.
  54. jassertfalse;
  55. }
  56. }
  57. auto url = [[NSURL alloc] initFileURLWithPath: juceStringToNS (currentFileOrDirectory.getFullPathName())];
  58. controller.reset ([controllerClassInstance initWithURL: url
  59. inMode: pickerMode]);
  60. [url release];
  61. }
  62. else
  63. {
  64. controller.reset ([controllerClassInstance initWithDocumentTypes: utTypeArray
  65. inMode: UIDocumentPickerModeOpen]);
  66. if (@available (iOS 11.0, *))
  67. [controller.get() setAllowsMultipleSelection: (flags & FileBrowserComponent::canSelectMultipleItems) != 0];
  68. }
  69. FileChooserControllerClass::setOwner (controller.get(), this);
  70. [controller.get() setDelegate: delegate.get()];
  71. [controller.get() setModalTransitionStyle: UIModalTransitionStyleCrossDissolve];
  72. setOpaque (false);
  73. if (fileChooser.parent != nullptr)
  74. {
  75. [controller.get() setModalPresentationStyle: UIModalPresentationFullScreen];
  76. auto chooserBounds = fileChooser.parent->getBounds();
  77. setBounds (chooserBounds);
  78. setAlwaysOnTop (true);
  79. fileChooser.parent->addAndMakeVisible (this);
  80. }
  81. else
  82. {
  83. if (SystemStats::isRunningInAppExtensionSandbox())
  84. {
  85. // Opening a native top-level window in an AUv3 is not allowed (sandboxing). You need to specify a
  86. // parent component (for example your editor) to parent the native file chooser window. To do this
  87. // specify a parent component in the FileChooser's constructor!
  88. jassertfalse;
  89. return;
  90. }
  91. auto chooserBounds = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  92. setBounds (chooserBounds);
  93. setAlwaysOnTop (true);
  94. setVisible (true);
  95. addToDesktop (0);
  96. }
  97. }
  98. ~Native() override
  99. {
  100. exitModalState (0);
  101. // Our old peer may not have received a becomeFirstResponder call at this point,
  102. // so the static currentlyFocusedPeer may be null.
  103. // We'll try to find an appropriate peer to focus.
  104. for (auto i = 0; i < ComponentPeer::getNumPeers(); ++i)
  105. if (auto* p = ComponentPeer::getPeer (i))
  106. if (p != getPeer())
  107. if (auto* view = (UIView*) p->getNativeHandle())
  108. [view becomeFirstResponder];
  109. }
  110. void launch() override
  111. {
  112. enterModalState (true, nullptr, true);
  113. }
  114. void runModally() override
  115. {
  116. #if JUCE_MODAL_LOOPS_PERMITTED
  117. runModalLoop();
  118. #else
  119. jassertfalse;
  120. #endif
  121. }
  122. void parentHierarchyChanged() override
  123. {
  124. auto* newPeer = dynamic_cast<UIViewComponentPeer*> (getPeer());
  125. if (peer != newPeer)
  126. {
  127. peer = newPeer;
  128. if (peer != nullptr)
  129. {
  130. if (auto* parentController = peer->controller)
  131. [parentController showViewController: controller.get() sender: parentController];
  132. peer->toFront (false);
  133. }
  134. }
  135. }
  136. private:
  137. //==============================================================================
  138. void handleAsyncUpdate() override
  139. {
  140. pickerWasCancelled();
  141. }
  142. //==============================================================================
  143. static StringArray getUTTypesForWildcards (const String& filterWildcards, String& firstExtension)
  144. {
  145. auto filters = StringArray::fromTokens (filterWildcards, ";", "");
  146. StringArray result;
  147. firstExtension = {};
  148. if (! filters.contains ("*") && filters.size() > 0)
  149. {
  150. for (auto filter : filters)
  151. {
  152. if (filter.isEmpty())
  153. continue;
  154. // iOS only supports file extension wild cards
  155. jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
  156. auto fileExtension = filter.fromLastOccurrenceOf (".", false, false);
  157. CFUniquePtr<CFStringRef> fileExtensionCF (fileExtension.toCFString());
  158. if (firstExtension.isEmpty())
  159. firstExtension = fileExtension;
  160. if (auto tag = CFUniquePtr<CFStringRef> (UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF.get(), nullptr)))
  161. result.add (String::fromCFString (tag.get()));
  162. }
  163. }
  164. else
  165. {
  166. result.add ("public.data");
  167. }
  168. return result;
  169. }
  170. static String getFilename (const File& path, const String& fallbackExtension)
  171. {
  172. auto filename = path.getFileNameWithoutExtension();
  173. auto extension = path.getFileExtension().substring (1);
  174. if (filename.isEmpty())
  175. filename = "Untitled";
  176. if (extension.isEmpty())
  177. extension = fallbackExtension;
  178. if (extension.isNotEmpty())
  179. filename += "." + extension;
  180. return filename;
  181. }
  182. //==============================================================================
  183. void didPickDocumentsAtURLs (NSArray<NSURL*>* urls)
  184. {
  185. cancelPendingUpdate();
  186. const auto isWriting = controller.get().documentPickerMode == UIDocumentPickerModeExportToService
  187. || controller.get().documentPickerMode == UIDocumentPickerModeMoveToService;
  188. const auto accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
  189. auto* fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
  190. auto* intents = [[[NSMutableArray alloc] init] autorelease];
  191. for (NSURL* url in urls)
  192. {
  193. auto* fileAccessIntent = isWriting
  194. ? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
  195. : [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
  196. [intents addObject: fileAccessIntent];
  197. }
  198. [fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
  199. {
  200. if (err != nil)
  201. {
  202. auto desc = [err localizedDescription];
  203. ignoreUnused (desc);
  204. jassertfalse;
  205. return;
  206. }
  207. Array<URL> result;
  208. for (NSURL* url in urls)
  209. {
  210. [url startAccessingSecurityScopedResource];
  211. NSError* error = nil;
  212. auto* bookmark = [url bookmarkDataWithOptions: 0
  213. includingResourceValuesForKeys: nil
  214. relativeToURL: nil
  215. error: &error];
  216. [bookmark retain];
  217. [url stopAccessingSecurityScopedResource];
  218. URL juceUrl (nsStringToJuce ([url absoluteString]));
  219. if (error == nil)
  220. {
  221. setURLBookmark (juceUrl, (void*) bookmark);
  222. }
  223. else
  224. {
  225. auto desc = [error localizedDescription];
  226. ignoreUnused (desc);
  227. jassertfalse;
  228. }
  229. result.add (std::move (juceUrl));
  230. }
  231. owner.finished (std::move (result));
  232. }];
  233. }
  234. void didPickDocumentAtURL (NSURL* url)
  235. {
  236. didPickDocumentsAtURLs (@[url]);
  237. }
  238. void pickerWasCancelled()
  239. {
  240. cancelPendingUpdate();
  241. owner.finished ({});
  242. // Calling owner.finished will delete this Pimpl instance, so don't call any more member functions here!
  243. }
  244. //==============================================================================
  245. struct FileChooserDelegateClass : public ObjCClass<NSObject<UIDocumentPickerDelegate>>
  246. {
  247. FileChooserDelegateClass() : ObjCClass<NSObject<UIDocumentPickerDelegate>> ("FileChooserDelegate_")
  248. {
  249. addIvar<Native*> ("owner");
  250. addMethod (@selector (documentPicker:didPickDocumentAtURL:), didPickDocumentAtURL);
  251. addMethod (@selector (documentPicker:didPickDocumentsAtURLs:), didPickDocumentsAtURLs);
  252. addMethod (@selector (documentPickerWasCancelled:), documentPickerWasCancelled);
  253. addProtocol (@protocol (UIDocumentPickerDelegate));
  254. registerClass();
  255. }
  256. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  257. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  258. //==============================================================================
  259. static void didPickDocumentAtURL (id self, SEL, UIDocumentPickerViewController*, NSURL* url)
  260. {
  261. if (auto* picker = getOwner (self))
  262. picker->didPickDocumentAtURL (url);
  263. }
  264. static void didPickDocumentsAtURLs (id self, SEL, UIDocumentPickerViewController*, NSArray<NSURL*>* urls)
  265. {
  266. if (auto* picker = getOwner (self))
  267. picker->didPickDocumentsAtURLs (urls);
  268. }
  269. static void documentPickerWasCancelled (id self, SEL, UIDocumentPickerViewController*)
  270. {
  271. if (auto* picker = getOwner (self))
  272. picker->pickerWasCancelled();
  273. }
  274. };
  275. struct FileChooserControllerClass : public ObjCClass<UIDocumentPickerViewController>
  276. {
  277. FileChooserControllerClass() : ObjCClass<UIDocumentPickerViewController> ("FileChooserController_")
  278. {
  279. addIvar<Native*> ("owner");
  280. addMethod (@selector (viewDidDisappear:), viewDidDisappear);
  281. registerClass();
  282. }
  283. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  284. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  285. //==============================================================================
  286. static void viewDidDisappear (id self, SEL, BOOL animated)
  287. {
  288. sendSuperclassMessage<void> (self, @selector (viewDidDisappear:), animated);
  289. if (auto* picker = getOwner (self))
  290. picker->triggerAsyncUpdate();
  291. }
  292. };
  293. //==============================================================================
  294. FileChooser& owner;
  295. NSUniquePtr<NSObject<UIDocumentPickerDelegate>> delegate;
  296. NSUniquePtr<UIDocumentPickerViewController> controller;
  297. UIViewComponentPeer* peer = nullptr;
  298. static FileChooserDelegateClass fileChooserDelegateClass;
  299. static FileChooserControllerClass fileChooserControllerClass;
  300. //==============================================================================
  301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  302. };
  303. //==============================================================================
  304. bool FileChooser::isPlatformDialogAvailable()
  305. {
  306. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  307. return false;
  308. #else
  309. return true;
  310. #endif
  311. }
  312. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  313. FilePreviewComponent*)
  314. {
  315. return std::make_shared<FileChooser::Native> (owner, flags);
  316. }
  317. #if JUCE_DEPRECATION_IGNORED
  318. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  319. #endif
  320. } // namespace juce