Audio plugin host https://kx.studio/carla
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.

382 lines
13KB

  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. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-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. namespace juce
  19. {
  20. class FileChooser::Native : public FileChooser::Pimpl,
  21. public Component,
  22. private AsyncUpdater
  23. {
  24. public:
  25. Native (FileChooser& fileChooser, int flags)
  26. : owner (fileChooser)
  27. {
  28. static FileChooserDelegateClass delegateClass;
  29. delegate.reset ([delegateClass.createInstance() init]);
  30. FileChooserDelegateClass::setOwner (delegate.get(), this);
  31. static FileChooserControllerClass controllerClass;
  32. auto* controllerClassInstance = controllerClass.createInstance();
  33. String firstFileExtension;
  34. auto utTypeArray = createNSArrayFromStringArray (getUTTypesForWildcards (owner.filters, firstFileExtension));
  35. if ((flags & FileBrowserComponent::saveMode) != 0)
  36. {
  37. auto currentFileOrDirectory = owner.startingFile;
  38. UIDocumentPickerMode pickerMode = currentFileOrDirectory.existsAsFile()
  39. ? UIDocumentPickerModeExportToService
  40. : UIDocumentPickerModeMoveToService;
  41. if (! currentFileOrDirectory.existsAsFile())
  42. {
  43. auto filename = getFilename (currentFileOrDirectory, firstFileExtension);
  44. auto tmpDirectory = File::createTempFile ("JUCE-filepath");
  45. if (tmpDirectory.createDirectory().wasOk())
  46. {
  47. currentFileOrDirectory = tmpDirectory.getChildFile (filename);
  48. currentFileOrDirectory.replaceWithText ("");
  49. }
  50. else
  51. {
  52. // Temporary directory creation failed! You need to specify a
  53. // path you have write access to. Saving will not work for
  54. // current path.
  55. jassertfalse;
  56. }
  57. }
  58. auto url = [[NSURL alloc] initFileURLWithPath: juceStringToNS (currentFileOrDirectory.getFullPathName())];
  59. controller.reset ([controllerClassInstance initWithURL: url
  60. inMode: pickerMode]);
  61. [url release];
  62. }
  63. else
  64. {
  65. controller.reset ([controllerClassInstance initWithDocumentTypes: utTypeArray
  66. inMode: UIDocumentPickerModeOpen]);
  67. }
  68. FileChooserControllerClass::setOwner (controller.get(), this);
  69. [controller.get() setDelegate: delegate.get()];
  70. [controller.get() setModalTransitionStyle: UIModalTransitionStyleCrossDissolve];
  71. setOpaque (false);
  72. if (fileChooser.parent != nullptr)
  73. {
  74. [controller.get() setModalPresentationStyle: UIModalPresentationFullScreen];
  75. auto chooserBounds = fileChooser.parent->getBounds();
  76. setBounds (chooserBounds);
  77. setAlwaysOnTop (true);
  78. fileChooser.parent->addAndMakeVisible (this);
  79. }
  80. else
  81. {
  82. if (SystemStats::isRunningInAppExtensionSandbox())
  83. {
  84. // Opening a native top-level window in an AUv3 is not allowed (sandboxing). You need to specify a
  85. // parent component (for example your editor) to parent the native file chooser window. To do this
  86. // specify a parent component in the FileChooser's constructor!
  87. jassertfalse;
  88. return;
  89. }
  90. auto chooserBounds = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  91. setBounds (chooserBounds);
  92. setAlwaysOnTop (true);
  93. setVisible (true);
  94. addToDesktop (0);
  95. }
  96. }
  97. ~Native() override
  98. {
  99. exitModalState (0);
  100. }
  101. void launch() override
  102. {
  103. enterModalState (true, nullptr, true);
  104. }
  105. void runModally() override
  106. {
  107. #if JUCE_MODAL_LOOPS_PERMITTED
  108. runModalLoop();
  109. #endif
  110. }
  111. void parentHierarchyChanged() override
  112. {
  113. auto* newPeer = dynamic_cast<UIViewComponentPeer*> (getPeer());
  114. if (peer != newPeer)
  115. {
  116. peer = newPeer;
  117. if (peer != nullptr)
  118. {
  119. if (auto* parentController = peer->controller)
  120. [parentController showViewController: controller.get() sender: parentController];
  121. peer->toFront (false);
  122. }
  123. }
  124. }
  125. private:
  126. //==============================================================================
  127. void handleAsyncUpdate() override
  128. {
  129. pickerWasCancelled();
  130. }
  131. //==============================================================================
  132. static StringArray getUTTypesForWildcards (const String& filterWildcards, String& firstExtension)
  133. {
  134. auto filters = StringArray::fromTokens (filterWildcards, ";", "");
  135. StringArray result;
  136. firstExtension = {};
  137. if (! filters.contains ("*") && filters.size() > 0)
  138. {
  139. for (auto filter : filters)
  140. {
  141. if (filter.isEmpty())
  142. continue;
  143. // iOS only supports file extension wild cards
  144. jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
  145. auto fileExtension = filter.fromLastOccurrenceOf (".", false, false);
  146. auto fileExtensionCF = fileExtension.toCFString();
  147. if (firstExtension.isEmpty())
  148. firstExtension = fileExtension;
  149. auto tag = UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF, nullptr);
  150. if (tag != nullptr)
  151. {
  152. result.add (String::fromCFString (tag));
  153. CFRelease (tag);
  154. }
  155. CFRelease (fileExtensionCF);
  156. }
  157. }
  158. else
  159. {
  160. result.add ("public.data");
  161. }
  162. return result;
  163. }
  164. static String getFilename (const File& path, const String& fallbackExtension)
  165. {
  166. auto filename = path.getFileNameWithoutExtension();
  167. auto extension = path.getFileExtension().substring (1);
  168. if (filename.isEmpty())
  169. filename = "Untitled";
  170. if (extension.isEmpty())
  171. extension = fallbackExtension;
  172. if (extension.isNotEmpty())
  173. filename += "." + extension;
  174. return filename;
  175. }
  176. //==============================================================================
  177. void didPickDocumentAtURL (NSURL* url)
  178. {
  179. cancelPendingUpdate();
  180. bool isWriting = controller.get().documentPickerMode == UIDocumentPickerModeExportToService
  181. | controller.get().documentPickerMode == UIDocumentPickerModeMoveToService;
  182. NSUInteger accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
  183. auto* fileAccessIntent = isWriting
  184. ? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
  185. : [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
  186. NSArray<NSFileAccessIntent*>* intents = @[fileAccessIntent];
  187. auto fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
  188. [fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
  189. {
  190. Array<URL> chooserResults;
  191. if (err == nil)
  192. {
  193. [url startAccessingSecurityScopedResource];
  194. NSError* error = nil;
  195. NSData* bookmark = [url bookmarkDataWithOptions: 0
  196. includingResourceValuesForKeys: nil
  197. relativeToURL: nil
  198. error: &error];
  199. [bookmark retain];
  200. [url stopAccessingSecurityScopedResource];
  201. URL juceUrl (nsStringToJuce ([url absoluteString]));
  202. if (error == nil)
  203. {
  204. setURLBookmark (juceUrl, (void*) bookmark);
  205. }
  206. else
  207. {
  208. auto desc = [error localizedDescription];
  209. ignoreUnused (desc);
  210. jassertfalse;
  211. }
  212. chooserResults.add (juceUrl);
  213. }
  214. else
  215. {
  216. auto desc = [err localizedDescription];
  217. ignoreUnused (desc);
  218. jassertfalse;
  219. }
  220. owner.finished (chooserResults);
  221. }];
  222. }
  223. void pickerWasCancelled()
  224. {
  225. cancelPendingUpdate();
  226. owner.finished ({});
  227. exitModalState (0);
  228. }
  229. //==============================================================================
  230. struct FileChooserDelegateClass : public ObjCClass<NSObject<UIDocumentPickerDelegate>>
  231. {
  232. FileChooserDelegateClass() : ObjCClass<NSObject<UIDocumentPickerDelegate>> ("FileChooserDelegate_")
  233. {
  234. addIvar<Native*> ("owner");
  235. addMethod (@selector (documentPicker:didPickDocumentAtURL:), didPickDocumentAtURL, "v@:@@");
  236. addMethod (@selector (documentPickerWasCancelled:), documentPickerWasCancelled, "v@:@");
  237. addProtocol (@protocol (UIDocumentPickerDelegate));
  238. registerClass();
  239. }
  240. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  241. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  242. //==============================================================================
  243. static void didPickDocumentAtURL (id self, SEL, UIDocumentPickerViewController*, NSURL* url)
  244. {
  245. if (auto* picker = getOwner (self))
  246. picker->didPickDocumentAtURL (url);
  247. }
  248. static void documentPickerWasCancelled (id self, SEL, UIDocumentPickerViewController*)
  249. {
  250. if (auto* picker = getOwner (self))
  251. picker->pickerWasCancelled();
  252. }
  253. };
  254. struct FileChooserControllerClass : public ObjCClass<UIDocumentPickerViewController>
  255. {
  256. FileChooserControllerClass() : ObjCClass<UIDocumentPickerViewController> ("FileChooserController_")
  257. {
  258. addIvar<Native*> ("owner");
  259. addMethod (@selector (viewDidDisappear:), viewDidDisappear, "v@:@c");
  260. registerClass();
  261. }
  262. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  263. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  264. //==============================================================================
  265. static void viewDidDisappear (id self, SEL, BOOL animated)
  266. {
  267. sendSuperclassMessage<void> (self, @selector (viewDidDisappear:), animated);
  268. if (auto* picker = getOwner (self))
  269. picker->triggerAsyncUpdate();
  270. }
  271. };
  272. //==============================================================================
  273. FileChooser& owner;
  274. std::unique_ptr<NSObject<UIDocumentPickerDelegate>, NSObjectDeleter> delegate;
  275. std::unique_ptr<UIDocumentPickerViewController, NSObjectDeleter> controller;
  276. UIViewComponentPeer* peer = nullptr;
  277. static FileChooserDelegateClass fileChooserDelegateClass;
  278. static FileChooserControllerClass fileChooserControllerClass;
  279. //==============================================================================
  280. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  281. };
  282. //==============================================================================
  283. bool FileChooser::isPlatformDialogAvailable()
  284. {
  285. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  286. return false;
  287. #else
  288. return true;
  289. #endif
  290. }
  291. FileChooser::Pimpl* FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  292. FilePreviewComponent*)
  293. {
  294. return new FileChooser::Native (owner, flags);
  295. }
  296. } // namespace juce