juce_mac_MainMenu.mm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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.action != nullptr)
  154. {
  155. MessageManager::callAsync (item.action);
  156. return;
  157. }
  158. if (item.customCallback != nullptr)
  159. if (! item.customCallback->menuItemTriggered())
  160. return;
  161. if (item.commandManager != nullptr)
  162. {
  163. ApplicationCommandTarget::InvocationInfo info (item.itemID);
  164. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  165. item.commandManager->invoke (info, true);
  166. }
  167. MessageManager::callAsync ([=]
  168. {
  169. if (instance != nullptr)
  170. instance->invokeDirectly (item.itemID, topLevelIndex);
  171. });
  172. }
  173. }
  174. void invokeDirectly (int commandId, int topLevelIndex)
  175. {
  176. if (currentModel != nullptr)
  177. currentModel->menuItemSelected (commandId, topLevelIndex);
  178. }
  179. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  180. const int topLevelMenuId, const int topLevelIndex)
  181. {
  182. const PopupMenu::Item& i = iter.getItem();
  183. NSString* text = juceStringToNS (i.text);
  184. if (text == nil)
  185. text = nsEmptyString();
  186. if (i.isSeparator)
  187. {
  188. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  189. }
  190. else if (i.isSectionHeader)
  191. {
  192. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  193. action: nil
  194. keyEquivalent: nsEmptyString()];
  195. [item setEnabled: false];
  196. }
  197. else if (i.subMenu != nullptr)
  198. {
  199. if (recentItemsMenuName.isNotEmpty() && i.text == recentItemsMenuName)
  200. {
  201. if (recent == nullptr)
  202. recent = std::make_unique<RecentFilesMenuItem>();
  203. if (recent->recentItem != nil)
  204. {
  205. if (NSMenu* parent = [recent->recentItem menu])
  206. [parent removeItem: recent->recentItem];
  207. [menuToAddTo addItem: recent->recentItem];
  208. return;
  209. }
  210. }
  211. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  212. action: nil
  213. keyEquivalent: nsEmptyString()];
  214. [item setTag: i.itemID];
  215. [item setEnabled: i.isEnabled];
  216. NSMenu* sub = createMenu (*i.subMenu, i.text, topLevelMenuId, topLevelIndex, false);
  217. [menuToAddTo setSubmenu: sub forItem: item];
  218. [sub release];
  219. }
  220. else
  221. {
  222. auto item = [[NSMenuItem alloc] initWithTitle: text
  223. action: @selector (menuItemInvoked:)
  224. keyEquivalent: nsEmptyString()];
  225. [item setTag: topLevelIndex];
  226. [item setEnabled: i.isEnabled];
  227. #if defined (MAC_OS_X_VERSION_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13
  228. [item setState: i.isTicked ? NSControlStateValueOn : NSControlStateValueOff];
  229. #else
  230. [item setState: i.isTicked ? NSOnState : NSOffState];
  231. #endif
  232. [item setTarget: (id) callback];
  233. auto* juceItem = new PopupMenu::Item (i);
  234. juceItem->customComponent = nullptr;
  235. [item setRepresentedObject: [createNSObjectFromJuceClass (juceItem) autorelease]];
  236. if (i.commandManager != nullptr)
  237. {
  238. for (auto& kp : i.commandManager->getKeyMappings()->getKeyPressesAssignedToCommand (i.itemID))
  239. {
  240. if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  241. && kp != KeyPress::deleteKey) // every time you press the key while editing text)
  242. {
  243. juce_wchar key = kp.getTextCharacter();
  244. if (key == 0)
  245. key = (juce_wchar) kp.getKeyCode();
  246. [item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
  247. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  248. }
  249. break;
  250. }
  251. }
  252. [menuToAddTo addItem: item];
  253. [item release];
  254. }
  255. }
  256. NSMenu* createMenu (const PopupMenu menu,
  257. const String& menuName,
  258. const int topLevelMenuId,
  259. const int topLevelIndex,
  260. const bool addDelegate)
  261. {
  262. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  263. [m setAutoenablesItems: false];
  264. if (addDelegate)
  265. [m setDelegate: (id<NSMenuDelegate>) callback];
  266. for (PopupMenu::MenuItemIterator iter (menu); iter.next();)
  267. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  268. [m update];
  269. return m;
  270. }
  271. static JuceMainMenuHandler* instance;
  272. MenuBarModel* currentModel = nullptr;
  273. std::unique_ptr<PopupMenu> extraAppleMenuItems;
  274. uint32 lastUpdateTime = 0;
  275. NSObject* callback = nil;
  276. String recentItemsMenuName;
  277. bool isOpen = false, defferedUpdateRequested = false;
  278. private:
  279. struct RecentFilesMenuItem
  280. {
  281. RecentFilesMenuItem() : recentItem (nil)
  282. {
  283. if (NSNib* menuNib = [[[NSNib alloc] initWithNibNamed: @"RecentFilesMenuTemplate" bundle: nil] autorelease])
  284. {
  285. NSArray* array = nil;
  286. #if (! defined (MAC_OS_X_VERSION_10_8)) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8
  287. [menuNib instantiateNibWithOwner: NSApp topLevelObjects: &array];
  288. #else
  289. [menuNib instantiateWithOwner: NSApp topLevelObjects: &array];
  290. #endif
  291. for (id object in array)
  292. {
  293. if ([object isKindOfClass: [NSMenu class]])
  294. {
  295. if (NSArray* items = [object itemArray])
  296. {
  297. if (NSMenuItem* item = findRecentFilesItem (items))
  298. {
  299. recentItem = [item retain];
  300. break;
  301. }
  302. }
  303. }
  304. }
  305. }
  306. }
  307. ~RecentFilesMenuItem()
  308. {
  309. [recentItem release];
  310. }
  311. static NSMenuItem* findRecentFilesItem (NSArray* const items)
  312. {
  313. for (id object in items)
  314. if (NSArray* subMenuItems = [[object submenu] itemArray])
  315. for (id subObject in subMenuItems)
  316. if ([subObject isKindOfClass: [NSMenuItem class]])
  317. return subObject;
  318. return nil;
  319. }
  320. NSMenuItem* recentItem;
  321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecentFilesMenuItem)
  322. };
  323. std::unique_ptr<RecentFilesMenuItem> recent;
  324. //==============================================================================
  325. static NSMenuItem* findMenuItemWithCommandID (NSMenu* const menu, int commandID)
  326. {
  327. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  328. {
  329. NSMenuItem* m = [menu itemAtIndex: i];
  330. if (auto* menuItem = getJuceClassFromNSObject<PopupMenu::Item> ([m representedObject]))
  331. if (menuItem->itemID == commandID)
  332. return m;
  333. if (NSMenu* sub = [m submenu])
  334. if (NSMenuItem* found = findMenuItemWithCommandID (sub, commandID))
  335. return found;
  336. }
  337. return nil;
  338. }
  339. static void flashMenuBar (NSMenu* menu)
  340. {
  341. if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
  342. return;
  343. [menu retain];
  344. const unichar f35Key = NSF35FunctionKey;
  345. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  346. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
  347. action: nil
  348. keyEquivalent: f35String];
  349. [item setTarget: nil];
  350. [menu insertItem: item atIndex: [menu numberOfItems]];
  351. [item release];
  352. if ([menu indexOfItem: item] >= 0)
  353. {
  354. NSEvent* f35Event = [NSEvent keyEventWithType: NSEventTypeKeyDown
  355. location: NSZeroPoint
  356. modifierFlags: NSEventModifierFlagCommand
  357. timestamp: 0
  358. windowNumber: 0
  359. context: [NSGraphicsContext currentContext]
  360. characters: f35String
  361. charactersIgnoringModifiers: f35String
  362. isARepeat: NO
  363. keyCode: 0];
  364. [menu performKeyEquivalent: f35Event];
  365. if ([menu indexOfItem: item] >= 0)
  366. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  367. }
  368. [menu release];
  369. }
  370. static unsigned int juceModsToNSMods (const ModifierKeys mods)
  371. {
  372. unsigned int m = 0;
  373. if (mods.isShiftDown()) m |= NSEventModifierFlagShift;
  374. if (mods.isCtrlDown()) m |= NSEventModifierFlagControl;
  375. if (mods.isAltDown()) m |= NSEventModifierFlagOption;
  376. if (mods.isCommandDown()) m |= NSEventModifierFlagCommand;
  377. return m;
  378. }
  379. // Apple Bug: For some reason [NSMenu removeAllItems] seems to leak it's objects
  380. // on shutdown, so we need this method to release the items one-by-one manually
  381. static void removeItemRecursive (NSMenu* parentMenu, int menuItemIndex)
  382. {
  383. if (isPositiveAndBelow (menuItemIndex, (int) [parentMenu numberOfItems]))
  384. {
  385. auto menuItem = [parentMenu itemAtIndex:menuItemIndex];
  386. if (auto submenu = [menuItem submenu])
  387. removeItemRecursive (submenu);
  388. [parentMenu removeItem:menuItem];
  389. }
  390. else
  391. jassertfalse;
  392. }
  393. static void removeItemRecursive (NSMenu* menu)
  394. {
  395. if (menu != nullptr)
  396. {
  397. auto n = static_cast<int> ([menu numberOfItems]);
  398. for (auto i = n; --i >= 0;)
  399. removeItemRecursive (menu, i);
  400. }
  401. }
  402. static NSMenu* getMainMenuBar()
  403. {
  404. return JuceMainMenuBarHolder::getInstance()->mainMenuBar;
  405. }
  406. //==============================================================================
  407. struct JuceMenuCallbackClass : public ObjCClass<NSObject>
  408. {
  409. JuceMenuCallbackClass() : ObjCClass<NSObject> ("JUCEMainMenu_")
  410. {
  411. addIvar<JuceMainMenuHandler*> ("owner");
  412. addMethod (@selector (menuItemInvoked:), menuItemInvoked, "v@:@");
  413. addMethod (@selector (menuNeedsUpdate:), menuNeedsUpdate, "v@:@");
  414. addProtocol (@protocol (NSMenuDelegate));
  415. registerClass();
  416. }
  417. static void setOwner (id self, JuceMainMenuHandler* owner)
  418. {
  419. object_setInstanceVariable (self, "owner", owner);
  420. }
  421. private:
  422. static void menuItemInvoked (id self, SEL, NSMenuItem* item)
  423. {
  424. auto owner = getIvar<JuceMainMenuHandler*> (self, "owner");
  425. if (auto* juceItem = getJuceClassFromNSObject<PopupMenu::Item> ([item representedObject]))
  426. {
  427. // 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
  428. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  429. // into the focused component and let it trigger the menu item indirectly.
  430. NSEvent* e = [NSApp currentEvent];
  431. if ([e type] == NSEventTypeKeyDown || [e type] == NSEventTypeKeyUp)
  432. {
  433. if (auto* focused = juce::Component::getCurrentlyFocusedComponent())
  434. {
  435. if (auto peer = dynamic_cast<juce::NSViewComponentPeer*> (focused->getPeer()))
  436. {
  437. if ([e type] == NSEventTypeKeyDown)
  438. peer->redirectKeyDown (e);
  439. else
  440. peer->redirectKeyUp (e);
  441. return;
  442. }
  443. }
  444. }
  445. owner->invoke (*juceItem, static_cast<int> ([item tag]));
  446. }
  447. }
  448. static void menuNeedsUpdate (id self, SEL, NSMenu* menu)
  449. {
  450. getIvar<JuceMainMenuHandler*> (self, "owner")->updateTopLevelMenu (menu);
  451. }
  452. };
  453. };
  454. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  455. //==============================================================================
  456. class TemporaryMainMenuWithStandardCommands
  457. {
  458. public:
  459. TemporaryMainMenuWithStandardCommands()
  460. : oldMenu (MenuBarModel::getMacMainMenu())
  461. {
  462. if (auto* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
  463. oldAppleMenu = std::make_unique<PopupMenu> (*appleMenu);
  464. if (auto* handler = JuceMainMenuHandler::instance)
  465. oldRecentItems = handler->recentItemsMenuName;
  466. MenuBarModel::setMacMainMenu (nullptr);
  467. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  468. {
  469. NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
  470. NSMenuItem* item;
  471. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
  472. action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
  473. [menu addItem: item];
  474. [item release];
  475. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
  476. action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
  477. [menu addItem: item];
  478. [item release];
  479. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
  480. action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
  481. [menu addItem: item];
  482. [item release];
  483. editMenuIndex = [mainMenu numberOfItems];
  484. item = [mainMenu addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
  485. action: nil keyEquivalent: nsEmptyString()];
  486. [mainMenu setSubmenu: menu forItem: item];
  487. [menu release];
  488. }
  489. // use a dummy modal component so that apps can tell that something is currently modal.
  490. dummyModalComponent.enterModalState (false);
  491. }
  492. ~TemporaryMainMenuWithStandardCommands()
  493. {
  494. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  495. [mainMenu removeItemAtIndex:editMenuIndex];
  496. MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu.get(), oldRecentItems);
  497. }
  498. private:
  499. MenuBarModel* const oldMenu;
  500. std::unique_ptr<PopupMenu> oldAppleMenu;
  501. String oldRecentItems;
  502. NSInteger editMenuIndex;
  503. // The OS view already plays an alert when clicking outside
  504. // the modal comp, so this override avoids adding extra
  505. // inappropriate noises when the cancel button is pressed.
  506. // This override is also important because it stops the base class
  507. // calling ModalComponentManager::bringToFront, which can get
  508. // recursive when file dialogs are involved
  509. struct SilentDummyModalComp : public Component
  510. {
  511. SilentDummyModalComp() {}
  512. void inputAttemptWhenModal() override {}
  513. };
  514. SilentDummyModalComp dummyModalComponent;
  515. };
  516. //==============================================================================
  517. namespace MainMenuHelpers
  518. {
  519. static NSString* translateMenuName (const String& name)
  520. {
  521. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  522. }
  523. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  524. {
  525. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  526. action: sel
  527. keyEquivalent: key] autorelease];
  528. [item setTarget: NSApp];
  529. [menu addItem: item];
  530. return item;
  531. }
  532. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  533. {
  534. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  535. {
  536. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  537. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  538. [menu addItem: [NSMenuItem separatorItem]];
  539. }
  540. // Services...
  541. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  542. action: nil keyEquivalent: nsEmptyString()] autorelease];
  543. [menu addItem: services];
  544. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  545. [menu setSubmenu: servicesMenu forItem: services];
  546. [NSApp setServicesMenu: servicesMenu];
  547. [menu addItem: [NSMenuItem separatorItem]];
  548. createMenuItem (menu, TRANS("Hide") + String (" ") + appName, @selector (hide:), nsStringLiteral ("h"));
  549. [createMenuItem (menu, TRANS("Hide Others"), @selector (hideOtherApplications:), nsStringLiteral ("h"))
  550. setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
  551. createMenuItem (menu, TRANS("Show All"), @selector (unhideAllApplications:), nsEmptyString());
  552. [menu addItem: [NSMenuItem separatorItem]];
  553. createMenuItem (menu, TRANS("Quit") + String (" ") + appName, @selector (terminate:), nsStringLiteral ("q"));
  554. }
  555. // Since our app has no NIB, this initialises a standard app menu...
  556. static void rebuildMainMenu (const PopupMenu* extraItems)
  557. {
  558. // this can't be used in a plugin!
  559. jassert (JUCEApplicationBase::isStandaloneApp());
  560. if (auto* app = JUCEApplicationBase::getInstance())
  561. {
  562. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  563. {
  564. if ([mainMenu numberOfItems] > 0)
  565. {
  566. if (auto appMenu = [[mainMenu itemAtIndex: 0] submenu])
  567. {
  568. [appMenu removeAllItems];
  569. MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
  570. }
  571. }
  572. }
  573. }
  574. }
  575. }
  576. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  577. const PopupMenu* extraAppleMenuItems,
  578. const String& recentItemsMenuName)
  579. {
  580. if (getMacMainMenu() != newMenuBarModel)
  581. {
  582. JUCE_AUTORELEASEPOOL
  583. {
  584. if (newMenuBarModel == nullptr)
  585. {
  586. delete JuceMainMenuHandler::instance;
  587. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  588. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  589. extraAppleMenuItems = nullptr;
  590. }
  591. else
  592. {
  593. if (JuceMainMenuHandler::instance == nullptr)
  594. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  595. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  596. }
  597. }
  598. }
  599. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  600. if (newMenuBarModel != nullptr)
  601. newMenuBarModel->menuItemsChanged();
  602. }
  603. MenuBarModel* MenuBarModel::getMacMainMenu()
  604. {
  605. if (auto* mm = JuceMainMenuHandler::instance)
  606. return mm->currentModel;
  607. return nullptr;
  608. }
  609. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  610. {
  611. if (auto* mm = JuceMainMenuHandler::instance)
  612. return mm->extraAppleMenuItems.get();
  613. return nullptr;
  614. }
  615. using MenuTrackingChangedCallback = void (*)(bool);
  616. extern MenuTrackingChangedCallback menuTrackingChangedCallback;
  617. static void mainMenuTrackingChanged (bool isTracking)
  618. {
  619. PopupMenu::dismissAllActiveMenus();
  620. if (auto* menuHandler = JuceMainMenuHandler::instance)
  621. {
  622. menuHandler->isOpen = isTracking;
  623. if (auto* model = menuHandler->currentModel)
  624. model->handleMenuBarActivate (isTracking);
  625. if (menuHandler->defferedUpdateRequested && ! isTracking)
  626. {
  627. menuHandler->defferedUpdateRequested = false;
  628. menuHandler->menuBarItemsChanged (menuHandler->currentModel);
  629. }
  630. }
  631. }
  632. void juce_initialiseMacMainMenu()
  633. {
  634. menuTrackingChangedCallback = mainMenuTrackingChanged;
  635. if (JuceMainMenuHandler::instance == nullptr)
  636. MainMenuHelpers::rebuildMainMenu (nullptr);
  637. }
  638. // (used from other modules that need to create an NSMenu)
  639. NSMenu* createNSMenu (const PopupMenu&, const String&, int, int, bool);
  640. NSMenu* createNSMenu (const PopupMenu& menu, const String& name, int topLevelMenuId, int topLevelIndex, bool addDelegate)
  641. {
  642. juce_initialiseMacMainMenu();
  643. if (auto* mm = JuceMainMenuHandler::instance)
  644. return mm->createMenu (menu, name, topLevelMenuId, topLevelIndex, addDelegate);
  645. jassertfalse; // calling this before making sure the OSX main menu stuff was initialised?
  646. return nil;
  647. }
  648. } // namespace juce