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.

806 lines
29KB

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