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.

388 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_16_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_16_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. #else
  114. jassertfalse;
  115. #endif
  116. }
  117. void parentHierarchyChanged() override
  118. {
  119. auto* newPeer = dynamic_cast<UIViewComponentPeer*> (getPeer());
  120. if (peer != newPeer)
  121. {
  122. peer = newPeer;
  123. if (peer != nullptr)
  124. {
  125. if (auto* parentController = peer->controller)
  126. [parentController showViewController: controller.get() sender: parentController];
  127. peer->toFront (false);
  128. }
  129. }
  130. }
  131. private:
  132. //==============================================================================
  133. void handleAsyncUpdate() override
  134. {
  135. pickerWasCancelled();
  136. }
  137. //==============================================================================
  138. static StringArray getUTTypesForWildcards (const String& filterWildcards, String& firstExtension)
  139. {
  140. auto filters = StringArray::fromTokens (filterWildcards, ";", "");
  141. StringArray result;
  142. firstExtension = {};
  143. if (! filters.contains ("*") && filters.size() > 0)
  144. {
  145. for (auto filter : filters)
  146. {
  147. if (filter.isEmpty())
  148. continue;
  149. // iOS only supports file extension wild cards
  150. jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
  151. auto fileExtension = filter.fromLastOccurrenceOf (".", false, false);
  152. CFUniquePtr<CFStringRef> fileExtensionCF (fileExtension.toCFString());
  153. if (firstExtension.isEmpty())
  154. firstExtension = fileExtension;
  155. if (auto tag = CFUniquePtr<CFStringRef> (UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF.get(), nullptr)))
  156. result.add (String::fromCFString (tag.get()));
  157. }
  158. }
  159. else
  160. {
  161. result.add ("public.data");
  162. }
  163. return result;
  164. }
  165. static String getFilename (const File& path, const String& fallbackExtension)
  166. {
  167. auto filename = path.getFileNameWithoutExtension();
  168. auto extension = path.getFileExtension().substring (1);
  169. if (filename.isEmpty())
  170. filename = "Untitled";
  171. if (extension.isEmpty())
  172. extension = fallbackExtension;
  173. if (extension.isNotEmpty())
  174. filename += "." + extension;
  175. return filename;
  176. }
  177. //==============================================================================
  178. void didPickDocumentAtURL (NSURL* url)
  179. {
  180. cancelPendingUpdate();
  181. bool isWriting = controller.get().documentPickerMode == UIDocumentPickerModeExportToService
  182. | controller.get().documentPickerMode == UIDocumentPickerModeMoveToService;
  183. NSUInteger accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
  184. auto* fileAccessIntent = isWriting
  185. ? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
  186. : [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
  187. NSArray<NSFileAccessIntent*>* intents = @[fileAccessIntent];
  188. auto fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
  189. [fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
  190. {
  191. Array<URL> chooserResults;
  192. if (err == nil)
  193. {
  194. [url startAccessingSecurityScopedResource];
  195. NSError* error = nil;
  196. NSData* bookmark = [url bookmarkDataWithOptions: 0
  197. includingResourceValuesForKeys: nil
  198. relativeToURL: nil
  199. error: &error];
  200. [bookmark retain];
  201. [url stopAccessingSecurityScopedResource];
  202. URL juceUrl (nsStringToJuce ([url absoluteString]));
  203. if (error == nil)
  204. {
  205. setURLBookmark (juceUrl, (void*) bookmark);
  206. }
  207. else
  208. {
  209. auto desc = [error localizedDescription];
  210. ignoreUnused (desc);
  211. jassertfalse;
  212. }
  213. chooserResults.add (juceUrl);
  214. }
  215. else
  216. {
  217. auto desc = [err localizedDescription];
  218. ignoreUnused (desc);
  219. jassertfalse;
  220. }
  221. owner.finished (chooserResults);
  222. }];
  223. }
  224. void pickerWasCancelled()
  225. {
  226. cancelPendingUpdate();
  227. owner.finished ({});
  228. exitModalState (0);
  229. }
  230. //==============================================================================
  231. struct FileChooserDelegateClass : public ObjCClass<NSObject<UIDocumentPickerDelegate>>
  232. {
  233. FileChooserDelegateClass() : ObjCClass<NSObject<UIDocumentPickerDelegate>> ("FileChooserDelegate_")
  234. {
  235. addIvar<Native*> ("owner");
  236. addMethod (@selector (documentPicker:didPickDocumentAtURL:), didPickDocumentAtURL, "v@:@@");
  237. addMethod (@selector (documentPickerWasCancelled:), documentPickerWasCancelled, "v@:@");
  238. addProtocol (@protocol (UIDocumentPickerDelegate));
  239. registerClass();
  240. }
  241. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  242. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  243. //==============================================================================
  244. static void didPickDocumentAtURL (id self, SEL, UIDocumentPickerViewController*, NSURL* url)
  245. {
  246. if (auto* picker = getOwner (self))
  247. picker->didPickDocumentAtURL (url);
  248. }
  249. static void documentPickerWasCancelled (id self, SEL, UIDocumentPickerViewController*)
  250. {
  251. if (auto* picker = getOwner (self))
  252. picker->pickerWasCancelled();
  253. }
  254. };
  255. struct FileChooserControllerClass : public ObjCClass<UIDocumentPickerViewController>
  256. {
  257. FileChooserControllerClass() : ObjCClass<UIDocumentPickerViewController> ("FileChooserController_")
  258. {
  259. addIvar<Native*> ("owner");
  260. addMethod (@selector (viewDidDisappear:), viewDidDisappear, "v@:@c");
  261. registerClass();
  262. }
  263. static void setOwner (id self, Native* owner) { object_setInstanceVariable (self, "owner", owner); }
  264. static Native* getOwner (id self) { return getIvar<Native*> (self, "owner"); }
  265. //==============================================================================
  266. static void viewDidDisappear (id self, SEL, BOOL animated)
  267. {
  268. sendSuperclassMessage<void> (self, @selector (viewDidDisappear:), animated);
  269. if (auto* picker = getOwner (self))
  270. picker->triggerAsyncUpdate();
  271. }
  272. };
  273. //==============================================================================
  274. FileChooser& owner;
  275. NSUniquePtr<NSObject<UIDocumentPickerDelegate>> delegate;
  276. NSUniquePtr<UIDocumentPickerViewController> controller;
  277. UIViewComponentPeer* peer = nullptr;
  278. static FileChooserDelegateClass fileChooserDelegateClass;
  279. static FileChooserControllerClass fileChooserControllerClass;
  280. //==============================================================================
  281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  282. };
  283. //==============================================================================
  284. bool FileChooser::isPlatformDialogAvailable()
  285. {
  286. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  287. return false;
  288. #else
  289. return true;
  290. #endif
  291. }
  292. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  293. FilePreviewComponent*)
  294. {
  295. return std::make_shared<FileChooser::Native> (owner, flags);
  296. }
  297. #if JUCE_DEPRECATION_IGNORED
  298. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  299. #endif
  300. #undef JUCE_DEPRECATION_IGNORED
  301. } // namespace juce