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.

589 lines
21KB

  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;
  19. END_JUCE_NAMESPACE
  20. using namespace juce;
  21. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  22. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  23. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  24. #else
  25. @interface JuceMenuCallback : NSObject
  26. #endif
  27. {
  28. JuceMainMenuHandler* owner;
  29. }
  30. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  31. - (void) dealloc;
  32. - (void) menuItemInvoked: (id) menu;
  33. - (void) menuNeedsUpdate: (NSMenu*) menu;
  34. @end
  35. BEGIN_JUCE_NAMESPACE
  36. //==============================================================================
  37. class JuceMainMenuHandler : private MenuBarModel::Listener,
  38. private DeletedAtShutdown
  39. {
  40. public:
  41. //==============================================================================
  42. JuceMainMenuHandler()
  43. : currentModel (nullptr),
  44. lastUpdateTime (0)
  45. {
  46. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  47. }
  48. ~JuceMainMenuHandler()
  49. {
  50. setMenu (nullptr);
  51. jassert (instance == this);
  52. instance = nullptr;
  53. [callback release];
  54. }
  55. void setMenu (MenuBarModel* const newMenuBarModel)
  56. {
  57. if (currentModel != newMenuBarModel)
  58. {
  59. if (currentModel != nullptr)
  60. currentModel->removeListener (this);
  61. currentModel = newMenuBarModel;
  62. if (currentModel != nullptr)
  63. currentModel->addListener (this);
  64. menuBarItemsChanged (nullptr);
  65. }
  66. }
  67. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  68. const String& name, const int menuId, const int tag)
  69. {
  70. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  71. action: nil
  72. keyEquivalent: nsEmptyString()];
  73. [item setTag: tag];
  74. NSMenu* sub = createMenu (child, name, menuId, tag);
  75. [parent setSubmenu: sub forItem: item];
  76. [sub setAutoenablesItems: false];
  77. [sub release];
  78. }
  79. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  80. const String& name, const int menuId, const int tag)
  81. {
  82. // Note: This method used to update the contents of the existing menu in-place, but that caused
  83. // weird side-effects which messed-up keyboard focus when switching between windows. By creating
  84. // a new menu and replacing the old one with it, that problem seems to be avoided..
  85. NSMenu* menu = [[NSMenu alloc] initWithTitle: juceStringToNS (name)];
  86. PopupMenu::MenuItemIterator iter (menuToCopy);
  87. while (iter.next())
  88. addMenuItem (iter, menu, menuId, tag);
  89. [menu setAutoenablesItems: false];
  90. [menu update];
  91. [parentItem setTag: tag];
  92. [parentItem setSubmenu: menu];
  93. [menu release];
  94. }
  95. void menuBarItemsChanged (MenuBarModel*)
  96. {
  97. lastUpdateTime = Time::getMillisecondCounter();
  98. StringArray menuNames;
  99. if (currentModel != nullptr)
  100. menuNames = currentModel->getMenuBarNames();
  101. NSMenu* menuBar = [NSApp mainMenu];
  102. while ([menuBar numberOfItems] > 1 + menuNames.size())
  103. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  104. int menuId = 1;
  105. for (int i = 0; i < menuNames.size(); ++i)
  106. {
  107. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  108. if (i >= [menuBar numberOfItems] - 1)
  109. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  110. else
  111. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  112. }
  113. }
  114. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  115. {
  116. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  117. if (item != nil)
  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. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  170. action: nil
  171. keyEquivalent: nsEmptyString()];
  172. [item setTag: iter.itemId];
  173. [item setEnabled: iter.isEnabled];
  174. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  175. [sub setDelegate: nil];
  176. [menuToAddTo setSubmenu: sub forItem: item];
  177. [sub release];
  178. }
  179. else
  180. {
  181. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  182. action: @selector (menuItemInvoked:)
  183. keyEquivalent: nsEmptyString()];
  184. [item setTag: iter.itemId];
  185. [item setEnabled: iter.isEnabled];
  186. [item setState: iter.isTicked ? NSOnState : NSOffState];
  187. [item setTarget: (id) callback];
  188. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  189. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  190. [item setRepresentedObject: info];
  191. if (iter.commandManager != nullptr)
  192. {
  193. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  194. ->getKeyPressesAssignedToCommand (iter.itemId));
  195. if (keyPresses.size() > 0)
  196. {
  197. const KeyPress& kp = keyPresses.getReference(0);
  198. if (kp.getKeyCode() != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
  199. && kp.getKeyCode() != KeyPress::deleteKey) // every time you press the key while editing text)
  200. {
  201. juce_wchar key = kp.getTextCharacter();
  202. if (key == 0)
  203. key = (juce_wchar) kp.getKeyCode();
  204. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  205. [item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
  206. }
  207. }
  208. }
  209. }
  210. }
  211. static JuceMainMenuHandler* instance;
  212. MenuBarModel* currentModel;
  213. uint32 lastUpdateTime;
  214. JuceMenuCallback* callback;
  215. private:
  216. //==============================================================================
  217. NSMenu* createMenu (const PopupMenu menu,
  218. const String& menuName,
  219. const int topLevelMenuId,
  220. const int topLevelIndex)
  221. {
  222. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  223. [m setAutoenablesItems: false];
  224. [m setDelegate: callback];
  225. PopupMenu::MenuItemIterator iter (menu);
  226. while (iter.next())
  227. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  228. [m update];
  229. return m;
  230. }
  231. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232. {
  233. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  234. {
  235. NSMenuItem* m = [menu itemAtIndex: i];
  236. if ([m tag] == info.commandID)
  237. return m;
  238. if ([m submenu] != nil)
  239. {
  240. NSMenuItem* found = findMenuItem ([m submenu], info);
  241. if (found != nil)
  242. return found;
  243. }
  244. }
  245. return nil;
  246. }
  247. static void flashMenuBar (NSMenu* menu)
  248. {
  249. if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
  250. return;
  251. [menu retain];
  252. const unichar f35Key = NSF35FunctionKey;
  253. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  254. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
  255. action: nil
  256. keyEquivalent: f35String];
  257. [item setTarget: nil];
  258. [menu insertItem: item atIndex: [menu numberOfItems]];
  259. [item release];
  260. if ([menu indexOfItem: item] >= 0)
  261. {
  262. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  263. location: NSZeroPoint
  264. modifierFlags: NSCommandKeyMask
  265. timestamp: 0
  266. windowNumber: 0
  267. context: [NSGraphicsContext currentContext]
  268. characters: f35String
  269. charactersIgnoringModifiers: f35String
  270. isARepeat: NO
  271. keyCode: 0];
  272. [menu performKeyEquivalent: f35Event];
  273. if ([menu indexOfItem: item] >= 0)
  274. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  275. }
  276. [menu release];
  277. }
  278. static unsigned int juceModsToNSMods (const ModifierKeys& mods)
  279. {
  280. unsigned int m = 0;
  281. if (mods.isShiftDown()) m |= NSShiftKeyMask;
  282. if (mods.isCtrlDown()) m |= NSControlKeyMask;
  283. if (mods.isAltDown()) m |= NSAlternateKeyMask;
  284. if (mods.isCommandDown()) m |= NSCommandKeyMask;
  285. return m;
  286. }
  287. class AsyncMenuUpdater : public CallbackMessage
  288. {
  289. public:
  290. AsyncMenuUpdater() {}
  291. void messageCallback()
  292. {
  293. if (JuceMainMenuHandler::instance != nullptr)
  294. JuceMainMenuHandler::instance->menuBarItemsChanged (nullptr);
  295. }
  296. private:
  297. JUCE_DECLARE_NON_COPYABLE (AsyncMenuUpdater);
  298. };
  299. class AsyncCommandInvoker : public CallbackMessage
  300. {
  301. public:
  302. AsyncCommandInvoker (const int commandId_, const int topLevelIndex_)
  303. : commandId (commandId_), topLevelIndex (topLevelIndex_)
  304. {}
  305. void messageCallback()
  306. {
  307. if (JuceMainMenuHandler::instance != nullptr)
  308. JuceMainMenuHandler::instance->invokeDirectly (commandId, topLevelIndex);
  309. }
  310. private:
  311. const int commandId, topLevelIndex;
  312. JUCE_DECLARE_NON_COPYABLE (AsyncCommandInvoker);
  313. };
  314. };
  315. JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
  316. END_JUCE_NAMESPACE
  317. //==============================================================================
  318. @implementation JuceMenuCallback
  319. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  320. {
  321. [super init];
  322. owner = owner_;
  323. return self;
  324. }
  325. - (void) dealloc
  326. {
  327. [super dealloc];
  328. }
  329. - (void) menuItemInvoked: (id) menu
  330. {
  331. NSMenuItem* item = (NSMenuItem*) menu;
  332. if ([[item representedObject] isKindOfClass: [NSArray class]])
  333. {
  334. // 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
  335. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  336. // into the focused component and let it trigger the menu item indirectly.
  337. NSEvent* e = [NSApp currentEvent];
  338. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  339. {
  340. if (juce::Component::getCurrentlyFocusedComponent() != nullptr)
  341. {
  342. juce::NSViewComponentPeer* peer = dynamic_cast <juce::NSViewComponentPeer*> (juce::Component::getCurrentlyFocusedComponent()->getPeer());
  343. if (peer != nullptr)
  344. {
  345. if ([e type] == NSKeyDown)
  346. peer->redirectKeyDown (e);
  347. else
  348. peer->redirectKeyUp (e);
  349. return;
  350. }
  351. }
  352. }
  353. NSArray* info = (NSArray*) [item representedObject];
  354. owner->invoke ((int) [item tag],
  355. (ApplicationCommandManager*) (pointer_sized_int)
  356. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  357. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  358. }
  359. }
  360. - (void) menuNeedsUpdate: (NSMenu*) menu;
  361. {
  362. if (JuceMainMenuHandler::instance != nullptr)
  363. JuceMainMenuHandler::instance->updateMenus (menu);
  364. }
  365. @end
  366. BEGIN_JUCE_NAMESPACE
  367. //==============================================================================
  368. namespace MainMenuHelpers
  369. {
  370. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  371. {
  372. if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
  373. {
  374. PopupMenu::MenuItemIterator iter (*extraItems);
  375. while (iter.next())
  376. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  377. [menu addItem: [NSMenuItem separatorItem]];
  378. }
  379. NSMenuItem* item;
  380. // Services...
  381. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Services"), nil)
  382. action: nil keyEquivalent: nsEmptyString()];
  383. [menu addItem: item];
  384. [item release];
  385. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Services")];
  386. [menu setSubmenu: servicesMenu forItem: item];
  387. [NSApp setServicesMenu: servicesMenu];
  388. [servicesMenu release];
  389. [menu addItem: [NSMenuItem separatorItem]];
  390. // Hide + Show stuff...
  391. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  392. action: @selector (hide:) keyEquivalent: nsStringLiteral ("h")];
  393. [item setTarget: NSApp];
  394. [menu addItem: item];
  395. [item release];
  396. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Hide Others"), nil)
  397. action: @selector (hideOtherApplications:) keyEquivalent: nsStringLiteral ("h")];
  398. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  399. [item setTarget: NSApp];
  400. [menu addItem: item];
  401. [item release];
  402. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Show All"), nil)
  403. action: @selector (unhideAllApplications:) keyEquivalent: nsEmptyString()];
  404. [item setTarget: NSApp];
  405. [menu addItem: item];
  406. [item release];
  407. [menu addItem: [NSMenuItem separatorItem]];
  408. // Quit item....
  409. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  410. action: @selector (terminate:) keyEquivalent: nsStringLiteral ("q")];
  411. [item setTarget: NSApp];
  412. [menu addItem: item];
  413. [item release];
  414. return menu;
  415. }
  416. // Since our app has no NIB, this initialises a standard app menu...
  417. void rebuildMainMenu (const PopupMenu* extraItems)
  418. {
  419. // this can't be used in a plugin!
  420. jassert (JUCEApplication::isStandaloneApp());
  421. if (JUCEApplication::getInstance() != nullptr)
  422. {
  423. JUCE_AUTORELEASEPOOL
  424. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("MainMenu")];
  425. NSMenuItem* item = [mainMenu addItemWithTitle: nsStringLiteral ("Apple") action: nil keyEquivalent: nsEmptyString()];
  426. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Apple")];
  427. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  428. [mainMenu setSubmenu: appMenu forItem: item];
  429. [NSApp setMainMenu: mainMenu];
  430. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  431. [appMenu release];
  432. [mainMenu release];
  433. }
  434. }
  435. }
  436. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  437. const PopupMenu* extraAppleMenuItems)
  438. {
  439. if (getMacMainMenu() != newMenuBarModel)
  440. {
  441. JUCE_AUTORELEASEPOOL
  442. if (newMenuBarModel == nullptr)
  443. {
  444. delete JuceMainMenuHandler::instance;
  445. jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
  446. jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
  447. extraAppleMenuItems = nullptr;
  448. }
  449. else
  450. {
  451. if (JuceMainMenuHandler::instance == nullptr)
  452. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  453. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  454. }
  455. }
  456. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  457. if (newMenuBarModel != nullptr)
  458. newMenuBarModel->menuItemsChanged();
  459. }
  460. MenuBarModel* MenuBarModel::getMacMainMenu()
  461. {
  462. return JuceMainMenuHandler::instance != nullptr
  463. ? JuceMainMenuHandler::instance->currentModel : nullptr;
  464. }
  465. void juce_initialiseMacMainMenu()
  466. {
  467. if (JuceMainMenuHandler::instance == nullptr)
  468. MainMenuHelpers::rebuildMainMenu (nullptr);
  469. }