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.

juce_mac_MainMenu.mm 31KB

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