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