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.

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