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.

juce_ios_FileChooser.mm 12KB

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