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.

406 lines
13KB

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