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.

803 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_DeclareSingleton_SingleThreaded (JuceMainMenuBarHolder, true)
  44. };
  45. juce_ImplementSingleton_SingleThreaded (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 = 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. removeItemRecursive (menu);
  110. auto updatedPopup = currentModel->getMenuForIndex (indexOfMenu, menuNames[indexOfMenu]);
  111. for (PopupMenu::MenuItemIterator iter (updatedPopup); iter.next();)
  112. addMenuItem (iter, menu, 1, indexOfMenu);
  113. [menu update];
  114. }
  115. void menuBarItemsChanged (MenuBarModel*) override
  116. {
  117. if (isOpen)
  118. {
  119. defferedUpdateRequested = true;
  120. return;
  121. }
  122. lastUpdateTime = Time::getMillisecondCounter();
  123. StringArray menuNames;
  124. if (currentModel != nullptr)
  125. menuNames = currentModel->getMenuBarNames();
  126. auto* menuBar = getMainMenuBar();
  127. while ([menuBar numberOfItems] > 1 + menuNames.size())
  128. removeItemRecursive (menuBar, static_cast<int> ([menuBar numberOfItems] - 1));
  129. int menuId = 1;
  130. for (int i = 0; i < menuNames.size(); ++i)
  131. {
  132. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames[i]));
  133. if (i >= [menuBar numberOfItems] - 1)
  134. addTopLevelMenu (menuBar, menu, menuNames[i], menuId, i);
  135. else
  136. updateTopLevelMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  137. }
  138. }
  139. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info) override
  140. {
  141. if ((info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0
  142. && info.invocationMethod != ApplicationCommandTarget::InvocationInfo::fromKeyPress)
  143. if (auto* item = findMenuItemWithCommandID (getMainMenuBar(), info.commandID))
  144. flashMenuBar ([item menu]);
  145. }
  146. void invoke (const PopupMenu::Item& item, int topLevelIndex) const
  147. {
  148. if (currentModel != nullptr)
  149. {
  150. if (item.customCallback != nullptr)
  151. if (! item.customCallback->menuItemTriggered())
  152. return;
  153. if (item.commandManager != nullptr)
  154. {
  155. ApplicationCommandTarget::InvocationInfo info (item.itemID);
  156. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  157. item.commandManager->invoke (info, true);
  158. }
  159. MessageManager::callAsync ([=]()
  160. {
  161. if (instance != nullptr)
  162. instance->invokeDirectly (item.itemID, topLevelIndex);
  163. });
  164. }
  165. }
  166. void invokeDirectly (int commandId, int topLevelIndex)
  167. {
  168. if (currentModel != nullptr)
  169. currentModel->menuItemSelected (commandId, topLevelIndex);
  170. }
  171. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  172. const int topLevelMenuId, const int topLevelIndex)
  173. {
  174. const PopupMenu::Item& i = iter.getItem();
  175. NSString* text = juceStringToNS (i.text);
  176. if (text == nil)
  177. text = nsEmptyString();
  178. if (i.isSeparator)
  179. {
  180. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  181. }
  182. else if (i.isSectionHeader)
  183. {
  184. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  185. action: nil
  186. keyEquivalent: nsEmptyString()];
  187. [item setEnabled: false];
  188. }
  189. else if (i.subMenu != nullptr)
  190. {
  191. if (i.text == recentItemsMenuName)
  192. {
  193. if (recent == nullptr)
  194. recent = new RecentFilesMenuItem();
  195. if (recent->recentItem != nil)
  196. {
  197. if (NSMenu* parent = [recent->recentItem menu])
  198. [parent removeItem: recent->recentItem];
  199. [menuToAddTo addItem: recent->recentItem];
  200. return;
  201. }
  202. }
  203. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  204. action: nil
  205. keyEquivalent: nsEmptyString()];
  206. [item setTag: i.itemID];
  207. [item setEnabled: i.isEnabled];
  208. NSMenu* sub = createMenu (*i.subMenu, i.text, topLevelMenuId, topLevelIndex, false);
  209. [menuToAddTo setSubmenu: sub forItem: item];
  210. [sub release];
  211. }
  212. else
  213. {
  214. auto* item = [[NSMenuItem alloc] initWithTitle: text
  215. action: @selector (menuItemInvoked:)
  216. keyEquivalent: nsEmptyString()];
  217. [item setTag: topLevelIndex];
  218. [item setEnabled: i.isEnabled];
  219. [item setState: i.isTicked ? NSOnState : NSOffState];
  220. [item setTarget: (id) callback];
  221. auto* juceItem = new PopupMenu::Item (i);
  222. juceItem->customComponent = nullptr;
  223. [item setRepresentedObject: [createNSObjectFromJuceClass (juceItem) autorelease]];
  224. if (i.commandManager != nullptr)
  225. {
  226. for (auto& kp : i.commandManager->getKeyMappings()->getKeyPressesAssignedToCommand (i.itemID))
  227. {
  228. if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  229. && kp != KeyPress::deleteKey) // every time you press the key while editing text)
  230. {
  231. juce_wchar key = kp.getTextCharacter();
  232. if (key == 0)
  233. key = (juce_wchar) kp.getKeyCode();
  234. [item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
  235. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  236. }
  237. break;
  238. }
  239. }
  240. [menuToAddTo addItem: item];
  241. [item release];
  242. }
  243. }
  244. NSMenu* createMenu (const PopupMenu menu,
  245. const String& menuName,
  246. const int topLevelMenuId,
  247. const int topLevelIndex,
  248. const bool addDelegate)
  249. {
  250. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  251. [m setAutoenablesItems: false];
  252. if (addDelegate)
  253. {
  254. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  255. [m setDelegate: (id<NSMenuDelegate>) callback];
  256. #else
  257. [m setDelegate: callback];
  258. #endif
  259. }
  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. ScopedPointer<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. ScopedPointer<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. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  409. addProtocol (@protocol (NSMenuDelegate));
  410. #endif
  411. registerClass();
  412. }
  413. static void setOwner (id self, JuceMainMenuHandler* owner)
  414. {
  415. object_setInstanceVariable (self, "owner", owner);
  416. }
  417. private:
  418. static void menuItemInvoked (id self, SEL, NSMenuItem* item)
  419. {
  420. auto owner = getIvar<JuceMainMenuHandler*> (self, "owner");
  421. if (auto* juceItem = getJuceClassFromNSObject<PopupMenu::Item> ([item representedObject]))
  422. {
  423. // 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
  424. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  425. // into the focused component and let it trigger the menu item indirectly.
  426. NSEvent* e = [NSApp currentEvent];
  427. if ([e type] == NSEventTypeKeyDown || [e type] == NSEventTypeKeyUp)
  428. {
  429. if (auto* focused = juce::Component::getCurrentlyFocusedComponent())
  430. {
  431. if (auto peer = dynamic_cast<juce::NSViewComponentPeer*> (focused->getPeer()))
  432. {
  433. if ([e type] == NSEventTypeKeyDown)
  434. peer->redirectKeyDown (e);
  435. else
  436. peer->redirectKeyUp (e);
  437. return;
  438. }
  439. }
  440. }
  441. owner->invoke (*juceItem, static_cast<int> ([item tag]));
  442. }
  443. }
  444. static void menuNeedsUpdate (id self, SEL, NSMenu* menu)
  445. {
  446. getIvar<JuceMainMenuHandler*> (self, "owner")->updateTopLevelMenu (menu);
  447. }
  448. };
  449. };
  450. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  451. //==============================================================================
  452. class TemporaryMainMenuWithStandardCommands
  453. {
  454. public:
  455. TemporaryMainMenuWithStandardCommands()
  456. : oldMenu (MenuBarModel::getMacMainMenu())
  457. {
  458. if (auto* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
  459. oldAppleMenu = new PopupMenu (*appleMenu);
  460. if (auto* handler = JuceMainMenuHandler::instance)
  461. oldRecentItems = handler->recentItemsMenuName;
  462. MenuBarModel::setMacMainMenu (nullptr);
  463. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  464. {
  465. NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
  466. NSMenuItem* item;
  467. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
  468. action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
  469. [menu addItem: item];
  470. [item release];
  471. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
  472. action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
  473. [menu addItem: item];
  474. [item release];
  475. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
  476. action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
  477. [menu addItem: item];
  478. [item release];
  479. item = [mainMenu addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
  480. action: nil keyEquivalent: nsEmptyString()];
  481. [mainMenu setSubmenu: menu forItem: item];
  482. [menu release];
  483. }
  484. // use a dummy modal component so that apps can tell that something is currently modal.
  485. dummyModalComponent.enterModalState (false);
  486. }
  487. ~TemporaryMainMenuWithStandardCommands()
  488. {
  489. MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu, oldRecentItems);
  490. }
  491. private:
  492. MenuBarModel* const oldMenu;
  493. ScopedPointer<PopupMenu> oldAppleMenu;
  494. String oldRecentItems;
  495. // The OS view already plays an alert when clicking outside
  496. // the modal comp, so this override avoids adding extra
  497. // inappropriate noises when the cancel button is pressed.
  498. // This override is also important because it stops the base class
  499. // calling ModalComponentManager::bringToFront, which can get
  500. // recursive when file dialogs are involved
  501. struct SilentDummyModalComp : public Component
  502. {
  503. SilentDummyModalComp() {}
  504. void inputAttemptWhenModal() override {}
  505. };
  506. SilentDummyModalComp dummyModalComponent;
  507. };
  508. //==============================================================================
  509. namespace MainMenuHelpers
  510. {
  511. static NSString* translateMenuName (const String& name)
  512. {
  513. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  514. }
  515. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  516. {
  517. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  518. action: sel
  519. keyEquivalent: key] autorelease];
  520. [item setTarget: NSApp];
  521. [menu addItem: item];
  522. return item;
  523. }
  524. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  525. {
  526. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  527. {
  528. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  529. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  530. [menu addItem: [NSMenuItem separatorItem]];
  531. }
  532. // Services...
  533. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  534. action: nil keyEquivalent: nsEmptyString()] autorelease];
  535. [menu addItem: services];
  536. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  537. [menu setSubmenu: servicesMenu forItem: services];
  538. [NSApp setServicesMenu: servicesMenu];
  539. [menu addItem: [NSMenuItem separatorItem]];
  540. createMenuItem (menu, TRANS("Hide") + String (" ") + appName, @selector (hide:), nsStringLiteral ("h"));
  541. [createMenuItem (menu, TRANS("Hide Others"), @selector (hideOtherApplications:), nsStringLiteral ("h"))
  542. setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
  543. createMenuItem (menu, TRANS("Show All"), @selector (unhideAllApplications:), nsEmptyString());
  544. [menu addItem: [NSMenuItem separatorItem]];
  545. createMenuItem (menu, TRANS("Quit") + String (" ") + appName, @selector (terminate:), nsStringLiteral ("q"));
  546. }
  547. // Since our app has no NIB, this initialises a standard app menu...
  548. static void rebuildMainMenu (const PopupMenu* extraItems)
  549. {
  550. // this can't be used in a plugin!
  551. jassert (JUCEApplicationBase::isStandaloneApp());
  552. if (auto* app = JUCEApplicationBase::getInstance())
  553. {
  554. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  555. {
  556. if ([mainMenu numberOfItems] > 0)
  557. {
  558. if (auto* appMenu = [[mainMenu itemAtIndex:0] submenu])
  559. {
  560. [appMenu removeAllItems];
  561. MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
  562. }
  563. }
  564. }
  565. }
  566. }
  567. }
  568. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  569. const PopupMenu* extraAppleMenuItems,
  570. const String& recentItemsMenuName)
  571. {
  572. if (getMacMainMenu() != newMenuBarModel)
  573. {
  574. JUCE_AUTORELEASEPOOL
  575. {
  576. if (newMenuBarModel == nullptr)
  577. {
  578. delete JuceMainMenuHandler::instance;
  579. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  580. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  581. extraAppleMenuItems = nullptr;
  582. }
  583. else
  584. {
  585. if (JuceMainMenuHandler::instance == nullptr)
  586. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  587. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  588. }
  589. }
  590. }
  591. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  592. if (newMenuBarModel != nullptr)
  593. newMenuBarModel->menuItemsChanged();
  594. }
  595. MenuBarModel* MenuBarModel::getMacMainMenu()
  596. {
  597. if (auto* mm = JuceMainMenuHandler::instance)
  598. return mm->currentModel;
  599. return nullptr;
  600. }
  601. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  602. {
  603. if (auto* mm = JuceMainMenuHandler::instance)
  604. return mm->extraAppleMenuItems.get();
  605. return nullptr;
  606. }
  607. typedef void (*MenuTrackingChangedCallback) (bool);
  608. extern MenuTrackingChangedCallback menuTrackingChangedCallback;
  609. static void mainMenuTrackingChanged (bool isTracking)
  610. {
  611. PopupMenu::dismissAllActiveMenus();
  612. if (auto* menuHandler = JuceMainMenuHandler::instance)
  613. {
  614. menuHandler->isOpen = isTracking;
  615. if (auto* model = menuHandler->currentModel)
  616. model->handleMenuBarActivate (isTracking);
  617. if (menuHandler->defferedUpdateRequested && ! isTracking)
  618. {
  619. menuHandler->defferedUpdateRequested = false;
  620. menuHandler->menuBarItemsChanged (menuHandler->currentModel);
  621. }
  622. }
  623. }
  624. void juce_initialiseMacMainMenu()
  625. {
  626. menuTrackingChangedCallback = mainMenuTrackingChanged;
  627. if (JuceMainMenuHandler::instance == nullptr)
  628. MainMenuHelpers::rebuildMainMenu (nullptr);
  629. }
  630. // (used from other modules that need to create an NSMenu)
  631. NSMenu* createNSMenu (const PopupMenu& menu, const String& name,
  632. int topLevelMenuId, int topLevelIndex, bool addDelegate)
  633. {
  634. juce_initialiseMacMainMenu();
  635. if (auto* mm = JuceMainMenuHandler::instance)
  636. return mm->createMenu (menu, name, topLevelMenuId, topLevelIndex, addDelegate);
  637. jassertfalse; // calling this before making sure the OSX main menu stuff was initialised?
  638. return nil;
  639. }
  640. } // namespace juce