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.

345 lines
12KB

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