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.

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