/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "nsMenuBarX.h" #include "nsMenuX.h" #include "nsMenuItemX.h" #include "nsMenuUtilsX.h" #include "nsCocoaFeatures.h" #include "nsCocoaUtils.h" #include "nsCocoaWindow.h" #include "nsChildView.h" #include "nsCOMPtr.h" #include "nsString.h" #include "nsGkAtoms.h" #include "nsObjCExceptions.h" #include "nsThreadUtils.h" #include "nsIContent.h" #include "nsIWidget.h" #include "nsIDocument.h" #include "nsIDOMDocument.h" #include "nsIDOMElement.h" #include "nsIAppStartup.h" #include "nsIStringBundle.h" #include "nsToolkitCompsCID.h" NativeMenuItemTarget* nsMenuBarX::sNativeEventTarget = nil; nsMenuBarX* nsMenuBarX::sLastGeckoMenuBarPainted = nullptr; // Weak nsMenuBarX* nsMenuBarX::sCurrentPaintDelayedMenuBar = nullptr; // Weak NSMenu* sApplicationMenu = nil; BOOL sApplicationMenuIsFallback = NO; BOOL gSomeMenuBarPainted = NO; // We keep references to the first quit and pref item content nodes we find, which // will be from the hidden window. We use these when the document for the current // window does not have a quit or pref item. We don't need strong refs here because // these items are always strong ref'd by their owning menu bar (instance variable). static nsIContent* sAboutItemContent = nullptr; static nsIContent* sPrefItemContent = nullptr; static nsIContent* sQuitItemContent = nullptr; NS_IMPL_ISUPPORTS(nsNativeMenuServiceX, nsINativeMenuService) NS_IMETHODIMP nsNativeMenuServiceX::CreateNativeMenuBar(nsIWidget* aParent, nsIContent* aMenuBarNode) { NS_ASSERTION(NS_IsMainThread(), "Attempting to create native menu bar on wrong thread!"); RefPtr mb = new nsMenuBarX(); if (!mb) return NS_ERROR_OUT_OF_MEMORY; return mb->Create(aParent, aMenuBarNode); } nsMenuBarX::nsMenuBarX() : nsMenuGroupOwnerX(), mParentWindow(nullptr), mAwaitingDelayedPaint(false) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; mNativeMenu = [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar" andMenuBarOwner:this]; NS_OBJC_END_TRY_ABORT_BLOCK; } nsMenuBarX::~nsMenuBarX() { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; if (nsMenuBarX::sLastGeckoMenuBarPainted == this) nsMenuBarX::sLastGeckoMenuBarPainted = nullptr; // the quit/pref items of a random window might have been used if there was no // hidden window, thus we need to invalidate the weak references. if (sAboutItemContent == mAboutItemContent) sAboutItemContent = nullptr; if (sQuitItemContent == mQuitItemContent) sQuitItemContent = nullptr; if (sPrefItemContent == mPrefItemContent) sPrefItemContent = nullptr; // make sure we unregister ourselves as a content observer if (mContent) { UnregisterForContentChanges(mContent); } // We have to manually clear the array here because clearing causes menu items // to call back into the menu bar to unregister themselves. We don't want to // depend on member variable ordering to ensure that the array gets cleared // before the registration hash table is destroyed. mMenuArray.Clear(); [mNativeMenu resetMenuBarOwner]; [mNativeMenu release]; NS_OBJC_END_TRY_ABORT_BLOCK; } nsresult nsMenuBarX::Create(nsIWidget* aParent, nsIContent* aContent) { if (!aParent) return NS_ERROR_INVALID_ARG; mParentWindow = aParent; mContent = aContent; if (mContent) { AquifyMenuBar(); nsresult rv = nsMenuGroupOwnerX::Create(mContent); if (NS_FAILED(rv)) return rv; RegisterForContentChanges(mContent, this); ConstructNativeMenus(); } else { ConstructFallbackNativeMenus(); } // Give this to the parent window. The parent takes ownership. static_cast(mParentWindow)->SetMenuBar(this); return NS_OK; } void nsMenuBarX::ConstructNativeMenus() { uint32_t count = mContent->GetChildCount(); for (uint32_t i = 0; i < count; i++) { nsIContent *menuContent = mContent->GetChildAt(i); if (menuContent && menuContent->IsXULElement(nsGkAtoms::menu)) { nsMenuX* newMenu = new nsMenuX(); if (newMenu) { nsresult rv = newMenu->Create(this, this, menuContent); if (NS_SUCCEEDED(rv)) InsertMenuAtIndex(newMenu, GetMenuCount()); else delete newMenu; } } } } void nsMenuBarX::ConstructFallbackNativeMenus() { if (sApplicationMenu) { // Menu has already been built. return; } nsCOMPtr stringBundle; nsCOMPtr bundleSvc = do_GetService(NS_STRINGBUNDLE_CONTRACTID); bundleSvc->CreateBundle("chrome://global/locale/fallbackMenubar.properties", getter_AddRefs(stringBundle)); if (!stringBundle) { return; } nsXPIDLString labelUTF16; nsXPIDLString keyUTF16; const char16_t* labelProp = MOZ_UTF16("quitMenuitem.label"); const char16_t* keyProp = MOZ_UTF16("quitMenuitem.key"); stringBundle->GetStringFromName(labelProp, getter_Copies(labelUTF16)); stringBundle->GetStringFromName(keyProp, getter_Copies(keyUTF16)); NSString* labelStr = [NSString stringWithUTF8String: NS_ConvertUTF16toUTF8(labelUTF16).get()]; NSString* keyStr= [NSString stringWithUTF8String: NS_ConvertUTF16toUTF8(keyUTF16).get()]; if (!nsMenuBarX::sNativeEventTarget) { nsMenuBarX::sNativeEventTarget = [[NativeMenuItemTarget alloc] init]; } sApplicationMenu = [[[[NSApp mainMenu] itemAtIndex:0] submenu] retain]; NSMenuItem* quitMenuItem = [[[NSMenuItem alloc] initWithTitle:labelStr action:@selector(menuItemHit:) keyEquivalent:keyStr] autorelease]; [quitMenuItem setTarget:nsMenuBarX::sNativeEventTarget]; [quitMenuItem setTag:eCommand_ID_Quit]; [sApplicationMenu addItem:quitMenuItem]; sApplicationMenuIsFallback = YES; } uint32_t nsMenuBarX::GetMenuCount() { return mMenuArray.Length(); } bool nsMenuBarX::MenuContainsAppMenu() { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN; return ([mNativeMenu numberOfItems] > 0 && [[mNativeMenu itemAtIndex:0] submenu] == sApplicationMenu); NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(false); } nsresult nsMenuBarX::InsertMenuAtIndex(nsMenuX* aMenu, uint32_t aIndex) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; // If we've only yet created a fallback global Application menu (using // ContructFallbackNativeMenus()), destroy it before recreating it properly. if (sApplicationMenu && sApplicationMenuIsFallback) { ResetNativeApplicationMenu(); } // If we haven't created a global Application menu yet, do it. if (!sApplicationMenu) { nsresult rv = NS_OK; // avoid warning about rv being unused rv = CreateApplicationMenu(aMenu); NS_ASSERTION(NS_SUCCEEDED(rv), "Can't create Application menu"); // Hook the new Application menu up to the menu bar. NSMenu* mainMenu = [NSApp mainMenu]; NS_ASSERTION([mainMenu numberOfItems] > 0, "Main menu does not have any items, something is terribly wrong!"); [[mainMenu itemAtIndex:0] setSubmenu:sApplicationMenu]; } // add menu to array that owns our menus mMenuArray.InsertElementAt(aIndex, aMenu); // hook up submenus nsIContent* menuContent = aMenu->Content(); if (menuContent->GetChildCount() > 0 && !nsMenuUtilsX::NodeIsHiddenOrCollapsed(menuContent)) { int insertionIndex = nsMenuUtilsX::CalculateNativeInsertionPoint(this, aMenu); if (MenuContainsAppMenu()) insertionIndex++; [mNativeMenu insertItem:aMenu->NativeMenuItem() atIndex:insertionIndex]; } return NS_OK; NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } void nsMenuBarX::RemoveMenuAtIndex(uint32_t aIndex) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; if (mMenuArray.Length() <= aIndex) { NS_ERROR("Attempting submenu removal with bad index!"); return; } // Our native menu and our internal menu object array might be out of sync. // This happens, for example, when a submenu is hidden. Because of this we // should not assume that a native submenu is hooked up. NSMenuItem* nativeMenuItem = mMenuArray[aIndex]->NativeMenuItem(); int nativeMenuItemIndex = [mNativeMenu indexOfItem:nativeMenuItem]; if (nativeMenuItemIndex != -1) [mNativeMenu removeItemAtIndex:nativeMenuItemIndex]; mMenuArray.RemoveElementAt(aIndex); NS_OBJC_END_TRY_ABORT_BLOCK; } void nsMenuBarX::ObserveAttributeChanged(nsIDocument* aDocument, nsIContent* aContent, nsIAtom* aAttribute) { } void nsMenuBarX::ObserveContentRemoved(nsIDocument* aDocument, nsIContent* aChild, int32_t aIndexInContainer) { RemoveMenuAtIndex(aIndexInContainer); } void nsMenuBarX::ObserveContentInserted(nsIDocument* aDocument, nsIContent* aContainer, nsIContent* aChild) { nsMenuX* newMenu = new nsMenuX(); if (newMenu) { nsresult rv = newMenu->Create(this, this, aChild); if (NS_SUCCEEDED(rv)) InsertMenuAtIndex(newMenu, aContainer->IndexOf(aChild)); else delete newMenu; } } void nsMenuBarX::ForceUpdateNativeMenuAt(const nsAString& indexString) { NSString* locationString = [NSString stringWithCharacters:reinterpret_cast(indexString.BeginReading()) length:indexString.Length()]; NSArray* indexes = [locationString componentsSeparatedByString:@"|"]; unsigned int indexCount = [indexes count]; if (indexCount == 0) return; nsMenuX* currentMenu = NULL; int targetIndex = [[indexes objectAtIndex:0] intValue]; int visible = 0; uint32_t length = mMenuArray.Length(); // first find a menu in the menu bar for (unsigned int i = 0; i < length; i++) { nsMenuX* menu = mMenuArray[i]; if (!nsMenuUtilsX::NodeIsHiddenOrCollapsed(menu->Content())) { visible++; if (visible == (targetIndex + 1)) { currentMenu = menu; break; } } } if (!currentMenu) return; // fake open/close to cause lazy update to happen so submenus populate currentMenu->MenuOpened(); currentMenu->MenuClosed(); // now find the correct submenu for (unsigned int i = 1; currentMenu && i < indexCount; i++) { targetIndex = [[indexes objectAtIndex:i] intValue]; visible = 0; length = currentMenu->GetItemCount(); for (unsigned int j = 0; j < length; j++) { nsMenuObjectX* targetMenu = currentMenu->GetItemAt(j); if (!targetMenu) return; if (!nsMenuUtilsX::NodeIsHiddenOrCollapsed(targetMenu->Content())) { visible++; if (targetMenu->MenuObjectType() == eSubmenuObjectType && visible == (targetIndex + 1)) { currentMenu = static_cast(targetMenu); // fake open/close to cause lazy update to happen currentMenu->MenuOpened(); currentMenu->MenuClosed(); break; } } } } } // Calling this forces a full reload of the menu system, reloading all native // menus and their items. // Without this testing is hard because changes to the DOM affect the native // menu system lazily. void nsMenuBarX::ForceNativeMenuReload() { // tear down everything while (GetMenuCount() > 0) RemoveMenuAtIndex(0); // construct everything ConstructNativeMenus(); } nsMenuX* nsMenuBarX::GetMenuAt(uint32_t aIndex) { if (mMenuArray.Length() <= aIndex) { NS_ERROR("Requesting menu at invalid index!"); return NULL; } return mMenuArray[aIndex]; } nsMenuX* nsMenuBarX::GetXULHelpMenu() { // The Help menu is usually (always?) the last one, so we start there and // count back. for (int32_t i = GetMenuCount() - 1; i >= 0; --i) { nsMenuX* aMenu = GetMenuAt(i); if (aMenu && nsMenuX::IsXULHelpMenu(aMenu->Content())) return aMenu; } return nil; } // On SnowLeopard and later we must tell the OS which is our Help menu. // Otherwise it will only add Spotlight for Help (the Search item) to our // Help menu if its label/title is "Help" -- i.e. if the menu is in English. // This resolves bugs 489196 and 539317. void nsMenuBarX::SetSystemHelpMenu() { if (!nsCocoaFeatures::OnSnowLeopardOrLater()) return; // not on 10.4 and 10.5 nsMenuX* xulHelpMenu = GetXULHelpMenu(); if (xulHelpMenu) { NSMenu* helpMenu = (NSMenu*)xulHelpMenu->NativeData(); if (helpMenu) [NSApp setHelpMenu:helpMenu]; } } nsresult nsMenuBarX::Paint(bool aDelayed) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; if (!aDelayed && mAwaitingDelayedPaint) { return NS_OK; } mAwaitingDelayedPaint = false; // Don't try to optimize anything in this painting by checking // sLastGeckoMenuBarPainted because the menubar can be manipulated by // native dialogs and sheet code and other things besides this paint method. // We have to keep the same menu item for the Application menu so we keep // passing it along. NSMenu* outgoingMenu = [NSApp mainMenu]; NS_ASSERTION([outgoingMenu numberOfItems] > 0, "Main menu does not have any items, something is terribly wrong!"); // To work around bug 722676, we sometimes need to delay making mNativeMenu // the main menu. This is an Apple bug that sometimes causes a top-level // menu item to remain highlighted after pressing a Cmd+key combination that // opens a new window, then closing the window. The OS temporarily // highlights the appropriate top-level menu item whenever you press the // Cmd+key combination for one of its submenus. (It does this by setting a // "pressed" attribute on it.) The OS then uses a timer to remove this // "pressed" attribute. But without our workaround we sometimes change the // main menu before the timer has fired, so when it fires the menu item it // was intended to unhighlight is no longer present in the main menu. This // causes the item to remain semi-permanently highlighted (until you quit // Firefox or navigate the main menu by hand). if ((outgoingMenu != mNativeMenu) && [outgoingMenu isKindOfClass:[GeckoNSMenu class]]) { if (aDelayed) { [(GeckoNSMenu *)outgoingMenu setDelayResignMainMenu:false]; } else if ([(GeckoNSMenu *)outgoingMenu delayResignMainMenu]) { PaintMenuBarAfterDelay(); return NS_OK; } } if (outgoingMenu != mNativeMenu) { NSMenuItem* appMenuItem = [[outgoingMenu itemAtIndex:0] retain]; [outgoingMenu removeItemAtIndex:0]; [mNativeMenu insertItem:appMenuItem atIndex:0]; [appMenuItem release]; // Set menu bar and event target. [NSApp setMainMenu:mNativeMenu]; } SetSystemHelpMenu(); nsMenuBarX::sLastGeckoMenuBarPainted = this; gSomeMenuBarPainted = YES; return NS_OK; NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } // Used to delay a call to nsMenuBarX::Paint(). Needed to work around // bug 722676. void nsMenuBarX::PaintMenuBarAfterDelay() { mAwaitingDelayedPaint = true; nsMenuBarX::sCurrentPaintDelayedMenuBar = this; [mNativeMenu retain]; // The delay for Apple's unhighlight timer is 0.1f, so we make ours a bit longer. [mNativeMenu performSelector:@selector(delayedPaintMenuBar:) withObject:nil afterDelay:0.15f]; } // Returns the 'key' attribute of the 'shortcutID' object (if any) in the // currently active menubar's DOM document. 'shortcutID' should be the id // (i.e. the name) of a component that defines a commonly used (and // localized) cmd+key shortcut, and belongs to a keyset containing similar // objects. For example "key_selectAll". Returns a value that can be // compared to the first character of [NSEvent charactersIgnoringModifiers] // when [NSEvent modifierFlags] == NSCommandKeyMask. char nsMenuBarX::GetLocalizedAccelKey(const char *shortcutID) { if (!sLastGeckoMenuBarPainted) return 0; nsCOMPtr domDoc(do_QueryInterface(sLastGeckoMenuBarPainted->mContent->OwnerDoc())); if (!domDoc) return 0; NS_ConvertASCIItoUTF16 shortcutIDStr((const char *)shortcutID); nsCOMPtr shortcutElement; domDoc->GetElementById(shortcutIDStr, getter_AddRefs(shortcutElement)); nsCOMPtr shortcutContent = do_QueryInterface(shortcutElement); if (!shortcutContent) return 0; nsAutoString key; shortcutContent->GetAttr(kNameSpaceID_None, nsGkAtoms::key, key); NS_LossyConvertUTF16toASCII keyASC(key.get()); const char *keyASCPtr = keyASC.get(); if (!keyASCPtr) return 0; // If keyID's 'key' attribute isn't exactly one character long, it's not // what we're looking for. if (strlen(keyASCPtr) != sizeof(char)) return 0; // Make sure retval is lower case. char retval = tolower(keyASCPtr[0]); return retval; } /* static */ void nsMenuBarX::ResetNativeApplicationMenu() { #if(0) // Hmmm. removeAllItems appears to be 10.6 specific. [sApplicationMenu removeAllItems]; #else // but we need this (see bug 1151345), so ... uint32_t currentCount = [sApplicationMenu numberOfItems]; for (uint32_t i=0; i