Audio plugin host https://kx.studio/carla
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.

790 lines
28KB

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