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.

415 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. //==============================================================================
  21. static NSMutableArray* createAllowedTypesArray (const StringArray& filters)
  22. {
  23. if (filters.size() == 0)
  24. return nil;
  25. NSMutableArray* filterArray = [[[NSMutableArray alloc] init] autorelease];
  26. for (int i = 0; i < filters.size(); ++i)
  27. {
  28. // From OS X 10.6 you can only specify allowed extensions, so any filters containing wildcards
  29. // must be of the form "*.extension"
  30. jassert (filters[i] == "*"
  31. || (filters[i].startsWith ("*.") && filters[i].lastIndexOfChar ('*') == 0));
  32. const String f (filters[i].replace ("*.", ""));
  33. if (f == "*")
  34. return nil;
  35. [filterArray addObject: juceStringToNS (f)];
  36. }
  37. return filterArray;
  38. }
  39. //==============================================================================
  40. class FileChooser::Native : public Component,
  41. public FileChooser::Pimpl
  42. {
  43. public:
  44. Native (FileChooser& fileChooser, int flags, FilePreviewComponent* previewComponent)
  45. : owner (fileChooser), preview (previewComponent),
  46. selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
  47. selectsFiles ((flags & FileBrowserComponent::canSelectFiles) != 0),
  48. isSave ((flags & FileBrowserComponent::saveMode) != 0),
  49. selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0)
  50. {
  51. setBounds (0, 0, 0, 0);
  52. setOpaque (true);
  53. panel = [&]
  54. {
  55. if (SystemStats::isAppSandboxEnabled())
  56. return isSave ? [[NSSavePanel alloc] init]
  57. : [[NSOpenPanel alloc] init];
  58. static SafeSavePanel safeSavePanel;
  59. static SafeOpenPanel safeOpenPanel;
  60. return isSave ? [safeSavePanel.createInstance() init]
  61. : [safeOpenPanel.createInstance() init];
  62. }();
  63. static DelegateClass delegateClass;
  64. delegate = [delegateClass.createInstance() init];
  65. object_setInstanceVariable (delegate, "cppObject", this);
  66. [panel setDelegate: delegate];
  67. filters.addTokens (owner.filters.replaceCharacters (",:", ";;"), ";", String());
  68. filters.trim();
  69. filters.removeEmptyStrings();
  70. auto* nsTitle = juceStringToNS (owner.title);
  71. [panel setTitle: nsTitle];
  72. [panel setReleasedWhenClosed: YES];
  73. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  74. [panel setAllowedFileTypes: createAllowedTypesArray (filters)];
  75. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  76. if (! isSave)
  77. {
  78. auto* openPanel = static_cast<NSOpenPanel*> (panel);
  79. [openPanel setCanChooseDirectories: selectsDirectories];
  80. [openPanel setCanChooseFiles: selectsFiles];
  81. [openPanel setAllowsMultipleSelection: selectMultiple];
  82. [openPanel setResolvesAliases: YES];
  83. [openPanel setMessage: nsTitle]; // equivalent to the title bar since 10.11
  84. if (owner.treatFilePackagesAsDirs)
  85. [openPanel setTreatsFilePackagesAsDirectories: YES];
  86. }
  87. if (preview != nullptr)
  88. {
  89. nsViewPreview = [[NSView alloc] initWithFrame: makeNSRect (preview->getLocalBounds())];
  90. [panel setAccessoryView: nsViewPreview];
  91. preview->addToDesktop (0, (void*) nsViewPreview);
  92. preview->setVisible (true);
  93. if (@available (macOS 10.11, *))
  94. {
  95. if (! isSave)
  96. {
  97. auto* openPanel = static_cast<NSOpenPanel*> (panel);
  98. [openPanel setAccessoryViewDisclosed: YES];
  99. }
  100. }
  101. }
  102. if (isSave || selectsDirectories)
  103. [panel setCanCreateDirectories: YES];
  104. [panel setLevel: NSModalPanelWindowLevel];
  105. if (owner.startingFile.isDirectory())
  106. {
  107. startingDirectory = owner.startingFile.getFullPathName();
  108. }
  109. else
  110. {
  111. startingDirectory = owner.startingFile.getParentDirectory().getFullPathName();
  112. filename = owner.startingFile.getFileName();
  113. }
  114. [panel setDirectoryURL: createNSURLFromFile (startingDirectory)];
  115. [panel setNameFieldStringValue: juceStringToNS (filename)];
  116. }
  117. ~Native() override
  118. {
  119. exitModalState (0);
  120. if (preview != nullptr)
  121. preview->removeFromDesktop();
  122. removeFromDesktop();
  123. if (panel != nil)
  124. {
  125. [panel setDelegate: nil];
  126. if (nsViewPreview != nil)
  127. {
  128. [panel setAccessoryView: nil];
  129. [nsViewPreview release];
  130. }
  131. [panel close];
  132. }
  133. if (delegate != nil)
  134. [delegate release];
  135. }
  136. void launch() override
  137. {
  138. if (panel != nil)
  139. {
  140. setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());
  141. addToDesktop (0);
  142. enterModalState (true);
  143. MessageManager::callAsync ([ref = SafePointer<Native> (this)]
  144. {
  145. if (ref == nullptr)
  146. return;
  147. [ref->panel beginWithCompletionHandler: CreateObjCBlock (ref.getComponent(), &Native::finished)];
  148. if (ref->preview != nullptr)
  149. ref->preview->toFront (true);
  150. });
  151. }
  152. }
  153. void runModally() override
  154. {
  155. #if JUCE_MODAL_LOOPS_PERMITTED
  156. ensurePanelSafe();
  157. std::unique_ptr<TemporaryMainMenuWithStandardCommands> tempMenu;
  158. if (JUCEApplicationBase::isStandaloneApp())
  159. tempMenu = std::make_unique<TemporaryMainMenuWithStandardCommands> (preview);
  160. jassert (panel != nil);
  161. auto result = [panel runModal];
  162. finished (result);
  163. #else
  164. jassertfalse;
  165. #endif
  166. }
  167. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  168. {
  169. return TemporaryMainMenuWithStandardCommands::checkModalEvent (preview, targetComponent);
  170. }
  171. private:
  172. //==============================================================================
  173. typedef NSObject<NSOpenSavePanelDelegate> DelegateType;
  174. static URL urlFromNSURL (NSURL* url)
  175. {
  176. const auto scheme = nsStringToJuce ([url scheme]);
  177. auto pathComponents = StringArray::fromTokens (nsStringToJuce ([url path]), "/", {});
  178. for (auto& component : pathComponents)
  179. component = URL::addEscapeChars (component, false);
  180. return { scheme + "://" + pathComponents.joinIntoString ("/") };
  181. }
  182. void finished (NSInteger result)
  183. {
  184. Array<URL> chooserResults;
  185. exitModalState (0);
  186. const auto okResult = []() -> NSInteger
  187. {
  188. if (@available (macOS 10.9, *))
  189. return NSModalResponseOK;
  190. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  191. return NSFileHandlingPanelOKButton;
  192. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  193. }();
  194. if (panel != nil && result == okResult)
  195. {
  196. auto addURLResult = [&chooserResults] (NSURL* urlToAdd)
  197. {
  198. chooserResults.add (urlFromNSURL (urlToAdd));
  199. };
  200. if (isSave)
  201. {
  202. addURLResult ([panel URL]);
  203. }
  204. else
  205. {
  206. auto* openPanel = static_cast<NSOpenPanel*> (panel);
  207. auto urls = [openPanel URLs];
  208. for (unsigned int i = 0; i < [urls count]; ++i)
  209. addURLResult ([urls objectAtIndex: i]);
  210. }
  211. }
  212. owner.finished (chooserResults);
  213. }
  214. BOOL shouldShowURL (const URL& urlToTest)
  215. {
  216. for (int i = filters.size(); --i >= 0;)
  217. if (urlToTest.getFileName().matchesWildcard (filters[i], true))
  218. return YES;
  219. const auto f = urlToTest.getLocalFile();
  220. return f.isDirectory()
  221. && ! [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (f.getFullPathName())];
  222. }
  223. void panelSelectionDidChange ([[maybe_unused]] id sender)
  224. {
  225. jassert (sender == panel);
  226. // NB: would need to extend FilePreviewComponent to handle the full list rather than just the first one
  227. if (preview != nullptr)
  228. preview->selectedFileChanged (File (getSelectedPaths()[0]));
  229. }
  230. StringArray getSelectedPaths() const
  231. {
  232. if (panel == nullptr)
  233. return {};
  234. StringArray paths;
  235. if (isSave)
  236. {
  237. paths.add (nsStringToJuce ([[panel URL] path]));
  238. }
  239. else
  240. {
  241. auto* urls = [static_cast<NSOpenPanel*> (panel) URLs];
  242. for (NSUInteger i = 0; i < [urls count]; ++i)
  243. paths.add (nsStringToJuce ([[urls objectAtIndex: i] path]));
  244. }
  245. return paths;
  246. }
  247. //==============================================================================
  248. FileChooser& owner;
  249. FilePreviewComponent* preview;
  250. NSView* nsViewPreview = nullptr;
  251. bool selectsDirectories, selectsFiles, isSave, selectMultiple;
  252. NSSavePanel* panel;
  253. DelegateType* delegate;
  254. StringArray filters;
  255. String startingDirectory, filename;
  256. void ensurePanelSafe()
  257. {
  258. // If you hit this, something (probably the plugin host) has modified the panel,
  259. // allowing the application to terminate while the panel's modal loop is running.
  260. // This is a very bad idea! Quitting from within the panel's modal loop may cause
  261. // your plugin/app destructor to run directly from within `runModally`, which will
  262. // dispose all app resources while they're still in use.
  263. // A safer alternative is to invoke the FileChooser with `launchAsync`, rather than
  264. // using the modal launchers.
  265. jassert ([panel preventsApplicationTerminationWhenModal]);
  266. }
  267. static BOOL preventsApplicationTerminationWhenModal (id, SEL) { return YES; }
  268. template <typename Base>
  269. struct SafeModalPanel : public ObjCClass<Base>
  270. {
  271. explicit SafeModalPanel (const char* name) : ObjCClass<Base> (name)
  272. {
  273. this->addMethod (@selector (preventsApplicationTerminationWhenModal),
  274. preventsApplicationTerminationWhenModal);
  275. this->registerClass();
  276. }
  277. };
  278. struct SafeSavePanel : SafeModalPanel<NSSavePanel>
  279. {
  280. SafeSavePanel() : SafeModalPanel ("SafeSavePanel_") {}
  281. };
  282. struct SafeOpenPanel : SafeModalPanel<NSOpenPanel>
  283. {
  284. SafeOpenPanel() : SafeModalPanel ("SafeOpenPanel_") {}
  285. };
  286. //==============================================================================
  287. struct DelegateClass : public ObjCClass<DelegateType>
  288. {
  289. DelegateClass() : ObjCClass<DelegateType> ("JUCEFileChooser_")
  290. {
  291. addIvar<Native*> ("cppObject");
  292. addMethod (@selector (panel:shouldEnableURL:), shouldEnableURL);
  293. addMethod (@selector (panelSelectionDidChange:), panelSelectionDidChange);
  294. addProtocol (@protocol (NSOpenSavePanelDelegate));
  295. registerClass();
  296. }
  297. private:
  298. static BOOL shouldEnableURL (id self, SEL, id /*sender*/, NSURL* url)
  299. {
  300. return getIvar<Native*> (self, "cppObject")->shouldShowURL (urlFromNSURL (url));
  301. }
  302. static void panelSelectionDidChange (id self, SEL, id sender)
  303. {
  304. getIvar<Native*> (self, "cppObject")->panelSelectionDidChange (sender);
  305. }
  306. };
  307. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  308. };
  309. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  310. FilePreviewComponent* preview)
  311. {
  312. return std::make_shared<FileChooser::Native> (owner, flags, preview);
  313. }
  314. bool FileChooser::isPlatformDialogAvailable()
  315. {
  316. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  317. return false;
  318. #else
  319. return true;
  320. #endif
  321. }
  322. }