1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "XULButtonElement.h"
8 #include "mozilla/Assertions.h"
9 #include "mozilla/Attributes.h"
10 #include "mozilla/FlushType.h"
11 #include "mozilla/UniquePtr.h"
12 #include "nsGkAtoms.h"
14 #include "nsXULPopupManager.h"
15 #include "nsMenuPopupFrame.h"
16 #include "nsContentUtils.h"
17 #include "nsXULElement.h"
18 #include "nsIDOMXULCommandDispatcher.h"
19 #include "nsCSSFrameConstructor.h"
20 #include "nsGlobalWindowOuter.h"
21 #include "nsIContentInlines.h"
22 #include "nsLayoutUtils.h"
23 #include "nsViewManager.h"
25 #include "nsFocusManager.h"
26 #include "nsIDocShell.h"
27 #include "nsPIDOMWindow.h"
28 #include "nsIInterfaceRequestorUtils.h"
29 #include "nsIBaseWindow.h"
31 #include "mozilla/dom/Document.h"
32 #include "nsPIWindowRoot.h"
33 #include "nsFrameManager.h"
34 #include "nsPresContextInlines.h"
35 #include "nsIObserverService.h"
36 #include "mozilla/AnimationUtils.h"
37 #include "mozilla/dom/DocumentInlines.h"
38 #include "mozilla/dom/Element.h"
39 #include "mozilla/dom/Event.h" // for Event
40 #include "mozilla/dom/HTMLSlotElement.h"
41 #include "mozilla/dom/KeyboardEvent.h"
42 #include "mozilla/dom/KeyboardEventBinding.h"
43 #include "mozilla/dom/MouseEvent.h"
44 #include "mozilla/dom/UIEvent.h"
45 #include "mozilla/dom/UserActivation.h"
46 #include "mozilla/dom/PopupPositionedEvent.h"
47 #include "mozilla/dom/PopupPositionedEventBinding.h"
48 #include "mozilla/dom/XULCommandEvent.h"
49 #include "mozilla/dom/XULMenuElement.h"
50 #include "mozilla/dom/XULMenuBarElement.h"
51 #include "mozilla/dom/XULPopupElement.h"
52 #include "mozilla/EventDispatcher.h"
53 #include "mozilla/EventStateManager.h"
54 #include "mozilla/LookAndFeel.h"
55 #include "mozilla/MouseEvents.h"
56 #include "mozilla/PresShell.h"
57 #include "mozilla/Services.h"
58 #include "mozilla/StaticPrefs_ui.h"
59 #include "mozilla/widget/nsAutoRollup.h"
60 #include "mozilla/widget/NativeMenuSupport.h"
62 using namespace mozilla
;
63 using namespace mozilla::dom
;
64 using mozilla::widget::NativeMenu
;
66 static_assert(KeyboardEvent_Binding::DOM_VK_HOME
==
67 KeyboardEvent_Binding::DOM_VK_END
+ 1 &&
68 KeyboardEvent_Binding::DOM_VK_LEFT
==
69 KeyboardEvent_Binding::DOM_VK_END
+ 2 &&
70 KeyboardEvent_Binding::DOM_VK_UP
==
71 KeyboardEvent_Binding::DOM_VK_END
+ 3 &&
72 KeyboardEvent_Binding::DOM_VK_RIGHT
==
73 KeyboardEvent_Binding::DOM_VK_END
+ 4 &&
74 KeyboardEvent_Binding::DOM_VK_DOWN
==
75 KeyboardEvent_Binding::DOM_VK_END
+ 5,
76 "nsXULPopupManager assumes some keyCode values are consecutive");
78 #define NS_DIRECTION_IS_INLINE(dir) \
79 (dir == eNavigationDirection_Start || dir == eNavigationDirection_End)
80 #define NS_DIRECTION_IS_BLOCK(dir) \
81 (dir == eNavigationDirection_Before || dir == eNavigationDirection_After)
82 #define NS_DIRECTION_IS_BLOCK_TO_EDGE(dir) \
83 (dir == eNavigationDirection_First || dir == eNavigationDirection_Last)
85 static_assert(static_cast<uint8_t>(mozilla::StyleDirection::Ltr
) == 0 &&
86 static_cast<uint8_t>(mozilla::StyleDirection::Rtl
) == 1,
87 "Left to Right should be 0 and Right to Left should be 1");
89 const nsNavigationDirection DirectionFromKeyCodeTable
[2][6] = {
91 eNavigationDirection_Last
, // KeyboardEvent_Binding::DOM_VK_END
92 eNavigationDirection_First
, // KeyboardEvent_Binding::DOM_VK_HOME
93 eNavigationDirection_Start
, // KeyboardEvent_Binding::DOM_VK_LEFT
94 eNavigationDirection_Before
, // KeyboardEvent_Binding::DOM_VK_UP
95 eNavigationDirection_End
, // KeyboardEvent_Binding::DOM_VK_RIGHT
96 eNavigationDirection_After
// KeyboardEvent_Binding::DOM_VK_DOWN
99 eNavigationDirection_Last
, // KeyboardEvent_Binding::DOM_VK_END
100 eNavigationDirection_First
, // KeyboardEvent_Binding::DOM_VK_HOME
101 eNavigationDirection_End
, // KeyboardEvent_Binding::DOM_VK_LEFT
102 eNavigationDirection_Before
, // KeyboardEvent_Binding::DOM_VK_UP
103 eNavigationDirection_Start
, // KeyboardEvent_Binding::DOM_VK_RIGHT
104 eNavigationDirection_After
// KeyboardEvent_Binding::DOM_VK_DOWN
107 nsXULPopupManager
* nsXULPopupManager::sInstance
= nullptr;
109 PendingPopup::PendingPopup(Element
* aPopup
, mozilla::dom::Event
* aEvent
)
110 : mPopup(aPopup
), mEvent(aEvent
), mModifiers(0) {
114 void PendingPopup::InitMousePoint() {
115 // get the event coordinates relative to the root frame of the document
116 // containing the popup.
121 WidgetEvent
* event
= mEvent
->WidgetEventPtr();
122 WidgetInputEvent
* inputEvent
= event
->AsInputEvent();
124 mModifiers
= inputEvent
->mModifiers
;
126 Document
* doc
= mPopup
->GetUncomposedDoc();
131 PresShell
* presShell
= doc
->GetPresShell();
132 nsPresContext
* presContext
;
133 if (presShell
&& (presContext
= presShell
->GetPresContext())) {
134 nsPresContext
* rootDocPresContext
= presContext
->GetRootPresContext();
135 if (!rootDocPresContext
) {
139 nsIFrame
* rootDocumentRootFrame
=
140 rootDocPresContext
->PresShell()->GetRootFrame();
141 if ((event
->mClass
== eMouseEventClass
||
142 event
->mClass
== eMouseScrollEventClass
||
143 event
->mClass
== eWheelEventClass
) &&
144 !event
->AsGUIEvent()->mWidget
) {
145 // no widget, so just use the client point if available
146 MouseEvent
* mouseEvent
= mEvent
->AsMouseEvent();
147 nsIntPoint
clientPt(mouseEvent
->ClientX(), mouseEvent
->ClientY());
149 // XXX this doesn't handle IFRAMEs in transforms
150 nsPoint thisDocToRootDocOffset
=
151 presShell
->GetRootFrame()->GetOffsetToCrossDoc(rootDocumentRootFrame
);
152 // convert to device pixels
153 mMousePoint
.x
= presContext
->AppUnitsToDevPixels(
154 nsPresContext::CSSPixelsToAppUnits(clientPt
.x
) +
155 thisDocToRootDocOffset
.x
);
156 mMousePoint
.y
= presContext
->AppUnitsToDevPixels(
157 nsPresContext::CSSPixelsToAppUnits(clientPt
.y
) +
158 thisDocToRootDocOffset
.y
);
159 } else if (rootDocumentRootFrame
) {
160 nsPoint pnt
= nsLayoutUtils::GetEventCoordinatesRelativeTo(
161 event
, RelativeTo
{rootDocumentRootFrame
});
163 LayoutDeviceIntPoint(rootDocPresContext
->AppUnitsToDevPixels(pnt
.x
),
164 rootDocPresContext
->AppUnitsToDevPixels(pnt
.y
));
169 already_AddRefed
<nsIContent
> PendingPopup::GetTriggerContent() const {
170 nsCOMPtr
<nsIContent
> target
=
171 do_QueryInterface(mEvent
? mEvent
->GetTarget() : nullptr);
172 return target
.forget();
175 uint16_t PendingPopup::MouseInputSource() const {
177 mozilla::WidgetMouseEventBase
* mouseEvent
=
178 mEvent
->WidgetEventPtr()->AsMouseEventBase();
180 return mouseEvent
->mInputSource
;
183 RefPtr
<XULCommandEvent
> commandEvent
= mEvent
->AsXULCommandEvent();
185 return commandEvent
->InputSource();
189 return MouseEvent_Binding::MOZ_SOURCE_UNKNOWN
;
192 XULPopupElement
* nsMenuChainItem::Element() { return &mFrame
->PopupElement(); }
194 void nsMenuChainItem::SetParent(UniquePtr
<nsMenuChainItem
> aParent
) {
195 MOZ_ASSERT_IF(aParent
, !aParent
->mChild
);
196 auto oldParent
= Detach();
197 mParent
= std::move(aParent
);
199 mParent
->mChild
= this;
203 UniquePtr
<nsMenuChainItem
> nsMenuChainItem::Detach() {
205 MOZ_ASSERT(mParent
->mChild
== this,
206 "Unexpected - parent's child not set to this");
207 mParent
->mChild
= nullptr;
209 return std::move(mParent
);
212 void nsXULPopupManager::RemoveMenuChainItem(nsMenuChainItem
* aItem
) {
213 auto parent
= aItem
->Detach();
214 if (auto* child
= aItem
->GetChild()) {
215 MOZ_ASSERT(aItem
!= mPopups
,
216 "Unexpected - popup with child at end of chain");
217 // This will kill aItem by changing child's mParent pointer.
218 child
->SetParent(std::move(parent
));
220 // An item without a child should be the first item in the chain, so set
221 // the first item pointer, pointed to by aRoot, to the parent.
222 MOZ_ASSERT(aItem
== mPopups
,
223 "Unexpected - popup with no child not at end of chain");
224 mPopups
= std::move(parent
);
228 void nsMenuChainItem::UpdateFollowAnchor() {
229 mFollowAnchor
= mFrame
->ShouldFollowAnchor(mCurrentRect
);
232 void nsMenuChainItem::CheckForAnchorChange() {
234 mFrame
->CheckForAnchorChange(mCurrentRect
);
238 NS_IMPL_ISUPPORTS(nsXULPopupManager
, nsIDOMEventListener
, nsIObserver
)
240 nsXULPopupManager::nsXULPopupManager()
241 : mActiveMenuBar(nullptr), mPopups(nullptr), mPendingPopup(nullptr) {
242 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
244 obs
->AddObserver(this, "xpcom-shutdown", false);
248 nsXULPopupManager::~nsXULPopupManager() {
249 NS_ASSERTION(!mPopups
, "XUL popups still open");
252 mNativeMenu
->RemoveObserver(this);
256 nsresult
nsXULPopupManager::Init() {
257 sInstance
= new nsXULPopupManager();
258 NS_ENSURE_TRUE(sInstance
, NS_ERROR_OUT_OF_MEMORY
);
259 NS_ADDREF(sInstance
);
263 void nsXULPopupManager::Shutdown() { NS_IF_RELEASE(sInstance
); }
266 nsXULPopupManager::Observe(nsISupports
* aSubject
, const char* aTopic
,
267 const char16_t
* aData
) {
268 if (!nsCRT::strcmp(aTopic
, "xpcom-shutdown")) {
270 mKeyListener
->RemoveEventListener(u
"keypress"_ns
, this, true);
271 mKeyListener
->RemoveEventListener(u
"keydown"_ns
, this, true);
272 mKeyListener
->RemoveEventListener(u
"keyup"_ns
, this, true);
273 mKeyListener
= nullptr;
275 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
277 obs
->RemoveObserver(this, "xpcom-shutdown");
284 nsXULPopupManager
* nsXULPopupManager::GetInstance() {
285 MOZ_ASSERT(sInstance
);
289 bool nsXULPopupManager::RollupTooltips() {
290 const RollupOptions options
{0, FlushViews::Yes
, nullptr, AllowAnimations::No
};
291 return RollupInternal(RollupKind::Tooltip
, options
, nullptr);
294 bool nsXULPopupManager::Rollup(const RollupOptions
& aOptions
,
295 nsIContent
** aLastRolledUp
) {
296 return RollupInternal(RollupKind::Menu
, aOptions
, aLastRolledUp
);
299 bool nsXULPopupManager::RollupNativeMenu() {
301 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
302 return menu
->Close();
307 bool nsXULPopupManager::RollupInternal(RollupKind aKind
,
308 const RollupOptions
& aOptions
,
309 nsIContent
** aLastRolledUp
) {
311 *aLastRolledUp
= nullptr;
314 // We can disable the autohide behavior via a pref to ease debugging.
315 if (StaticPrefs::ui_popup_disable_autohide()) {
316 // Required on linux to allow events to work on other targets.
318 mWidget
->CaptureRollupEvents(false);
323 nsMenuChainItem
* item
= GetRollupItem(aKind
);
328 // We need to get the popup that will be closed last, so that widget can
329 // keep track of it so it doesn't reopen if a mousedown event is going to
330 // processed. Keep going up the menu chain to get the first level menu of
331 // the same type. If a different type is encountered it means we have,
332 // for example, a menulist or context menu inside a panel, and we want to
333 // treat these as distinct. It's possible that this menu doesn't end up
334 // closing because the popuphiding event was cancelled, but in that case
335 // we don't need to deal with the menu reopening as it will already still
337 nsMenuChainItem
* first
= item
;
338 while (first
->GetParent()) {
339 nsMenuChainItem
* parent
= first
->GetParent();
340 if (first
->Frame()->GetPopupType() != parent
->Frame()->GetPopupType() ||
341 first
->IsContextMenu() != parent
->IsContextMenu()) {
347 *aLastRolledUp
= first
->Element();
350 ConsumeOutsideClicksResult consumeResult
=
351 item
->Frame()->ConsumeOutsideClicks();
352 bool consume
= consumeResult
== ConsumeOutsideClicks_True
;
355 // If norolluponanchor is true, then don't rollup when clicking the anchor.
356 // This would be used to allow adjusting the caret position in an
357 // autocomplete field without hiding the popup for example.
358 bool noRollupOnAnchor
=
359 (!consume
&& aOptions
.mPoint
&&
360 item
->Frame()->GetContent()->AsElement()->AttrValueIs(
361 kNameSpaceID_None
, nsGkAtoms::norolluponanchor
, nsGkAtoms::_true
,
364 // When ConsumeOutsideClicks_ParentOnly is used, always consume the click
365 // when the click was over the anchor. This way, clicking on a menu doesn't
367 if ((consumeResult
== ConsumeOutsideClicks_ParentOnly
|| noRollupOnAnchor
) &&
369 nsMenuPopupFrame
* popupFrame
= item
->Frame();
370 CSSIntRect anchorRect
= [&] {
371 if (popupFrame
->IsAnchored()) {
372 // Check if the popup has an anchor rectangle set. If not, get the
373 // rectangle from the anchor element.
374 auto r
= popupFrame
->GetScreenAnchorRect();
375 if (r
.x
!= -1 && r
.y
!= -1) {
376 // Prefer the untransformed anchor rect, so as to account for Wayland
377 // properly. Note we still need to check GetScreenAnchorRect() tho, so
378 // as to detect whether the anchor came from the popup opening call,
379 // or from an element (in which case we want to take the code-path
381 auto untransformed
= popupFrame
->GetUntransformedAnchorRect();
382 if (!untransformed
.IsEmpty()) {
383 return CSSIntRect::FromAppUnitsRounded(untransformed
);
389 auto* anchor
= Element::FromNodeOrNull(popupFrame
->GetAnchor());
394 // Check if the anchor has indicated another node to use for checking
395 // for roll-up. That way, we can anchor a popup on anonymous content
396 // or an individual icon, while clicking elsewhere within a button or
397 // other container doesn't result in us re-opening the popup.
398 nsAutoString consumeAnchor
;
399 anchor
->GetAttr(nsGkAtoms::consumeanchor
, consumeAnchor
);
400 if (!consumeAnchor
.IsEmpty()) {
401 if (Element
* newAnchor
=
402 anchor
->OwnerDoc()->GetElementById(consumeAnchor
)) {
407 nsIFrame
* f
= anchor
->GetPrimaryFrame();
411 return f
->GetScreenRect();
414 // It's possible that some other element is above the anchor at the same
415 // position, but the only thing that would happen is that the mouse
416 // event will get consumed, so here only a quick coordinates check is
417 // done rather than a slower complete check of what is at that location.
418 nsPresContext
* presContext
= item
->Frame()->PresContext();
419 CSSIntPoint posCSSPixels
=
420 presContext
->DevPixelsToIntCSSPixels(*aOptions
.mPoint
);
421 if (anchorRect
.Contains(posCSSPixels
)) {
422 if (consumeResult
== ConsumeOutsideClicks_ParentOnly
) {
426 if (noRollupOnAnchor
) {
436 // If a number of popups to close has been specified, determine the last
438 Element
* lastPopup
= nullptr;
439 uint32_t count
= aOptions
.mCount
;
440 if (count
&& count
!= UINT32_MAX
) {
441 nsMenuChainItem
* last
= item
;
442 while (--count
&& last
->GetParent()) {
443 last
= last
->GetParent();
446 lastPopup
= last
->Element();
450 nsPresContext
* presContext
= item
->Frame()->PresContext();
451 RefPtr
<nsViewManager
> viewManager
=
452 presContext
->PresShell()->GetViewManager();
454 HidePopupOptions options
{HidePopupOption::HideChain
,
455 HidePopupOption::DeselectMenu
,
456 HidePopupOption::IsRollup
};
457 if (aOptions
.mAllowAnimations
== AllowAnimations::No
) {
458 options
+= HidePopupOption::DisableAnimations
;
461 HidePopup(item
->Element(), options
, lastPopup
);
463 if (aOptions
.mFlush
== FlushViews::Yes
) {
464 // The popup's visibility doesn't update until the minimize animation
465 // has finished, so call UpdateWidgetGeometry to update it right away.
466 viewManager
->UpdateWidgetGeometry();
472 ////////////////////////////////////////////////////////////////////////
473 bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent() {
474 // should rollup only for autocomplete widgets
475 // XXXndeakin this should really be something the popup has more control over
477 nsMenuChainItem
* item
= GetTopVisibleMenu();
482 nsIContent
* content
= item
->Frame()->GetContent();
483 if (!content
|| !content
->IsElement()) return false;
485 Element
* element
= content
->AsElement();
486 if (element
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::rolluponmousewheel
,
487 nsGkAtoms::_true
, eCaseMatters
))
490 if (element
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::rolluponmousewheel
,
491 nsGkAtoms::_false
, eCaseMatters
))
495 element
->GetAttr(nsGkAtoms::type
, value
);
496 return StringBeginsWith(value
, u
"autocomplete"_ns
);
499 bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent() {
500 nsMenuChainItem
* item
= GetTopVisibleMenu();
505 nsMenuPopupFrame
* frame
= item
->Frame();
506 if (frame
->GetPopupType() != PopupType::Panel
) return true;
508 return !frame
->GetContent()->AsElement()->AttrValueIs(
509 kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
, eCaseMatters
);
512 // a menu should not roll up if activated by a mouse activate message (eg.
514 bool nsXULPopupManager::ShouldRollupOnMouseActivate() { return false; }
516 uint32_t nsXULPopupManager::GetSubmenuWidgetChain(
517 nsTArray
<nsIWidget
*>* aWidgetChain
) {
518 // this method is used by the widget code to determine the list of popups
519 // that are open. If a mouse click occurs outside one of these popups, the
520 // panels will roll up. If the click is inside a popup, they will not roll up
521 uint32_t count
= 0, sameTypeCount
= 0;
523 NS_ASSERTION(aWidgetChain
, "null parameter");
524 nsMenuChainItem
* item
= GetTopVisibleMenu();
526 nsMenuChainItem
* parent
= item
->GetParent();
527 if (!item
->IsNoAutoHide()) {
528 nsCOMPtr
<nsIWidget
> widget
= item
->Frame()->GetWidget();
529 NS_ASSERTION(widget
, "open popup has no widget");
531 aWidgetChain
->AppendElement(widget
.get());
532 // In the case when a menulist inside a panel is open, clicking in the
533 // panel should still roll up the menu, so if a different type is found,
535 if (!sameTypeCount
) {
538 item
->Frame()->GetPopupType() !=
539 parent
->Frame()->GetPopupType() ||
540 item
->IsContextMenu() != parent
->IsContextMenu()) {
541 sameTypeCount
= count
;
549 return sameTypeCount
;
552 nsIWidget
* nsXULPopupManager::GetRollupWidget() {
553 nsMenuChainItem
* item
= GetTopVisibleMenu();
554 return item
? item
->Frame()->GetWidget() : nullptr;
557 void nsXULPopupManager::AdjustPopupsOnWindowChange(
558 nsPIDOMWindowOuter
* aWindow
) {
559 // When the parent window is moved, adjust any child popups. Dismissable
560 // menus and panels are expected to roll up when a window is moved, so there
561 // is no need to check these popups, only the noautohide popups.
563 // The items are added to a list so that they can be adjusted bottom to top.
564 nsTArray
<nsMenuPopupFrame
*> list
;
566 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
567 // only move popups that are within the same window and where auto
568 // positioning has not been disabled
569 if (!item
->IsNoAutoHide()) {
572 nsMenuPopupFrame
* frame
= item
->Frame();
573 nsIContent
* popup
= frame
->GetContent();
577 Document
* document
= popup
->GetUncomposedDoc();
581 nsPIDOMWindowOuter
* window
= document
->GetWindow();
585 window
= window
->GetPrivateRoot();
586 if (window
== aWindow
) {
587 list
.AppendElement(frame
);
591 for (int32_t l
= list
.Length() - 1; l
>= 0; l
--) {
592 list
[l
]->SetPopupPosition(true);
596 void nsXULPopupManager::AdjustPopupsOnWindowChange(PresShell
* aPresShell
) {
597 if (aPresShell
->GetDocument()) {
598 AdjustPopupsOnWindowChange(aPresShell
->GetDocument()->GetWindow());
602 static nsMenuPopupFrame
* GetPopupToMoveOrResize(nsIFrame
* aFrame
) {
603 nsMenuPopupFrame
* menuPopupFrame
= do_QueryFrame(aFrame
);
604 if (!menuPopupFrame
) return nullptr;
606 // no point moving or resizing hidden popups
607 if (!menuPopupFrame
->IsVisible()) return nullptr;
609 nsIWidget
* widget
= menuPopupFrame
->GetWidget();
610 if (widget
&& !widget
->IsVisible()) return nullptr;
612 return menuPopupFrame
;
615 void nsXULPopupManager::PopupMoved(nsIFrame
* aFrame
,
616 const LayoutDeviceIntPoint
& aPoint
,
617 bool aByMoveToRect
) {
618 nsMenuPopupFrame
* menuPopupFrame
= GetPopupToMoveOrResize(aFrame
);
619 if (!menuPopupFrame
) {
623 nsView
* view
= menuPopupFrame
->GetView();
628 menuPopupFrame
->WidgetPositionOrSizeDidChange();
630 // Don't do anything if the popup is already at the specified location. This
631 // prevents recursive calls when a popup is positioned.
632 LayoutDeviceIntRect curDevBounds
= view
->RecalcWidgetBounds();
633 nsIWidget
* widget
= menuPopupFrame
->GetWidget();
634 if (curDevBounds
.TopLeft() == aPoint
&&
636 widget
->GetClientOffset() == menuPopupFrame
->GetLastClientOffset())) {
640 // Update the popup's position using SetPopupPosition if the popup is
641 // anchored and at the parent level as these maintain their position
642 // relative to the parent window (except if positioned by move to rect, in
643 // which case we better make sure that layout matches that). Otherwise, just
644 // update the popup to the specified screen coordinates.
645 if (menuPopupFrame
->IsAnchored() &&
646 menuPopupFrame
->GetPopupLevel() == widget::PopupLevel::Parent
&&
648 menuPopupFrame
->SetPopupPosition(true);
651 aPoint
/ menuPopupFrame
->PresContext()->CSSToDevPixelScale();
652 menuPopupFrame
->MoveTo(cssPos
, false, aByMoveToRect
);
656 void nsXULPopupManager::PopupResized(nsIFrame
* aFrame
,
657 const LayoutDeviceIntSize
& aSize
) {
658 nsMenuPopupFrame
* menuPopupFrame
= GetPopupToMoveOrResize(aFrame
);
659 if (!menuPopupFrame
) {
663 menuPopupFrame
->WidgetPositionOrSizeDidChange();
665 nsView
* view
= menuPopupFrame
->GetView();
670 const LayoutDeviceIntRect curDevBounds
= view
->RecalcWidgetBounds();
671 // If the size is what we think it is, we have nothing to do.
672 if (curDevBounds
.Size() == aSize
) {
676 Element
* popup
= menuPopupFrame
->GetContent()->AsElement();
678 // Only set the width and height if the popup already has these attributes.
679 if (!popup
->HasAttr(nsGkAtoms::width
) || !popup
->HasAttr(nsGkAtoms::height
)) {
683 // The size is different. Convert the actual size to css pixels and store it
684 // as 'width' and 'height' attributes on the popup.
685 nsPresContext
* presContext
= menuPopupFrame
->PresContext();
687 CSSIntSize
newCSS(presContext
->DevPixelsToIntCSSPixels(aSize
.width
),
688 presContext
->DevPixelsToIntCSSPixels(aSize
.height
));
690 nsAutoString width
, height
;
691 width
.AppendInt(newCSS
.width
);
692 height
.AppendInt(newCSS
.height
);
693 // FIXME(emilio): aNotify should be consistent (probably true in the two calls
695 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::width
, width
, false);
696 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::height
, height
, true);
699 nsMenuPopupFrame
* nsXULPopupManager::GetPopupFrameForContent(
700 nsIContent
* aContent
, bool aShouldFlush
) {
702 Document
* document
= aContent
->GetUncomposedDoc();
704 if (RefPtr
<PresShell
> presShell
= document
->GetPresShell()) {
705 presShell
->FlushPendingNotifications(FlushType::Layout
);
710 return do_QueryFrame(aContent
->GetPrimaryFrame());
713 nsMenuChainItem
* nsXULPopupManager::GetRollupItem(RollupKind aKind
) {
714 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
715 if (item
->Frame()->PopupState() == ePopupInvisible
) {
718 MOZ_ASSERT_IF(item
->Frame()->GetPopupType() == PopupType::Tooltip
,
719 item
->IsNoAutoHide());
720 const bool valid
= aKind
== RollupKind::Tooltip
721 ? item
->Frame()->GetPopupType() == PopupType::Tooltip
722 : !item
->IsNoAutoHide();
730 void nsXULPopupManager::SetActiveMenuBar(XULMenuBarElement
* aMenuBar
,
733 mActiveMenuBar
= aMenuBar
;
734 } else if (mActiveMenuBar
== aMenuBar
) {
735 mActiveMenuBar
= nullptr;
737 UpdateKeyboardListeners();
740 static CloseMenuMode
GetCloseMenuMode(nsIContent
* aMenu
) {
741 if (!aMenu
->IsElement()) {
742 return CloseMenuMode_Auto
;
745 static Element::AttrValuesArray strings
[] = {nsGkAtoms::none
,
746 nsGkAtoms::single
, nullptr};
747 switch (aMenu
->AsElement()->FindAttrValueIn(
748 kNameSpaceID_None
, nsGkAtoms::closemenu
, strings
, eCaseMatters
)) {
750 return CloseMenuMode_None
;
752 return CloseMenuMode_Single
;
754 return CloseMenuMode_Auto
;
758 auto nsXULPopupManager::MayShowMenu(nsIContent
* aMenu
) -> MayShowMenuResult
{
759 if (mNativeMenu
&& aMenu
->IsElement() &&
760 mNativeMenu
->Element()->Contains(aMenu
)) {
764 auto* menu
= XULButtonElement::FromNode(aMenu
);
769 nsMenuPopupFrame
* popupFrame
= menu
->GetMenuPopup(FlushType::None
);
770 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
773 return {false, menu
, popupFrame
};
776 void nsXULPopupManager::ShowMenu(nsIContent
* aMenu
, bool aSelectFirstItem
) {
777 auto mayShowResult
= MayShowMenu(aMenu
);
778 if (NS_WARN_IF(!mayShowResult
)) {
782 if (mayShowResult
.mIsNative
) {
783 mNativeMenu
->OpenSubmenu(aMenu
->AsElement());
787 nsMenuPopupFrame
* popupFrame
= mayShowResult
.mMenuPopupFrame
;
789 // inherit whether or not we're a context menu from the parent
790 const bool onMenuBar
= mayShowResult
.mMenuButton
->IsOnMenuBar();
791 const bool onmenu
= mayShowResult
.mMenuButton
->IsOnMenu();
792 const bool parentIsContextMenu
= mayShowResult
.mMenuButton
->IsOnContextMenu();
794 nsAutoString position
;
797 if (aMenu
->IsXULElement(nsGkAtoms::menulist
)) {
798 position
.AssignLiteral("selection");
802 if (onMenuBar
|| !onmenu
)
803 position
.AssignLiteral("after_start");
805 position
.AssignLiteral("end_before");
807 // there is no trigger event for menus
808 popupFrame
->InitializePopup(aMenu
, nullptr, position
, 0, 0,
809 MenuPopupAnchorType_Node
, true);
810 PendingPopup
pendingPopup(&popupFrame
->PopupElement(), nullptr);
811 BeginShowingPopup(pendingPopup
, parentIsContextMenu
, aSelectFirstItem
);
814 static bool ShouldUseNativeContextMenus() {
815 #ifdef HAS_NATIVE_MENU_SUPPORT
816 return mozilla::widget::NativeMenuSupport::ShouldUseNativeContextMenus();
822 void nsXULPopupManager::ShowPopup(Element
* aPopup
, nsIContent
* aAnchorContent
,
823 const nsAString
& aPosition
, int32_t aXPos
,
824 int32_t aYPos
, bool aIsContextMenu
,
825 bool aAttributesOverride
,
826 bool aSelectFirstItem
, Event
* aTriggerEvent
) {
828 // On Mac, use a native menu if possible since the non-native menu looks out
829 // of place. Native menus for anchored popups are not currently implemented,
830 // so fall back to the non-native path below if `aAnchorContent` is given. We
831 // also fall back if the position string is not empty so we don't break tests
832 // that either themselves call or test app features that call
833 // `openPopup(null, "position")`.
834 if (!aAnchorContent
&& aPosition
.IsEmpty() && ShouldUseNativeContextMenus() &&
835 aPopup
->IsAnyOfXULElements(nsGkAtoms::menu
, nsGkAtoms::menupopup
) &&
836 ShowPopupAsNativeMenu(aPopup
, aXPos
, aYPos
, aIsContextMenu
,
842 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
843 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
847 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
848 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
850 popupFrame
->InitializePopup(aAnchorContent
, triggerContent
, aPosition
, aXPos
,
851 aYPos
, MenuPopupAnchorType_Node
,
852 aAttributesOverride
);
854 BeginShowingPopup(pendingPopup
, aIsContextMenu
, aSelectFirstItem
);
857 void nsXULPopupManager::ShowPopupAtScreen(Element
* aPopup
, int32_t aXPos
,
858 int32_t aYPos
, bool aIsContextMenu
,
859 Event
* aTriggerEvent
) {
860 if (aIsContextMenu
&& ShouldUseNativeContextMenus() &&
861 ShowPopupAsNativeMenu(aPopup
, aXPos
, aYPos
, aIsContextMenu
,
866 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
867 if (!popupFrame
|| !MayShowPopup(popupFrame
)) return;
869 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
870 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
872 popupFrame
->InitializePopupAtScreen(triggerContent
, aXPos
, aYPos
,
874 BeginShowingPopup(pendingPopup
, aIsContextMenu
, false);
877 bool nsXULPopupManager::ShowPopupAsNativeMenu(Element
* aPopup
, int32_t aXPos
,
880 Event
* aTriggerEvent
) {
882 NS_WARNING("Native menu still open when trying to open another");
883 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
885 menu
->RemoveObserver(this);
886 mNativeMenu
= nullptr;
889 RefPtr
<NativeMenu
> menu
;
890 #ifdef HAS_NATIVE_MENU_SUPPORT
891 menu
= mozilla::widget::NativeMenuSupport::CreateNativeContextMenu(aPopup
);
898 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
903 // Hide the menu from our accessibility code so that we don't dispatch custom
904 // accessibility notifications which would conflict with the system ones.
905 aPopup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::aria_hidden
, u
"true"_ns
, true);
907 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
908 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
910 popupFrame
->InitializePopupAsNativeContextMenu(triggerContent
, aXPos
, aYPos
);
912 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
913 nsEventStatus status
= FirePopupShowingEvent(pendingPopup
, presContext
);
915 // if the event was cancelled, don't open the popup, reset its state back
916 // to closed and clear its trigger content.
917 if (status
== nsEventStatus_eConsumeNoDefault
) {
918 if ((popupFrame
= GetPopupFrameForContent(aPopup
, true))) {
919 popupFrame
->SetPopupState(ePopupClosed
);
920 popupFrame
->ClearTriggerContent();
926 mNativeMenu
->AddObserver(this);
927 nsIFrame
* frame
= presContext
->PresShell()->GetCurrentEventFrame();
929 frame
= presContext
->PresShell()->GetRootFrame();
931 mNativeMenu
->ShowAsContextMenu(frame
, CSSIntPoint(aXPos
, aYPos
),
934 // While the native menu is open, it consumes mouseup events.
935 // Clear any :active state, mouse capture state and drag tracking now.
936 EventStateManager
* activeESM
= static_cast<EventStateManager
*>(
937 EventStateManager::GetActiveEventStateManager());
939 EventStateManager::ClearGlobalActiveContent(activeESM
);
940 activeESM
->StopTrackingDragGesture(true);
942 PresShell::ReleaseCapturingContent();
947 void nsXULPopupManager::OnNativeMenuOpened() {
952 RefPtr
<nsXULPopupManager
> kungFuDeathGrip(this);
954 nsCOMPtr
<nsIContent
> popup
= mNativeMenu
->Element();
955 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, true);
957 popupFrame
->SetPopupState(ePopupShown
);
961 void nsXULPopupManager::OnNativeMenuClosed() {
966 RefPtr
<nsXULPopupManager
> kungFuDeathGrip(this);
968 bool shouldHideChain
=
969 mNativeMenuActivatedItemCloseMenuMode
== Some(CloseMenuMode_Auto
);
971 nsCOMPtr
<nsIContent
> popup
= mNativeMenu
->Element();
972 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, true);
974 popupFrame
->ClearTriggerContentIncludingDocument();
975 popupFrame
->SetPopupState(ePopupClosed
);
977 mNativeMenu
->RemoveObserver(this);
978 mNativeMenu
= nullptr;
979 mNativeMenuActivatedItemCloseMenuMode
= Nothing();
980 mNativeMenuSubmenuStates
.Clear();
982 // Stop hiding the menu from accessibility code, in case it gets opened as a
983 // non-native menu in the future.
984 popup
->AsElement()->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::aria_hidden
,
987 if (shouldHideChain
&& mPopups
&&
988 mPopups
->GetPopupType() == PopupType::Menu
) {
989 // A menu item was activated before this menu closed, and the item requested
990 // the entire popup chain to be closed, which includes any open non-native
992 // Close the non-native menus now. This matches the HidePopup call in
993 // nsXULMenuCommandEvent::Run.
994 HidePopup(mPopups
->Element(), {HidePopupOption::HideChain
});
998 void nsXULPopupManager::OnNativeSubMenuWillOpen(
999 mozilla::dom::Element
* aPopupElement
) {
1000 mNativeMenuSubmenuStates
.InsertOrUpdate(aPopupElement
, ePopupShowing
);
1003 void nsXULPopupManager::OnNativeSubMenuDidOpen(
1004 mozilla::dom::Element
* aPopupElement
) {
1005 mNativeMenuSubmenuStates
.InsertOrUpdate(aPopupElement
, ePopupShown
);
1008 void nsXULPopupManager::OnNativeSubMenuClosed(
1009 mozilla::dom::Element
* aPopupElement
) {
1010 mNativeMenuSubmenuStates
.Remove(aPopupElement
);
1013 void nsXULPopupManager::OnNativeMenuWillActivateItem(
1014 mozilla::dom::Element
* aMenuItemElement
) {
1019 CloseMenuMode cmm
= GetCloseMenuMode(aMenuItemElement
);
1020 mNativeMenuActivatedItemCloseMenuMode
= Some(cmm
);
1022 if (cmm
== CloseMenuMode_Auto
) {
1023 // If any non-native menus are visible (for example because the context menu
1024 // was opened on a non-native menu item, e.g. in a bookmarks folder), hide
1025 // the non-native menus before executing the item.
1026 HideOpenMenusBeforeExecutingMenu(CloseMenuMode_Auto
);
1030 void nsXULPopupManager::ShowPopupAtScreenRect(
1031 Element
* aPopup
, const nsAString
& aPosition
, const nsIntRect
& aRect
,
1032 bool aIsContextMenu
, bool aAttributesOverride
, Event
* aTriggerEvent
) {
1033 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
1034 if (!popupFrame
|| !MayShowPopup(popupFrame
)) return;
1036 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
1037 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
1039 popupFrame
->InitializePopupAtRect(triggerContent
, aPosition
, aRect
,
1040 aAttributesOverride
);
1042 BeginShowingPopup(pendingPopup
, aIsContextMenu
, false);
1045 void nsXULPopupManager::ShowTooltipAtScreen(
1046 Element
* aPopup
, nsIContent
* aTriggerContent
,
1047 const LayoutDeviceIntPoint
& aScreenPoint
) {
1048 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
1049 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
1053 PendingPopup
pendingPopup(aPopup
, nullptr);
1055 nsPresContext
* pc
= popupFrame
->PresContext();
1056 pendingPopup
.SetMousePoint([&] {
1057 // Event coordinates are relative to the root widget
1058 if (nsPresContext
* rootPresContext
= pc
->GetRootPresContext()) {
1059 if (nsCOMPtr
<nsIWidget
> rootWidget
= rootPresContext
->GetRootWidget()) {
1060 return aScreenPoint
- rootWidget
->WidgetToScreenOffset();
1063 return aScreenPoint
;
1066 auto screenCSSPoint
=
1067 CSSIntPoint::Round(aScreenPoint
/ pc
->CSSToDevPixelScale());
1068 popupFrame
->InitializePopupAtScreen(aTriggerContent
, screenCSSPoint
.x
,
1069 screenCSSPoint
.y
, false);
1071 BeginShowingPopup(pendingPopup
, false, false);
1074 static void CheckCaretDrawingState() {
1075 // There is 1 caret per document, we need to find the focused
1076 // document and erase its caret.
1077 nsFocusManager
* fm
= nsFocusManager::GetFocusManager();
1079 nsCOMPtr
<mozIDOMWindowProxy
> window
;
1080 fm
->GetFocusedWindow(getter_AddRefs(window
));
1081 if (!window
) return;
1083 auto* piWindow
= nsPIDOMWindowOuter::From(window
);
1084 MOZ_ASSERT(piWindow
);
1086 nsCOMPtr
<Document
> focusedDoc
= piWindow
->GetDoc();
1087 if (!focusedDoc
) return;
1089 PresShell
* presShell
= focusedDoc
->GetPresShell();
1094 RefPtr
<nsCaret
> caret
= presShell
->GetCaret();
1096 caret
->SchedulePaint();
1100 void nsXULPopupManager::ShowPopupCallback(Element
* aPopup
,
1101 nsMenuPopupFrame
* aPopupFrame
,
1102 bool aIsContextMenu
,
1103 bool aSelectFirstItem
) {
1104 PopupType popupType
= aPopupFrame
->GetPopupType();
1105 const bool isMenu
= popupType
== PopupType::Menu
;
1107 // Popups normally hide when an outside click occurs. Panels may use
1108 // the noautohide attribute to disable this behaviour. It is expected
1109 // that the application will hide these popups manually. The tooltip
1110 // listener will handle closing the tooltip also.
1112 aPopupFrame
->IsNoAutoHide() || popupType
== PopupType::Tooltip
;
1114 auto item
= MakeUnique
<nsMenuChainItem
>(aPopupFrame
, isNoAutoHide
,
1115 aIsContextMenu
, popupType
);
1117 // install keyboard event listeners for navigating menus. For panels, the
1118 // escape key may be used to close the panel. However, the ignorekeys
1119 // attribute may be used to disable adding these event listeners for popups
1120 // that want to handle their own keyboard events.
1121 nsAutoString ignorekeys
;
1122 aPopup
->GetAttr(nsGkAtoms::ignorekeys
, ignorekeys
);
1123 if (ignorekeys
.EqualsLiteral("true")) {
1124 item
->SetIgnoreKeys(eIgnoreKeys_True
);
1125 } else if (ignorekeys
.EqualsLiteral("shortcuts")) {
1126 item
->SetIgnoreKeys(eIgnoreKeys_Shortcuts
);
1130 // if the menu is on a menubar, use the menubar's listener instead
1131 if (auto* menu
= aPopupFrame
->PopupElement().GetContainingMenu()) {
1132 item
->SetOnMenuBar(menu
->IsOnMenuBar());
1136 // use a weak frame as the popup will set an open attribute if it is a menu
1137 AutoWeakFrame
weakFrame(aPopupFrame
);
1138 aPopupFrame
->ShowPopup(aIsContextMenu
);
1139 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1141 item
->UpdateFollowAnchor();
1143 // popups normally hide when an outside click occurs. Panels may use
1144 // the noautohide attribute to disable this behaviour. It is expected
1145 // that the application will hide these popups manually. The tooltip
1146 // listener will handle closing the tooltip also.
1147 nsIContent
* oldmenu
= nullptr;
1149 oldmenu
= mPopups
->Element();
1151 item
->SetParent(std::move(mPopups
));
1152 mPopups
= std::move(item
);
1153 SetCaptureState(oldmenu
);
1154 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1156 RefPtr popup
= &aPopupFrame
->PopupElement();
1157 popup
->PopupOpened(aSelectFirstItem
);
1160 UpdateMenuItems(aPopup
);
1163 // Caret visibility may have been affected, ensure that
1164 // the caret isn't now drawn when it shouldn't be.
1165 CheckCaretDrawingState();
1168 nsMenuChainItem
* nsXULPopupManager::FindPopup(Element
* aPopup
) const {
1169 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1170 if (item
->Frame()->GetContent() == aPopup
) {
1177 void nsXULPopupManager::HidePopup(Element
* aPopup
, HidePopupOptions aOptions
,
1178 Element
* aLastPopup
) {
1179 if (mNativeMenu
&& mNativeMenu
->Element() == aPopup
) {
1180 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
1181 (void)menu
->Close();
1185 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(aPopup
->GetPrimaryFrame());
1190 nsMenuChainItem
* foundPopup
= FindPopup(aPopup
);
1192 RefPtr
<Element
> popupToHide
, nextPopup
, lastPopup
;
1195 if (foundPopup
->IsNoAutoHide()) {
1196 // If this is a noautohide panel, remove it but don't close any other
1198 popupToHide
= aPopup
;
1199 // XXX This preserves behavior but why is it the right thing to do?
1200 aOptions
-= HidePopupOption::DeselectMenu
;
1202 // At this point, foundPopup will be set to the found item in the list. If
1203 // foundPopup is the topmost menu, the one to remove, then there are no
1204 // other popups to hide. If foundPopup is not the topmost menu, then there
1205 // may be open submenus below it. In this case, we need to make sure that
1206 // those submenus are closed up first. To do this, we scan up the menu
1207 // list to find the topmost popup with only menus between it and
1208 // foundPopup and close that menu first. In synchronous mode, the
1209 // FirePopupHidingEvent method will be called which in turn calls
1210 // HidePopupCallback to close up the next popup in the chain. These two
1211 // methods will be called in sequence recursively to close up all the
1212 // necessary popups. In asynchronous mode, a similar process occurs except
1213 // that the FirePopupHidingEvent method is called asynchronously. In
1214 // either case, nextPopup is set to the content node of the next popup to
1215 // close, and lastPopup is set to the last popup in the chain to close,
1216 // which will be aPopup, or null to close up all menus.
1218 nsMenuChainItem
* topMenu
= foundPopup
;
1219 // Use IsMenu to ensure that foundPopup is a menu and scan down the child
1220 // list until a non-menu is found. If foundPopup isn't a menu at all,
1221 // don't scan and just close up this menu.
1222 if (foundPopup
->IsMenu()) {
1223 nsMenuChainItem
* child
= foundPopup
->GetChild();
1224 while (child
&& child
->IsMenu()) {
1226 child
= child
->GetChild();
1230 popupToHide
= topMenu
->Element();
1231 popupFrame
= topMenu
->Frame();
1233 const bool hideChain
= aOptions
.contains(HidePopupOption::HideChain
);
1235 // Close up another popup if there is one, and we are either hiding the
1236 // entire chain or the item to hide isn't the topmost popup.
1237 nsMenuChainItem
* parent
= topMenu
->GetParent();
1238 if (parent
&& (hideChain
|| topMenu
!= foundPopup
)) {
1239 while (parent
&& parent
->IsNoAutoHide()) {
1240 parent
= parent
->GetParent();
1244 nextPopup
= parent
->Element();
1248 lastPopup
= aLastPopup
? aLastPopup
: (hideChain
? nullptr : aPopup
);
1250 } else if (popupFrame
->PopupState() == ePopupPositioning
) {
1251 // When the popup is in the popuppositioning state, it will not be in the
1252 // mPopups list. We need another way to find it and make sure it does not
1253 // continue the popup showing process.
1254 popupToHide
= aPopup
;
1261 nsPopupState state
= popupFrame
->PopupState();
1262 if (state
== ePopupHiding
) {
1263 // If the popup is already being hidden, don't fire another popuphiding
1264 // event. But finish hiding it sync if we need to.
1265 if (aOptions
.contains(HidePopupOption::DisableAnimations
) &&
1266 !aOptions
.contains(HidePopupOption::Async
)) {
1267 HidePopupCallback(popupToHide
, popupFrame
, nullptr, nullptr,
1268 popupFrame
->GetPopupType(), aOptions
);
1273 // Change the popup state to hiding. Don't set the hiding state if the
1274 // popup is invisible, otherwise nsMenuPopupFrame::HidePopup will
1275 // run again. In the invisible state, we just want the events to fire.
1276 if (state
!= ePopupInvisible
) {
1277 popupFrame
->SetPopupState(ePopupHiding
);
1280 // For menus, popupToHide is always the frontmost item in the list to hide.
1281 if (aOptions
.contains(HidePopupOption::Async
)) {
1282 nsCOMPtr
<nsIRunnable
> event
=
1283 new nsXULPopupHidingEvent(popupToHide
, nextPopup
, lastPopup
,
1284 popupFrame
->GetPopupType(), aOptions
);
1285 aPopup
->OwnerDoc()->Dispatch(TaskCategory::Other
, event
.forget());
1287 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1288 FirePopupHidingEvent(popupToHide
, nextPopup
, lastPopup
, presContext
,
1289 popupFrame
->GetPopupType(), aOptions
);
1293 void nsXULPopupManager::HideMenu(nsIContent
* aMenu
) {
1294 if (mNativeMenu
&& aMenu
->IsElement() &&
1295 mNativeMenu
->Element()->Contains(aMenu
)) {
1296 mNativeMenu
->CloseSubmenu(aMenu
->AsElement());
1300 auto* button
= XULButtonElement::FromNode(aMenu
);
1301 if (!button
|| !button
->IsMenu()) {
1304 auto* popup
= button
->GetMenuPopupContent();
1308 HidePopup(popup
, {HidePopupOption::DeselectMenu
});
1311 // This is used to hide the popup after a transition finishes.
1312 class TransitionEnder final
: public nsIDOMEventListener
{
1314 // Effectively const but is cycle collected
1315 MOZ_KNOWN_LIVE RefPtr
<Element
> mElement
;
1318 virtual ~TransitionEnder() = default;
1321 HidePopupOptions mOptions
;
1323 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
1324 NS_DECL_CYCLE_COLLECTION_CLASS(TransitionEnder
)
1326 TransitionEnder(Element
* aElement
, HidePopupOptions aOptions
)
1327 : mElement(aElement
), mOptions(aOptions
) {}
1329 MOZ_CAN_RUN_SCRIPT NS_IMETHOD
HandleEvent(Event
* aEvent
) override
{
1330 mElement
->RemoveSystemEventListener(u
"transitionend"_ns
, this, false);
1331 mElement
->RemoveSystemEventListener(u
"transitioncancel"_ns
, this, false);
1333 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(mElement
->GetPrimaryFrame());
1334 if (!popupFrame
|| popupFrame
->PopupState() != ePopupHiding
) {
1338 // Now hide the popup. There could be other properties transitioning, but
1339 // we'll assume they all end at the same time and just hide the popup upon
1340 // the first one ending.
1341 if (RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance()) {
1342 pm
->HidePopupCallback(mElement
, popupFrame
, nullptr, nullptr,
1343 popupFrame
->GetPopupType(), mOptions
);
1350 NS_IMPL_CYCLE_COLLECTING_ADDREF(TransitionEnder
)
1351 NS_IMPL_CYCLE_COLLECTING_RELEASE(TransitionEnder
)
1352 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TransitionEnder
)
1353 NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener
)
1354 NS_INTERFACE_MAP_ENTRY(nsISupports
)
1355 NS_INTERFACE_MAP_END
1357 NS_IMPL_CYCLE_COLLECTION(TransitionEnder
, mElement
);
1358 void nsXULPopupManager::HidePopupCallback(
1359 Element
* aPopup
, nsMenuPopupFrame
* aPopupFrame
, Element
* aNextPopup
,
1360 Element
* aLastPopup
, PopupType aPopupType
, HidePopupOptions aOptions
) {
1361 if (mCloseTimer
&& mTimerMenu
== aPopupFrame
) {
1362 mCloseTimer
->Cancel();
1363 mCloseTimer
= nullptr;
1364 mTimerMenu
= nullptr;
1367 // The popup to hide is aPopup. Search the list again to find the item that
1368 // corresponds to the popup to hide aPopup. This is done because it's
1369 // possible someone added another item (attempted to open another popup)
1370 // or removed a popup frame during the event processing so the item isn't at
1371 // the front anymore.
1372 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1373 if (item
->Element() == aPopup
) {
1374 RemoveMenuChainItem(item
);
1375 SetCaptureState(aPopup
);
1380 AutoWeakFrame
weakFrame(aPopupFrame
);
1381 aPopupFrame
->HidePopup(aOptions
.contains(HidePopupOption::DeselectMenu
),
1383 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1385 // send the popuphidden event synchronously. This event has no default
1387 nsEventStatus status
= nsEventStatus_eIgnore
;
1388 WidgetMouseEvent
event(true, eXULPopupHidden
, nullptr,
1389 WidgetMouseEvent::eReal
);
1390 RefPtr
<nsPresContext
> presContext
= aPopupFrame
->PresContext();
1391 EventDispatcher::Dispatch(aPopup
, presContext
, &event
, nullptr, &status
);
1392 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1394 // Force any popups that might be anchored on elements within this popup to
1396 UpdatePopupPositions(presContext
->RefreshDriver());
1398 // if there are more popups to close, look for the next one
1399 if (aNextPopup
&& aPopup
!= aLastPopup
) {
1400 nsMenuChainItem
* foundMenu
= FindPopup(aNextPopup
);
1402 // continue hiding the chain of popups until the last popup aLastPopup
1403 // is reached, or until a popup of a different type is reached. This
1404 // last check is needed so that a menulist inside a non-menu panel only
1405 // closes the menu and not the panel as well.
1406 if (foundMenu
&& (aLastPopup
|| aPopupType
== foundMenu
->GetPopupType())) {
1407 nsCOMPtr
<Element
> popupToHide
= foundMenu
->Element();
1408 nsMenuChainItem
* parent
= foundMenu
->GetParent();
1410 nsCOMPtr
<Element
> nextPopup
;
1411 if (parent
&& popupToHide
!= aLastPopup
) nextPopup
= parent
->Element();
1413 nsMenuPopupFrame
* popupFrame
= foundMenu
->Frame();
1414 nsPopupState state
= popupFrame
->PopupState();
1415 if (state
== ePopupHiding
) return;
1416 if (state
!= ePopupInvisible
) popupFrame
->SetPopupState(ePopupHiding
);
1418 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1419 FirePopupHidingEvent(popupToHide
, nextPopup
, aLastPopup
, presContext
,
1420 foundMenu
->GetPopupType(), aOptions
);
1425 void nsXULPopupManager::HidePopupAfterDelay(nsMenuPopupFrame
* aPopup
,
1427 // Don't close up immediately.
1428 // Kick off a close timer.
1431 // Kick off the timer.
1432 nsIEventTarget
* target
=
1433 aPopup
->PopupElement().OwnerDoc()->EventTargetFor(TaskCategory::Other
);
1434 NS_NewTimerWithFuncCallback(
1435 getter_AddRefs(mCloseTimer
),
1436 [](nsITimer
* aTimer
, void* aClosure
) {
1437 if (nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance()) {
1438 pm
->KillMenuTimer();
1441 nullptr, aDelay
, nsITimer::TYPE_ONE_SHOT
, "KillMenuTimer", target
);
1442 // the popup will call PopupDestroyed if it is destroyed, which checks if it
1443 // is set to mTimerMenu, so it should be safe to keep a reference to it
1444 mTimerMenu
= aPopup
;
1447 void nsXULPopupManager::HidePopupsInList(
1448 const nsTArray
<nsMenuPopupFrame
*>& aFrames
) {
1449 // Create a weak frame list. This is done in a separate array with the
1450 // right capacity predetermined to avoid multiple allocations.
1451 nsTArray
<WeakFrame
> weakPopups(aFrames
.Length());
1453 for (f
= 0; f
< aFrames
.Length(); f
++) {
1454 WeakFrame
* wframe
= weakPopups
.AppendElement();
1455 if (wframe
) *wframe
= aFrames
[f
];
1458 for (f
= 0; f
< weakPopups
.Length(); f
++) {
1459 // check to ensure that the frame is still alive before hiding it.
1460 if (weakPopups
[f
].IsAlive()) {
1461 auto* frame
= static_cast<nsMenuPopupFrame
*>(weakPopups
[f
].GetFrame());
1462 frame
->HidePopup(true, ePopupInvisible
);
1466 SetCaptureState(nullptr);
1469 bool nsXULPopupManager::IsChildOfDocShell(Document
* aDoc
,
1470 nsIDocShellTreeItem
* aExpected
) {
1471 nsCOMPtr
<nsIDocShellTreeItem
> docShellItem(aDoc
->GetDocShell());
1472 while (docShellItem
) {
1473 if (docShellItem
== aExpected
) return true;
1475 nsCOMPtr
<nsIDocShellTreeItem
> parent
;
1476 docShellItem
->GetInProcessParent(getter_AddRefs(parent
));
1477 docShellItem
= parent
;
1483 void nsXULPopupManager::HidePopupsInDocShell(
1484 nsIDocShellTreeItem
* aDocShellToHide
) {
1485 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
1487 // Iterate to get the set of popup frames to hide
1488 nsMenuChainItem
* item
= mPopups
.get();
1490 // Get the parent before calling detach so that we can keep iterating.
1491 nsMenuChainItem
* parent
= item
->GetParent();
1492 if (item
->Frame()->PopupState() != ePopupInvisible
&&
1493 IsChildOfDocShell(item
->Element()->OwnerDoc(), aDocShellToHide
)) {
1494 nsMenuPopupFrame
* frame
= item
->Frame();
1495 RemoveMenuChainItem(item
);
1496 popupsToHide
.AppendElement(frame
);
1501 HidePopupsInList(popupsToHide
);
1504 void nsXULPopupManager::UpdatePopupPositions(nsRefreshDriver
* aRefreshDriver
) {
1505 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1506 if (item
->Frame()->PresContext()->RefreshDriver() == aRefreshDriver
) {
1507 item
->CheckForAnchorChange();
1512 void nsXULPopupManager::UpdateFollowAnchor(nsMenuPopupFrame
* aPopup
) {
1513 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1514 if (item
->Frame() == aPopup
) {
1515 item
->UpdateFollowAnchor();
1521 void nsXULPopupManager::HideOpenMenusBeforeExecutingMenu(CloseMenuMode aMode
) {
1522 if (aMode
== CloseMenuMode_None
) {
1526 // When a menuitem is selected to be executed, first hide all the open
1527 // popups, but don't remove them yet. This is needed when a menu command
1528 // opens a modal dialog. The views associated with the popups needed to be
1529 // hidden and the accesibility events fired before the command executes, but
1530 // the popuphiding/popuphidden events are fired afterwards.
1531 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
1532 nsMenuChainItem
* item
= GetTopVisibleMenu();
1534 // if it isn't a <menupopup>, don't close it automatically
1535 if (!item
->IsMenu()) {
1539 nsMenuChainItem
* next
= item
->GetParent();
1540 popupsToHide
.AppendElement(item
->Frame());
1541 if (aMode
== CloseMenuMode_Single
) {
1542 // only close one level of menu
1548 // Now hide the popups. If the closemenu mode is auto, deselect the menu,
1549 // otherwise only one popup is closing, so keep the parent menu selected.
1550 HidePopupsInList(popupsToHide
);
1553 void nsXULPopupManager::ExecuteMenu(nsIContent
* aMenu
,
1554 nsXULMenuCommandEvent
* aEvent
) {
1555 CloseMenuMode cmm
= GetCloseMenuMode(aMenu
);
1556 HideOpenMenusBeforeExecutingMenu(cmm
);
1557 aEvent
->SetCloseMenuMode(cmm
);
1558 nsCOMPtr
<nsIRunnable
> event
= aEvent
;
1559 aMenu
->OwnerDoc()->Dispatch(TaskCategory::Other
, event
.forget());
1562 bool nsXULPopupManager::ActivateNativeMenuItem(nsIContent
* aItem
,
1563 mozilla::Modifiers aModifiers
,
1565 mozilla::ErrorResult
& aRv
) {
1566 if (mNativeMenu
&& aItem
->IsElement() &&
1567 mNativeMenu
->Element()->Contains(aItem
)) {
1568 mNativeMenu
->ActivateItem(aItem
->AsElement(), aModifiers
, aButton
, aRv
);
1574 nsEventStatus
nsXULPopupManager::FirePopupShowingEvent(
1575 const PendingPopup
& aPendingPopup
, nsPresContext
* aPresContext
) {
1576 // Cache the pending popup so that the trigger node and other properties can
1577 // be retrieved during the popupshowing event. It will be cleared below after
1578 // the event has fired.
1579 AutoRestore
<const PendingPopup
*> restorePendingPopup(mPendingPopup
);
1580 mPendingPopup
= &aPendingPopup
;
1582 nsEventStatus status
= nsEventStatus_eIgnore
;
1583 WidgetMouseEvent
event(true, eXULPopupShowing
, nullptr,
1584 WidgetMouseEvent::eReal
);
1586 // coordinates are relative to the root widget
1587 nsPresContext
* rootPresContext
= aPresContext
->GetRootPresContext();
1588 if (rootPresContext
) {
1590 rootPresContext
->PresShell()->GetViewManager()->GetRootWidget();
1592 event
.mWidget
= nullptr;
1595 event
.mInputSource
= aPendingPopup
.MouseInputSource();
1596 event
.mRefPoint
= aPendingPopup
.mMousePoint
;
1597 event
.mModifiers
= aPendingPopup
.mModifiers
;
1598 RefPtr
<nsIContent
> popup
= aPendingPopup
.mPopup
;
1599 EventDispatcher::Dispatch(popup
, aPresContext
, &event
, nullptr, &status
);
1604 void nsXULPopupManager::BeginShowingPopup(const PendingPopup
& aPendingPopup
,
1605 bool aIsContextMenu
,
1606 bool aSelectFirstItem
) {
1607 RefPtr
<Element
> popup
= aPendingPopup
.mPopup
;
1609 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(popup
->GetPrimaryFrame());
1610 if (NS_WARN_IF(!popupFrame
)) {
1614 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1615 RefPtr
<PresShell
> presShell
= presContext
->PresShell();
1616 presShell
->FrameNeedsReflow(popupFrame
, IntrinsicDirty::FrameAndAncestors
,
1619 PopupType popupType
= popupFrame
->GetPopupType();
1621 nsEventStatus status
= FirePopupShowingEvent(aPendingPopup
, presContext
);
1623 // if a panel, blur whatever has focus so that the panel can take the focus.
1624 // This is done after the popupshowing event in case that event is cancelled.
1625 // Using noautofocus="true" will disable this behaviour, which is needed for
1626 // the autocomplete widget as it manages focus itself.
1627 if (popupType
== PopupType::Panel
&&
1628 !popup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::noautofocus
,
1629 nsGkAtoms::_true
, eCaseMatters
)) {
1630 if (RefPtr
<nsFocusManager
> fm
= nsFocusManager::GetFocusManager()) {
1631 Document
* doc
= popup
->GetUncomposedDoc();
1633 // Only remove the focus if the currently focused item is ouside the
1634 // popup. It isn't a big deal if the current focus is in a child popup
1635 // inside the popup as that shouldn't be visible. This check ensures that
1636 // a node inside the popup that is focused during a popupshowing event
1638 RefPtr
<Element
> currentFocus
= fm
->GetFocusedElement();
1639 if (doc
&& currentFocus
&&
1640 !nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus
, popup
)) {
1641 nsCOMPtr
<nsPIDOMWindowOuter
> outerWindow
= doc
->GetWindow();
1642 fm
->ClearFocus(outerWindow
);
1647 popup
->OwnerDoc()->FlushPendingNotifications(FlushType::Frames
);
1649 // get the frame again in case it went away
1650 popupFrame
= do_QueryFrame(popup
->GetPrimaryFrame());
1654 // if the event was cancelled or the popup was closed in the mean time, don't
1655 // open the popup, reset its state back to closed and clear its trigger
1657 if (popupFrame
->PopupState() == ePopupClosed
||
1658 status
== nsEventStatus_eConsumeNoDefault
) {
1659 popupFrame
->SetPopupState(ePopupClosed
);
1660 popupFrame
->ClearTriggerContent();
1663 // Now check if we need to fire the popuppositioned event. If not, call
1664 // ShowPopupCallback directly.
1665 // The popuppositioned event only fires on arrow panels for now.
1666 if (popup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
,
1668 popupFrame
->ShowWithPositionedEvent();
1669 presShell
->FrameNeedsReflow(popupFrame
, IntrinsicDirty::FrameAndAncestors
,
1670 NS_FRAME_HAS_DIRTY_CHILDREN
);
1672 ShowPopupCallback(popup
, popupFrame
, aIsContextMenu
, aSelectFirstItem
);
1676 void nsXULPopupManager::FirePopupHidingEvent(Element
* aPopup
,
1677 Element
* aNextPopup
,
1678 Element
* aLastPopup
,
1679 nsPresContext
* aPresContext
,
1680 PopupType aPopupType
,
1681 HidePopupOptions aOptions
) {
1682 nsCOMPtr
<nsIContent
> popup
= aPopup
;
1683 RefPtr
<PresShell
> presShell
= aPresContext
->PresShell();
1684 Unused
<< presShell
; // This presShell may be keeping things alive
1685 // on non GTK platforms
1687 nsEventStatus status
= nsEventStatus_eIgnore
;
1688 WidgetMouseEvent
event(true, eXULPopupHiding
, nullptr,
1689 WidgetMouseEvent::eReal
);
1690 EventDispatcher::Dispatch(aPopup
, aPresContext
, &event
, nullptr, &status
);
1692 // when a panel is closed, blur whatever has focus inside the popup
1693 if (aPopupType
== PopupType::Panel
&&
1694 (!aPopup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::noautofocus
,
1695 nsGkAtoms::_true
, eCaseMatters
))) {
1696 if (RefPtr
<nsFocusManager
> fm
= nsFocusManager::GetFocusManager()) {
1697 Document
* doc
= aPopup
->GetUncomposedDoc();
1699 // Remove the focus from the focused node only if it is inside the popup.
1700 RefPtr
<Element
> currentFocus
= fm
->GetFocusedElement();
1701 if (doc
&& currentFocus
&&
1702 nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus
, aPopup
)) {
1703 nsCOMPtr
<nsPIDOMWindowOuter
> outerWindow
= doc
->GetWindow();
1704 fm
->ClearFocus(outerWindow
);
1709 aPopup
->OwnerDoc()->FlushPendingNotifications(FlushType::Frames
);
1711 // get frame again in case it went away
1712 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(aPopup
->GetPrimaryFrame());
1717 // If the event was cancelled, don't hide the popup, and reset its
1718 // state back to open. Only popups in chrome shells can prevent a popup
1720 if (status
== nsEventStatus_eConsumeNoDefault
&&
1721 !popupFrame
->IsInContentShell()) {
1723 // If an attempt was made to hide this popup before the popupshown event
1724 // fired, then ePopupShown is set here even though it should be
1725 // ePopupVisible. This probably isn't worth the hassle of handling.
1726 popupFrame
->SetPopupState(ePopupShown
);
1730 const bool shouldAnimate
= [&] {
1731 if (!LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations
)) {
1732 // Animations are not supported by the platform, avoid transitioning.
1735 if (aOptions
.contains(HidePopupOption::DisableAnimations
)) {
1736 // Animations are not allowed by our caller.
1740 // If there is a next popup, indicating that mutliple popups are rolling
1741 // up, don't wait and hide the popup right away since the effect would
1742 // likely be undesirable.
1745 nsAutoString animate
;
1746 if (!aPopup
->GetAttr(nsGkAtoms::animate
, animate
)) {
1749 // If animate="false" then don't transition at all.
1750 if (animate
.EqualsLiteral("false")) {
1753 // If animate="cancel", only show the transition if cancelling the popup
1755 if (animate
.EqualsLiteral("cancel") &&
1756 !aOptions
.contains(HidePopupOption::IsRollup
)) {
1761 // If we should animate the popup, check if it has a closing transition
1762 // and wait for it to finish.
1763 // The transition would still occur either way, but if we don't wait the
1764 // view will be hidden and you won't be able to see it.
1765 if (shouldAnimate
&& AnimationUtils::HasCurrentTransitions(
1766 aPopup
, PseudoStyleType::NotPseudo
)) {
1767 RefPtr
<TransitionEnder
> ender
= new TransitionEnder(aPopup
, aOptions
);
1768 aPopup
->AddSystemEventListener(u
"transitionend"_ns
, ender
, false, false);
1769 aPopup
->AddSystemEventListener(u
"transitioncancel"_ns
, ender
, false, false);
1773 HidePopupCallback(aPopup
, popupFrame
, aNextPopup
, aLastPopup
, aPopupType
,
1777 bool nsXULPopupManager::IsPopupOpen(Element
* aPopup
) {
1778 if (mNativeMenu
&& mNativeMenu
->Element() == aPopup
) {
1782 // a popup is open if it is in the open list. The assertions ensure that the
1783 // frame is in the correct state. If the popup is in the hiding or invisible
1784 // state, it will still be in the open popup list until it is closed.
1785 if (nsMenuChainItem
* item
= FindPopup(aPopup
)) {
1786 NS_ASSERTION(item
->Frame()->IsOpen() ||
1787 item
->Frame()->PopupState() == ePopupHiding
||
1788 item
->Frame()->PopupState() == ePopupInvisible
,
1789 "popup in open list not actually open");
1796 nsIFrame
* nsXULPopupManager::GetTopPopup(PopupType aType
) {
1797 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1798 if (item
->Frame()->IsVisible() &&
1799 (item
->GetPopupType() == aType
|| aType
== PopupType::Any
)) {
1800 return item
->Frame();
1806 nsIContent
* nsXULPopupManager::GetTopActiveMenuItemContent() {
1807 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1808 if (!item
->Frame()->IsVisible()) {
1811 if (auto* content
= item
->Frame()->PopupElement().GetActiveMenuChild()) {
1818 void nsXULPopupManager::GetVisiblePopups(nsTArray
<nsIFrame
*>& aPopups
) {
1820 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1821 // Skip panels which are not visible as well as popups that are transparent
1823 if (item
->Frame()->IsVisible() && !item
->Frame()->IsMouseTransparent()) {
1824 aPopups
.AppendElement(item
->Frame());
1829 already_AddRefed
<nsINode
> nsXULPopupManager::GetLastTriggerNode(
1830 Document
* aDocument
, bool aIsTooltip
) {
1831 if (!aDocument
) return nullptr;
1833 RefPtr
<nsINode
> node
;
1835 // If a pending popup is set, it means that a popupshowing event is being
1836 // fired. In this case, just use the cached node, as the popup is not yet in
1837 // the list of open popups.
1838 RefPtr
<nsIContent
> openingPopup
=
1839 mPendingPopup
? mPendingPopup
->mPopup
: nullptr;
1840 if (openingPopup
&& openingPopup
->GetUncomposedDoc() == aDocument
&&
1841 aIsTooltip
== openingPopup
->IsXULElement(nsGkAtoms::tooltip
)) {
1842 node
= nsMenuPopupFrame::GetTriggerContent(
1843 GetPopupFrameForContent(openingPopup
, false));
1844 } else if (mNativeMenu
&& !aIsTooltip
) {
1845 RefPtr
<dom::Element
> popup
= mNativeMenu
->Element();
1846 if (popup
->GetUncomposedDoc() == aDocument
) {
1847 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, false);
1848 node
= nsMenuPopupFrame::GetTriggerContent(popupFrame
);
1851 for (nsMenuChainItem
* item
= mPopups
.get(); item
;
1852 item
= item
->GetParent()) {
1853 // look for a popup of the same type and document.
1854 if ((item
->GetPopupType() == PopupType::Tooltip
) == aIsTooltip
&&
1855 item
->Element()->GetUncomposedDoc() == aDocument
) {
1856 node
= nsMenuPopupFrame::GetTriggerContent(item
->Frame());
1864 return node
.forget();
1867 bool nsXULPopupManager::MayShowPopup(nsMenuPopupFrame
* aPopup
) {
1868 // if a popup's IsOpen method returns true, then the popup must always be in
1869 // the popup chain scanned in IsPopupOpen.
1870 NS_ASSERTION(!aPopup
->IsOpen() || IsPopupOpen(&aPopup
->PopupElement()),
1871 "popup frame state doesn't match XULPopupManager open state");
1873 nsPopupState state
= aPopup
->PopupState();
1875 // if the popup is not in the open popup chain, then it must have a state that
1876 // is either closed, in the process of being shown, or invisible.
1877 NS_ASSERTION(IsPopupOpen(&aPopup
->PopupElement()) || state
== ePopupClosed
||
1878 state
== ePopupShowing
|| state
== ePopupPositioning
||
1879 state
== ePopupInvisible
,
1880 "popup not in XULPopupManager open list is open");
1882 // don't show popups unless they are closed or invisible
1883 if (state
!= ePopupClosed
&& state
!= ePopupInvisible
) return false;
1885 // Don't show popups that we already have in our popup chain
1886 if (IsPopupOpen(&aPopup
->PopupElement())) {
1887 NS_WARNING("Refusing to show duplicate popup");
1891 // if the popup was just rolled up, don't reopen it
1892 if (mozilla::widget::nsAutoRollup::GetLastRollup() == aPopup
->GetContent()) {
1896 nsCOMPtr
<nsIDocShell
> docShell
= aPopup
->PresContext()->GetDocShell();
1898 nsCOMPtr
<nsIBaseWindow
> baseWin
= do_QueryInterface(docShell
);
1903 nsCOMPtr
<nsIDocShellTreeItem
> root
;
1904 docShell
->GetInProcessRootTreeItem(getter_AddRefs(root
));
1909 nsCOMPtr
<nsPIDOMWindowOuter
> rootWin
= root
->GetWindow();
1911 MOZ_RELEASE_ASSERT(XRE_IsParentProcess(),
1912 "Cannot have XUL in content process showing popups.");
1914 // chrome shells can always open popups, but other types of shells can only
1915 // open popups when they are focused and visible
1916 if (docShell
->ItemType() != nsIDocShellTreeItem::typeChrome
) {
1917 // only allow popups in active windows
1918 nsFocusManager
* fm
= nsFocusManager::GetFocusManager();
1919 if (!fm
|| !rootWin
) {
1923 nsCOMPtr
<nsPIDOMWindowOuter
> activeWindow
= fm
->GetActiveWindow();
1924 if (activeWindow
!= rootWin
) {
1928 // only allow popups in visible frames
1929 // TODO: This visibility check should be replaced with a check of
1930 // bc->IsActive(). It is okay for now since this is only called
1931 // in the parent process. Bug 1698533.
1933 baseWin
->GetVisibility(&visible
);
1939 // platforms respond differently when an popup is opened in a minimized
1940 // window, so this is always disabled.
1941 nsCOMPtr
<nsIWidget
> mainWidget
;
1942 baseWin
->GetMainWidget(getter_AddRefs(mainWidget
));
1943 if (mainWidget
&& mainWidget
->SizeMode() == nsSizeMode_Minimized
) {
1949 auto globalWin
= nsGlobalWindowOuter::Cast(rootWin
.get());
1950 if (globalWin
->IsInModalState()) {
1956 // cannot open a popup that is a submenu of a menupopup that isn't open.
1957 if (auto* menu
= aPopup
->PopupElement().GetContainingMenu()) {
1958 if (auto* parent
= XULPopupElement::FromNodeOrNull(menu
->GetMenuParent())) {
1959 nsMenuPopupFrame
* f
= do_QueryFrame(parent
->GetPrimaryFrame());
1960 if (f
&& !f
->IsOpen()) {
1969 void nsXULPopupManager::PopupDestroyed(nsMenuPopupFrame
* aPopup
) {
1970 // when a popup frame is destroyed, just unhook it from the list of popups
1971 CancelMenuTimer(aPopup
);
1973 nsMenuChainItem
* item
= FindPopup(&aPopup
->PopupElement());
1978 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
1979 // XXXndeakin shouldn't this only happen for menus?
1980 if (!item
->IsNoAutoHide() && item
->Frame()->PopupState() != ePopupInvisible
) {
1981 // Iterate through any child menus and hide them as well, since the
1982 // parent is going away. We won't remove them from the list yet, just
1983 // hide them, as they will be removed from the list when this function
1984 // gets called for that child frame.
1985 for (auto* child
= item
->GetChild(); child
; child
= child
->GetChild()) {
1986 // If the popup is a child frame of the menu that was destroyed, add it
1987 // to the list of popups to hide. Don't bother with the events since the
1988 // frames are going away. If the child menu is not a child frame, for
1989 // example, a context menu, use HidePopup instead, but call it
1990 // asynchronously since we are in the middle of frame destruction.
1991 if (nsLayoutUtils::IsProperAncestorFrame(item
->Frame(), child
->Frame())) {
1992 popupsToHide
.AppendElement(child
->Frame());
1994 // HidePopup will take care of hiding any of its children, so
1995 // break out afterwards
1996 HidePopup(child
->Element(), {HidePopupOption::Async
});
2002 RemoveMenuChainItem(item
);
2003 HidePopupsInList(popupsToHide
);
2006 bool nsXULPopupManager::HasContextMenu(nsMenuPopupFrame
* aPopup
) {
2007 nsMenuChainItem
* item
= GetTopVisibleMenu();
2008 while (item
&& item
->Frame() != aPopup
) {
2009 if (item
->IsContextMenu()) return true;
2010 item
= item
->GetParent();
2016 void nsXULPopupManager::SetCaptureState(nsIContent
* aOldPopup
) {
2017 nsMenuChainItem
* item
= GetTopVisibleMenu();
2018 if (item
&& aOldPopup
== item
->Element()) return;
2021 mWidget
->CaptureRollupEvents(false);
2026 nsMenuPopupFrame
* popup
= item
->Frame();
2027 mWidget
= popup
->GetWidget();
2029 mWidget
->CaptureRollupEvents(true);
2033 UpdateKeyboardListeners();
2036 void nsXULPopupManager::UpdateKeyboardListeners() {
2037 nsCOMPtr
<EventTarget
> newTarget
;
2038 bool isForMenu
= false;
2039 if (nsMenuChainItem
* item
= GetTopVisibleMenu()) {
2040 if (item
->IgnoreKeys() != eIgnoreKeys_True
) {
2041 newTarget
= item
->Element()->GetComposedDoc();
2043 isForMenu
= item
->GetPopupType() == PopupType::Menu
;
2044 } else if (mActiveMenuBar
&& mActiveMenuBar
->IsActiveByKeyboard()) {
2045 // Only listen for key events iff menubar is activated via key, see
2047 newTarget
= mActiveMenuBar
->GetComposedDoc();
2051 if (mKeyListener
!= newTarget
) {
2052 OwningNonNull
<nsXULPopupManager
> kungFuDeathGrip(*this);
2054 mKeyListener
->RemoveEventListener(u
"keypress"_ns
, this, true);
2055 mKeyListener
->RemoveEventListener(u
"keydown"_ns
, this, true);
2056 mKeyListener
->RemoveEventListener(u
"keyup"_ns
, this, true);
2057 mKeyListener
= nullptr;
2058 nsContentUtils::NotifyInstalledMenuKeyboardListener(false);
2062 newTarget
->AddEventListener(u
"keypress"_ns
, this, true);
2063 newTarget
->AddEventListener(u
"keydown"_ns
, this, true);
2064 newTarget
->AddEventListener(u
"keyup"_ns
, this, true);
2065 nsContentUtils::NotifyInstalledMenuKeyboardListener(isForMenu
);
2066 mKeyListener
= newTarget
;
2071 void nsXULPopupManager::UpdateMenuItems(Element
* aPopup
) {
2072 // Walk all of the menu's children, checking to see if any of them has a
2073 // command attribute. If so, then several attributes must potentially be
2076 nsCOMPtr
<Document
> document
= aPopup
->GetUncomposedDoc();
2081 // When a menu is opened, make sure that command updating is unlocked first.
2082 nsCOMPtr
<nsIDOMXULCommandDispatcher
> commandDispatcher
=
2083 document
->GetCommandDispatcher();
2084 if (commandDispatcher
) {
2085 commandDispatcher
->Unlock();
2088 for (nsCOMPtr
<nsIContent
> grandChild
= aPopup
->GetFirstChild(); grandChild
;
2089 grandChild
= grandChild
->GetNextSibling()) {
2090 if (grandChild
->IsXULElement(nsGkAtoms::menugroup
)) {
2091 if (grandChild
->GetChildCount() == 0) {
2094 grandChild
= grandChild
->GetFirstChild();
2096 if (grandChild
->IsXULElement(nsGkAtoms::menuitem
)) {
2097 // See if we have a command attribute.
2098 Element
* grandChildElement
= grandChild
->AsElement();
2099 nsAutoString command
;
2100 grandChildElement
->GetAttr(nsGkAtoms::command
, command
);
2101 if (!command
.IsEmpty()) {
2102 // We do! Look it up in our document
2103 RefPtr
<dom::Element
> commandElement
= document
->GetElementById(command
);
2104 if (commandElement
) {
2105 nsAutoString commandValue
;
2106 // The menu's disabled state needs to be updated to match the command.
2107 if (commandElement
->GetAttr(nsGkAtoms::disabled
, commandValue
))
2108 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::disabled
,
2109 commandValue
, true);
2111 grandChildElement
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::disabled
,
2114 // The menu's label, accesskey checked and hidden states need to be
2115 // updated to match the command. Note that unlike the disabled state
2116 // if the command has *no* value, we assume the menu is supplying its
2118 if (commandElement
->GetAttr(nsGkAtoms::label
, commandValue
))
2119 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::label
,
2120 commandValue
, true);
2122 if (commandElement
->GetAttr(nsGkAtoms::accesskey
, commandValue
))
2123 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::accesskey
,
2124 commandValue
, true);
2126 if (commandElement
->GetAttr(nsGkAtoms::checked
, commandValue
))
2127 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::checked
,
2128 commandValue
, true);
2130 if (commandElement
->GetAttr(nsGkAtoms::hidden
, commandValue
))
2131 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::hidden
,
2132 commandValue
, true);
2136 if (!grandChild
->GetNextSibling() &&
2137 grandChild
->GetParent()->IsXULElement(nsGkAtoms::menugroup
)) {
2138 grandChild
= grandChild
->GetParent();
2145 // The item selection timer has fired, we might have to readjust the
2146 // selected item. There are two cases here that we are trying to deal with:
2147 // (1) diagonal movement from a parent menu to a submenu passing briefly over
2149 // (2) moving out from a submenu to a parent or grandparent menu.
2150 // In both cases, |mTimerMenu| is the menu item that might have an open submenu
2151 // and the first item in |mPopups| is the item the mouse is currently over,
2152 // which could be none of them.
2155 // As the mouse moves from the parent item of a submenu (we'll call 'A')
2156 // diagonally into the submenu, it probably passes through one or more
2157 // sibilings (B). As the mouse passes through B, it becomes the current menu
2158 // item and the timer is set and mTimerMenu is set to A. Before the timer
2159 // fires, the mouse leaves the menu containing A and B and enters the submenus.
2160 // Now when the timer fires, |mPopups| is null (!= |mTimerMenu|) so we have to
2161 // see if anything in A's children is selected (recall that even disabled items
2162 // are selected, the style just doesn't show it). If that is the case, we need
2163 // to set the selected item back to A.
2166 // Item A has an open submenu, and in it there is an item (B) which also has an
2167 // open submenu (so there are 3 menus displayed right now). The mouse then
2168 // leaves B's child submenu and selects an item that is a sibling of A, call it
2169 // C. When the mouse enters C, the timer is set and |mTimerMenu| is A and
2170 // |mPopups| is C. As the timer fires, the mouse is still within C. The correct
2171 // behavior is to set the current item to C and close up the chain parented at
2174 // This brings up the question of is the logic of case (1) enough? The answer
2175 // is no, and is discussed in bugzilla bug 29400. Case (1) asks if A's submenu
2176 // has a selected child, and if it does, set the selected item to A. Because B
2177 // has a submenu open, it is selected and as a result, A is set to be the
2178 // selected item even though the mouse rests in C -- very wrong.
2180 // The solution is to use the same idea, but instead of only checking one
2181 // level, drill all the way down to the deepest open submenu and check if it
2182 // has something selected. Since the mouse is in a grandparent, it won't, and
2183 // we know that we can safely close up A and all its children.
2185 // The code below melds the two cases together.
2187 void nsXULPopupManager::KillMenuTimer() {
2188 if (mCloseTimer
&& mTimerMenu
) {
2189 mCloseTimer
->Cancel();
2190 mCloseTimer
= nullptr;
2192 if (mTimerMenu
->IsOpen()) {
2193 HidePopup(&mTimerMenu
->PopupElement(), {HidePopupOption::Async
});
2197 mTimerMenu
= nullptr;
2200 void nsXULPopupManager::CancelMenuTimer(nsMenuPopupFrame
* aMenu
) {
2201 if (mCloseTimer
&& mTimerMenu
== aMenu
) {
2202 mCloseTimer
->Cancel();
2203 mCloseTimer
= nullptr;
2204 mTimerMenu
= nullptr;
2208 bool nsXULPopupManager::HandleShortcutNavigation(KeyboardEvent
& aKeyEvent
,
2209 nsMenuPopupFrame
* aFrame
) {
2210 // On Windows, don't check shortcuts when the accelerator key is down.
2212 WidgetInputEvent
* evt
= aKeyEvent
.WidgetEventPtr()->AsInputEvent();
2213 if (evt
&& evt
->IsAccel()) {
2219 if (nsMenuChainItem
* item
= GetTopVisibleMenu()) {
2220 aFrame
= item
->Frame();
2225 bool action
= false;
2226 RefPtr result
= aFrame
->FindMenuWithShortcut(aKeyEvent
, action
);
2230 RefPtr popup
= &aFrame
->PopupElement();
2231 popup
->SetActiveMenuChild(result
, XULMenuParentElement::ByKey::Yes
);
2233 WidgetEvent
* evt
= aKeyEvent
.WidgetEventPtr();
2234 result
->HandleEnterKeyPress(*evt
);
2239 // Only do shortcut navigation when the menubar is activated via keyboard.
2240 if (mActiveMenuBar
) {
2241 RefPtr menubar
= mActiveMenuBar
;
2242 if (RefPtr result
= menubar
->FindMenuWithShortcut(aKeyEvent
)) {
2243 result
->OpenMenuPopup(true);
2247 // Behavior on Windows - this item is on the menu bar, beep and deactivate
2249 // TODO(emilio): This is rather odd, and I cannot get the beep to work,
2250 // but this matches what old code was doing...
2251 if (nsCOMPtr
<nsISound
> sound
= do_GetService("@mozilla.org/sound;1")) {
2254 menubar
->SetActive(false);
2260 bool nsXULPopupManager::HandleKeyboardNavigation(uint32_t aKeyCode
) {
2261 if (nsMenuChainItem
* nextitem
= GetTopVisibleMenu()) {
2262 nextitem
->Element()->OwnerDoc()->FlushPendingNotifications(
2266 // navigate up through the open menus, looking for the topmost one
2267 // in the same hierarchy
2268 nsMenuChainItem
* item
= nullptr;
2269 nsMenuChainItem
* nextitem
= GetTopVisibleMenu();
2272 nextitem
= item
->GetParent();
2277 // stop if the parent isn't a menu
2278 if (!nextitem
->IsMenu()) {
2282 // Check to make sure that the parent is actually the parent menu. It won't
2283 // be if the parent is in a different frame hierarchy, for example, for a
2284 // context menu opened on another menu.
2285 XULPopupElement
& expectedParent
= nextitem
->Frame()->PopupElement();
2286 auto* menu
= item
->Frame()->PopupElement().GetContainingMenu();
2287 if (!menu
|| menu
->GetMenuParent() != &expectedParent
) {
2292 nsIFrame
* itemFrame
;
2294 itemFrame
= item
->Frame();
2295 } else if (mActiveMenuBar
) {
2296 itemFrame
= mActiveMenuBar
->GetPrimaryFrame();
2304 nsNavigationDirection theDirection
;
2305 NS_ASSERTION(aKeyCode
>= KeyboardEvent_Binding::DOM_VK_END
&&
2306 aKeyCode
<= KeyboardEvent_Binding::DOM_VK_DOWN
,
2307 "Illegal key code");
2308 theDirection
= NS_DIRECTION_FROM_KEY_CODE(itemFrame
, aKeyCode
);
2310 bool selectFirstItem
= true;
2311 #ifdef MOZ_WIDGET_GTK
2313 XULButtonElement
* currentItem
= nullptr;
2314 if (item
&& mActiveMenuBar
&& NS_DIRECTION_IS_INLINE(theDirection
)) {
2315 currentItem
= item
->Frame()->PopupElement().GetActiveMenuChild();
2316 // If nothing is selected in the menu and we have a menubar, let it
2317 // handle the movement not to steal focus from it.
2322 // On menu change, only select first item if an item is already selected.
2323 selectFirstItem
= !!currentItem
;
2327 // if a popup is open, first check for navigation within the popup
2328 if (item
&& HandleKeyboardNavigationInPopup(item
, theDirection
)) {
2332 // no popup handled the key, so check the active menubar, if any
2333 if (!mActiveMenuBar
) {
2336 RefPtr menubar
= mActiveMenuBar
;
2337 if (NS_DIRECTION_IS_INLINE(theDirection
)) {
2338 RefPtr prevActiveItem
= menubar
->GetActiveMenuChild();
2339 const bool open
= prevActiveItem
&& prevActiveItem
->IsMenuPopupOpen();
2340 RefPtr nextItem
= theDirection
== eNavigationDirection_End
2341 ? menubar
->GetNextMenuItem()
2342 : menubar
->GetPrevMenuItem();
2343 menubar
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2344 if (open
&& nextItem
) {
2345 nextItem
->OpenMenuPopup(selectFirstItem
);
2349 if (NS_DIRECTION_IS_BLOCK(theDirection
)) {
2350 // Open the menu and select its first item.
2351 if (RefPtr currentMenu
= menubar
->GetActiveMenuChild()) {
2352 ShowMenu(currentMenu
, selectFirstItem
);
2359 bool nsXULPopupManager::HandleKeyboardNavigationInPopup(
2360 nsMenuChainItem
* item
, nsMenuPopupFrame
* aFrame
,
2361 nsNavigationDirection aDir
) {
2362 NS_ASSERTION(aFrame
, "aFrame is null");
2363 NS_ASSERTION(!item
|| item
->Frame() == aFrame
,
2364 "aFrame is expected to be equal to item->Frame()");
2366 using Wrap
= XULMenuParentElement::Wrap
;
2367 RefPtr
<XULPopupElement
> menu
= &aFrame
->PopupElement();
2369 aFrame
->ClearIncrementalString();
2370 RefPtr currentItem
= aFrame
->GetCurrentMenuItem();
2372 // This method only gets called if we're open.
2373 if (!currentItem
&& NS_DIRECTION_IS_INLINE(aDir
)) {
2374 // We've been opened, but we haven't had anything selected.
2375 // We can handle End, but our parent handles Start.
2376 if (aDir
== eNavigationDirection_End
) {
2377 if (RefPtr nextItem
= menu
->GetNextMenuItem(Wrap::No
)) {
2378 menu
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2385 const bool isContainer
= currentItem
&& !currentItem
->IsMenuItem();
2386 const bool isOpen
= currentItem
&& currentItem
->IsMenuPopupOpen();
2388 // For an open popup, have the child process the event
2389 nsMenuChainItem
* child
= item
? item
->GetChild() : nullptr;
2390 if (child
&& HandleKeyboardNavigationInPopup(child
, aDir
)) {
2393 } else if (aDir
== eNavigationDirection_End
&& isContainer
&&
2394 !currentItem
->IsDisabled()) {
2395 currentItem
->OpenMenuPopup(true);
2399 // For block progression, we can move in either direction
2400 if (NS_DIRECTION_IS_BLOCK(aDir
) || NS_DIRECTION_IS_BLOCK_TO_EDGE(aDir
)) {
2401 RefPtr
<XULButtonElement
> nextItem
= nullptr;
2403 if (aDir
== eNavigationDirection_Before
||
2404 aDir
== eNavigationDirection_After
) {
2405 // Cursor navigation does not wrap on Mac or for menulists on Windows.
2408 aFrame
->IsMenuList() ? Wrap::No
: Wrap::Yes
;
2409 #elif defined XP_MACOSX
2415 if (aDir
== eNavigationDirection_Before
) {
2416 nextItem
= menu
->GetPrevMenuItem(wrap
);
2418 nextItem
= menu
->GetNextMenuItem(wrap
);
2420 } else if (aDir
== eNavigationDirection_First
) {
2421 nextItem
= menu
->GetFirstMenuItem();
2423 nextItem
= menu
->GetLastMenuItem();
2427 menu
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2430 } else if (currentItem
&& isOpen
&& aDir
== eNavigationDirection_Start
) {
2431 // close a submenu when Left is pressed
2432 if (nsMenuPopupFrame
* popupFrame
=
2433 currentItem
->GetMenuPopup(FlushType::None
)) {
2434 HidePopup(&popupFrame
->PopupElement(), {});
2442 bool nsXULPopupManager::HandleKeyboardEventWithKeyCode(
2443 KeyboardEvent
* aKeyEvent
, nsMenuChainItem
* aTopVisibleMenuItem
) {
2444 uint32_t keyCode
= aKeyEvent
->KeyCode();
2446 // Escape should close panels, but the other keys should have no effect.
2447 if (aTopVisibleMenuItem
&&
2448 aTopVisibleMenuItem
->GetPopupType() != PopupType::Menu
) {
2449 if (keyCode
== KeyboardEvent_Binding::DOM_VK_ESCAPE
) {
2450 HidePopup(aTopVisibleMenuItem
->Element(), {HidePopupOption::IsRollup
});
2451 aKeyEvent
->StopPropagation();
2452 aKeyEvent
->StopCrossProcessForwarding();
2453 aKeyEvent
->PreventDefault();
2458 bool consume
= (aTopVisibleMenuItem
|| mActiveMenuBar
);
2460 case KeyboardEvent_Binding::DOM_VK_UP
:
2461 case KeyboardEvent_Binding::DOM_VK_DOWN
:
2463 // roll up the popup when alt+up/down are pressed within a menulist.
2464 if (aKeyEvent
->AltKey() && aTopVisibleMenuItem
&&
2465 aTopVisibleMenuItem
->Frame()->IsMenuList()) {
2472 case KeyboardEvent_Binding::DOM_VK_LEFT
:
2473 case KeyboardEvent_Binding::DOM_VK_RIGHT
:
2474 case KeyboardEvent_Binding::DOM_VK_HOME
:
2475 case KeyboardEvent_Binding::DOM_VK_END
:
2476 HandleKeyboardNavigation(keyCode
);
2479 case KeyboardEvent_Binding::DOM_VK_PAGE_DOWN
:
2480 case KeyboardEvent_Binding::DOM_VK_PAGE_UP
:
2481 if (aTopVisibleMenuItem
) {
2482 aTopVisibleMenuItem
->Frame()->ChangeByPage(
2483 keyCode
== KeyboardEvent_Binding::DOM_VK_PAGE_UP
);
2487 case KeyboardEvent_Binding::DOM_VK_ESCAPE
:
2488 // Pressing Escape hides one level of menus only. If no menu is open,
2489 // check if a menubar is active and inform it that a menu closed. Even
2490 // though in this latter case, a menu didn't actually close, the effect
2491 // ends up being the same. Similar for the tab key below.
2492 if (aTopVisibleMenuItem
) {
2493 HidePopup(aTopVisibleMenuItem
->Element(), {HidePopupOption::IsRollup
});
2494 } else if (mActiveMenuBar
) {
2495 RefPtr menubar
= mActiveMenuBar
;
2496 menubar
->SetActive(false);
2500 case KeyboardEvent_Binding::DOM_VK_TAB
:
2502 case KeyboardEvent_Binding::DOM_VK_F10
:
2504 if (aTopVisibleMenuItem
&&
2505 !aTopVisibleMenuItem
->Frame()->PopupElement().AttrValueIs(
2506 kNameSpaceID_None
, nsGkAtoms::activateontab
, nsGkAtoms::_true
,
2508 // Close popups or deactivate menubar when Tab or F10 are pressed
2511 } else if (mActiveMenuBar
) {
2512 RefPtr menubar
= mActiveMenuBar
;
2513 menubar
->SetActive(false);
2516 // Intentional fall-through to RETURN case
2519 case KeyboardEvent_Binding::DOM_VK_RETURN
: {
2520 // If there is a popup open, check if the current item needs to be opened.
2521 // Otherwise, tell the active menubar, if any, to activate the menu. The
2522 // Enter method will return a menu if one needs to be opened as a result.
2523 WidgetEvent
* event
= aKeyEvent
->WidgetEventPtr();
2524 if (aTopVisibleMenuItem
) {
2525 aTopVisibleMenuItem
->Frame()->HandleEnterKeyPress(*event
);
2526 } else if (mActiveMenuBar
) {
2527 RefPtr menubar
= mActiveMenuBar
;
2528 menubar
->HandleEnterKeyPress(*event
);
2538 aKeyEvent
->StopPropagation();
2539 aKeyEvent
->StopCrossProcessForwarding();
2540 aKeyEvent
->PreventDefault();
2545 nsresult
nsXULPopupManager::HandleEvent(Event
* aEvent
) {
2546 RefPtr
<KeyboardEvent
> keyEvent
= aEvent
->AsKeyboardEvent();
2547 NS_ENSURE_TRUE(keyEvent
, NS_ERROR_UNEXPECTED
);
2549 // handlers shouldn't be triggered by non-trusted events.
2550 if (!keyEvent
->IsTrusted()) {
2554 nsAutoString eventType
;
2555 keyEvent
->GetType(eventType
);
2556 if (eventType
.EqualsLiteral("keyup")) {
2557 return KeyUp(keyEvent
);
2559 if (eventType
.EqualsLiteral("keydown")) {
2560 return KeyDown(keyEvent
);
2562 if (eventType
.EqualsLiteral("keypress")) {
2563 return KeyPress(keyEvent
);
2566 MOZ_ASSERT_UNREACHABLE("Unexpected eventType");
2570 nsresult
nsXULPopupManager::UpdateIgnoreKeys(bool aIgnoreKeys
) {
2571 nsMenuChainItem
* item
= GetTopVisibleMenu();
2573 item
->SetIgnoreKeys(aIgnoreKeys
? eIgnoreKeys_True
: eIgnoreKeys_Shortcuts
);
2575 UpdateKeyboardListeners();
2579 nsPopupState
nsXULPopupManager::GetPopupState(Element
* aPopupElement
) {
2580 if (mNativeMenu
&& mNativeMenu
->Element()->Contains(aPopupElement
)) {
2581 if (aPopupElement
!= mNativeMenu
->Element()) {
2582 // Submenu state is stored in mNativeMenuSubmenuStates.
2583 return mNativeMenuSubmenuStates
.MaybeGet(aPopupElement
)
2584 .valueOr(ePopupClosed
);
2586 // mNativeMenu->Element()'s state is stored in its nsMenuPopupFrame.
2589 nsMenuPopupFrame
* menuPopupFrame
=
2590 do_QueryFrame(aPopupElement
->GetPrimaryFrame());
2591 if (menuPopupFrame
) {
2592 return menuPopupFrame
->PopupState();
2594 return ePopupClosed
;
2597 nsresult
nsXULPopupManager::KeyUp(KeyboardEvent
* aKeyEvent
) {
2598 // don't do anything if a menu isn't open or a menubar isn't active
2599 if (!mActiveMenuBar
) {
2600 nsMenuChainItem
* item
= GetTopVisibleMenu();
2601 if (!item
|| item
->GetPopupType() != PopupType::Menu
) return NS_OK
;
2603 if (item
->IgnoreKeys() == eIgnoreKeys_Shortcuts
) {
2604 aKeyEvent
->StopCrossProcessForwarding();
2609 aKeyEvent
->StopPropagation();
2610 aKeyEvent
->StopCrossProcessForwarding();
2611 aKeyEvent
->PreventDefault();
2613 return NS_OK
; // I am consuming event
2616 nsresult
nsXULPopupManager::KeyDown(KeyboardEvent
* aKeyEvent
) {
2617 nsMenuChainItem
* item
= GetTopVisibleMenu();
2618 if (item
&& item
->Frame()->PopupElement().IsLocked()) {
2622 if (HandleKeyboardEventWithKeyCode(aKeyEvent
, item
)) {
2626 // don't do anything if a menu isn't open or a menubar isn't active
2627 if (!mActiveMenuBar
&& (!item
|| item
->GetPopupType() != PopupType::Menu
))
2630 // Since a menu was open, stop propagation of the event to keep other event
2631 // listeners from becoming confused.
2632 if (!item
|| item
->IgnoreKeys() != eIgnoreKeys_Shortcuts
) {
2633 aKeyEvent
->StopPropagation();
2636 // If the key just pressed is the access key (usually Alt),
2637 // dismiss and unfocus the menu.
2638 uint32_t menuAccessKey
= LookAndFeel::GetMenuAccessKey();
2639 if (menuAccessKey
) {
2640 uint32_t theChar
= aKeyEvent
->KeyCode();
2642 if (theChar
== menuAccessKey
) {
2643 bool ctrl
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_CONTROL
&&
2644 aKeyEvent
->CtrlKey());
2645 bool alt
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_ALT
&&
2646 aKeyEvent
->AltKey());
2647 bool shift
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_SHIFT
&&
2648 aKeyEvent
->ShiftKey());
2649 bool meta
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_META
&&
2650 aKeyEvent
->MetaKey());
2651 if (!(ctrl
|| alt
|| shift
|| meta
)) {
2652 // The access key just went down and no other
2653 // modifiers are already down.
2654 nsMenuChainItem
* item
= GetTopVisibleMenu();
2655 if (item
&& !item
->Frame()->IsMenuList()) {
2657 } else if (mActiveMenuBar
) {
2658 RefPtr menubar
= mActiveMenuBar
;
2659 menubar
->SetActive(false);
2662 // Clear the item to avoid bugs as it may have been deleted during
2666 aKeyEvent
->StopPropagation();
2667 aKeyEvent
->PreventDefault();
2671 aKeyEvent
->StopCrossProcessForwarding();
2675 nsresult
nsXULPopupManager::KeyPress(KeyboardEvent
* aKeyEvent
) {
2676 // Don't check prevent default flag -- menus always get first shot at key
2679 nsMenuChainItem
* item
= GetTopVisibleMenu();
2680 if (item
&& (item
->Frame()->PopupElement().IsLocked() ||
2681 item
->GetPopupType() != PopupType::Menu
)) {
2685 // if a menu is open or a menubar is active, it consumes the key event
2686 bool consume
= (item
|| mActiveMenuBar
);
2688 WidgetInputEvent
* evt
= aKeyEvent
->WidgetEventPtr()->AsInputEvent();
2689 bool isAccel
= evt
&& evt
->IsAccel();
2691 // When ignorekeys="shortcuts" is used, we don't call preventDefault on the
2692 // key event when the accelerator key is pressed. This allows another
2693 // listener to handle keys. For instance, this allows global shortcuts to
2694 // still apply while a menu is open.
2695 if (item
&& item
->IgnoreKeys() == eIgnoreKeys_Shortcuts
&& isAccel
) {
2699 HandleShortcutNavigation(*aKeyEvent
, nullptr);
2701 aKeyEvent
->StopCrossProcessForwarding();
2703 aKeyEvent
->StopPropagation();
2704 aKeyEvent
->PreventDefault();
2707 return NS_OK
; // I am consuming event
2711 nsXULPopupHidingEvent::Run() {
2712 RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance();
2713 Document
* document
= mPopup
->GetUncomposedDoc();
2714 if (pm
&& document
) {
2715 if (RefPtr
<nsPresContext
> presContext
= document
->GetPresContext()) {
2716 nsCOMPtr
<Element
> popup
= mPopup
;
2717 nsCOMPtr
<Element
> nextPopup
= mNextPopup
;
2718 nsCOMPtr
<Element
> lastPopup
= mLastPopup
;
2719 pm
->FirePopupHidingEvent(popup
, nextPopup
, lastPopup
, presContext
,
2720 mPopupType
, mOptions
);
2726 bool nsXULPopupPositionedEvent::DispatchIfNeeded(Element
* aPopup
) {
2727 // The popuppositioned event only fires on arrow panels for now.
2728 if (aPopup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
,
2730 nsCOMPtr
<nsIRunnable
> event
= new nsXULPopupPositionedEvent(aPopup
);
2731 aPopup
->OwnerDoc()->Dispatch(TaskCategory::Other
, event
.forget());
2738 static void AlignmentPositionToString(nsMenuPopupFrame
* aFrame
,
2739 nsAString
& aString
) {
2741 int8_t position
= aFrame
->GetAlignmentPosition();
2743 case POPUPPOSITION_AFTERSTART
:
2744 return aString
.AssignLiteral("after_start");
2745 case POPUPPOSITION_AFTEREND
:
2746 return aString
.AssignLiteral("after_end");
2747 case POPUPPOSITION_BEFORESTART
:
2748 return aString
.AssignLiteral("before_start");
2749 case POPUPPOSITION_BEFOREEND
:
2750 return aString
.AssignLiteral("before_end");
2751 case POPUPPOSITION_STARTBEFORE
:
2752 return aString
.AssignLiteral("start_before");
2753 case POPUPPOSITION_ENDBEFORE
:
2754 return aString
.AssignLiteral("end_before");
2755 case POPUPPOSITION_STARTAFTER
:
2756 return aString
.AssignLiteral("start_after");
2757 case POPUPPOSITION_ENDAFTER
:
2758 return aString
.AssignLiteral("end_after");
2759 case POPUPPOSITION_OVERLAP
:
2760 return aString
.AssignLiteral("overlap");
2761 case POPUPPOSITION_AFTERPOINTER
:
2762 return aString
.AssignLiteral("after_pointer");
2763 case POPUPPOSITION_SELECTION
:
2764 return aString
.AssignLiteral("selection");
2766 // Leave as an empty string.
2771 static void PopupAlignmentToString(nsMenuPopupFrame
* aFrame
,
2772 nsAString
& aString
) {
2774 int alignment
= aFrame
->GetPopupAlignment();
2775 switch (alignment
) {
2776 case POPUPALIGNMENT_TOPLEFT
:
2777 return aString
.AssignLiteral("topleft");
2778 case POPUPALIGNMENT_TOPRIGHT
:
2779 return aString
.AssignLiteral("topright");
2780 case POPUPALIGNMENT_BOTTOMLEFT
:
2781 return aString
.AssignLiteral("bottomleft");
2782 case POPUPALIGNMENT_BOTTOMRIGHT
:
2783 return aString
.AssignLiteral("bottomright");
2784 case POPUPALIGNMENT_LEFTCENTER
:
2785 return aString
.AssignLiteral("leftcenter");
2786 case POPUPALIGNMENT_RIGHTCENTER
:
2787 return aString
.AssignLiteral("rightcenter");
2788 case POPUPALIGNMENT_TOPCENTER
:
2789 return aString
.AssignLiteral("topcenter");
2790 case POPUPALIGNMENT_BOTTOMCENTER
:
2791 return aString
.AssignLiteral("bottomcenter");
2793 // Leave as an empty string.
2799 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2800 nsXULPopupPositionedEvent::Run() {
2801 RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance();
2805 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(mPopup
->GetPrimaryFrame());
2810 popupFrame
->WillDispatchPopupPositioned();
2812 // At this point, hidePopup may have been called but it currently has no
2813 // way to stop this event. However, if hidePopup was called, the popup
2814 // will now be in the hiding or closed state. If we are in the shown or
2815 // positioning state instead, we can assume that we are still clear to
2816 // open/move the popup
2817 nsPopupState state
= popupFrame
->PopupState();
2818 if (state
!= ePopupPositioning
&& state
!= ePopupShown
) {
2822 // Note that the offset might be along either the X or Y axis, but for the
2823 // sake of simplicity we use a point with only the X axis set so we can
2824 // use ToNearestPixels().
2825 int32_t popupOffset
= nsPoint(popupFrame
->GetAlignmentOffset(), 0)
2826 .ToNearestPixels(AppUnitsPerCSSPixel())
2829 PopupPositionedEventInit init
;
2830 init
.mComposed
= true;
2831 init
.mIsAnchored
= popupFrame
->IsAnchored();
2832 init
.mAlignmentOffset
= popupOffset
;
2833 AlignmentPositionToString(popupFrame
, init
.mAlignmentPosition
);
2834 PopupAlignmentToString(popupFrame
, init
.mPopupAlignment
);
2835 RefPtr
<PopupPositionedEvent
> event
=
2836 PopupPositionedEvent::Constructor(mPopup
, u
"popuppositioned"_ns
, init
);
2837 event
->SetTrusted(true);
2839 mPopup
->DispatchEvent(*event
);
2841 // Get the popup frame and make sure it is still in the positioning
2842 // state. If it isn't, someone may have tried to reshow or hide it
2843 // during the popuppositioned event.
2844 // Alternately, this event may have been fired in reponse to moving the
2845 // popup rather than opening it. In that case, we are done.
2846 popupFrame
= do_QueryFrame(mPopup
->GetPrimaryFrame());
2847 if (popupFrame
&& popupFrame
->PopupState() == ePopupPositioning
) {
2848 pm
->ShowPopupCallback(mPopup
, popupFrame
, false, false);
2855 nsXULMenuCommandEvent::Run() {
2856 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
2861 RefPtr menu
= XULButtonElement::FromNode(mMenu
);
2864 if (menu
->GetXULBoolAttr(nsGkAtoms::checked
)) {
2865 menu
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::checked
, true);
2867 menu
->SetAttr(kNameSpaceID_None
, nsGkAtoms::checked
, u
"true"_ns
, true);
2871 // The order of the nsViewManager and PresShell COM pointers is
2872 // important below. We want the pres shell to get released before the
2873 // associated view manager on exit from this function.
2875 // XXXndeakin is this still needed?
2876 RefPtr
<nsPresContext
> presContext
= menu
->OwnerDoc()->GetPresContext();
2877 RefPtr
<PresShell
> presShell
=
2878 presContext
? presContext
->PresShell() : nullptr;
2879 RefPtr
<nsViewManager
> kungFuDeathGrip
=
2880 presShell
? presShell
->GetViewManager() : nullptr;
2881 Unused
<< kungFuDeathGrip
; // Not referred to directly within this function
2883 // Deselect ourselves.
2884 if (mCloseMenuMode
!= CloseMenuMode_None
) {
2885 if (RefPtr parent
= menu
->GetMenuParent()) {
2886 if (parent
->GetActiveMenuChild() == menu
) {
2887 parent
->SetActiveMenuChild(nullptr);
2892 AutoHandlingUserInputStatePusher
userInpStatePusher(mUserInput
);
2893 nsContentUtils::DispatchXULCommand(
2894 menu
, mIsTrusted
, nullptr, presShell
, mModifiers
& MODIFIER_CONTROL
,
2895 mModifiers
& MODIFIER_ALT
, mModifiers
& MODIFIER_SHIFT
,
2896 mModifiers
& MODIFIER_META
, 0, mButton
);
2898 if (mCloseMenuMode
!= CloseMenuMode_None
) {
2899 if (RefPtr popup
= menu
->GetContainingPopupElement()) {
2900 HidePopupOptions options
{HidePopupOption::DeselectMenu
};
2901 if (mCloseMenuMode
== CloseMenuMode_Auto
) {
2902 options
+= HidePopupOption::HideChain
;
2904 pm
->HidePopup(popup
, options
);