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.

850 lines
31KB

  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. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  21. const auto menuItemInvokedSelector = @selector (menuItemInvoked:);
  22. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  23. //==============================================================================
  24. struct JuceMainMenuBarHolder final : private DeletedAtShutdown
  25. {
  26. JuceMainMenuBarHolder()
  27. : mainMenuBar ([[NSMenu alloc] initWithTitle: nsStringLiteral ("MainMenu")])
  28. {
  29. auto item = [mainMenuBar addItemWithTitle: nsStringLiteral ("Apple")
  30. action: nil
  31. keyEquivalent: nsEmptyString()];
  32. auto appMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Apple")];
  33. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  34. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  35. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  36. [mainMenuBar setSubmenu: appMenu forItem: item];
  37. [appMenu release];
  38. [NSApp setMainMenu: mainMenuBar];
  39. }
  40. ~JuceMainMenuBarHolder()
  41. {
  42. clearSingletonInstance();
  43. [NSApp setMainMenu: nil];
  44. [mainMenuBar release];
  45. }
  46. NSMenu* mainMenuBar = nil;
  47. JUCE_DECLARE_SINGLETON_SINGLETHREADED (JuceMainMenuBarHolder, true)
  48. };
  49. JUCE_IMPLEMENT_SINGLETON (JuceMainMenuBarHolder)
  50. //==============================================================================
  51. class JuceMainMenuHandler final : private MenuBarModel::Listener,
  52. private DeletedAtShutdown
  53. {
  54. public:
  55. JuceMainMenuHandler()
  56. {
  57. static JuceMenuCallbackClass cls;
  58. callback = [cls.createInstance() init];
  59. JuceMenuCallbackClass::setOwner (callback, this);
  60. }
  61. ~JuceMainMenuHandler() override
  62. {
  63. setMenu (nullptr, nullptr, String());
  64. jassert (instance == this);
  65. instance = nullptr;
  66. [callback release];
  67. }
  68. void setMenu (MenuBarModel* const newMenuBarModel,
  69. const PopupMenu* newExtraAppleMenuItems,
  70. const String& recentItemsName)
  71. {
  72. recentItemsMenuName = recentItemsName;
  73. if (currentModel != newMenuBarModel)
  74. {
  75. if (currentModel != nullptr)
  76. currentModel->removeListener (this);
  77. currentModel = newMenuBarModel;
  78. if (currentModel != nullptr)
  79. currentModel->addListener (this);
  80. menuBarItemsChanged (nullptr);
  81. }
  82. extraAppleMenuItems.reset (createCopyIfNotNull (newExtraAppleMenuItems));
  83. }
  84. void addTopLevelMenu (NSMenu* parent, const PopupMenu& child, const String& name, int menuId, int topLevelIndex)
  85. {
  86. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  87. action: nil
  88. keyEquivalent: nsEmptyString()];
  89. NSMenu* sub = createMenu (child, name, menuId, topLevelIndex, true);
  90. [parent setSubmenu: sub forItem: item];
  91. [sub release];
  92. }
  93. void updateTopLevelMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy, const String& name, int menuId, int topLevelIndex)
  94. {
  95. // Note: This method used to update the contents of the existing menu in-place, but that caused
  96. // weird side-effects which messed-up keyboard focus when switching between windows. By creating
  97. // a new menu and replacing the old one with it, that problem seems to be avoided..
  98. NSMenu* menu = [[NSMenu alloc] initWithTitle: juceStringToNS (name)];
  99. for (PopupMenu::MenuItemIterator iter (menuToCopy); iter.next();)
  100. addMenuItem (iter, menu, menuId, topLevelIndex);
  101. [menu update];
  102. removeItemRecursive ([parentItem submenu]);
  103. [parentItem setSubmenu: menu];
  104. [menu release];
  105. }
  106. void updateTopLevelMenu (NSMenu* menu)
  107. {
  108. NSMenu* superMenu = [menu supermenu];
  109. auto menuNames = currentModel->getMenuBarNames();
  110. auto indexOfMenu = (int) [superMenu indexOfItemWithSubmenu: menu] - 1;
  111. if (indexOfMenu >= 0)
  112. {
  113. removeItemRecursive (menu);
  114. auto updatedPopup = currentModel->getMenuForIndex (indexOfMenu, menuNames[indexOfMenu]);
  115. for (PopupMenu::MenuItemIterator iter (updatedPopup); iter.next();)
  116. addMenuItem (iter, menu, 1, indexOfMenu);
  117. [menu update];
  118. }
  119. }
  120. void menuBarItemsChanged (MenuBarModel*) override
  121. {
  122. if (isOpen)
  123. {
  124. defferedUpdateRequested = true;
  125. return;
  126. }
  127. lastUpdateTime = Time::getMillisecondCounter();
  128. StringArray menuNames;
  129. if (currentModel != nullptr)
  130. menuNames = currentModel->getMenuBarNames();
  131. auto* menuBar = getMainMenuBar();
  132. while ([menuBar numberOfItems] > 1 + menuNames.size())
  133. removeItemRecursive (menuBar, static_cast<int> ([menuBar numberOfItems] - 1));
  134. int menuId = 1;
  135. for (int i = 0; i < menuNames.size(); ++i)
  136. {
  137. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames[i]));
  138. if (i >= [menuBar numberOfItems] - 1)
  139. addTopLevelMenu (menuBar, menu, menuNames[i], menuId, i);
  140. else
  141. updateTopLevelMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  142. }
  143. }
  144. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info) override
  145. {
  146. if ((info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0
  147. && info.invocationMethod != ApplicationCommandTarget::InvocationInfo::fromKeyPress)
  148. if (auto* item = findMenuItemWithCommandID (getMainMenuBar(), info.commandID))
  149. flashMenuBar ([item menu]);
  150. }
  151. void invoke (const PopupMenu::Item& item, int topLevelIndex) const
  152. {
  153. if (currentModel != nullptr)
  154. {
  155. if (item.action != nullptr)
  156. {
  157. MessageManager::callAsync (item.action);
  158. return;
  159. }
  160. if (item.customCallback != nullptr)
  161. if (! item.customCallback->menuItemTriggered())
  162. return;
  163. if (item.commandManager != nullptr)
  164. {
  165. ApplicationCommandTarget::InvocationInfo info (item.itemID);
  166. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  167. item.commandManager->invoke (info, true);
  168. }
  169. MessageManager::callAsync ([=]
  170. {
  171. if (instance != nullptr)
  172. instance->invokeDirectly (item.itemID, topLevelIndex);
  173. });
  174. }
  175. }
  176. void invokeDirectly (int commandId, int topLevelIndex)
  177. {
  178. if (currentModel != nullptr)
  179. currentModel->menuItemSelected (commandId, topLevelIndex);
  180. }
  181. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  182. const int topLevelMenuId, const int topLevelIndex)
  183. {
  184. const PopupMenu::Item& i = iter.getItem();
  185. NSString* text = juceStringToNS (i.text);
  186. if (text == nil)
  187. text = nsEmptyString();
  188. if (i.isSeparator)
  189. {
  190. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  191. }
  192. else if (i.isSectionHeader)
  193. {
  194. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  195. action: nil
  196. keyEquivalent: nsEmptyString()];
  197. [item setEnabled: false];
  198. }
  199. else if (i.subMenu != nullptr)
  200. {
  201. if (recentItemsMenuName.isNotEmpty() && i.text == recentItemsMenuName)
  202. {
  203. if (recent == nullptr)
  204. recent = std::make_unique<RecentFilesMenuItem>();
  205. if (recent->recentItem != nil)
  206. {
  207. if (NSMenu* parent = [recent->recentItem menu])
  208. [parent removeItem: recent->recentItem];
  209. [menuToAddTo addItem: recent->recentItem];
  210. return;
  211. }
  212. }
  213. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  214. action: nil
  215. keyEquivalent: nsEmptyString()];
  216. [item setTag: i.itemID];
  217. [item setEnabled: i.isEnabled];
  218. NSMenu* sub = createMenu (*i.subMenu, i.text, topLevelMenuId, topLevelIndex, false);
  219. [menuToAddTo setSubmenu: sub forItem: item];
  220. [sub release];
  221. }
  222. else
  223. {
  224. auto item = [[NSMenuItem alloc] initWithTitle: text
  225. action: menuItemInvokedSelector
  226. keyEquivalent: nsEmptyString()];
  227. [item setTag: topLevelIndex];
  228. [item setEnabled: i.isEnabled];
  229. [item setState: i.isTicked ? NSControlStateValueOn : NSControlStateValueOff];
  230. [item setTarget: (id) callback];
  231. auto* juceItem = new PopupMenu::Item (i);
  232. juceItem->customComponent = nullptr;
  233. [item setRepresentedObject: [createNSObjectFromJuceClass (juceItem) autorelease]];
  234. if (i.commandManager != nullptr)
  235. {
  236. for (auto& kp : i.commandManager->getKeyMappings()->getKeyPressesAssignedToCommand (i.itemID))
  237. {
  238. if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  239. && kp != KeyPress::deleteKey) // every time you press the key while editing text)
  240. {
  241. juce_wchar key = kp.getTextCharacter();
  242. if (key == 0)
  243. key = (juce_wchar) kp.getKeyCode();
  244. [item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
  245. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  246. }
  247. break;
  248. }
  249. }
  250. [menuToAddTo addItem: item];
  251. [item release];
  252. }
  253. }
  254. NSMenu* createMenu (const PopupMenu menu,
  255. const String& menuName,
  256. const int topLevelMenuId,
  257. const int topLevelIndex,
  258. const bool addDelegate)
  259. {
  260. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  261. if (addDelegate)
  262. [m setDelegate: (id<NSMenuDelegate>) callback];
  263. for (PopupMenu::MenuItemIterator iter (menu); iter.next();)
  264. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  265. [m update];
  266. return m;
  267. }
  268. static JuceMainMenuHandler* instance;
  269. MenuBarModel* currentModel = nullptr;
  270. std::unique_ptr<PopupMenu> extraAppleMenuItems;
  271. uint32 lastUpdateTime = 0;
  272. NSObject* callback = nil;
  273. String recentItemsMenuName;
  274. bool isOpen = false, defferedUpdateRequested = false;
  275. private:
  276. struct RecentFilesMenuItem
  277. {
  278. RecentFilesMenuItem() : recentItem (nil)
  279. {
  280. if (NSNib* menuNib = [[[NSNib alloc] initWithNibNamed: @"RecentFilesMenuTemplate" bundle: nil] autorelease])
  281. {
  282. NSArray* array = nil;
  283. if (@available (macOS 10.11, *))
  284. {
  285. [menuNib instantiateWithOwner: NSApp
  286. topLevelObjects: &array];
  287. }
  288. else
  289. {
  290. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  291. [menuNib instantiateNibWithOwner: NSApp
  292. topLevelObjects: &array];
  293. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  294. }
  295. for (id object in array)
  296. {
  297. if ([object isKindOfClass: [NSMenu class]])
  298. {
  299. if (NSArray* items = [object itemArray])
  300. {
  301. if (NSMenuItem* item = findRecentFilesItem (items))
  302. {
  303. recentItem = [item retain];
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. ~RecentFilesMenuItem()
  312. {
  313. [recentItem release];
  314. }
  315. static NSMenuItem* findRecentFilesItem (NSArray* const items)
  316. {
  317. for (id object in items)
  318. if (NSArray* subMenuItems = [[object submenu] itemArray])
  319. for (id subObject in subMenuItems)
  320. if ([subObject isKindOfClass: [NSMenuItem class]])
  321. return subObject;
  322. return nil;
  323. }
  324. NSMenuItem* recentItem;
  325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecentFilesMenuItem)
  326. };
  327. std::unique_ptr<RecentFilesMenuItem> recent;
  328. //==============================================================================
  329. static NSMenuItem* findMenuItemWithCommandID (NSMenu* const menu, int commandID)
  330. {
  331. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  332. {
  333. NSMenuItem* m = [menu itemAtIndex: i];
  334. if (auto* menuItem = getJuceClassFromNSObject<PopupMenu::Item> ([m representedObject]))
  335. if (menuItem->itemID == commandID)
  336. return m;
  337. if (NSMenu* sub = [m submenu])
  338. if (NSMenuItem* found = findMenuItemWithCommandID (sub, commandID))
  339. return found;
  340. }
  341. return nil;
  342. }
  343. static void flashMenuBar (NSMenu* menu)
  344. {
  345. if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
  346. return;
  347. [menu retain];
  348. const unichar f35Key = NSF35FunctionKey;
  349. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  350. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
  351. action: menuItemInvokedSelector
  352. keyEquivalent: f35String];
  353. // When the f35Event is invoked, the item's enablement is checked and a
  354. // NSBeep is triggered if the item appears to be disabled.
  355. // This ValidatorClass exists solely to return YES from validateMenuItem.
  356. struct ValidatorClass final : public ObjCClass<NSObject>
  357. {
  358. ValidatorClass() : ObjCClass ("JUCEMenuValidator_")
  359. {
  360. addMethod (menuItemInvokedSelector, [] (id, SEL, NSMenuItem*) {});
  361. addMethod (@selector (validateMenuItem:), [] (id, SEL, NSMenuItem*) { return YES; });
  362. addProtocol (@protocol (NSMenuItemValidation));
  363. registerClass();
  364. }
  365. };
  366. static ValidatorClass validatorClass;
  367. static auto* vcInstance = validatorClass.createInstance();
  368. [item setTarget: vcInstance];
  369. [menu insertItem: item atIndex: [menu numberOfItems]];
  370. [item release];
  371. if ([menu indexOfItem: item] >= 0)
  372. {
  373. NSEvent* f35Event = [NSEvent keyEventWithType: NSEventTypeKeyDown
  374. location: NSZeroPoint
  375. modifierFlags: NSEventModifierFlagCommand
  376. timestamp: 0
  377. windowNumber: 0
  378. context: [NSGraphicsContext currentContext]
  379. characters: f35String
  380. charactersIgnoringModifiers: f35String
  381. isARepeat: NO
  382. keyCode: 0];
  383. [menu performKeyEquivalent: f35Event];
  384. if ([menu indexOfItem: item] >= 0)
  385. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  386. }
  387. [menu release];
  388. }
  389. static unsigned int juceModsToNSMods (const ModifierKeys mods)
  390. {
  391. unsigned int m = 0;
  392. if (mods.isShiftDown()) m |= NSEventModifierFlagShift;
  393. if (mods.isCtrlDown()) m |= NSEventModifierFlagControl;
  394. if (mods.isAltDown()) m |= NSEventModifierFlagOption;
  395. if (mods.isCommandDown()) m |= NSEventModifierFlagCommand;
  396. return m;
  397. }
  398. // Apple Bug: For some reason [NSMenu removeAllItems] seems to leak its objects
  399. // on shutdown, so we need this method to release the items one-by-one manually
  400. static void removeItemRecursive (NSMenu* parentMenu, int menuItemIndex)
  401. {
  402. if (isPositiveAndBelow (menuItemIndex, (int) [parentMenu numberOfItems]))
  403. {
  404. if (auto menuItem = [parentMenu itemAtIndex:menuItemIndex])
  405. {
  406. if (auto submenu = [menuItem submenu])
  407. removeItemRecursive (submenu);
  408. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
  409. [parentMenu removeItem: menuItem];
  410. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  411. }
  412. }
  413. else
  414. jassertfalse;
  415. }
  416. static void removeItemRecursive (NSMenu* menu)
  417. {
  418. if (menu != nullptr)
  419. {
  420. auto n = static_cast<int> ([menu numberOfItems]);
  421. for (auto i = n; --i >= 0;)
  422. removeItemRecursive (menu, i);
  423. }
  424. }
  425. static NSMenu* getMainMenuBar()
  426. {
  427. return JuceMainMenuBarHolder::getInstance()->mainMenuBar;
  428. }
  429. //==============================================================================
  430. struct JuceMenuCallbackClass final : public ObjCClass<NSObject>
  431. {
  432. JuceMenuCallbackClass() : ObjCClass ("JUCEMainMenu_")
  433. {
  434. addIvar<JuceMainMenuHandler*> ("owner");
  435. addMethod (menuItemInvokedSelector, [] (id self, SEL, NSMenuItem* item)
  436. {
  437. if (auto* juceItem = getPopupMenuItem (item))
  438. getOwner (self)->invoke (*juceItem, static_cast<int> ([item tag]));
  439. });
  440. addMethod (@selector (menuNeedsUpdate:), [] (id self, SEL, NSMenu* menu)
  441. {
  442. getOwner (self)->updateTopLevelMenu (menu);
  443. });
  444. addMethod (@selector (validateMenuItem:), [] (id, SEL, NSMenuItem* item) -> BOOL
  445. {
  446. if (auto* juceItem = getPopupMenuItem (item))
  447. return juceItem->isEnabled;
  448. return YES;
  449. });
  450. addProtocol (@protocol (NSMenuDelegate));
  451. addProtocol (@protocol (NSMenuItemValidation));
  452. registerClass();
  453. }
  454. static void setOwner (id self, JuceMainMenuHandler* owner)
  455. {
  456. object_setInstanceVariable (self, "owner", owner);
  457. }
  458. private:
  459. static PopupMenu::Item* getPopupMenuItem (NSMenuItem* item)
  460. {
  461. return getJuceClassFromNSObject<PopupMenu::Item> ([item representedObject]);
  462. }
  463. static JuceMainMenuHandler* getOwner (id self)
  464. {
  465. return getIvar<JuceMainMenuHandler*> (self, "owner");
  466. }
  467. };
  468. };
  469. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  470. //==============================================================================
  471. class TemporaryMainMenuWithStandardCommands
  472. {
  473. public:
  474. explicit TemporaryMainMenuWithStandardCommands (FilePreviewComponent* filePreviewComponent)
  475. : oldMenu (MenuBarModel::getMacMainMenu()), dummyModalComponent (filePreviewComponent)
  476. {
  477. if (auto* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
  478. oldAppleMenu = std::make_unique<PopupMenu> (*appleMenu);
  479. if (auto* handler = JuceMainMenuHandler::instance)
  480. oldRecentItems = handler->recentItemsMenuName;
  481. MenuBarModel::setMacMainMenu (nullptr);
  482. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  483. {
  484. NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
  485. NSMenuItem* item;
  486. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
  487. action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
  488. [menu addItem: item];
  489. [item release];
  490. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
  491. action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
  492. [menu addItem: item];
  493. [item release];
  494. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
  495. action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
  496. [menu addItem: item];
  497. [item release];
  498. editMenuIndex = [mainMenu numberOfItems];
  499. item = [mainMenu addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
  500. action: nil keyEquivalent: nsEmptyString()];
  501. [mainMenu setSubmenu: menu forItem: item];
  502. [menu release];
  503. }
  504. // use a dummy modal component so that apps can tell that something is currently modal.
  505. dummyModalComponent.enterModalState (false);
  506. }
  507. ~TemporaryMainMenuWithStandardCommands()
  508. {
  509. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  510. [mainMenu removeItemAtIndex:editMenuIndex];
  511. MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu.get(), oldRecentItems);
  512. }
  513. static bool checkModalEvent (FilePreviewComponent* preview, const Component* targetComponent)
  514. {
  515. if (targetComponent == nullptr)
  516. return false;
  517. return (targetComponent == preview
  518. || targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr);
  519. }
  520. private:
  521. MenuBarModel* const oldMenu = nullptr;
  522. std::unique_ptr<PopupMenu> oldAppleMenu;
  523. String oldRecentItems;
  524. NSInteger editMenuIndex;
  525. // The OS view already plays an alert when clicking outside
  526. // the modal comp, so this override avoids adding extra
  527. // inappropriate noises when the cancel button is pressed.
  528. // This override is also important because it stops the base class
  529. // calling ModalComponentManager::bringToFront, which can get
  530. // recursive when file dialogs are involved
  531. struct SilentDummyModalComp final : public Component
  532. {
  533. explicit SilentDummyModalComp (FilePreviewComponent* p)
  534. : preview (p) {}
  535. void inputAttemptWhenModal() override {}
  536. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  537. {
  538. return checkModalEvent (preview, targetComponent);
  539. }
  540. FilePreviewComponent* preview = nullptr;
  541. };
  542. SilentDummyModalComp dummyModalComponent;
  543. };
  544. //==============================================================================
  545. namespace MainMenuHelpers
  546. {
  547. static NSString* translateMenuName (const String& name)
  548. {
  549. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  550. }
  551. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  552. {
  553. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  554. action: sel
  555. keyEquivalent: key] autorelease];
  556. [item setTarget: NSApp];
  557. [menu addItem: item];
  558. return item;
  559. }
  560. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  561. {
  562. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  563. {
  564. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  565. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  566. [menu addItem: [NSMenuItem separatorItem]];
  567. }
  568. // Services...
  569. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  570. action: nil keyEquivalent: nsEmptyString()] autorelease];
  571. [menu addItem: services];
  572. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  573. [menu setSubmenu: servicesMenu forItem: services];
  574. [NSApp setServicesMenu: servicesMenu];
  575. [menu addItem: [NSMenuItem separatorItem]];
  576. createMenuItem (menu, TRANS ("Hide") + String (" ") + appName, @selector (hide:), nsStringLiteral ("h"));
  577. [createMenuItem (menu, TRANS ("Hide Others"), @selector (hideOtherApplications:), nsStringLiteral ("h"))
  578. setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
  579. createMenuItem (menu, TRANS ("Show All"), @selector (unhideAllApplications:), nsEmptyString());
  580. [menu addItem: [NSMenuItem separatorItem]];
  581. createMenuItem (menu, TRANS ("Quit") + String (" ") + appName, @selector (terminate:), nsStringLiteral ("q"));
  582. }
  583. // Since our app has no NIB, this initialises a standard app menu...
  584. static void rebuildMainMenu (const PopupMenu* extraItems)
  585. {
  586. // this can't be used in a plugin!
  587. jassert (JUCEApplicationBase::isStandaloneApp());
  588. if (auto* app = JUCEApplicationBase::getInstance())
  589. {
  590. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  591. {
  592. if ([mainMenu numberOfItems] > 0)
  593. {
  594. if (auto appMenu = [[mainMenu itemAtIndex: 0] submenu])
  595. {
  596. [appMenu removeAllItems];
  597. MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
  598. }
  599. }
  600. }
  601. }
  602. }
  603. }
  604. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  605. const PopupMenu* extraAppleMenuItems,
  606. const String& recentItemsMenuName)
  607. {
  608. if (getMacMainMenu() != newMenuBarModel)
  609. {
  610. JUCE_AUTORELEASEPOOL
  611. {
  612. if (newMenuBarModel == nullptr)
  613. {
  614. delete JuceMainMenuHandler::instance;
  615. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  616. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  617. extraAppleMenuItems = nullptr;
  618. }
  619. else
  620. {
  621. if (JuceMainMenuHandler::instance == nullptr)
  622. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  623. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  624. }
  625. }
  626. }
  627. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  628. if (newMenuBarModel != nullptr)
  629. newMenuBarModel->menuItemsChanged();
  630. }
  631. MenuBarModel* MenuBarModel::getMacMainMenu()
  632. {
  633. if (auto* mm = JuceMainMenuHandler::instance)
  634. return mm->currentModel;
  635. return nullptr;
  636. }
  637. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  638. {
  639. if (auto* mm = JuceMainMenuHandler::instance)
  640. return mm->extraAppleMenuItems.get();
  641. return nullptr;
  642. }
  643. using MenuTrackingChangedCallback = void (*)(bool);
  644. extern MenuTrackingChangedCallback menuTrackingChangedCallback;
  645. static void mainMenuTrackingChanged (bool isTracking)
  646. {
  647. PopupMenu::dismissAllActiveMenus();
  648. if (auto* menuHandler = JuceMainMenuHandler::instance)
  649. {
  650. menuHandler->isOpen = isTracking;
  651. if (auto* model = menuHandler->currentModel)
  652. model->handleMenuBarActivate (isTracking);
  653. if (menuHandler->defferedUpdateRequested && ! isTracking)
  654. {
  655. menuHandler->defferedUpdateRequested = false;
  656. menuHandler->menuBarItemsChanged (menuHandler->currentModel);
  657. }
  658. }
  659. }
  660. static void initialiseMacMainMenu()
  661. {
  662. menuTrackingChangedCallback = mainMenuTrackingChanged;
  663. if (JuceMainMenuHandler::instance == nullptr)
  664. MainMenuHelpers::rebuildMainMenu (nullptr);
  665. }
  666. // (used from other modules that need to create an NSMenu)
  667. NSMenu* createNSMenu (const PopupMenu&, const String&, int, int, bool);
  668. NSMenu* createNSMenu (const PopupMenu& menu, const String& name, int topLevelMenuId, int topLevelIndex, bool addDelegate)
  669. {
  670. initialiseMacMainMenu();
  671. if (auto* mm = JuceMainMenuHandler::instance)
  672. return mm->createMenu (menu, name, topLevelMenuId, topLevelIndex, addDelegate);
  673. jassertfalse; // calling this before making sure the OSX main menu stuff was initialised?
  674. return nil;
  675. }
  676. } // namespace juce