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.

847 lines
31KB

  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. /* Returns true if and only if the peer handles the event. */
  428. static bool tryPassingKeyEventToPeer (NSMenuItem* item)
  429. {
  430. auto* e = [NSApp currentEvent];
  431. if ([e type] != NSEventTypeKeyDown && [e type] != NSEventTypeKeyUp)
  432. return false;
  433. const auto triggeredByShortcut = [[e charactersIgnoringModifiers] isEqualToString: [item keyEquivalent]]
  434. && ([e modifierFlags] & ~(NSUInteger) 0xFFFF) == [item keyEquivalentModifierMask];
  435. if (! triggeredByShortcut)
  436. return false;
  437. if (auto* focused = juce::Component::getCurrentlyFocusedComponent())
  438. {
  439. if (auto* peer = dynamic_cast<juce::NSViewComponentPeer*> (focused->getPeer()))
  440. {
  441. if ([e type] == NSEventTypeKeyDown)
  442. peer->redirectKeyDown (e);
  443. else
  444. peer->redirectKeyUp (e);
  445. return true;
  446. }
  447. }
  448. return false;
  449. }
  450. static void menuItemInvoked (id self, SEL, NSMenuItem* item)
  451. {
  452. if (tryPassingKeyEventToPeer (item))
  453. return;
  454. if (auto* juceItem = getJuceClassFromNSObject<PopupMenu::Item> ([item representedObject]))
  455. getIvar<JuceMainMenuHandler*> (self, "owner")->invoke (*juceItem, static_cast<int> ([item tag]));
  456. }
  457. static void menuNeedsUpdate (id self, SEL, NSMenu* menu)
  458. {
  459. getIvar<JuceMainMenuHandler*> (self, "owner")->updateTopLevelMenu (menu);
  460. }
  461. };
  462. };
  463. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  464. //==============================================================================
  465. class TemporaryMainMenuWithStandardCommands
  466. {
  467. public:
  468. explicit TemporaryMainMenuWithStandardCommands (FilePreviewComponent* filePreviewComponent)
  469. : oldMenu (MenuBarModel::getMacMainMenu()), dummyModalComponent (filePreviewComponent)
  470. {
  471. if (auto* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
  472. oldAppleMenu = std::make_unique<PopupMenu> (*appleMenu);
  473. if (auto* handler = JuceMainMenuHandler::instance)
  474. oldRecentItems = handler->recentItemsMenuName;
  475. MenuBarModel::setMacMainMenu (nullptr);
  476. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  477. {
  478. NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
  479. NSMenuItem* item;
  480. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
  481. action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
  482. [menu addItem: item];
  483. [item release];
  484. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
  485. action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
  486. [menu addItem: item];
  487. [item release];
  488. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
  489. action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
  490. [menu addItem: item];
  491. [item release];
  492. editMenuIndex = [mainMenu numberOfItems];
  493. item = [mainMenu addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
  494. action: nil keyEquivalent: nsEmptyString()];
  495. [mainMenu setSubmenu: menu forItem: item];
  496. [menu release];
  497. }
  498. // use a dummy modal component so that apps can tell that something is currently modal.
  499. dummyModalComponent.enterModalState (false);
  500. }
  501. ~TemporaryMainMenuWithStandardCommands()
  502. {
  503. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  504. [mainMenu removeItemAtIndex:editMenuIndex];
  505. MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu.get(), oldRecentItems);
  506. }
  507. static bool checkModalEvent (FilePreviewComponent* preview, const Component* targetComponent)
  508. {
  509. if (targetComponent == nullptr)
  510. return false;
  511. return (targetComponent == preview
  512. || targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr);
  513. }
  514. private:
  515. MenuBarModel* const oldMenu = nullptr;
  516. std::unique_ptr<PopupMenu> oldAppleMenu;
  517. String oldRecentItems;
  518. NSInteger editMenuIndex;
  519. // The OS view already plays an alert when clicking outside
  520. // the modal comp, so this override avoids adding extra
  521. // inappropriate noises when the cancel button is pressed.
  522. // This override is also important because it stops the base class
  523. // calling ModalComponentManager::bringToFront, which can get
  524. // recursive when file dialogs are involved
  525. struct SilentDummyModalComp : public Component
  526. {
  527. explicit SilentDummyModalComp (FilePreviewComponent* p)
  528. : preview (p) {}
  529. void inputAttemptWhenModal() override {}
  530. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  531. {
  532. return checkModalEvent (preview, targetComponent);
  533. }
  534. FilePreviewComponent* preview = nullptr;
  535. };
  536. SilentDummyModalComp dummyModalComponent;
  537. };
  538. //==============================================================================
  539. namespace MainMenuHelpers
  540. {
  541. static NSString* translateMenuName (const String& name)
  542. {
  543. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  544. }
  545. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  546. {
  547. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  548. action: sel
  549. keyEquivalent: key] autorelease];
  550. [item setTarget: NSApp];
  551. [menu addItem: item];
  552. return item;
  553. }
  554. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  555. {
  556. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  557. {
  558. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  559. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  560. [menu addItem: [NSMenuItem separatorItem]];
  561. }
  562. // Services...
  563. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  564. action: nil keyEquivalent: nsEmptyString()] autorelease];
  565. [menu addItem: services];
  566. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  567. [menu setSubmenu: servicesMenu forItem: services];
  568. [NSApp setServicesMenu: servicesMenu];
  569. [menu addItem: [NSMenuItem separatorItem]];
  570. createMenuItem (menu, TRANS("Hide") + String (" ") + appName, @selector (hide:), nsStringLiteral ("h"));
  571. [createMenuItem (menu, TRANS("Hide Others"), @selector (hideOtherApplications:), nsStringLiteral ("h"))
  572. setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
  573. createMenuItem (menu, TRANS("Show All"), @selector (unhideAllApplications:), nsEmptyString());
  574. [menu addItem: [NSMenuItem separatorItem]];
  575. createMenuItem (menu, TRANS("Quit") + String (" ") + appName, @selector (terminate:), nsStringLiteral ("q"));
  576. }
  577. // Since our app has no NIB, this initialises a standard app menu...
  578. static void rebuildMainMenu (const PopupMenu* extraItems)
  579. {
  580. // this can't be used in a plugin!
  581. jassert (JUCEApplicationBase::isStandaloneApp());
  582. if (auto* app = JUCEApplicationBase::getInstance())
  583. {
  584. if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
  585. {
  586. if ([mainMenu numberOfItems] > 0)
  587. {
  588. if (auto appMenu = [[mainMenu itemAtIndex: 0] submenu])
  589. {
  590. [appMenu removeAllItems];
  591. MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
  592. }
  593. }
  594. }
  595. }
  596. }
  597. }
  598. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  599. const PopupMenu* extraAppleMenuItems,
  600. const String& recentItemsMenuName)
  601. {
  602. if (getMacMainMenu() != newMenuBarModel)
  603. {
  604. JUCE_AUTORELEASEPOOL
  605. {
  606. if (newMenuBarModel == nullptr)
  607. {
  608. delete JuceMainMenuHandler::instance;
  609. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  610. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  611. extraAppleMenuItems = nullptr;
  612. }
  613. else
  614. {
  615. if (JuceMainMenuHandler::instance == nullptr)
  616. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  617. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  618. }
  619. }
  620. }
  621. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  622. if (newMenuBarModel != nullptr)
  623. newMenuBarModel->menuItemsChanged();
  624. }
  625. MenuBarModel* MenuBarModel::getMacMainMenu()
  626. {
  627. if (auto* mm = JuceMainMenuHandler::instance)
  628. return mm->currentModel;
  629. return nullptr;
  630. }
  631. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  632. {
  633. if (auto* mm = JuceMainMenuHandler::instance)
  634. return mm->extraAppleMenuItems.get();
  635. return nullptr;
  636. }
  637. using MenuTrackingChangedCallback = void (*)(bool);
  638. extern MenuTrackingChangedCallback menuTrackingChangedCallback;
  639. static void mainMenuTrackingChanged (bool isTracking)
  640. {
  641. PopupMenu::dismissAllActiveMenus();
  642. if (auto* menuHandler = JuceMainMenuHandler::instance)
  643. {
  644. menuHandler->isOpen = isTracking;
  645. if (auto* model = menuHandler->currentModel)
  646. model->handleMenuBarActivate (isTracking);
  647. if (menuHandler->defferedUpdateRequested && ! isTracking)
  648. {
  649. menuHandler->defferedUpdateRequested = false;
  650. menuHandler->menuBarItemsChanged (menuHandler->currentModel);
  651. }
  652. }
  653. }
  654. void juce_initialiseMacMainMenu()
  655. {
  656. menuTrackingChangedCallback = mainMenuTrackingChanged;
  657. if (JuceMainMenuHandler::instance == nullptr)
  658. MainMenuHelpers::rebuildMainMenu (nullptr);
  659. }
  660. // (used from other modules that need to create an NSMenu)
  661. NSMenu* createNSMenu (const PopupMenu&, const String&, int, int, bool);
  662. NSMenu* createNSMenu (const PopupMenu& menu, const String& name, int topLevelMenuId, int topLevelIndex, bool addDelegate)
  663. {
  664. juce_initialiseMacMainMenu();
  665. if (auto* mm = JuceMainMenuHandler::instance)
  666. return mm->createMenu (menu, name, topLevelMenuId, topLevelIndex, addDelegate);
  667. jassertfalse; // calling this before making sure the OSX main menu stuff was initialised?
  668. return nil;
  669. }
  670. } // namespace juce