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.

660 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. class JuceMainMenuHandler : private MenuBarModel::Listener,
  19. private DeletedAtShutdown
  20. {
  21. public:
  22. JuceMainMenuHandler()
  23. : currentModel (nullptr),
  24. lastUpdateTime (0)
  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);
  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. lastUpdateTime = Time::getMillisecondCounter();
  99. StringArray menuNames;
  100. if (currentModel != nullptr)
  101. menuNames = currentModel->getMenuBarNames();
  102. NSMenu* menuBar = [NSApp mainMenu];
  103. while ([menuBar numberOfItems] > 1 + menuNames.size())
  104. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  105. int menuId = 1;
  106. for (int i = 0; i < menuNames.size(); ++i)
  107. {
  108. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  109. if (i >= [menuBar numberOfItems] - 1)
  110. addTopLevelMenu (menuBar, menu, menuNames[i], menuId, i);
  111. else
  112. updateTopLevelMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  113. }
  114. }
  115. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  116. {
  117. if (NSMenuItem* item = findMenuItem ([NSApp mainMenu], info))
  118. flashMenuBar ([item menu]);
  119. }
  120. void updateMenus (NSMenu* menu)
  121. {
  122. if (PopupMenu::dismissAllActiveMenus())
  123. {
  124. // If we were running a juce menu, then we should let that modal loop finish before allowing
  125. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  126. if ([menu respondsToSelector: @selector (cancelTracking)])
  127. [menu performSelector: @selector (cancelTracking)];
  128. }
  129. if (Time::getMillisecondCounter() > lastUpdateTime + 100)
  130. (new AsyncMenuUpdater())->post();
  131. }
  132. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  133. {
  134. if (currentModel != nullptr)
  135. {
  136. if (commandManager != nullptr)
  137. {
  138. ApplicationCommandTarget::InvocationInfo info (commandId);
  139. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  140. commandManager->invoke (info, true);
  141. }
  142. (new AsyncCommandInvoker (commandId, topLevelIndex))->post();
  143. }
  144. }
  145. void invokeDirectly (const int commandId, const int topLevelIndex)
  146. {
  147. if (currentModel != nullptr)
  148. currentModel->menuItemSelected (commandId, topLevelIndex);
  149. }
  150. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  151. const int topLevelMenuId, const int topLevelIndex)
  152. {
  153. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  154. if (text == nil)
  155. text = nsEmptyString();
  156. if (iter.isSeparator)
  157. {
  158. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  159. }
  160. else if (iter.isSectionHeader)
  161. {
  162. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  163. action: nil
  164. keyEquivalent: nsEmptyString()];
  165. [item setEnabled: false];
  166. }
  167. else if (iter.subMenu != nullptr)
  168. {
  169. if (iter.itemName == recentItemsMenuName)
  170. {
  171. if (recent == nullptr)
  172. recent = new RecentFilesMenuItem();
  173. if (recent->recentItem != nil)
  174. {
  175. [menuToAddTo addItem: [recent->recentItem copyWithZone: nil]];
  176. return;
  177. }
  178. }
  179. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  180. action: nil
  181. keyEquivalent: nsEmptyString()];
  182. [item setTag: iter.itemId];
  183. [item setEnabled: iter.isEnabled];
  184. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  185. [sub setDelegate: nil];
  186. [menuToAddTo setSubmenu: sub forItem: item];
  187. [sub release];
  188. }
  189. else
  190. {
  191. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  192. action: @selector (menuItemInvoked:)
  193. keyEquivalent: nsEmptyString()];
  194. [item setTag: iter.itemId];
  195. [item setEnabled: iter.isEnabled];
  196. [item setState: iter.isTicked ? NSOnState : NSOffState];
  197. [item setTarget: (id) callback];
  198. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_uint) (void*) iter.commandManager]];
  199. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  200. [item setRepresentedObject: info];
  201. if (iter.commandManager != nullptr)
  202. {
  203. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  204. ->getKeyPressesAssignedToCommand (iter.itemId));
  205. if (keyPresses.size() > 0)
  206. {
  207. const KeyPress& kp = keyPresses.getReference(0);
  208. if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  209. && kp != KeyPress::deleteKey) // every time you press the key while editing text)
  210. {
  211. juce_wchar key = kp.getTextCharacter();
  212. if (key == 0)
  213. key = (juce_wchar) kp.getKeyCode();
  214. [item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
  215. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  216. }
  217. }
  218. }
  219. }
  220. }
  221. static JuceMainMenuHandler* instance;
  222. MenuBarModel* currentModel;
  223. ScopedPointer<PopupMenu> extraAppleMenuItems;
  224. uint32 lastUpdateTime;
  225. NSObject* callback;
  226. String recentItemsMenuName;
  227. private:
  228. struct RecentFilesMenuItem
  229. {
  230. RecentFilesMenuItem() : recentItem (nil)
  231. {
  232. if (NSNib* menuNib = [[[NSNib alloc] initWithNibNamed: @"RecentFilesMenuTemplate" bundle: nil] autorelease])
  233. {
  234. NSArray* array = nil;
  235. [menuNib instantiateNibWithOwner: NSApp topLevelObjects: &array];
  236. for (id object in array)
  237. {
  238. if ([object isKindOfClass: [NSMenu class]])
  239. {
  240. if (NSArray* items = [object itemArray])
  241. {
  242. recentItem = [findRecentFilesItem (items) retain];
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. }
  249. ~RecentFilesMenuItem()
  250. {
  251. [recentItem release];
  252. }
  253. NSMenuItem* recentItem;
  254. private:
  255. static NSMenuItem* findRecentFilesItem (NSArray* const items)
  256. {
  257. for (id object in items)
  258. if (NSArray* subMenuItems = [[object submenu] itemArray])
  259. for (id subObject in subMenuItems)
  260. if ([subObject isKindOfClass: [NSMenuItem class]])
  261. return subObject;
  262. return nil;
  263. }
  264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecentFilesMenuItem);
  265. };
  266. ScopedPointer<RecentFilesMenuItem> recent;
  267. //==============================================================================
  268. NSMenu* createMenu (const PopupMenu menu,
  269. const String& menuName,
  270. const int topLevelMenuId,
  271. const int topLevelIndex)
  272. {
  273. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  274. [m setAutoenablesItems: false];
  275. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  276. [m setDelegate: (id<NSMenuDelegate>) callback];
  277. #else
  278. [m setDelegate: callback];
  279. #endif
  280. for (PopupMenu::MenuItemIterator iter (menu); iter.next();)
  281. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  282. [m update];
  283. return m;
  284. }
  285. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  286. {
  287. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  288. {
  289. NSMenuItem* m = [menu itemAtIndex: i];
  290. if ([m tag] == info.commandID)
  291. return m;
  292. if (NSMenu* sub = [m submenu])
  293. if (NSMenuItem* found = findMenuItem (sub, info))
  294. return found;
  295. }
  296. return nil;
  297. }
  298. static void flashMenuBar (NSMenu* menu)
  299. {
  300. if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
  301. return;
  302. [menu retain];
  303. const unichar f35Key = NSF35FunctionKey;
  304. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  305. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
  306. action: nil
  307. keyEquivalent: f35String];
  308. [item setTarget: nil];
  309. [menu insertItem: item atIndex: [menu numberOfItems]];
  310. [item release];
  311. if ([menu indexOfItem: item] >= 0)
  312. {
  313. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  314. location: NSZeroPoint
  315. modifierFlags: NSCommandKeyMask
  316. timestamp: 0
  317. windowNumber: 0
  318. context: [NSGraphicsContext currentContext]
  319. characters: f35String
  320. charactersIgnoringModifiers: f35String
  321. isARepeat: NO
  322. keyCode: 0];
  323. [menu performKeyEquivalent: f35Event];
  324. if ([menu indexOfItem: item] >= 0)
  325. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  326. }
  327. [menu release];
  328. }
  329. static unsigned int juceModsToNSMods (const ModifierKeys& mods)
  330. {
  331. unsigned int m = 0;
  332. if (mods.isShiftDown()) m |= NSShiftKeyMask;
  333. if (mods.isCtrlDown()) m |= NSControlKeyMask;
  334. if (mods.isAltDown()) m |= NSAlternateKeyMask;
  335. if (mods.isCommandDown()) m |= NSCommandKeyMask;
  336. return m;
  337. }
  338. class AsyncMenuUpdater : public CallbackMessage
  339. {
  340. public:
  341. AsyncMenuUpdater() {}
  342. void messageCallback()
  343. {
  344. if (instance != nullptr)
  345. instance->menuBarItemsChanged (nullptr);
  346. }
  347. private:
  348. JUCE_DECLARE_NON_COPYABLE (AsyncMenuUpdater);
  349. };
  350. class AsyncCommandInvoker : public CallbackMessage
  351. {
  352. public:
  353. AsyncCommandInvoker (const int commandId_, const int topLevelIndex_)
  354. : commandId (commandId_), topLevelIndex (topLevelIndex_)
  355. {}
  356. void messageCallback()
  357. {
  358. if (instance != nullptr)
  359. instance->invokeDirectly (commandId, topLevelIndex);
  360. }
  361. private:
  362. const int commandId, topLevelIndex;
  363. JUCE_DECLARE_NON_COPYABLE (AsyncCommandInvoker);
  364. };
  365. //==============================================================================
  366. struct JuceMenuCallbackClass : public ObjCClass <NSObject>
  367. {
  368. JuceMenuCallbackClass() : ObjCClass <NSObject> ("JUCEMainMenu_")
  369. {
  370. addIvar<JuceMainMenuHandler*> ("owner");
  371. addMethod (@selector (menuItemInvoked:), menuItemInvoked, "v@:@");
  372. addMethod (@selector (menuNeedsUpdate:), menuNeedsUpdate, "v@:@");
  373. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  374. addProtocol (@protocol (NSMenuDelegate));
  375. #endif
  376. registerClass();
  377. }
  378. static void setOwner (id self, JuceMainMenuHandler* owner)
  379. {
  380. object_setInstanceVariable (self, "owner", owner);
  381. }
  382. private:
  383. static void menuItemInvoked (id self, SEL, id menu)
  384. {
  385. JuceMainMenuHandler* const owner = getIvar<JuceMainMenuHandler*> (self, "owner");
  386. NSMenuItem* item = (NSMenuItem*) menu;
  387. if ([[item representedObject] isKindOfClass: [NSArray class]])
  388. {
  389. // 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
  390. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  391. // into the focused component and let it trigger the menu item indirectly.
  392. NSEvent* e = [NSApp currentEvent];
  393. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  394. {
  395. if (juce::Component* focused = juce::Component::getCurrentlyFocusedComponent())
  396. {
  397. if (juce::NSViewComponentPeer* peer = dynamic_cast <juce::NSViewComponentPeer*> (focused->getPeer()))
  398. {
  399. if ([e type] == NSKeyDown)
  400. peer->redirectKeyDown (e);
  401. else
  402. peer->redirectKeyUp (e);
  403. return;
  404. }
  405. }
  406. }
  407. NSArray* info = (NSArray*) [item representedObject];
  408. owner->invoke ((int) [item tag],
  409. (ApplicationCommandManager*) (pointer_sized_int)
  410. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  411. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  412. }
  413. }
  414. static void menuNeedsUpdate (id self, SEL, NSMenu* menu)
  415. {
  416. if (instance != nullptr)
  417. instance->updateMenus (menu);
  418. }
  419. };
  420. };
  421. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  422. //==============================================================================
  423. namespace MainMenuHelpers
  424. {
  425. static NSString* translateMenuName (const String& name)
  426. {
  427. return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
  428. }
  429. static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
  430. {
  431. NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
  432. action: sel
  433. keyEquivalent: key] autorelease];
  434. [item setTarget: NSApp];
  435. [menu addItem: item];
  436. return item;
  437. }
  438. static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  439. {
  440. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  441. {
  442. for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
  443. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  444. [menu addItem: [NSMenuItem separatorItem]];
  445. }
  446. // Services...
  447. NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
  448. action: nil keyEquivalent: nsEmptyString()] autorelease];
  449. [menu addItem: services];
  450. NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
  451. [menu setSubmenu: servicesMenu forItem: services];
  452. [NSApp setServicesMenu: servicesMenu];
  453. [menu addItem: [NSMenuItem separatorItem]];
  454. createMenuItem (menu, "Hide " + appName, @selector (hide:), nsStringLiteral ("h"));
  455. [createMenuItem (menu, "Hide Others", @selector (hideOtherApplications:), nsStringLiteral ("h"))
  456. setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  457. createMenuItem (menu, "Show All", @selector (unhideAllApplications:), nsEmptyString());
  458. [menu addItem: [NSMenuItem separatorItem]];
  459. createMenuItem (menu, "Quit " + appName, @selector (terminate:), nsStringLiteral ("q"));
  460. }
  461. // Since our app has no NIB, this initialises a standard app menu...
  462. static void rebuildMainMenu (const PopupMenu* extraItems)
  463. {
  464. // this can't be used in a plugin!
  465. jassert (JUCEApplication::isStandaloneApp());
  466. if (JUCEApplication::getInstance() != nullptr)
  467. {
  468. JUCE_AUTORELEASEPOOL
  469. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("MainMenu")];
  470. NSMenuItem* item = [mainMenu addItemWithTitle: nsStringLiteral ("Apple") action: nil keyEquivalent: nsEmptyString()];
  471. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Apple")];
  472. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  473. [mainMenu setSubmenu: appMenu forItem: item];
  474. [NSApp setMainMenu: mainMenu];
  475. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  476. [appMenu release];
  477. [mainMenu release];
  478. }
  479. }
  480. }
  481. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  482. const PopupMenu* extraAppleMenuItems,
  483. const String& recentItemsMenuName)
  484. {
  485. if (getMacMainMenu() != newMenuBarModel)
  486. {
  487. JUCE_AUTORELEASEPOOL
  488. if (newMenuBarModel == nullptr)
  489. {
  490. delete JuceMainMenuHandler::instance;
  491. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  492. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  493. extraAppleMenuItems = nullptr;
  494. }
  495. else
  496. {
  497. if (JuceMainMenuHandler::instance == nullptr)
  498. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  499. JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
  500. }
  501. }
  502. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  503. if (newMenuBarModel != nullptr)
  504. newMenuBarModel->menuItemsChanged();
  505. }
  506. MenuBarModel* MenuBarModel::getMacMainMenu()
  507. {
  508. return JuceMainMenuHandler::instance != nullptr
  509. ? JuceMainMenuHandler::instance->currentModel : nullptr;
  510. }
  511. const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
  512. {
  513. return JuceMainMenuHandler::instance != nullptr
  514. ? JuceMainMenuHandler::instance->extraAppleMenuItems.get() : nullptr;
  515. }
  516. typedef void (*MenuTrackingBeganCallback)();
  517. extern MenuTrackingBeganCallback menuTrackingBeganCallback;
  518. static void mainMenuTrackingBegan()
  519. {
  520. PopupMenu::dismissAllActiveMenus();
  521. }
  522. void juce_initialiseMacMainMenu()
  523. {
  524. menuTrackingBeganCallback = mainMenuTrackingBegan;
  525. if (JuceMainMenuHandler::instance == nullptr)
  526. MainMenuHelpers::rebuildMainMenu (nullptr);
  527. }