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.

401 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. if (panel != nil && result ==
  170. #if defined (MAC_OS_X_VERSION_10_9) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
  171. NSModalResponseOK)
  172. #else
  173. NSFileHandlingPanelOKButton)
  174. #endif
  175. {
  176. auto addURLResult = [&chooserResults] (NSURL* urlToAdd)
  177. {
  178. auto scheme = nsStringToJuce ([urlToAdd scheme]);
  179. auto pathComponents = StringArray::fromTokens (nsStringToJuce ([urlToAdd path]), "/", {});
  180. for (auto& component : pathComponents)
  181. component = URL::addEscapeChars (component, false);
  182. chooserResults.add (URL (scheme + "://" + pathComponents.joinIntoString ("/")));
  183. };
  184. if (isSave)
  185. {
  186. addURLResult ([panel URL]);
  187. }
  188. else
  189. {
  190. auto* openPanel = static_cast<NSOpenPanel*> (panel);
  191. auto urls = [openPanel URLs];
  192. for (unsigned int i = 0; i < [urls count]; ++i)
  193. addURLResult ([urls objectAtIndex: i]);
  194. }
  195. }
  196. owner.finished (chooserResults);
  197. }
  198. bool shouldShowFilename (const String& filenameToTest)
  199. {
  200. const File f (filenameToTest);
  201. auto nsFilename = juceStringToNS (filenameToTest);
  202. for (int i = filters.size(); --i >= 0;)
  203. if (f.getFileName().matchesWildcard (filters[i], true))
  204. return true;
  205. return f.isDirectory()
  206. && ! [[NSWorkspace sharedWorkspace] isFilePackageAtPath: nsFilename];
  207. }
  208. void panelSelectionDidChange (id sender)
  209. {
  210. jassert (sender == panel);
  211. ignoreUnused (sender);
  212. // NB: would need to extend FilePreviewComponent to handle the full list rather than just the first one
  213. if (preview != nullptr)
  214. preview->selectedFileChanged (File (getSelectedPaths()[0]));
  215. }
  216. StringArray getSelectedPaths() const
  217. {
  218. if (panel == nullptr)
  219. return {};
  220. StringArray paths;
  221. if (isSave)
  222. {
  223. paths.add (nsStringToJuce ([[panel URL] path]));
  224. }
  225. else
  226. {
  227. auto* urls = [static_cast<NSOpenPanel*> (panel) URLs];
  228. for (NSUInteger i = 0; i < [urls count]; ++i)
  229. paths.add (nsStringToJuce ([[urls objectAtIndex: i] path]));
  230. }
  231. return paths;
  232. }
  233. //==============================================================================
  234. FileChooser& owner;
  235. FilePreviewComponent* preview;
  236. NSView* nsViewPreview = nullptr;
  237. bool selectsDirectories, selectsFiles, isSave, selectMultiple;
  238. NSSavePanel* panel;
  239. DelegateType* delegate;
  240. StringArray filters;
  241. String startingDirectory, filename;
  242. void ensurePanelSafe()
  243. {
  244. // If you hit this, something (probably the plugin host) has modified the panel,
  245. // allowing the application to terminate while the panel's modal loop is running.
  246. // This is a very bad idea! Quitting from within the panel's modal loop may cause
  247. // your plugin/app destructor to run directly from within `runModally`, which will
  248. // dispose all app resources while they're still in use.
  249. // A safer alternative is to invoke the FileChooser with `launchAsync`, rather than
  250. // using the modal launchers.
  251. jassert ([panel preventsApplicationTerminationWhenModal]);
  252. }
  253. static BOOL preventsApplicationTerminationWhenModal() { return YES; }
  254. template <typename Base>
  255. struct SafeModalPanel : public ObjCClass<Base>
  256. {
  257. explicit SafeModalPanel (const char* name) : ObjCClass<Base> (name)
  258. {
  259. this->addMethod (@selector (preventsApplicationTerminationWhenModal),
  260. preventsApplicationTerminationWhenModal,
  261. "c@:");
  262. this->registerClass();
  263. }
  264. };
  265. struct SafeSavePanel : SafeModalPanel<NSSavePanel>
  266. {
  267. SafeSavePanel() : SafeModalPanel ("SaveSavePanel_") {}
  268. };
  269. struct SafeOpenPanel : SafeModalPanel<NSOpenPanel>
  270. {
  271. SafeOpenPanel() : SafeModalPanel ("SaveOpenPanel_") {}
  272. };
  273. //==============================================================================
  274. struct DelegateClass : public ObjCClass<DelegateType>
  275. {
  276. DelegateClass() : ObjCClass<DelegateType> ("JUCEFileChooser_")
  277. {
  278. addIvar<Native*> ("cppObject");
  279. addMethod (@selector (panel:shouldShowFilename:), shouldShowFilename, "c@:@@");
  280. addMethod (@selector (panelSelectionDidChange:), panelSelectionDidChange, "c@");
  281. addProtocol (@protocol (NSOpenSavePanelDelegate));
  282. registerClass();
  283. }
  284. private:
  285. static BOOL shouldShowFilename (id self, SEL, id /*sender*/, NSString* filename)
  286. {
  287. auto* _this = getIvar<Native*> (self, "cppObject");
  288. return _this->shouldShowFilename (nsStringToJuce (filename)) ? YES : NO;
  289. }
  290. static void panelSelectionDidChange (id self, SEL, id sender)
  291. {
  292. auto* _this = getIvar<Native*> (self, "cppObject");
  293. _this->panelSelectionDidChange (sender);
  294. }
  295. };
  296. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
  297. };
  298. std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
  299. FilePreviewComponent* preview)
  300. {
  301. return std::make_shared<FileChooser::Native> (owner, flags, preview);
  302. }
  303. bool FileChooser::isPlatformDialogAvailable()
  304. {
  305. #if JUCE_DISABLE_NATIVE_FILECHOOSERS
  306. return false;
  307. #else
  308. return true;
  309. #endif
  310. }
  311. }