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.

804 lines
29KB

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