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.

393 lines
14KB

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