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.

816 lines
29KB

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