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.

748 lines
28KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class JuceMainMenuHandler : private MenuBarModel::Listener,
  18. private DeletedAtShutdown
  19. {
  20. public:
  21. JuceMainMenuHandler()
  22. : currentModel (nullptr),
  23. lastUpdateTime (0),
  24. isOpen (false)
  25. {
  26. static JuceMenuCallbackClass cls;
  27. callback = [cls.createInstance() init];
  28. JuceMenuCallbackClass::setOwner (callback, this);
  29. }
  30. ~JuceMainMenuHandler()
  31. {
  32. setMenu (nullptr, nullptr, String::empty);
  33. jassert (instance == this);
  34. instance = nullptr;
  35. [callback release];
  36. }
  37. void setMenu (MenuBarModel* const newMenuBarModel,
  38. const PopupMenu* newExtraAppleMenuItems,
  39. const String& recentItemsName)
  40. {
  41. recentItemsMenuName = recentItemsName;
  42. if (currentModel != newMenuBarModel)
  43. {
  44. if (currentModel != nullptr)
  45. currentModel->removeListener (this);
  46. currentModel = newMenuBarModel;
  47. if (currentModel != nullptr)
  48. currentModel->addListener (this);
  49. menuBarItemsChanged (nullptr);
  50. }
  51. extraAppleMenuItems = createCopyIfNotNull (newExtraAppleMenuItems);
  52. }
  53. void addTopLevelMenu (NSMenu* parent, const PopupMenu& child,
  54. const String& name, const int menuId, const int tag)
  55. {
  56. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  57. action: nil
  58. keyEquivalent: nsEmptyString()];
  59. [item setTag: tag];
  60. NSMenu* sub = createMenu (child, name, menuId, tag, true);
  61. [parent setSubmenu: sub forItem: item];
  62. [sub setAutoenablesItems: false];
  63. [sub release];
  64. }
  65. void updateTopLevelMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  66. const String& name, const int menuId, const int tag)
  67. {
  68. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  69. static bool is10_4 = (SystemStats::getOperatingSystemType() == SystemStats::MacOSX_10_4);
  70. if (is10_4)
  71. {
  72. [parentItem setTag: tag];
  73. NSMenu* menu = [parentItem submenu];
  74. [menu setTitle: juceStringToNS (name)];
  75. while ([menu numberOfItems] > 0)
  76. [menu removeItemAtIndex: 0];
  77. for (PopupMenu::MenuItemIterator iter (menuToCopy); iter.next();)
  78. addMenuItem (iter, menu, menuId, tag);
  79. [menu setAutoenablesItems: false];
  80. [menu update];
  81. return;
  82. }
  83. #endif
  84. // Note: This method used to update the contents of the existing menu in-place, but that caused
  85. // weird side-effects which messed-up keyboard focus when switching between windows. By creating
  86. // a new menu and replacing the old one with it, that problem seems to be avoided..
  87. NSMenu* menu = [[NSMenu alloc] initWithTitle: juceStringToNS (name)];
  88. for (PopupMenu::MenuItemIterator iter (menuToCopy); iter.next();)
  89. addMenuItem (iter, menu, menuId, tag);
  90. [menu setAutoenablesItems: false];
  91. [menu update];
  92. [parentItem setTag: tag];
  93. [parentItem setSubmenu: menu];
  94. [menu release];
  95. }
  96. void menuBarItemsChanged (MenuBarModel*)
  97. {
  98. if (isOpen)
  99. return;
  100. lastUpdateTime = Time::getMillisecondCounter();
  101. StringArray menuNames;
  102. if (currentModel != nullptr)
  103. menuNames = currentModel->getMenuBarNames();
  104. NSMenu* menuBar = [[NSApp mainMenu] retain];
  105. while ([menuBar numberOfItems] > 1 + menuNames.size())
  106. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  107. int menuId = 1;
  108. for (int i = 0; i < menuNames.size(); ++i)
  109. {
  110. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  111. if (i >= [menuBar numberOfItems] - 1)
  112. addTopLevelMenu (menuBar, menu, menuNames[i], menuId, i);
  113. else
  114. updateTopLevelMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  115. }
  116. [menuBar release];
  117. }
  118. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  119. {
  120. if (NSMenuItem* item = findMenuItem ([NSApp mainMenu], info))
  121. flashMenuBar ([item menu]);
  122. }
  123. void updateMenus (NSMenu* menu)
  124. {
  125. if (PopupMenu::dismissAllActiveMenus())
  126. {
  127. // If we were running a juce menu, then we should let that modal loop finish before allowing
  128. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  129. if ([menu respondsToSelector: @selector (cancelTracking)])
  130. [menu performSelector: @selector (cancelTracking)];
  131. }
  132. if (Time::getMillisecondCounter() > lastUpdateTime + 100)
  133. (new AsyncMenuUpdater())->post();
  134. }
  135. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  136. {
  137. if (currentModel != nullptr)
  138. {
  139. if (commandManager != nullptr)
  140. {
  141. ApplicationCommandTarget::InvocationInfo info (commandId);
  142. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  143. commandManager->invoke (info, true);
  144. }
  145. (new AsyncCommandInvoker (commandId, topLevelIndex))->post();
  146. }
  147. }
  148. void invokeDirectly (const int commandId, const int topLevelIndex)
  149. {
  150. if (currentModel != nullptr)
  151. currentModel->menuItemSelected (commandId, topLevelIndex);
  152. }
  153. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  154. const int topLevelMenuId, const int topLevelIndex)
  155. {
  156. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  157. if (text == nil)
  158. text = nsEmptyString();
  159. if (iter.isSeparator)
  160. {
  161. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  162. }
  163. else if (iter.isSectionHeader)
  164. {
  165. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  166. action: nil
  167. keyEquivalent: nsEmptyString()];
  168. [item setEnabled: false];
  169. }
  170. else if (iter.subMenu != nullptr)
  171. {
  172. if (iter.itemName == recentItemsMenuName)
  173. {
  174. if (recent == nullptr)
  175. recent = new RecentFilesMenuItem();
  176. if (recent->recentItem != nil)
  177. {
  178. [menuToAddTo addItem: [recent->recentItem copyWithZone: nil]];
  179. return;
  180. }
  181. }
  182. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  183. action: nil
  184. keyEquivalent: nsEmptyString()];
  185. [item setTag: iter.itemId];
  186. [item setEnabled: iter.isEnabled];
  187. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex, false);
  188. [menuToAddTo setSubmenu: sub forItem: item];
  189. [sub release];
  190. }
  191. else
  192. {
  193. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  194. action: @selector (menuItemInvoked:)
  195. keyEquivalent: nsEmptyString()];
  196. [item setTag: iter.itemId];
  197. [item setEnabled: iter.isEnabled];
  198. [item setState: iter.isTicked ? NSOnState : NSOffState];
  199. [item setTarget: (id) callback];
  200. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_uint) (void*) iter.commandManager]];
  201. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  202. [item setRepresentedObject: info];
  203. if (iter.commandManager != nullptr)
  204. {
  205. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  206. ->getKeyPressesAssignedToCommand (iter.itemId));
  207. if (keyPresses.size() > 0)
  208. {
  209. const KeyPress& kp = keyPresses.getReference(0);
  210. if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  211. && kp != KeyPress::deleteKey) // every time you press the key while editing text)
  212. {
  213. juce_wchar key = kp.getTextCharacter();
  214. if (key == 0)
  215. key = (juce_wchar) kp.getKeyCode();
  216. [item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
  217. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  218. }
  219. }
  220. }
  221. }
  222. }
  223. static JuceMainMenuHandler* instance;
  224. MenuBarModel* currentModel;
  225. ScopedPointer<PopupMenu> extraAppleMenuItems;
  226. uint32 lastUpdateTime;
  227. NSObject* callback;
  228. String recentItemsMenuName;
  229. bool isOpen;
  230. private:
  231. struct RecentFilesMenuItem
  232. {
  233. RecentFilesMenuItem() : recentItem (nil)
  234. {
  235. if (NSNib* menuNib = [[[NSNib alloc] initWithNibNamed: @"RecentFilesMenuTemplate" bundle: nil] autorelease])
  236. {
  237. NSArray* array = nil;
  238. #if (! defined (MAC_OS_X_VERSION_10_8)) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8
  239. [menuNib instantiateNibWithOwner: NSApp topLevelObjects: &array];
  240. #else
  241. [menuNib instantiateWithOwner: NSApp topLevelObjects: &array];
  242. #endif
  243. for (id object in array)
  244. {
  245. if ([object isKindOfClass: [NSMenu class]])
  246. {
  247. if (NSArray* items = [object itemArray])
  248. {
  249. if (NSMenuItem* item = findRecentFilesItem (items))
  250. {
  251. recentItem = [item retain];
  252. break;
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. ~RecentFilesMenuItem()
  260. {
  261. [recentItem release];
  262. }
  263. static NSMenuItem* findRecentFilesItem (NSArray* const items)
  264. {
  265. for (id object in items)
  266. if (NSArray* subMenuItems = [[object submenu] itemArray])
  267. for (id subObject in subMenuItems)
  268. if ([subObject isKindOfClass: [NSMenuItem class]])
  269. return subObject;
  270. return nil;
  271. }
  272. NSMenuItem* recentItem;
  273. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecentFilesMenuItem)
  274. };
  275. ScopedPointer<RecentFilesMenuItem> recent;
  276. //==============================================================================
  277. NSMenu* createMenu (const PopupMenu menu,
  278. const String& menuName,
  279. const int topLevelMenuId,
  280. const int topLevelIndex,
  281. const bool addDelegate)
  282. {
  283. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  284. [m setAutoenablesItems: false];
  285. if (addDelegate)
  286. {
  287. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  288. [m setDelegate: (id<NSMenuDelegate>) callback];
  289. #else
  290. [m setDelegate: callback];
  291. #endif
  292. }
  293. for (PopupMenu::MenuItemIterator iter (menu); iter.next();)
  294. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  295. [m update];
  296. return m;
  297. }
  298. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  299. {
  300. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  301. {
  302. NSMenuItem* m = [menu itemAtIndex: i];
  303. if ([m tag] == info.commandID)
  304. return m;
  305. if (NSMenu* sub = [m submenu])
  306. if (NSMenuItem* found = findMenuItem (sub, info))
  307. return found;
  308. }
  309. return nil;
  310. }
  311. static void flashMenuBar (NSMenu* menu)
  312. {
  313. if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
  314. return;
  315. [menu retain];
  316. const unichar f35Key = NSF35FunctionKey;
  317. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  318. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
  319. action: nil
  320. keyEquivalent: f35String];
  321. [item setTarget: nil];
  322. [menu insertItem: item atIndex: [menu numberOfItems]];
  323. [item release];
  324. if ([menu indexOfItem: item] >= 0)
  325. {
  326. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  327. location: NSZeroPoint
  328. modifierFlags: NSCommandKeyMask
  329. timestamp: 0
  330. windowNumber: 0
  331. context: [NSGraphicsContext currentContext]
  332. characters: f35String
  333. charactersIgnoringModifiers: f35String
  334. isARepeat: NO
  335. keyCode: 0];
  336. [menu performKeyEquivalent: f35Event];
  337. if ([menu indexOfItem: item] >= 0)
  338. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  339. }
  340. [menu release];
  341. }
  342. static unsigned int juceModsToNSMods (const ModifierKeys mods)
  343. {
  344. unsigned int m = 0;
  345. if (mods.isShiftDown()) m |= NSShiftKeyMask;
  346. if (mods.isCtrlDown()) m |= NSControlKeyMask;
  347. if (mods.isAltDown()) m |= NSAlternateKeyMask;
  348. if (mods.isCommandDown()) m |= NSCommandKeyMask;
  349. return m;
  350. }
  351. class AsyncMenuUpdater : public CallbackMessage
  352. {
  353. public:
  354. AsyncMenuUpdater() {}
  355. void messageCallback() override
  356. {
  357. if (instance != nullptr)
  358. instance->menuBarItemsChanged (nullptr);
  359. }
  360. private:
  361. JUCE_DECLARE_NON_COPYABLE (AsyncMenuUpdater)
  362. };
  363. class AsyncCommandInvoker : public CallbackMessage
  364. {
  365. public:
  366. AsyncCommandInvoker (const int commandId_, const int topLevelIndex_)
  367. : commandId (commandId_), topLevelIndex (topLevelIndex_)
  368. {}
  369. void messageCallback() override
  370. {
  371. if (instance != nullptr)
  372. instance->invokeDirectly (commandId, topLevelIndex);
  373. }
  374. private:
  375. const int commandId, topLevelIndex;
  376. JUCE_DECLARE_NON_COPYABLE (AsyncCommandInvoker)
  377. };
  378. //==============================================================================
  379. struct JuceMenuCallbackClass : public ObjCClass <NSObject>
  380. {
  381. JuceMenuCallbackClass() : ObjCClass <NSObject> ("JUCEMainMenu_")
  382. {
  383. addIvar<JuceMainMenuHandler*> ("owner");
  384. addMethod (@selector (menuItemInvoked:), menuItemInvoked, "v@:@");
  385. addMethod (@selector (menuNeedsUpdate:), menuNeedsUpdate, "v@:@");
  386. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  387. addProtocol (@protocol (NSMenuDelegate));
  388. #endif
  389. registerClass();
  390. }
  391. static void setOwner (id self, JuceMainMenuHandler* owner)
  392. {
  393. object_setInstanceVariable (self, "owner", owner);
  394. }
  395. private:
  396. static void menuItemInvoked (id self, SEL, NSMenuItem* item)
  397. {
  398. JuceMainMenuHandler* const owner = getIvar<JuceMainMenuHandler*> (self, "owner");
  399. if ([[item representedObject] isKindOfClass: [NSArray class]])
  400. {
  401. // 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
  402. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  403. // into the focused component and let it trigger the menu item indirectly.
  404. NSEvent* e = [NSApp currentEvent];
  405. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  406. {
  407. if (juce::Component* focused = juce::Component::getCurrentlyFocusedComponent())
  408. {
  409. if (juce::NSViewComponentPeer* peer = dynamic_cast <juce::NSViewComponentPeer*> (focused->getPeer()))
  410. {
  411. if ([e type] == NSKeyDown)
  412. peer->redirectKeyDown (e);
  413. else
  414. peer->redirectKeyUp (e);
  415. return;
  416. }
  417. }
  418. }
  419. NSArray* info = (NSArray*) [item representedObject];
  420. owner->invoke ((int) [item tag],
  421. (ApplicationCommandManager*) (pointer_sized_int)
  422. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  423. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  424. }
  425. }
  426. static void menuNeedsUpdate (id, SEL, NSMenu* menu)
  427. {
  428. if (instance != nullptr)
  429. instance->updateMenus (menu);
  430. }
  431. };
  432. };
  433. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  434. //==============================================================================
  435. class TemporaryMainMenuWithStandardCommands
  436. {
  437. public:
  438. TemporaryMainMenuWithStandardCommands()
  439. : oldMenu (MenuBarModel::getMacMainMenu()), oldAppleMenu (nullptr)
  440. {
  441. if (const PopupMenu* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
  442. oldAppleMenu = new PopupMenu (*appleMenu);
  443. if (JuceMainMenuHandler::instance != nullptr)
  444. oldRecentItems = JuceMainMenuHandler::instance->recentItemsMenuName;
  445. MenuBarModel::setMacMainMenu (nullptr);
  446. NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
  447. NSMenuItem* item;
  448. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
  449. action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
  450. [menu addItem: item];
  451. [item release];
  452. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
  453. action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
  454. [menu addItem: item];
  455. [item release];
  456. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
  457. action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
  458. [menu addItem: item];
  459. [item release];
  460. item = [[NSApp mainMenu] addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
  461. action: nil keyEquivalent: nsEmptyString()];
  462. [[NSApp mainMenu] setSubmenu: menu forItem: item];
  463. [menu release];
  464. // use a dummy modal component so that apps can tell that something is currently modal.
  465. dummyModalComponent.enterModalState();
  466. }
  467. ~TemporaryMainMenuWithStandardCommands()
  468. {
  469. MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu, oldRecentItems);
  470. }
  471. private:
  472. MenuBarModel* oldMenu;
  473. ScopedPointer<PopupMenu> oldAppleMenu;
  474. String oldRecentItems;
  475. // The OS view already plays an alert when clicking outside
  476. // the modal comp, so this override avoids adding extra
  477. // inappropriate noises when the cancel button is pressed.
  478. // This override is also important because it stops the base class
  479. // calling ModalComponentManager::bringToFront, which can get
  480. // recursive when file dialogs are involved
  481. class SilentDummyModalComp : public Component
  482. {
  483. public:
  484. SilentDummyModalComp() {}
  485. void inputAttemptWhenModal() {}
  486. };
  487. SilentDummyModalComp dummyModalComponent;
  488. };
  489. //==============================================================================
  490. namespace MainMenuHelpers
  491. {
  492. static NSString* translateMenuName (const String& name)
  493. {
  494. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  495. }
  496. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  497. {
  498. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  499. action: sel
  500. keyEquivalent: key] autorelease];
  501. [item setTarget: NSApp];
  502. [menu addItem: item];
  503. return item;
  504. }
  505. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  506. {
  507. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  508. {
  509. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  510. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  511. [menu addItem: [NSMenuItem separatorItem]];
  512. }
  513. // Services...
  514. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  515. action: nil keyEquivalent: nsEmptyString()] autorelease];
  516. [menu addItem: services];
  517. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  518. [menu setSubmenu: servicesMenu forItem: services];
  519. [NSApp setServicesMenu: servicesMenu];
  520. [menu addItem: [NSMenuItem separatorItem]];
  521. createMenuItem (menu, "Hide " + appName, @selector (hide:), nsStringLiteral ("h"));
  522. [createMenuItem (menu, "Hide Others", @selector (hideOtherApplications:), nsStringLiteral ("h"))
  523. setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  524. createMenuItem (menu, "Show All", @selector (unhideAllApplications:), nsEmptyString());
  525. [menu addItem: [NSMenuItem separatorItem]];
  526. createMenuItem (menu, "Quit " + appName, @selector (terminate:), nsStringLiteral ("q"));
  527. }
  528. // Since our app has no NIB, this initialises a standard app menu...
  529. static void rebuildMainMenu (const PopupMenu* extraItems)
  530. {
  531. // this can't be used in a plugin!
  532. jassert (JUCEApplication::isStandaloneApp());
  533. if (JUCEApplication* app = JUCEApplication::getInstance())
  534. {
  535. JUCE_AUTORELEASEPOOL
  536. {
  537. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("MainMenu")];
  538. NSMenuItem* item = [mainMenu addItemWithTitle: nsStringLiteral ("Apple") action: nil keyEquivalent: nsEmptyString()];
  539. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Apple")];
  540. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  541. [mainMenu setSubmenu: appMenu forItem: item];
  542. [NSApp setMainMenu: mainMenu];
  543. MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
  544. [appMenu release];
  545. [mainMenu release];
  546. }
  547. }
  548. }
  549. }
  550. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  551. const PopupMenu* extraAppleMenuItems,
  552. const String& recentItemsMenuName)
  553. {
  554. if (getMacMainMenu() != newMenuBarModel)
  555. {
  556. JUCE_AUTORELEASEPOOL
  557. {
  558. if (newMenuBarModel == nullptr)
  559. {
  560. delete JuceMainMenuHandler::instance;
  561. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  562. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  563. extraAppleMenuItems = nullptr;
  564. }
  565. else
  566. {
  567. if (JuceMainMenuHandler::instance == nullptr)
  568. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  569. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  570. }
  571. }
  572. }
  573. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  574. if (newMenuBarModel != nullptr)
  575. newMenuBarModel->menuItemsChanged();
  576. }
  577. MenuBarModel* MenuBarModel::getMacMainMenu()
  578. {
  579. return JuceMainMenuHandler::instance != nullptr
  580. ? JuceMainMenuHandler::instance->currentModel : nullptr;
  581. }
  582. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  583. {
  584. return JuceMainMenuHandler::instance != nullptr
  585. ? JuceMainMenuHandler::instance->extraAppleMenuItems.get() : nullptr;
  586. }
  587. typedef void (*MenuTrackingChangedCallback) (bool);
  588. extern MenuTrackingChangedCallback menuTrackingChangedCallback;
  589. static void mainMenuTrackingChanged (bool isTracking)
  590. {
  591. PopupMenu::dismissAllActiveMenus();
  592. if (JuceMainMenuHandler::instance != nullptr)
  593. JuceMainMenuHandler::instance->isOpen = isTracking;
  594. }
  595. void juce_initialiseMacMainMenu()
  596. {
  597. menuTrackingChangedCallback = mainMenuTrackingChanged;
  598. if (JuceMainMenuHandler::instance == nullptr)
  599. MainMenuHelpers::rebuildMainMenu (nullptr);
  600. }