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::AddMenuChainItem(UniquePtr
<nsMenuChainItem
> aItem
) {
213 PopupType popupType
= aItem
->Frame()->GetPopupType();
214 if (StaticPrefs::layout_cursor_disable_for_popups() &&
215 popupType
!= PopupType::Tooltip
) {
216 nsPresContext
* rootPresContext
=
217 aItem
->Frame()->PresContext()->GetRootPresContext();
218 if (nsCOMPtr
<nsIWidget
> rootWidget
= rootPresContext
->GetRootWidget()) {
219 rootWidget
->SetCustomCursorAllowed(false);
223 // popups normally hide when an outside click occurs. Panels may use
224 // the noautohide attribute to disable this behaviour. It is expected
225 // that the application will hide these popups manually. The tooltip
226 // listener will handle closing the tooltip also.
227 nsIContent
* oldmenu
= nullptr;
229 oldmenu
= mPopups
->Element();
231 aItem
->SetParent(std::move(mPopups
));
232 mPopups
= std::move(aItem
);
233 SetCaptureState(oldmenu
);
236 void nsXULPopupManager::RemoveMenuChainItem(nsMenuChainItem
* aItem
) {
237 nsPresContext
* presContext
=
238 aItem
->Frame()->PresContext()->GetRootPresContext();
239 auto matcher
= [&](nsMenuChainItem
* aChainItem
) -> bool {
240 return aChainItem
!= aItem
&&
242 aChainItem
->Frame()->PresContext()->GetRootPresContext();
244 nsCOMPtr
<nsIWidget
> rootWidget
=
245 presContext
->GetRootPresContext()->GetRootWidget();
246 if (!FirstMatchingPopup(matcher
) && rootWidget
) {
247 rootWidget
->SetCustomCursorAllowed(true);
250 auto parent
= aItem
->Detach();
251 if (auto* child
= aItem
->GetChild()) {
252 MOZ_ASSERT(aItem
!= mPopups
,
253 "Unexpected - popup with child at end of chain");
254 // This will kill aItem by changing child's mParent pointer.
255 child
->SetParent(std::move(parent
));
257 // An item without a child should be the first item in the chain, so set
258 // the first item pointer, pointed to by aRoot, to the parent.
259 MOZ_ASSERT(aItem
== mPopups
,
260 "Unexpected - popup with no child not at end of chain");
261 mPopups
= std::move(parent
);
265 nsMenuChainItem
* nsXULPopupManager::FirstMatchingPopup(
266 mozilla::FunctionRef
<bool(nsMenuChainItem
*)> aMatcher
) const {
267 for (nsMenuChainItem
* popup
= mPopups
.get(); popup
;
268 popup
= popup
->GetParent()) {
269 if (aMatcher(popup
)) {
276 void nsMenuChainItem::UpdateFollowAnchor() {
277 mFollowAnchor
= mFrame
->ShouldFollowAnchor(mCurrentRect
);
280 void nsMenuChainItem::CheckForAnchorChange() {
282 mFrame
->CheckForAnchorChange(mCurrentRect
);
286 NS_IMPL_ISUPPORTS(nsXULPopupManager
, nsIDOMEventListener
, nsIObserver
)
288 nsXULPopupManager::nsXULPopupManager()
289 : mActiveMenuBar(nullptr), mPopups(nullptr), mPendingPopup(nullptr) {
290 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
292 obs
->AddObserver(this, "xpcom-shutdown", false);
296 nsXULPopupManager::~nsXULPopupManager() {
297 NS_ASSERTION(!mPopups
, "XUL popups still open");
300 mNativeMenu
->RemoveObserver(this);
304 nsresult
nsXULPopupManager::Init() {
305 sInstance
= new nsXULPopupManager();
306 NS_ENSURE_TRUE(sInstance
, NS_ERROR_OUT_OF_MEMORY
);
307 NS_ADDREF(sInstance
);
311 void nsXULPopupManager::Shutdown() { NS_IF_RELEASE(sInstance
); }
314 nsXULPopupManager::Observe(nsISupports
* aSubject
, const char* aTopic
,
315 const char16_t
* aData
) {
316 if (!nsCRT::strcmp(aTopic
, "xpcom-shutdown")) {
318 mKeyListener
->RemoveEventListener(u
"keypress"_ns
, this, true);
319 mKeyListener
->RemoveEventListener(u
"keydown"_ns
, this, true);
320 mKeyListener
->RemoveEventListener(u
"keyup"_ns
, this, true);
321 mKeyListener
= nullptr;
323 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
325 obs
->RemoveObserver(this, "xpcom-shutdown");
332 nsXULPopupManager
* nsXULPopupManager::GetInstance() {
333 MOZ_ASSERT(sInstance
);
337 bool nsXULPopupManager::RollupTooltips() {
338 const RollupOptions options
{0, FlushViews::Yes
, nullptr, AllowAnimations::No
};
339 return RollupInternal(RollupKind::Tooltip
, options
, nullptr);
342 bool nsXULPopupManager::Rollup(const RollupOptions
& aOptions
,
343 nsIContent
** aLastRolledUp
) {
344 return RollupInternal(RollupKind::Menu
, aOptions
, aLastRolledUp
);
347 bool nsXULPopupManager::RollupNativeMenu() {
349 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
350 return menu
->Close();
355 bool nsXULPopupManager::RollupInternal(RollupKind aKind
,
356 const RollupOptions
& aOptions
,
357 nsIContent
** aLastRolledUp
) {
359 *aLastRolledUp
= nullptr;
362 // We can disable the autohide behavior via a pref to ease debugging.
363 if (StaticPrefs::ui_popup_disable_autohide()) {
364 // Required on linux to allow events to work on other targets.
366 mWidget
->CaptureRollupEvents(false);
371 nsMenuChainItem
* item
= GetRollupItem(aKind
);
376 // We need to get the popup that will be closed last, so that widget can
377 // keep track of it so it doesn't reopen if a mousedown event is going to
378 // processed. Keep going up the menu chain to get the first level menu of
379 // the same type. If a different type is encountered it means we have,
380 // for example, a menulist or context menu inside a panel, and we want to
381 // treat these as distinct. It's possible that this menu doesn't end up
382 // closing because the popuphiding event was cancelled, but in that case
383 // we don't need to deal with the menu reopening as it will already still
385 nsMenuChainItem
* first
= item
;
386 while (first
->GetParent()) {
387 nsMenuChainItem
* parent
= first
->GetParent();
388 if (first
->Frame()->GetPopupType() != parent
->Frame()->GetPopupType() ||
389 first
->IsContextMenu() != parent
->IsContextMenu()) {
395 *aLastRolledUp
= first
->Element();
398 ConsumeOutsideClicksResult consumeResult
=
399 item
->Frame()->ConsumeOutsideClicks();
400 bool consume
= consumeResult
== ConsumeOutsideClicks_True
;
403 // If norolluponanchor is true, then don't rollup when clicking the anchor.
404 // This would be used to allow adjusting the caret position in an
405 // autocomplete field without hiding the popup for example.
406 bool noRollupOnAnchor
=
407 (!consume
&& aOptions
.mPoint
&&
408 item
->Frame()->GetContent()->AsElement()->AttrValueIs(
409 kNameSpaceID_None
, nsGkAtoms::norolluponanchor
, nsGkAtoms::_true
,
412 // When ConsumeOutsideClicks_ParentOnly is used, always consume the click
413 // when the click was over the anchor. This way, clicking on a menu doesn't
415 if ((consumeResult
== ConsumeOutsideClicks_ParentOnly
|| noRollupOnAnchor
) &&
417 nsMenuPopupFrame
* popupFrame
= item
->Frame();
418 CSSIntRect anchorRect
= [&] {
419 if (popupFrame
->IsAnchored()) {
420 // Check if the popup has an anchor rectangle set. If not, get the
421 // rectangle from the anchor element.
422 auto r
= popupFrame
->GetScreenAnchorRect();
423 if (r
.x
!= -1 && r
.y
!= -1) {
424 // Prefer the untransformed anchor rect, so as to account for Wayland
425 // properly. Note we still need to check GetScreenAnchorRect() tho, so
426 // as to detect whether the anchor came from the popup opening call,
427 // or from an element (in which case we want to take the code-path
429 auto untransformed
= popupFrame
->GetUntransformedAnchorRect();
430 if (!untransformed
.IsEmpty()) {
431 return CSSIntRect::FromAppUnitsRounded(untransformed
);
437 auto* anchor
= Element::FromNodeOrNull(popupFrame
->GetAnchor());
442 // Check if the anchor has indicated another node to use for checking
443 // for roll-up. That way, we can anchor a popup on anonymous content
444 // or an individual icon, while clicking elsewhere within a button or
445 // other container doesn't result in us re-opening the popup.
446 nsAutoString consumeAnchor
;
447 anchor
->GetAttr(nsGkAtoms::consumeanchor
, consumeAnchor
);
448 if (!consumeAnchor
.IsEmpty()) {
449 if (Element
* newAnchor
=
450 anchor
->OwnerDoc()->GetElementById(consumeAnchor
)) {
455 nsIFrame
* f
= anchor
->GetPrimaryFrame();
459 return f
->GetScreenRect();
462 // It's possible that some other element is above the anchor at the same
463 // position, but the only thing that would happen is that the mouse
464 // event will get consumed, so here only a quick coordinates check is
465 // done rather than a slower complete check of what is at that location.
466 nsPresContext
* presContext
= item
->Frame()->PresContext();
467 CSSIntPoint posCSSPixels
=
468 presContext
->DevPixelsToIntCSSPixels(*aOptions
.mPoint
);
469 if (anchorRect
.Contains(posCSSPixels
)) {
470 if (consumeResult
== ConsumeOutsideClicks_ParentOnly
) {
474 if (noRollupOnAnchor
) {
484 // If a number of popups to close has been specified, determine the last
486 Element
* lastPopup
= nullptr;
487 uint32_t count
= aOptions
.mCount
;
488 if (count
&& count
!= UINT32_MAX
) {
489 nsMenuChainItem
* last
= item
;
490 while (--count
&& last
->GetParent()) {
491 last
= last
->GetParent();
494 lastPopup
= last
->Element();
498 nsPresContext
* presContext
= item
->Frame()->PresContext();
499 RefPtr
<nsViewManager
> viewManager
=
500 presContext
->PresShell()->GetViewManager();
502 HidePopupOptions options
{HidePopupOption::HideChain
,
503 HidePopupOption::DeselectMenu
,
504 HidePopupOption::IsRollup
};
505 if (aOptions
.mAllowAnimations
== AllowAnimations::No
) {
506 options
+= HidePopupOption::DisableAnimations
;
509 HidePopup(item
->Element(), options
, lastPopup
);
511 if (aOptions
.mFlush
== FlushViews::Yes
) {
512 // The popup's visibility doesn't update until the minimize animation
513 // has finished, so call UpdateWidgetGeometry to update it right away.
514 viewManager
->UpdateWidgetGeometry();
520 ////////////////////////////////////////////////////////////////////////
521 bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent() {
522 // should rollup only for autocomplete widgets
523 // XXXndeakin this should really be something the popup has more control over
525 nsMenuChainItem
* item
= GetTopVisibleMenu();
530 nsIContent
* content
= item
->Frame()->GetContent();
531 if (!content
|| !content
->IsElement()) return false;
533 Element
* element
= content
->AsElement();
534 if (element
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::rolluponmousewheel
,
535 nsGkAtoms::_true
, eCaseMatters
))
538 if (element
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::rolluponmousewheel
,
539 nsGkAtoms::_false
, eCaseMatters
))
543 element
->GetAttr(nsGkAtoms::type
, value
);
544 return StringBeginsWith(value
, u
"autocomplete"_ns
);
547 bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent() {
548 nsMenuChainItem
* item
= GetTopVisibleMenu();
553 nsMenuPopupFrame
* frame
= item
->Frame();
554 if (frame
->GetPopupType() != PopupType::Panel
) return true;
556 return !frame
->GetContent()->AsElement()->AttrValueIs(
557 kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
, eCaseMatters
);
560 // a menu should not roll up if activated by a mouse activate message (eg.
562 bool nsXULPopupManager::ShouldRollupOnMouseActivate() { return false; }
564 uint32_t nsXULPopupManager::GetSubmenuWidgetChain(
565 nsTArray
<nsIWidget
*>* aWidgetChain
) {
566 // this method is used by the widget code to determine the list of popups
567 // that are open. If a mouse click occurs outside one of these popups, the
568 // panels will roll up. If the click is inside a popup, they will not roll up
569 uint32_t count
= 0, sameTypeCount
= 0;
571 NS_ASSERTION(aWidgetChain
, "null parameter");
572 nsMenuChainItem
* item
= GetTopVisibleMenu();
574 nsMenuChainItem
* parent
= item
->GetParent();
575 if (!item
->IsNoAutoHide()) {
576 nsCOMPtr
<nsIWidget
> widget
= item
->Frame()->GetWidget();
577 NS_ASSERTION(widget
, "open popup has no widget");
579 aWidgetChain
->AppendElement(widget
.get());
580 // In the case when a menulist inside a panel is open, clicking in the
581 // panel should still roll up the menu, so if a different type is found,
583 if (!sameTypeCount
) {
586 item
->Frame()->GetPopupType() !=
587 parent
->Frame()->GetPopupType() ||
588 item
->IsContextMenu() != parent
->IsContextMenu()) {
589 sameTypeCount
= count
;
597 return sameTypeCount
;
600 nsIWidget
* nsXULPopupManager::GetRollupWidget() {
601 nsMenuChainItem
* item
= GetTopVisibleMenu();
602 return item
? item
->Frame()->GetWidget() : nullptr;
605 void nsXULPopupManager::AdjustPopupsOnWindowChange(
606 nsPIDOMWindowOuter
* aWindow
) {
607 // When the parent window is moved, adjust any child popups. Dismissable
608 // menus and panels are expected to roll up when a window is moved, so there
609 // is no need to check these popups, only the noautohide popups.
611 // The items are added to a list so that they can be adjusted bottom to top.
612 nsTArray
<nsMenuPopupFrame
*> list
;
614 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
615 // only move popups that are within the same window and where auto
616 // positioning has not been disabled
617 if (!item
->IsNoAutoHide()) {
620 nsMenuPopupFrame
* frame
= item
->Frame();
621 nsIContent
* popup
= frame
->GetContent();
625 Document
* document
= popup
->GetUncomposedDoc();
629 nsPIDOMWindowOuter
* window
= document
->GetWindow();
633 window
= window
->GetPrivateRoot();
634 if (window
== aWindow
) {
635 list
.AppendElement(frame
);
639 for (int32_t l
= list
.Length() - 1; l
>= 0; l
--) {
640 list
[l
]->SetPopupPosition(true);
644 void nsXULPopupManager::AdjustPopupsOnWindowChange(PresShell
* aPresShell
) {
645 if (aPresShell
->GetDocument()) {
646 AdjustPopupsOnWindowChange(aPresShell
->GetDocument()->GetWindow());
650 static nsMenuPopupFrame
* GetPopupToMoveOrResize(nsIFrame
* aFrame
) {
651 nsMenuPopupFrame
* menuPopupFrame
= do_QueryFrame(aFrame
);
652 if (!menuPopupFrame
) return nullptr;
654 // no point moving or resizing hidden popups
655 if (!menuPopupFrame
->IsVisible()) return nullptr;
657 nsIWidget
* widget
= menuPopupFrame
->GetWidget();
658 if (widget
&& !widget
->IsVisible()) return nullptr;
660 return menuPopupFrame
;
663 void nsXULPopupManager::PopupMoved(nsIFrame
* aFrame
,
664 const LayoutDeviceIntPoint
& aPoint
,
665 bool aByMoveToRect
) {
666 nsMenuPopupFrame
* menuPopupFrame
= GetPopupToMoveOrResize(aFrame
);
667 if (!menuPopupFrame
) {
671 nsView
* view
= menuPopupFrame
->GetView();
676 menuPopupFrame
->WidgetPositionOrSizeDidChange();
678 // Don't do anything if the popup is already at the specified location. This
679 // prevents recursive calls when a popup is positioned.
680 LayoutDeviceIntRect curDevBounds
= view
->RecalcWidgetBounds();
681 nsIWidget
* widget
= menuPopupFrame
->GetWidget();
682 if (curDevBounds
.TopLeft() == aPoint
&&
684 widget
->GetClientOffset() == menuPopupFrame
->GetLastClientOffset())) {
688 // Update the popup's position using SetPopupPosition if the popup is
689 // anchored and at the parent level as these maintain their position
690 // relative to the parent window (except if positioned by move to rect, in
691 // which case we better make sure that layout matches that). Otherwise, just
692 // update the popup to the specified screen coordinates.
693 if (menuPopupFrame
->IsAnchored() &&
694 menuPopupFrame
->GetPopupLevel() == widget::PopupLevel::Parent
&&
696 menuPopupFrame
->SetPopupPosition(true);
699 aPoint
/ menuPopupFrame
->PresContext()->CSSToDevPixelScale();
700 menuPopupFrame
->MoveTo(cssPos
, false, aByMoveToRect
);
704 void nsXULPopupManager::PopupResized(nsIFrame
* aFrame
,
705 const LayoutDeviceIntSize
& aSize
) {
706 nsMenuPopupFrame
* menuPopupFrame
= GetPopupToMoveOrResize(aFrame
);
707 if (!menuPopupFrame
) {
711 menuPopupFrame
->WidgetPositionOrSizeDidChange();
713 nsView
* view
= menuPopupFrame
->GetView();
718 const LayoutDeviceIntRect curDevBounds
= view
->RecalcWidgetBounds();
719 // If the size is what we think it is, we have nothing to do.
720 if (curDevBounds
.Size() == aSize
) {
724 Element
* popup
= menuPopupFrame
->GetContent()->AsElement();
726 // Only set the width and height if the popup already has these attributes.
727 if (!popup
->HasAttr(nsGkAtoms::width
) || !popup
->HasAttr(nsGkAtoms::height
)) {
731 // The size is different. Convert the actual size to css pixels and store it
732 // as 'width' and 'height' attributes on the popup.
733 nsPresContext
* presContext
= menuPopupFrame
->PresContext();
735 CSSIntSize
newCSS(presContext
->DevPixelsToIntCSSPixels(aSize
.width
),
736 presContext
->DevPixelsToIntCSSPixels(aSize
.height
));
738 nsAutoString width
, height
;
739 width
.AppendInt(newCSS
.width
);
740 height
.AppendInt(newCSS
.height
);
741 // FIXME(emilio): aNotify should be consistent (probably true in the two calls
743 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::width
, width
, false);
744 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::height
, height
, true);
747 nsMenuPopupFrame
* nsXULPopupManager::GetPopupFrameForContent(
748 nsIContent
* aContent
, bool aShouldFlush
) {
750 Document
* document
= aContent
->GetUncomposedDoc();
752 if (RefPtr
<PresShell
> presShell
= document
->GetPresShell()) {
753 presShell
->FlushPendingNotifications(FlushType::Layout
);
758 return do_QueryFrame(aContent
->GetPrimaryFrame());
761 nsMenuChainItem
* nsXULPopupManager::GetRollupItem(RollupKind aKind
) {
762 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
763 if (item
->Frame()->PopupState() == ePopupInvisible
) {
766 MOZ_ASSERT_IF(item
->Frame()->GetPopupType() == PopupType::Tooltip
,
767 item
->IsNoAutoHide());
768 const bool valid
= aKind
== RollupKind::Tooltip
769 ? item
->Frame()->GetPopupType() == PopupType::Tooltip
770 : !item
->IsNoAutoHide();
778 void nsXULPopupManager::SetActiveMenuBar(XULMenuBarElement
* aMenuBar
,
781 mActiveMenuBar
= aMenuBar
;
782 } else if (mActiveMenuBar
== aMenuBar
) {
783 mActiveMenuBar
= nullptr;
785 UpdateKeyboardListeners();
788 static CloseMenuMode
GetCloseMenuMode(nsIContent
* aMenu
) {
789 if (!aMenu
->IsElement()) {
790 return CloseMenuMode_Auto
;
793 static Element::AttrValuesArray strings
[] = {nsGkAtoms::none
,
794 nsGkAtoms::single
, nullptr};
795 switch (aMenu
->AsElement()->FindAttrValueIn(
796 kNameSpaceID_None
, nsGkAtoms::closemenu
, strings
, eCaseMatters
)) {
798 return CloseMenuMode_None
;
800 return CloseMenuMode_Single
;
802 return CloseMenuMode_Auto
;
806 auto nsXULPopupManager::MayShowMenu(nsIContent
* aMenu
) -> MayShowMenuResult
{
807 if (mNativeMenu
&& aMenu
->IsElement() &&
808 mNativeMenu
->Element()->Contains(aMenu
)) {
812 auto* menu
= XULButtonElement::FromNode(aMenu
);
817 nsMenuPopupFrame
* popupFrame
= menu
->GetMenuPopup(FlushType::None
);
818 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
821 return {false, menu
, popupFrame
};
824 void nsXULPopupManager::ShowMenu(nsIContent
* aMenu
, bool aSelectFirstItem
) {
825 auto mayShowResult
= MayShowMenu(aMenu
);
826 if (NS_WARN_IF(!mayShowResult
)) {
830 if (mayShowResult
.mIsNative
) {
831 mNativeMenu
->OpenSubmenu(aMenu
->AsElement());
835 nsMenuPopupFrame
* popupFrame
= mayShowResult
.mMenuPopupFrame
;
837 // inherit whether or not we're a context menu from the parent
838 const bool onMenuBar
= mayShowResult
.mMenuButton
->IsOnMenuBar();
839 const bool onmenu
= mayShowResult
.mMenuButton
->IsOnMenu();
840 const bool parentIsContextMenu
= mayShowResult
.mMenuButton
->IsOnContextMenu();
842 nsAutoString position
;
845 if (aMenu
->IsXULElement(nsGkAtoms::menulist
)) {
846 position
.AssignLiteral("selection");
850 if (onMenuBar
|| !onmenu
)
851 position
.AssignLiteral("after_start");
853 position
.AssignLiteral("end_before");
855 // there is no trigger event for menus
856 popupFrame
->InitializePopup(aMenu
, nullptr, position
, 0, 0,
857 MenuPopupAnchorType_Node
, true);
858 PendingPopup
pendingPopup(&popupFrame
->PopupElement(), nullptr);
859 BeginShowingPopup(pendingPopup
, parentIsContextMenu
, aSelectFirstItem
);
862 static bool ShouldUseNativeContextMenus() {
863 #ifdef HAS_NATIVE_MENU_SUPPORT
864 return mozilla::widget::NativeMenuSupport::ShouldUseNativeContextMenus();
870 void nsXULPopupManager::ShowPopup(Element
* aPopup
, nsIContent
* aAnchorContent
,
871 const nsAString
& aPosition
, int32_t aXPos
,
872 int32_t aYPos
, bool aIsContextMenu
,
873 bool aAttributesOverride
,
874 bool aSelectFirstItem
, Event
* aTriggerEvent
) {
876 // On Mac, use a native menu if possible since the non-native menu looks out
877 // of place. Native menus for anchored popups are not currently implemented,
878 // so fall back to the non-native path below if `aAnchorContent` is given. We
879 // also fall back if the position string is not empty so we don't break tests
880 // that either themselves call or test app features that call
881 // `openPopup(null, "position")`.
882 if (!aAnchorContent
&& aPosition
.IsEmpty() && ShouldUseNativeContextMenus() &&
883 aPopup
->IsAnyOfXULElements(nsGkAtoms::menu
, nsGkAtoms::menupopup
) &&
884 ShowPopupAsNativeMenu(aPopup
, aXPos
, aYPos
, aIsContextMenu
,
890 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
891 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
895 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
896 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
898 popupFrame
->InitializePopup(aAnchorContent
, triggerContent
, aPosition
, aXPos
,
899 aYPos
, MenuPopupAnchorType_Node
,
900 aAttributesOverride
);
902 BeginShowingPopup(pendingPopup
, aIsContextMenu
, aSelectFirstItem
);
905 void nsXULPopupManager::ShowPopupAtScreen(Element
* aPopup
, int32_t aXPos
,
906 int32_t aYPos
, bool aIsContextMenu
,
907 Event
* aTriggerEvent
) {
908 if (aIsContextMenu
&& ShouldUseNativeContextMenus() &&
909 ShowPopupAsNativeMenu(aPopup
, aXPos
, aYPos
, aIsContextMenu
,
914 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
915 if (!popupFrame
|| !MayShowPopup(popupFrame
)) return;
917 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
918 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
920 popupFrame
->InitializePopupAtScreen(triggerContent
, aXPos
, aYPos
,
922 BeginShowingPopup(pendingPopup
, aIsContextMenu
, false);
925 bool nsXULPopupManager::ShowPopupAsNativeMenu(Element
* aPopup
, int32_t aXPos
,
928 Event
* aTriggerEvent
) {
930 NS_WARNING("Native menu still open when trying to open another");
931 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
933 menu
->RemoveObserver(this);
934 mNativeMenu
= nullptr;
937 RefPtr
<NativeMenu
> menu
;
938 #ifdef HAS_NATIVE_MENU_SUPPORT
939 menu
= mozilla::widget::NativeMenuSupport::CreateNativeContextMenu(aPopup
);
946 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
951 // Hide the menu from our accessibility code so that we don't dispatch custom
952 // accessibility notifications which would conflict with the system ones.
953 aPopup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::aria_hidden
, u
"true"_ns
, true);
955 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
956 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
958 popupFrame
->InitializePopupAsNativeContextMenu(triggerContent
, aXPos
, aYPos
);
960 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
961 nsEventStatus status
= FirePopupShowingEvent(pendingPopup
, presContext
);
963 // if the event was cancelled, don't open the popup, reset its state back
964 // to closed and clear its trigger content.
965 if (status
== nsEventStatus_eConsumeNoDefault
) {
966 if ((popupFrame
= GetPopupFrameForContent(aPopup
, true))) {
967 popupFrame
->SetPopupState(ePopupClosed
);
968 popupFrame
->ClearTriggerContent();
974 mNativeMenu
->AddObserver(this);
975 nsIFrame
* frame
= presContext
->PresShell()->GetCurrentEventFrame();
977 frame
= presContext
->PresShell()->GetRootFrame();
979 mNativeMenu
->ShowAsContextMenu(frame
, CSSIntPoint(aXPos
, aYPos
),
982 // While the native menu is open, it consumes mouseup events.
983 // Clear any :active state, mouse capture state and drag tracking now.
984 EventStateManager
* activeESM
= static_cast<EventStateManager
*>(
985 EventStateManager::GetActiveEventStateManager());
987 EventStateManager::ClearGlobalActiveContent(activeESM
);
988 activeESM
->StopTrackingDragGesture(true);
990 PresShell::ReleaseCapturingContent();
995 void nsXULPopupManager::OnNativeMenuOpened() {
1000 RefPtr
<nsXULPopupManager
> kungFuDeathGrip(this);
1002 nsCOMPtr
<nsIContent
> popup
= mNativeMenu
->Element();
1003 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, true);
1005 popupFrame
->SetPopupState(ePopupShown
);
1009 void nsXULPopupManager::OnNativeMenuClosed() {
1014 RefPtr
<nsXULPopupManager
> kungFuDeathGrip(this);
1016 bool shouldHideChain
=
1017 mNativeMenuActivatedItemCloseMenuMode
== Some(CloseMenuMode_Auto
);
1019 nsCOMPtr
<nsIContent
> popup
= mNativeMenu
->Element();
1020 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, true);
1022 popupFrame
->ClearTriggerContentIncludingDocument();
1023 popupFrame
->SetPopupState(ePopupClosed
);
1025 mNativeMenu
->RemoveObserver(this);
1026 mNativeMenu
= nullptr;
1027 mNativeMenuActivatedItemCloseMenuMode
= Nothing();
1028 mNativeMenuSubmenuStates
.Clear();
1030 // Stop hiding the menu from accessibility code, in case it gets opened as a
1031 // non-native menu in the future.
1032 popup
->AsElement()->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::aria_hidden
,
1035 if (shouldHideChain
&& mPopups
&&
1036 mPopups
->GetPopupType() == PopupType::Menu
) {
1037 // A menu item was activated before this menu closed, and the item requested
1038 // the entire popup chain to be closed, which includes any open non-native
1040 // Close the non-native menus now. This matches the HidePopup call in
1041 // nsXULMenuCommandEvent::Run.
1042 HidePopup(mPopups
->Element(), {HidePopupOption::HideChain
});
1046 void nsXULPopupManager::OnNativeSubMenuWillOpen(
1047 mozilla::dom::Element
* aPopupElement
) {
1048 mNativeMenuSubmenuStates
.InsertOrUpdate(aPopupElement
, ePopupShowing
);
1051 void nsXULPopupManager::OnNativeSubMenuDidOpen(
1052 mozilla::dom::Element
* aPopupElement
) {
1053 mNativeMenuSubmenuStates
.InsertOrUpdate(aPopupElement
, ePopupShown
);
1056 void nsXULPopupManager::OnNativeSubMenuClosed(
1057 mozilla::dom::Element
* aPopupElement
) {
1058 mNativeMenuSubmenuStates
.Remove(aPopupElement
);
1061 void nsXULPopupManager::OnNativeMenuWillActivateItem(
1062 mozilla::dom::Element
* aMenuItemElement
) {
1067 CloseMenuMode cmm
= GetCloseMenuMode(aMenuItemElement
);
1068 mNativeMenuActivatedItemCloseMenuMode
= Some(cmm
);
1070 if (cmm
== CloseMenuMode_Auto
) {
1071 // If any non-native menus are visible (for example because the context menu
1072 // was opened on a non-native menu item, e.g. in a bookmarks folder), hide
1073 // the non-native menus before executing the item.
1074 HideOpenMenusBeforeExecutingMenu(CloseMenuMode_Auto
);
1078 void nsXULPopupManager::ShowPopupAtScreenRect(
1079 Element
* aPopup
, const nsAString
& aPosition
, const nsIntRect
& aRect
,
1080 bool aIsContextMenu
, bool aAttributesOverride
, Event
* aTriggerEvent
) {
1081 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
1082 if (!popupFrame
|| !MayShowPopup(popupFrame
)) return;
1084 PendingPopup
pendingPopup(aPopup
, aTriggerEvent
);
1085 nsCOMPtr
<nsIContent
> triggerContent
= pendingPopup
.GetTriggerContent();
1087 popupFrame
->InitializePopupAtRect(triggerContent
, aPosition
, aRect
,
1088 aAttributesOverride
);
1090 BeginShowingPopup(pendingPopup
, aIsContextMenu
, false);
1093 void nsXULPopupManager::ShowTooltipAtScreen(
1094 Element
* aPopup
, nsIContent
* aTriggerContent
,
1095 const LayoutDeviceIntPoint
& aScreenPoint
) {
1096 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(aPopup
, true);
1097 if (!popupFrame
|| !MayShowPopup(popupFrame
)) {
1101 PendingPopup
pendingPopup(aPopup
, nullptr);
1103 nsPresContext
* pc
= popupFrame
->PresContext();
1104 pendingPopup
.SetMousePoint([&] {
1105 // Event coordinates are relative to the root widget
1106 if (nsPresContext
* rootPresContext
= pc
->GetRootPresContext()) {
1107 if (nsCOMPtr
<nsIWidget
> rootWidget
= rootPresContext
->GetRootWidget()) {
1108 return aScreenPoint
- rootWidget
->WidgetToScreenOffset();
1111 return aScreenPoint
;
1114 auto screenCSSPoint
=
1115 CSSIntPoint::Round(aScreenPoint
/ pc
->CSSToDevPixelScale());
1116 popupFrame
->InitializePopupAtScreen(aTriggerContent
, screenCSSPoint
.x
,
1117 screenCSSPoint
.y
, false);
1119 BeginShowingPopup(pendingPopup
, false, false);
1122 static void CheckCaretDrawingState() {
1123 // There is 1 caret per document, we need to find the focused
1124 // document and erase its caret.
1125 nsFocusManager
* fm
= nsFocusManager::GetFocusManager();
1127 nsCOMPtr
<mozIDOMWindowProxy
> window
;
1128 fm
->GetFocusedWindow(getter_AddRefs(window
));
1129 if (!window
) return;
1131 auto* piWindow
= nsPIDOMWindowOuter::From(window
);
1132 MOZ_ASSERT(piWindow
);
1134 nsCOMPtr
<Document
> focusedDoc
= piWindow
->GetDoc();
1135 if (!focusedDoc
) return;
1137 PresShell
* presShell
= focusedDoc
->GetPresShell();
1142 RefPtr
<nsCaret
> caret
= presShell
->GetCaret();
1144 caret
->SchedulePaint();
1148 void nsXULPopupManager::ShowPopupCallback(Element
* aPopup
,
1149 nsMenuPopupFrame
* aPopupFrame
,
1150 bool aIsContextMenu
,
1151 bool aSelectFirstItem
) {
1152 PopupType popupType
= aPopupFrame
->GetPopupType();
1153 const bool isMenu
= popupType
== PopupType::Menu
;
1155 // Popups normally hide when an outside click occurs. Panels may use
1156 // the noautohide attribute to disable this behaviour. It is expected
1157 // that the application will hide these popups manually. The tooltip
1158 // listener will handle closing the tooltip also.
1160 aPopupFrame
->IsNoAutoHide() || popupType
== PopupType::Tooltip
;
1162 auto item
= MakeUnique
<nsMenuChainItem
>(aPopupFrame
, isNoAutoHide
,
1163 aIsContextMenu
, popupType
);
1165 // install keyboard event listeners for navigating menus. For panels, the
1166 // escape key may be used to close the panel. However, the ignorekeys
1167 // attribute may be used to disable adding these event listeners for popups
1168 // that want to handle their own keyboard events.
1169 nsAutoString ignorekeys
;
1170 aPopup
->GetAttr(nsGkAtoms::ignorekeys
, ignorekeys
);
1171 if (ignorekeys
.EqualsLiteral("true")) {
1172 item
->SetIgnoreKeys(eIgnoreKeys_True
);
1173 } else if (ignorekeys
.EqualsLiteral("shortcuts")) {
1174 item
->SetIgnoreKeys(eIgnoreKeys_Shortcuts
);
1178 // if the menu is on a menubar, use the menubar's listener instead
1179 if (auto* menu
= aPopupFrame
->PopupElement().GetContainingMenu()) {
1180 item
->SetOnMenuBar(menu
->IsOnMenuBar());
1184 // use a weak frame as the popup will set an open attribute if it is a menu
1185 AutoWeakFrame
weakFrame(aPopupFrame
);
1186 aPopupFrame
->ShowPopup(aIsContextMenu
);
1187 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1189 item
->UpdateFollowAnchor();
1191 AddMenuChainItem(std::move(item
));
1192 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1194 RefPtr popup
= &aPopupFrame
->PopupElement();
1195 popup
->PopupOpened(aSelectFirstItem
);
1198 UpdateMenuItems(aPopup
);
1201 // Caret visibility may have been affected, ensure that
1202 // the caret isn't now drawn when it shouldn't be.
1203 CheckCaretDrawingState();
1206 nsMenuChainItem
* nsXULPopupManager::FindPopup(Element
* aPopup
) const {
1207 auto matcher
= [&](nsMenuChainItem
* aItem
) -> bool {
1208 return aItem
->Frame()->GetContent() == aPopup
;
1210 return FirstMatchingPopup(matcher
);
1213 void nsXULPopupManager::HidePopup(Element
* aPopup
, HidePopupOptions aOptions
,
1214 Element
* aLastPopup
) {
1215 if (mNativeMenu
&& mNativeMenu
->Element() == aPopup
) {
1216 RefPtr
<NativeMenu
> menu
= mNativeMenu
;
1217 (void)menu
->Close();
1221 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(aPopup
->GetPrimaryFrame());
1226 nsMenuChainItem
* foundPopup
= FindPopup(aPopup
);
1228 RefPtr
<Element
> popupToHide
, nextPopup
, lastPopup
;
1231 if (foundPopup
->IsNoAutoHide()) {
1232 // If this is a noautohide panel, remove it but don't close any other
1234 popupToHide
= aPopup
;
1235 // XXX This preserves behavior but why is it the right thing to do?
1236 aOptions
-= HidePopupOption::DeselectMenu
;
1238 // At this point, foundPopup will be set to the found item in the list. If
1239 // foundPopup is the topmost menu, the one to remove, then there are no
1240 // other popups to hide. If foundPopup is not the topmost menu, then there
1241 // may be open submenus below it. In this case, we need to make sure that
1242 // those submenus are closed up first. To do this, we scan up the menu
1243 // list to find the topmost popup with only menus between it and
1244 // foundPopup and close that menu first. In synchronous mode, the
1245 // FirePopupHidingEvent method will be called which in turn calls
1246 // HidePopupCallback to close up the next popup in the chain. These two
1247 // methods will be called in sequence recursively to close up all the
1248 // necessary popups. In asynchronous mode, a similar process occurs except
1249 // that the FirePopupHidingEvent method is called asynchronously. In
1250 // either case, nextPopup is set to the content node of the next popup to
1251 // close, and lastPopup is set to the last popup in the chain to close,
1252 // which will be aPopup, or null to close up all menus.
1254 nsMenuChainItem
* topMenu
= foundPopup
;
1255 // Use IsMenu to ensure that foundPopup is a menu and scan down the child
1256 // list until a non-menu is found. If foundPopup isn't a menu at all,
1257 // don't scan and just close up this menu.
1258 if (foundPopup
->IsMenu()) {
1259 nsMenuChainItem
* child
= foundPopup
->GetChild();
1260 while (child
&& child
->IsMenu()) {
1262 child
= child
->GetChild();
1266 popupToHide
= topMenu
->Element();
1267 popupFrame
= topMenu
->Frame();
1269 const bool hideChain
= aOptions
.contains(HidePopupOption::HideChain
);
1271 // Close up another popup if there is one, and we are either hiding the
1272 // entire chain or the item to hide isn't the topmost popup.
1273 nsMenuChainItem
* parent
= topMenu
->GetParent();
1274 if (parent
&& (hideChain
|| topMenu
!= foundPopup
)) {
1275 while (parent
&& parent
->IsNoAutoHide()) {
1276 parent
= parent
->GetParent();
1280 nextPopup
= parent
->Element();
1284 lastPopup
= aLastPopup
? aLastPopup
: (hideChain
? nullptr : aPopup
);
1286 } else if (popupFrame
->PopupState() == ePopupPositioning
) {
1287 // When the popup is in the popuppositioning state, it will not be in the
1288 // mPopups list. We need another way to find it and make sure it does not
1289 // continue the popup showing process.
1290 popupToHide
= aPopup
;
1297 nsPopupState state
= popupFrame
->PopupState();
1298 if (state
== ePopupHiding
) {
1299 // If the popup is already being hidden, don't fire another popuphiding
1300 // event. But finish hiding it sync if we need to.
1301 if (aOptions
.contains(HidePopupOption::DisableAnimations
) &&
1302 !aOptions
.contains(HidePopupOption::Async
)) {
1303 HidePopupCallback(popupToHide
, popupFrame
, nullptr, nullptr,
1304 popupFrame
->GetPopupType(), aOptions
);
1309 // Change the popup state to hiding. Don't set the hiding state if the
1310 // popup is invisible, otherwise nsMenuPopupFrame::HidePopup will
1311 // run again. In the invisible state, we just want the events to fire.
1312 if (state
!= ePopupInvisible
) {
1313 popupFrame
->SetPopupState(ePopupHiding
);
1316 // For menus, popupToHide is always the frontmost item in the list to hide.
1317 if (aOptions
.contains(HidePopupOption::Async
)) {
1318 nsCOMPtr
<nsIRunnable
> event
=
1319 new nsXULPopupHidingEvent(popupToHide
, nextPopup
, lastPopup
,
1320 popupFrame
->GetPopupType(), aOptions
);
1321 aPopup
->OwnerDoc()->Dispatch(event
.forget());
1323 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1324 FirePopupHidingEvent(popupToHide
, nextPopup
, lastPopup
, presContext
,
1325 popupFrame
->GetPopupType(), aOptions
);
1329 void nsXULPopupManager::HideMenu(nsIContent
* aMenu
) {
1330 if (mNativeMenu
&& aMenu
->IsElement() &&
1331 mNativeMenu
->Element()->Contains(aMenu
)) {
1332 mNativeMenu
->CloseSubmenu(aMenu
->AsElement());
1336 auto* button
= XULButtonElement::FromNode(aMenu
);
1337 if (!button
|| !button
->IsMenu()) {
1340 auto* popup
= button
->GetMenuPopupContent();
1344 HidePopup(popup
, {HidePopupOption::DeselectMenu
});
1347 // This is used to hide the popup after a transition finishes.
1348 class TransitionEnder final
: public nsIDOMEventListener
{
1350 // Effectively const but is cycle collected
1351 MOZ_KNOWN_LIVE RefPtr
<Element
> mElement
;
1354 virtual ~TransitionEnder() = default;
1357 HidePopupOptions mOptions
;
1359 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
1360 NS_DECL_CYCLE_COLLECTION_CLASS(TransitionEnder
)
1362 TransitionEnder(Element
* aElement
, HidePopupOptions aOptions
)
1363 : mElement(aElement
), mOptions(aOptions
) {}
1365 MOZ_CAN_RUN_SCRIPT NS_IMETHOD
HandleEvent(Event
* aEvent
) override
{
1366 mElement
->RemoveSystemEventListener(u
"transitionend"_ns
, this, false);
1367 mElement
->RemoveSystemEventListener(u
"transitioncancel"_ns
, this, false);
1369 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(mElement
->GetPrimaryFrame());
1370 if (!popupFrame
|| popupFrame
->PopupState() != ePopupHiding
) {
1374 // Now hide the popup. There could be other properties transitioning, but
1375 // we'll assume they all end at the same time and just hide the popup upon
1376 // the first one ending.
1377 if (RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance()) {
1378 pm
->HidePopupCallback(mElement
, popupFrame
, nullptr, nullptr,
1379 popupFrame
->GetPopupType(), mOptions
);
1386 NS_IMPL_CYCLE_COLLECTING_ADDREF(TransitionEnder
)
1387 NS_IMPL_CYCLE_COLLECTING_RELEASE(TransitionEnder
)
1388 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TransitionEnder
)
1389 NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener
)
1390 NS_INTERFACE_MAP_ENTRY(nsISupports
)
1391 NS_INTERFACE_MAP_END
1393 NS_IMPL_CYCLE_COLLECTION(TransitionEnder
, mElement
);
1394 void nsXULPopupManager::HidePopupCallback(
1395 Element
* aPopup
, nsMenuPopupFrame
* aPopupFrame
, Element
* aNextPopup
,
1396 Element
* aLastPopup
, PopupType aPopupType
, HidePopupOptions aOptions
) {
1397 if (mCloseTimer
&& mTimerMenu
== aPopupFrame
) {
1398 mCloseTimer
->Cancel();
1399 mCloseTimer
= nullptr;
1400 mTimerMenu
= nullptr;
1403 // The popup to hide is aPopup. Search the list again to find the item that
1404 // corresponds to the popup to hide aPopup. This is done because it's
1405 // possible someone added another item (attempted to open another popup)
1406 // or removed a popup frame during the event processing so the item isn't at
1407 // the front anymore.
1408 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1409 if (item
->Element() == aPopup
) {
1410 RemoveMenuChainItem(item
);
1411 SetCaptureState(aPopup
);
1416 AutoWeakFrame
weakFrame(aPopupFrame
);
1417 aPopupFrame
->HidePopup(aOptions
.contains(HidePopupOption::DeselectMenu
),
1419 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1421 // send the popuphidden event synchronously. This event has no default
1423 nsEventStatus status
= nsEventStatus_eIgnore
;
1424 WidgetMouseEvent
event(true, eXULPopupHidden
, nullptr,
1425 WidgetMouseEvent::eReal
);
1426 RefPtr
<nsPresContext
> presContext
= aPopupFrame
->PresContext();
1427 EventDispatcher::Dispatch(aPopup
, presContext
, &event
, nullptr, &status
);
1428 NS_ENSURE_TRUE_VOID(weakFrame
.IsAlive());
1430 // Force any popups that might be anchored on elements within this popup to
1432 UpdatePopupPositions(presContext
->RefreshDriver());
1434 // if there are more popups to close, look for the next one
1435 if (aNextPopup
&& aPopup
!= aLastPopup
) {
1436 nsMenuChainItem
* foundMenu
= FindPopup(aNextPopup
);
1438 // continue hiding the chain of popups until the last popup aLastPopup
1439 // is reached, or until a popup of a different type is reached. This
1440 // last check is needed so that a menulist inside a non-menu panel only
1441 // closes the menu and not the panel as well.
1442 if (foundMenu
&& (aLastPopup
|| aPopupType
== foundMenu
->GetPopupType())) {
1443 nsCOMPtr
<Element
> popupToHide
= foundMenu
->Element();
1444 nsMenuChainItem
* parent
= foundMenu
->GetParent();
1446 nsCOMPtr
<Element
> nextPopup
;
1447 if (parent
&& popupToHide
!= aLastPopup
) nextPopup
= parent
->Element();
1449 nsMenuPopupFrame
* popupFrame
= foundMenu
->Frame();
1450 nsPopupState state
= popupFrame
->PopupState();
1451 if (state
== ePopupHiding
) return;
1452 if (state
!= ePopupInvisible
) popupFrame
->SetPopupState(ePopupHiding
);
1454 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1455 FirePopupHidingEvent(popupToHide
, nextPopup
, aLastPopup
, presContext
,
1456 foundMenu
->GetPopupType(), aOptions
);
1461 void nsXULPopupManager::HidePopupAfterDelay(nsMenuPopupFrame
* aPopup
,
1463 // Don't close up immediately.
1464 // Kick off a close timer.
1467 // Kick off the timer.
1468 nsIEventTarget
* target
= GetMainThreadSerialEventTarget();
1469 NS_NewTimerWithFuncCallback(
1470 getter_AddRefs(mCloseTimer
),
1471 [](nsITimer
* aTimer
, void* aClosure
) {
1472 if (nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance()) {
1473 pm
->KillMenuTimer();
1476 nullptr, aDelay
, nsITimer::TYPE_ONE_SHOT
, "KillMenuTimer", target
);
1477 // the popup will call PopupDestroyed if it is destroyed, which checks if it
1478 // is set to mTimerMenu, so it should be safe to keep a reference to it
1479 mTimerMenu
= aPopup
;
1482 void nsXULPopupManager::HidePopupsInList(
1483 const nsTArray
<nsMenuPopupFrame
*>& aFrames
) {
1484 // Create a weak frame list. This is done in a separate array with the
1485 // right capacity predetermined to avoid multiple allocations.
1486 nsTArray
<WeakFrame
> weakPopups(aFrames
.Length());
1488 for (f
= 0; f
< aFrames
.Length(); f
++) {
1489 WeakFrame
* wframe
= weakPopups
.AppendElement();
1490 if (wframe
) *wframe
= aFrames
[f
];
1493 for (f
= 0; f
< weakPopups
.Length(); f
++) {
1494 // check to ensure that the frame is still alive before hiding it.
1495 if (weakPopups
[f
].IsAlive()) {
1496 auto* frame
= static_cast<nsMenuPopupFrame
*>(weakPopups
[f
].GetFrame());
1497 frame
->HidePopup(true, ePopupInvisible
);
1501 SetCaptureState(nullptr);
1504 bool nsXULPopupManager::IsChildOfDocShell(Document
* aDoc
,
1505 nsIDocShellTreeItem
* aExpected
) {
1506 nsCOMPtr
<nsIDocShellTreeItem
> docShellItem(aDoc
->GetDocShell());
1507 while (docShellItem
) {
1508 if (docShellItem
== aExpected
) return true;
1510 nsCOMPtr
<nsIDocShellTreeItem
> parent
;
1511 docShellItem
->GetInProcessParent(getter_AddRefs(parent
));
1512 docShellItem
= parent
;
1518 void nsXULPopupManager::HidePopupsInDocShell(
1519 nsIDocShellTreeItem
* aDocShellToHide
) {
1520 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
1522 // Iterate to get the set of popup frames to hide
1523 nsMenuChainItem
* item
= mPopups
.get();
1525 // Get the parent before calling detach so that we can keep iterating.
1526 nsMenuChainItem
* parent
= item
->GetParent();
1527 if (item
->Frame()->PopupState() != ePopupInvisible
&&
1528 IsChildOfDocShell(item
->Element()->OwnerDoc(), aDocShellToHide
)) {
1529 nsMenuPopupFrame
* frame
= item
->Frame();
1530 RemoveMenuChainItem(item
);
1531 popupsToHide
.AppendElement(frame
);
1536 HidePopupsInList(popupsToHide
);
1539 void nsXULPopupManager::UpdatePopupPositions(nsRefreshDriver
* aRefreshDriver
) {
1540 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1541 if (item
->Frame()->PresContext()->RefreshDriver() == aRefreshDriver
) {
1542 item
->CheckForAnchorChange();
1547 void nsXULPopupManager::UpdateFollowAnchor(nsMenuPopupFrame
* aPopup
) {
1548 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1549 if (item
->Frame() == aPopup
) {
1550 item
->UpdateFollowAnchor();
1556 void nsXULPopupManager::HideOpenMenusBeforeExecutingMenu(CloseMenuMode aMode
) {
1557 if (aMode
== CloseMenuMode_None
) {
1561 // When a menuitem is selected to be executed, first hide all the open
1562 // popups, but don't remove them yet. This is needed when a menu command
1563 // opens a modal dialog. The views associated with the popups needed to be
1564 // hidden and the accesibility events fired before the command executes, but
1565 // the popuphiding/popuphidden events are fired afterwards.
1566 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
1567 nsMenuChainItem
* item
= GetTopVisibleMenu();
1569 // if it isn't a <menupopup>, don't close it automatically
1570 if (!item
->IsMenu()) {
1574 nsMenuChainItem
* next
= item
->GetParent();
1575 popupsToHide
.AppendElement(item
->Frame());
1576 if (aMode
== CloseMenuMode_Single
) {
1577 // only close one level of menu
1583 // Now hide the popups. If the closemenu mode is auto, deselect the menu,
1584 // otherwise only one popup is closing, so keep the parent menu selected.
1585 HidePopupsInList(popupsToHide
);
1588 void nsXULPopupManager::ExecuteMenu(nsIContent
* aMenu
,
1589 nsXULMenuCommandEvent
* aEvent
) {
1590 CloseMenuMode cmm
= GetCloseMenuMode(aMenu
);
1591 HideOpenMenusBeforeExecutingMenu(cmm
);
1592 aEvent
->SetCloseMenuMode(cmm
);
1593 nsCOMPtr
<nsIRunnable
> event
= aEvent
;
1594 aMenu
->OwnerDoc()->Dispatch(event
.forget());
1597 bool nsXULPopupManager::ActivateNativeMenuItem(nsIContent
* aItem
,
1598 mozilla::Modifiers aModifiers
,
1600 mozilla::ErrorResult
& aRv
) {
1601 if (mNativeMenu
&& aItem
->IsElement() &&
1602 mNativeMenu
->Element()->Contains(aItem
)) {
1603 mNativeMenu
->ActivateItem(aItem
->AsElement(), aModifiers
, aButton
, aRv
);
1609 nsEventStatus
nsXULPopupManager::FirePopupShowingEvent(
1610 const PendingPopup
& aPendingPopup
, nsPresContext
* aPresContext
) {
1611 // Cache the pending popup so that the trigger node and other properties can
1612 // be retrieved during the popupshowing event. It will be cleared below after
1613 // the event has fired.
1614 AutoRestore
<const PendingPopup
*> restorePendingPopup(mPendingPopup
);
1615 mPendingPopup
= &aPendingPopup
;
1617 nsEventStatus status
= nsEventStatus_eIgnore
;
1618 WidgetMouseEvent
event(true, eXULPopupShowing
, nullptr,
1619 WidgetMouseEvent::eReal
);
1621 // coordinates are relative to the root widget
1622 nsPresContext
* rootPresContext
= aPresContext
->GetRootPresContext();
1623 if (rootPresContext
) {
1625 rootPresContext
->PresShell()->GetViewManager()->GetRootWidget();
1627 event
.mWidget
= nullptr;
1630 event
.mInputSource
= aPendingPopup
.MouseInputSource();
1631 event
.mRefPoint
= aPendingPopup
.mMousePoint
;
1632 event
.mModifiers
= aPendingPopup
.mModifiers
;
1633 RefPtr
<nsIContent
> popup
= aPendingPopup
.mPopup
;
1634 EventDispatcher::Dispatch(popup
, aPresContext
, &event
, nullptr, &status
);
1639 void nsXULPopupManager::BeginShowingPopup(const PendingPopup
& aPendingPopup
,
1640 bool aIsContextMenu
,
1641 bool aSelectFirstItem
) {
1642 RefPtr
<Element
> popup
= aPendingPopup
.mPopup
;
1644 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(popup
->GetPrimaryFrame());
1645 if (NS_WARN_IF(!popupFrame
)) {
1649 RefPtr
<nsPresContext
> presContext
= popupFrame
->PresContext();
1650 RefPtr
<PresShell
> presShell
= presContext
->PresShell();
1651 presShell
->FrameNeedsReflow(popupFrame
, IntrinsicDirty::FrameAndAncestors
,
1654 PopupType popupType
= popupFrame
->GetPopupType();
1656 nsEventStatus status
= FirePopupShowingEvent(aPendingPopup
, presContext
);
1658 // if a panel, blur whatever has focus so that the panel can take the focus.
1659 // This is done after the popupshowing event in case that event is cancelled.
1660 // Using noautofocus="true" will disable this behaviour, which is needed for
1661 // the autocomplete widget as it manages focus itself.
1662 if (popupType
== PopupType::Panel
&&
1663 !popup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::noautofocus
,
1664 nsGkAtoms::_true
, eCaseMatters
)) {
1665 if (RefPtr
<nsFocusManager
> fm
= nsFocusManager::GetFocusManager()) {
1666 Document
* doc
= popup
->GetUncomposedDoc();
1668 // Only remove the focus if the currently focused item is ouside the
1669 // popup. It isn't a big deal if the current focus is in a child popup
1670 // inside the popup as that shouldn't be visible. This check ensures that
1671 // a node inside the popup that is focused during a popupshowing event
1673 RefPtr
<Element
> currentFocus
= fm
->GetFocusedElement();
1674 if (doc
&& currentFocus
&&
1675 !nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus
, popup
)) {
1676 nsCOMPtr
<nsPIDOMWindowOuter
> outerWindow
= doc
->GetWindow();
1677 fm
->ClearFocus(outerWindow
);
1682 popup
->OwnerDoc()->FlushPendingNotifications(FlushType::Frames
);
1684 // get the frame again in case it went away
1685 popupFrame
= do_QueryFrame(popup
->GetPrimaryFrame());
1689 // if the event was cancelled or the popup was closed in the mean time, don't
1690 // open the popup, reset its state back to closed and clear its trigger
1692 if (popupFrame
->PopupState() == ePopupClosed
||
1693 status
== nsEventStatus_eConsumeNoDefault
) {
1694 popupFrame
->SetPopupState(ePopupClosed
);
1695 popupFrame
->ClearTriggerContent();
1698 // Now check if we need to fire the popuppositioned event. If not, call
1699 // ShowPopupCallback directly.
1700 // The popuppositioned event only fires on arrow panels for now.
1701 if (popup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
,
1703 popupFrame
->ShowWithPositionedEvent();
1704 presShell
->FrameNeedsReflow(popupFrame
, IntrinsicDirty::FrameAndAncestors
,
1705 NS_FRAME_HAS_DIRTY_CHILDREN
);
1707 ShowPopupCallback(popup
, popupFrame
, aIsContextMenu
, aSelectFirstItem
);
1711 void nsXULPopupManager::FirePopupHidingEvent(Element
* aPopup
,
1712 Element
* aNextPopup
,
1713 Element
* aLastPopup
,
1714 nsPresContext
* aPresContext
,
1715 PopupType aPopupType
,
1716 HidePopupOptions aOptions
) {
1717 nsCOMPtr
<nsIContent
> popup
= aPopup
;
1718 RefPtr
<PresShell
> presShell
= aPresContext
->PresShell();
1719 Unused
<< presShell
; // This presShell may be keeping things alive
1720 // on non GTK platforms
1722 nsEventStatus status
= nsEventStatus_eIgnore
;
1723 WidgetMouseEvent
event(true, eXULPopupHiding
, nullptr,
1724 WidgetMouseEvent::eReal
);
1725 EventDispatcher::Dispatch(aPopup
, aPresContext
, &event
, nullptr, &status
);
1727 // when a panel is closed, blur whatever has focus inside the popup
1728 if (aPopupType
== PopupType::Panel
&&
1729 (!aPopup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::noautofocus
,
1730 nsGkAtoms::_true
, eCaseMatters
))) {
1731 if (RefPtr
<nsFocusManager
> fm
= nsFocusManager::GetFocusManager()) {
1732 Document
* doc
= aPopup
->GetUncomposedDoc();
1734 // Remove the focus from the focused node only if it is inside the popup.
1735 RefPtr
<Element
> currentFocus
= fm
->GetFocusedElement();
1736 if (doc
&& currentFocus
&&
1737 nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus
, aPopup
)) {
1738 nsCOMPtr
<nsPIDOMWindowOuter
> outerWindow
= doc
->GetWindow();
1739 fm
->ClearFocus(outerWindow
);
1744 aPopup
->OwnerDoc()->FlushPendingNotifications(FlushType::Frames
);
1746 // get frame again in case it went away
1747 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(aPopup
->GetPrimaryFrame());
1752 // If the event was cancelled, don't hide the popup, and reset its
1753 // state back to open. Only popups in chrome shells can prevent a popup
1755 if (status
== nsEventStatus_eConsumeNoDefault
&&
1756 !popupFrame
->IsInContentShell()) {
1758 // If an attempt was made to hide this popup before the popupshown event
1759 // fired, then ePopupShown is set here even though it should be
1760 // ePopupVisible. This probably isn't worth the hassle of handling.
1761 popupFrame
->SetPopupState(ePopupShown
);
1765 const bool shouldAnimate
= [&] {
1766 if (!LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations
)) {
1767 // Animations are not supported by the platform, avoid transitioning.
1770 if (aOptions
.contains(HidePopupOption::DisableAnimations
)) {
1771 // Animations are not allowed by our caller.
1775 // If there is a next popup, indicating that mutliple popups are rolling
1776 // up, don't wait and hide the popup right away since the effect would
1777 // likely be undesirable.
1780 nsAutoString animate
;
1781 if (!aPopup
->GetAttr(nsGkAtoms::animate
, animate
)) {
1784 // If animate="false" then don't transition at all.
1785 if (animate
.EqualsLiteral("false")) {
1788 // If animate="cancel", only show the transition if cancelling the popup
1790 if (animate
.EqualsLiteral("cancel") &&
1791 !aOptions
.contains(HidePopupOption::IsRollup
)) {
1796 // If we should animate the popup, check if it has a closing transition
1797 // and wait for it to finish.
1798 // The transition would still occur either way, but if we don't wait the
1799 // view will be hidden and you won't be able to see it.
1800 if (shouldAnimate
&& AnimationUtils::HasCurrentTransitions(
1801 aPopup
, PseudoStyleType::NotPseudo
)) {
1802 RefPtr
<TransitionEnder
> ender
= new TransitionEnder(aPopup
, aOptions
);
1803 aPopup
->AddSystemEventListener(u
"transitionend"_ns
, ender
, false, false);
1804 aPopup
->AddSystemEventListener(u
"transitioncancel"_ns
, ender
, false, false);
1808 HidePopupCallback(aPopup
, popupFrame
, aNextPopup
, aLastPopup
, aPopupType
,
1812 bool nsXULPopupManager::IsPopupOpen(Element
* aPopup
) {
1813 if (mNativeMenu
&& mNativeMenu
->Element() == aPopup
) {
1817 // a popup is open if it is in the open list. The assertions ensure that the
1818 // frame is in the correct state. If the popup is in the hiding or invisible
1819 // state, it will still be in the open popup list until it is closed.
1820 if (nsMenuChainItem
* item
= FindPopup(aPopup
)) {
1821 NS_ASSERTION(item
->Frame()->IsOpen() ||
1822 item
->Frame()->PopupState() == ePopupHiding
||
1823 item
->Frame()->PopupState() == ePopupInvisible
,
1824 "popup in open list not actually open");
1831 nsIFrame
* nsXULPopupManager::GetTopPopup(PopupType aType
) {
1832 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1833 if (item
->Frame()->IsVisible() &&
1834 (item
->GetPopupType() == aType
|| aType
== PopupType::Any
)) {
1835 return item
->Frame();
1841 nsIContent
* nsXULPopupManager::GetTopActiveMenuItemContent() {
1842 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1843 if (!item
->Frame()->IsVisible()) {
1846 if (auto* content
= item
->Frame()->PopupElement().GetActiveMenuChild()) {
1853 void nsXULPopupManager::GetVisiblePopups(nsTArray
<nsIFrame
*>& aPopups
) {
1855 for (nsMenuChainItem
* item
= mPopups
.get(); item
; item
= item
->GetParent()) {
1856 // Skip panels which are not visible as well as popups that are transparent
1858 if (item
->Frame()->IsVisible() && !item
->Frame()->IsMouseTransparent()) {
1859 aPopups
.AppendElement(item
->Frame());
1864 already_AddRefed
<nsINode
> nsXULPopupManager::GetLastTriggerNode(
1865 Document
* aDocument
, bool aIsTooltip
) {
1866 if (!aDocument
) return nullptr;
1868 RefPtr
<nsINode
> node
;
1870 // If a pending popup is set, it means that a popupshowing event is being
1871 // fired. In this case, just use the cached node, as the popup is not yet in
1872 // the list of open popups.
1873 RefPtr
<nsIContent
> openingPopup
=
1874 mPendingPopup
? mPendingPopup
->mPopup
: nullptr;
1875 if (openingPopup
&& openingPopup
->GetUncomposedDoc() == aDocument
&&
1876 aIsTooltip
== openingPopup
->IsXULElement(nsGkAtoms::tooltip
)) {
1877 node
= nsMenuPopupFrame::GetTriggerContent(
1878 GetPopupFrameForContent(openingPopup
, false));
1879 } else if (mNativeMenu
&& !aIsTooltip
) {
1880 RefPtr
<dom::Element
> popup
= mNativeMenu
->Element();
1881 if (popup
->GetUncomposedDoc() == aDocument
) {
1882 nsMenuPopupFrame
* popupFrame
= GetPopupFrameForContent(popup
, false);
1883 node
= nsMenuPopupFrame::GetTriggerContent(popupFrame
);
1886 for (nsMenuChainItem
* item
= mPopups
.get(); item
;
1887 item
= item
->GetParent()) {
1888 // look for a popup of the same type and document.
1889 if ((item
->GetPopupType() == PopupType::Tooltip
) == aIsTooltip
&&
1890 item
->Element()->GetUncomposedDoc() == aDocument
) {
1891 node
= nsMenuPopupFrame::GetTriggerContent(item
->Frame());
1899 return node
.forget();
1902 bool nsXULPopupManager::MayShowPopup(nsMenuPopupFrame
* aPopup
) {
1903 // if a popup's IsOpen method returns true, then the popup must always be in
1904 // the popup chain scanned in IsPopupOpen.
1905 NS_ASSERTION(!aPopup
->IsOpen() || IsPopupOpen(&aPopup
->PopupElement()),
1906 "popup frame state doesn't match XULPopupManager open state");
1908 nsPopupState state
= aPopup
->PopupState();
1910 // if the popup is not in the open popup chain, then it must have a state that
1911 // is either closed, in the process of being shown, or invisible.
1912 NS_ASSERTION(IsPopupOpen(&aPopup
->PopupElement()) || state
== ePopupClosed
||
1913 state
== ePopupShowing
|| state
== ePopupPositioning
||
1914 state
== ePopupInvisible
,
1915 "popup not in XULPopupManager open list is open");
1917 // don't show popups unless they are closed or invisible
1918 if (state
!= ePopupClosed
&& state
!= ePopupInvisible
) return false;
1920 // Don't show popups that we already have in our popup chain
1921 if (IsPopupOpen(&aPopup
->PopupElement())) {
1922 NS_WARNING("Refusing to show duplicate popup");
1926 // if the popup was just rolled up, don't reopen it
1927 if (mozilla::widget::nsAutoRollup::GetLastRollup() == aPopup
->GetContent()) {
1931 nsCOMPtr
<nsIDocShell
> docShell
= aPopup
->PresContext()->GetDocShell();
1933 nsCOMPtr
<nsIBaseWindow
> baseWin
= do_QueryInterface(docShell
);
1938 nsCOMPtr
<nsIDocShellTreeItem
> root
;
1939 docShell
->GetInProcessRootTreeItem(getter_AddRefs(root
));
1944 nsCOMPtr
<nsPIDOMWindowOuter
> rootWin
= root
->GetWindow();
1946 MOZ_RELEASE_ASSERT(XRE_IsParentProcess(),
1947 "Cannot have XUL in content process showing popups.");
1949 // chrome shells can always open popups, but other types of shells can only
1950 // open popups when they are focused and visible
1951 if (docShell
->ItemType() != nsIDocShellTreeItem::typeChrome
) {
1952 // only allow popups in active windows
1953 nsFocusManager
* fm
= nsFocusManager::GetFocusManager();
1954 if (!fm
|| !rootWin
) {
1958 nsCOMPtr
<nsPIDOMWindowOuter
> activeWindow
= fm
->GetActiveWindow();
1959 if (activeWindow
!= rootWin
) {
1963 // only allow popups in visible frames
1964 // TODO: This visibility check should be replaced with a check of
1965 // bc->IsActive(). It is okay for now since this is only called
1966 // in the parent process. Bug 1698533.
1968 baseWin
->GetVisibility(&visible
);
1974 // platforms respond differently when an popup is opened in a minimized
1975 // window, so this is always disabled.
1976 nsCOMPtr
<nsIWidget
> mainWidget
;
1977 baseWin
->GetMainWidget(getter_AddRefs(mainWidget
));
1978 if (mainWidget
&& mainWidget
->SizeMode() == nsSizeMode_Minimized
) {
1984 auto globalWin
= nsGlobalWindowOuter::Cast(rootWin
.get());
1985 if (globalWin
->IsInModalState()) {
1991 // cannot open a popup that is a submenu of a menupopup that isn't open.
1992 if (auto* menu
= aPopup
->PopupElement().GetContainingMenu()) {
1993 if (auto* parent
= XULPopupElement::FromNodeOrNull(menu
->GetMenuParent())) {
1994 nsMenuPopupFrame
* f
= do_QueryFrame(parent
->GetPrimaryFrame());
1995 if (f
&& !f
->IsOpen()) {
2004 void nsXULPopupManager::PopupDestroyed(nsMenuPopupFrame
* aPopup
) {
2005 // when a popup frame is destroyed, just unhook it from the list of popups
2006 CancelMenuTimer(aPopup
);
2008 nsMenuChainItem
* item
= FindPopup(&aPopup
->PopupElement());
2013 nsTArray
<nsMenuPopupFrame
*> popupsToHide
;
2014 // XXXndeakin shouldn't this only happen for menus?
2015 if (!item
->IsNoAutoHide() && item
->Frame()->PopupState() != ePopupInvisible
) {
2016 // Iterate through any child menus and hide them as well, since the
2017 // parent is going away. We won't remove them from the list yet, just
2018 // hide them, as they will be removed from the list when this function
2019 // gets called for that child frame.
2020 for (auto* child
= item
->GetChild(); child
; child
= child
->GetChild()) {
2021 // If the popup is a child frame of the menu that was destroyed, add it
2022 // to the list of popups to hide. Don't bother with the events since the
2023 // frames are going away. If the child menu is not a child frame, for
2024 // example, a context menu, use HidePopup instead, but call it
2025 // asynchronously since we are in the middle of frame destruction.
2026 if (nsLayoutUtils::IsProperAncestorFrame(item
->Frame(), child
->Frame())) {
2027 popupsToHide
.AppendElement(child
->Frame());
2029 // HidePopup will take care of hiding any of its children, so
2030 // break out afterwards
2031 HidePopup(child
->Element(), {HidePopupOption::Async
});
2037 RemoveMenuChainItem(item
);
2038 HidePopupsInList(popupsToHide
);
2041 bool nsXULPopupManager::HasContextMenu(nsMenuPopupFrame
* aPopup
) {
2042 nsMenuChainItem
* item
= GetTopVisibleMenu();
2043 while (item
&& item
->Frame() != aPopup
) {
2044 if (item
->IsContextMenu()) return true;
2045 item
= item
->GetParent();
2051 void nsXULPopupManager::SetCaptureState(nsIContent
* aOldPopup
) {
2052 nsMenuChainItem
* item
= GetTopVisibleMenu();
2053 if (item
&& aOldPopup
== item
->Element()) return;
2056 mWidget
->CaptureRollupEvents(false);
2061 nsMenuPopupFrame
* popup
= item
->Frame();
2062 mWidget
= popup
->GetWidget();
2064 mWidget
->CaptureRollupEvents(true);
2068 UpdateKeyboardListeners();
2071 void nsXULPopupManager::UpdateKeyboardListeners() {
2072 nsCOMPtr
<EventTarget
> newTarget
;
2073 bool isForMenu
= false;
2074 if (nsMenuChainItem
* item
= GetTopVisibleMenu()) {
2075 if (item
->IgnoreKeys() != eIgnoreKeys_True
) {
2076 newTarget
= item
->Element()->GetComposedDoc();
2078 isForMenu
= item
->GetPopupType() == PopupType::Menu
;
2079 } else if (mActiveMenuBar
&& mActiveMenuBar
->IsActiveByKeyboard()) {
2080 // Only listen for key events iff menubar is activated via key, see
2082 newTarget
= mActiveMenuBar
->GetComposedDoc();
2086 if (mKeyListener
!= newTarget
) {
2087 OwningNonNull
<nsXULPopupManager
> kungFuDeathGrip(*this);
2089 mKeyListener
->RemoveEventListener(u
"keypress"_ns
, this, true);
2090 mKeyListener
->RemoveEventListener(u
"keydown"_ns
, this, true);
2091 mKeyListener
->RemoveEventListener(u
"keyup"_ns
, this, true);
2092 mKeyListener
= nullptr;
2093 nsContentUtils::NotifyInstalledMenuKeyboardListener(false);
2097 newTarget
->AddEventListener(u
"keypress"_ns
, this, true);
2098 newTarget
->AddEventListener(u
"keydown"_ns
, this, true);
2099 newTarget
->AddEventListener(u
"keyup"_ns
, this, true);
2100 nsContentUtils::NotifyInstalledMenuKeyboardListener(isForMenu
);
2101 mKeyListener
= newTarget
;
2106 void nsXULPopupManager::UpdateMenuItems(Element
* aPopup
) {
2107 // Walk all of the menu's children, checking to see if any of them has a
2108 // command attribute. If so, then several attributes must potentially be
2111 nsCOMPtr
<Document
> document
= aPopup
->GetUncomposedDoc();
2116 // When a menu is opened, make sure that command updating is unlocked first.
2117 nsCOMPtr
<nsIDOMXULCommandDispatcher
> commandDispatcher
=
2118 document
->GetCommandDispatcher();
2119 if (commandDispatcher
) {
2120 commandDispatcher
->Unlock();
2123 for (nsCOMPtr
<nsIContent
> grandChild
= aPopup
->GetFirstChild(); grandChild
;
2124 grandChild
= grandChild
->GetNextSibling()) {
2125 if (grandChild
->IsXULElement(nsGkAtoms::menugroup
)) {
2126 if (grandChild
->GetChildCount() == 0) {
2129 grandChild
= grandChild
->GetFirstChild();
2131 if (grandChild
->IsXULElement(nsGkAtoms::menuitem
)) {
2132 // See if we have a command attribute.
2133 Element
* grandChildElement
= grandChild
->AsElement();
2134 nsAutoString command
;
2135 grandChildElement
->GetAttr(nsGkAtoms::command
, command
);
2136 if (!command
.IsEmpty()) {
2137 // We do! Look it up in our document
2138 RefPtr
<dom::Element
> commandElement
= document
->GetElementById(command
);
2139 if (commandElement
) {
2140 nsAutoString commandValue
;
2141 // The menu's disabled state needs to be updated to match the command.
2142 if (commandElement
->GetAttr(nsGkAtoms::disabled
, commandValue
))
2143 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::disabled
,
2144 commandValue
, true);
2146 grandChildElement
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::disabled
,
2149 // The menu's label, accesskey checked and hidden states need to be
2150 // updated to match the command. Note that unlike the disabled state
2151 // if the command has *no* value, we assume the menu is supplying its
2153 if (commandElement
->GetAttr(nsGkAtoms::label
, commandValue
))
2154 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::label
,
2155 commandValue
, true);
2157 if (commandElement
->GetAttr(nsGkAtoms::accesskey
, commandValue
))
2158 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::accesskey
,
2159 commandValue
, true);
2161 if (commandElement
->GetAttr(nsGkAtoms::checked
, commandValue
))
2162 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::checked
,
2163 commandValue
, true);
2165 if (commandElement
->GetAttr(nsGkAtoms::hidden
, commandValue
))
2166 grandChildElement
->SetAttr(kNameSpaceID_None
, nsGkAtoms::hidden
,
2167 commandValue
, true);
2171 if (!grandChild
->GetNextSibling() &&
2172 grandChild
->GetParent()->IsXULElement(nsGkAtoms::menugroup
)) {
2173 grandChild
= grandChild
->GetParent();
2180 // The item selection timer has fired, we might have to readjust the
2181 // selected item. There are two cases here that we are trying to deal with:
2182 // (1) diagonal movement from a parent menu to a submenu passing briefly over
2184 // (2) moving out from a submenu to a parent or grandparent menu.
2185 // In both cases, |mTimerMenu| is the menu item that might have an open submenu
2186 // and the first item in |mPopups| is the item the mouse is currently over,
2187 // which could be none of them.
2190 // As the mouse moves from the parent item of a submenu (we'll call 'A')
2191 // diagonally into the submenu, it probably passes through one or more
2192 // sibilings (B). As the mouse passes through B, it becomes the current menu
2193 // item and the timer is set and mTimerMenu is set to A. Before the timer
2194 // fires, the mouse leaves the menu containing A and B and enters the submenus.
2195 // Now when the timer fires, |mPopups| is null (!= |mTimerMenu|) so we have to
2196 // see if anything in A's children is selected (recall that even disabled items
2197 // are selected, the style just doesn't show it). If that is the case, we need
2198 // to set the selected item back to A.
2201 // Item A has an open submenu, and in it there is an item (B) which also has an
2202 // open submenu (so there are 3 menus displayed right now). The mouse then
2203 // leaves B's child submenu and selects an item that is a sibling of A, call it
2204 // C. When the mouse enters C, the timer is set and |mTimerMenu| is A and
2205 // |mPopups| is C. As the timer fires, the mouse is still within C. The correct
2206 // behavior is to set the current item to C and close up the chain parented at
2209 // This brings up the question of is the logic of case (1) enough? The answer
2210 // is no, and is discussed in bugzilla bug 29400. Case (1) asks if A's submenu
2211 // has a selected child, and if it does, set the selected item to A. Because B
2212 // has a submenu open, it is selected and as a result, A is set to be the
2213 // selected item even though the mouse rests in C -- very wrong.
2215 // The solution is to use the same idea, but instead of only checking one
2216 // level, drill all the way down to the deepest open submenu and check if it
2217 // has something selected. Since the mouse is in a grandparent, it won't, and
2218 // we know that we can safely close up A and all its children.
2220 // The code below melds the two cases together.
2222 void nsXULPopupManager::KillMenuTimer() {
2223 if (mCloseTimer
&& mTimerMenu
) {
2224 mCloseTimer
->Cancel();
2225 mCloseTimer
= nullptr;
2227 if (mTimerMenu
->IsOpen()) {
2228 HidePopup(&mTimerMenu
->PopupElement(), {HidePopupOption::Async
});
2232 mTimerMenu
= nullptr;
2235 void nsXULPopupManager::CancelMenuTimer(nsMenuPopupFrame
* aMenu
) {
2236 if (mCloseTimer
&& mTimerMenu
== aMenu
) {
2237 mCloseTimer
->Cancel();
2238 mCloseTimer
= nullptr;
2239 mTimerMenu
= nullptr;
2243 bool nsXULPopupManager::HandleShortcutNavigation(KeyboardEvent
& aKeyEvent
,
2244 nsMenuPopupFrame
* aFrame
) {
2245 // On Windows, don't check shortcuts when the accelerator key is down.
2247 WidgetInputEvent
* evt
= aKeyEvent
.WidgetEventPtr()->AsInputEvent();
2248 if (evt
&& evt
->IsAccel()) {
2254 if (nsMenuChainItem
* item
= GetTopVisibleMenu()) {
2255 aFrame
= item
->Frame();
2260 bool action
= false;
2261 RefPtr result
= aFrame
->FindMenuWithShortcut(aKeyEvent
, action
);
2265 RefPtr popup
= &aFrame
->PopupElement();
2266 popup
->SetActiveMenuChild(result
, XULMenuParentElement::ByKey::Yes
);
2268 WidgetEvent
* evt
= aKeyEvent
.WidgetEventPtr();
2269 result
->HandleEnterKeyPress(*evt
);
2274 // Only do shortcut navigation when the menubar is activated via keyboard.
2275 if (mActiveMenuBar
) {
2276 RefPtr menubar
= mActiveMenuBar
;
2277 if (RefPtr result
= menubar
->FindMenuWithShortcut(aKeyEvent
)) {
2278 result
->OpenMenuPopup(true);
2282 // Behavior on Windows - this item is on the menu bar, beep and deactivate
2284 // TODO(emilio): This is rather odd, and I cannot get the beep to work,
2285 // but this matches what old code was doing...
2286 if (nsCOMPtr
<nsISound
> sound
= do_GetService("@mozilla.org/sound;1")) {
2289 menubar
->SetActive(false);
2295 bool nsXULPopupManager::HandleKeyboardNavigation(uint32_t aKeyCode
) {
2296 if (nsMenuChainItem
* nextitem
= GetTopVisibleMenu()) {
2297 nextitem
->Element()->OwnerDoc()->FlushPendingNotifications(
2301 // navigate up through the open menus, looking for the topmost one
2302 // in the same hierarchy
2303 nsMenuChainItem
* item
= nullptr;
2304 nsMenuChainItem
* nextitem
= GetTopVisibleMenu();
2307 nextitem
= item
->GetParent();
2312 // stop if the parent isn't a menu
2313 if (!nextitem
->IsMenu()) {
2317 // Check to make sure that the parent is actually the parent menu. It won't
2318 // be if the parent is in a different frame hierarchy, for example, for a
2319 // context menu opened on another menu.
2320 XULPopupElement
& expectedParent
= nextitem
->Frame()->PopupElement();
2321 auto* menu
= item
->Frame()->PopupElement().GetContainingMenu();
2322 if (!menu
|| menu
->GetMenuParent() != &expectedParent
) {
2327 nsIFrame
* itemFrame
;
2329 itemFrame
= item
->Frame();
2330 } else if (mActiveMenuBar
) {
2331 itemFrame
= mActiveMenuBar
->GetPrimaryFrame();
2339 nsNavigationDirection theDirection
;
2340 NS_ASSERTION(aKeyCode
>= KeyboardEvent_Binding::DOM_VK_END
&&
2341 aKeyCode
<= KeyboardEvent_Binding::DOM_VK_DOWN
,
2342 "Illegal key code");
2343 theDirection
= NS_DIRECTION_FROM_KEY_CODE(itemFrame
, aKeyCode
);
2345 bool selectFirstItem
= true;
2346 #ifdef MOZ_WIDGET_GTK
2348 XULButtonElement
* currentItem
= nullptr;
2349 if (item
&& mActiveMenuBar
&& NS_DIRECTION_IS_INLINE(theDirection
)) {
2350 currentItem
= item
->Frame()->PopupElement().GetActiveMenuChild();
2351 // If nothing is selected in the menu and we have a menubar, let it
2352 // handle the movement not to steal focus from it.
2357 // On menu change, only select first item if an item is already selected.
2358 selectFirstItem
= !!currentItem
;
2362 // if a popup is open, first check for navigation within the popup
2363 if (item
&& HandleKeyboardNavigationInPopup(item
, theDirection
)) {
2367 // no popup handled the key, so check the active menubar, if any
2368 if (!mActiveMenuBar
) {
2371 RefPtr menubar
= mActiveMenuBar
;
2372 if (NS_DIRECTION_IS_INLINE(theDirection
)) {
2373 RefPtr prevActiveItem
= menubar
->GetActiveMenuChild();
2374 const bool open
= prevActiveItem
&& prevActiveItem
->IsMenuPopupOpen();
2375 RefPtr nextItem
= theDirection
== eNavigationDirection_End
2376 ? menubar
->GetNextMenuItem()
2377 : menubar
->GetPrevMenuItem();
2378 menubar
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2379 if (open
&& nextItem
) {
2380 nextItem
->OpenMenuPopup(selectFirstItem
);
2384 if (NS_DIRECTION_IS_BLOCK(theDirection
)) {
2385 // Open the menu and select its first item.
2386 if (RefPtr currentMenu
= menubar
->GetActiveMenuChild()) {
2387 ShowMenu(currentMenu
, selectFirstItem
);
2394 bool nsXULPopupManager::HandleKeyboardNavigationInPopup(
2395 nsMenuChainItem
* item
, nsMenuPopupFrame
* aFrame
,
2396 nsNavigationDirection aDir
) {
2397 NS_ASSERTION(aFrame
, "aFrame is null");
2398 NS_ASSERTION(!item
|| item
->Frame() == aFrame
,
2399 "aFrame is expected to be equal to item->Frame()");
2401 using Wrap
= XULMenuParentElement::Wrap
;
2402 RefPtr
<XULPopupElement
> menu
= &aFrame
->PopupElement();
2404 aFrame
->ClearIncrementalString();
2405 RefPtr currentItem
= aFrame
->GetCurrentMenuItem();
2407 // This method only gets called if we're open.
2408 if (!currentItem
&& NS_DIRECTION_IS_INLINE(aDir
)) {
2409 // We've been opened, but we haven't had anything selected.
2410 // We can handle End, but our parent handles Start.
2411 if (aDir
== eNavigationDirection_End
) {
2412 if (RefPtr nextItem
= menu
->GetNextMenuItem(Wrap::No
)) {
2413 menu
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2420 const bool isContainer
= currentItem
&& !currentItem
->IsMenuItem();
2421 const bool isOpen
= currentItem
&& currentItem
->IsMenuPopupOpen();
2423 // For an open popup, have the child process the event
2424 nsMenuChainItem
* child
= item
? item
->GetChild() : nullptr;
2425 if (child
&& HandleKeyboardNavigationInPopup(child
, aDir
)) {
2428 } else if (aDir
== eNavigationDirection_End
&& isContainer
&&
2429 !currentItem
->IsDisabled()) {
2430 currentItem
->OpenMenuPopup(true);
2434 // For block progression, we can move in either direction
2435 if (NS_DIRECTION_IS_BLOCK(aDir
) || NS_DIRECTION_IS_BLOCK_TO_EDGE(aDir
)) {
2436 RefPtr
<XULButtonElement
> nextItem
= nullptr;
2438 if (aDir
== eNavigationDirection_Before
||
2439 aDir
== eNavigationDirection_After
) {
2440 // Cursor navigation does not wrap on Mac or for menulists on Windows.
2443 aFrame
->IsMenuList() ? Wrap::No
: Wrap::Yes
;
2444 #elif defined XP_MACOSX
2450 if (aDir
== eNavigationDirection_Before
) {
2451 nextItem
= menu
->GetPrevMenuItem(wrap
);
2453 nextItem
= menu
->GetNextMenuItem(wrap
);
2455 } else if (aDir
== eNavigationDirection_First
) {
2456 nextItem
= menu
->GetFirstMenuItem();
2458 nextItem
= menu
->GetLastMenuItem();
2462 menu
->SetActiveMenuChild(nextItem
, XULMenuParentElement::ByKey::Yes
);
2465 } else if (currentItem
&& isOpen
&& aDir
== eNavigationDirection_Start
) {
2466 // close a submenu when Left is pressed
2467 if (nsMenuPopupFrame
* popupFrame
=
2468 currentItem
->GetMenuPopup(FlushType::None
)) {
2469 HidePopup(&popupFrame
->PopupElement(), {});
2477 bool nsXULPopupManager::HandleKeyboardEventWithKeyCode(
2478 KeyboardEvent
* aKeyEvent
, nsMenuChainItem
* aTopVisibleMenuItem
) {
2479 uint32_t keyCode
= aKeyEvent
->KeyCode();
2481 // Escape should close panels, but the other keys should have no effect.
2482 if (aTopVisibleMenuItem
&&
2483 aTopVisibleMenuItem
->GetPopupType() != PopupType::Menu
) {
2484 if (keyCode
== KeyboardEvent_Binding::DOM_VK_ESCAPE
) {
2485 HidePopup(aTopVisibleMenuItem
->Element(), {HidePopupOption::IsRollup
});
2486 aKeyEvent
->StopPropagation();
2487 aKeyEvent
->StopCrossProcessForwarding();
2488 aKeyEvent
->PreventDefault();
2493 bool consume
= (aTopVisibleMenuItem
|| mActiveMenuBar
);
2495 case KeyboardEvent_Binding::DOM_VK_UP
:
2496 case KeyboardEvent_Binding::DOM_VK_DOWN
:
2498 // roll up the popup when alt+up/down are pressed within a menulist.
2499 if (aKeyEvent
->AltKey() && aTopVisibleMenuItem
&&
2500 aTopVisibleMenuItem
->Frame()->IsMenuList()) {
2507 case KeyboardEvent_Binding::DOM_VK_LEFT
:
2508 case KeyboardEvent_Binding::DOM_VK_RIGHT
:
2509 case KeyboardEvent_Binding::DOM_VK_HOME
:
2510 case KeyboardEvent_Binding::DOM_VK_END
:
2511 HandleKeyboardNavigation(keyCode
);
2514 case KeyboardEvent_Binding::DOM_VK_PAGE_DOWN
:
2515 case KeyboardEvent_Binding::DOM_VK_PAGE_UP
:
2516 if (aTopVisibleMenuItem
) {
2517 aTopVisibleMenuItem
->Frame()->ChangeByPage(
2518 keyCode
== KeyboardEvent_Binding::DOM_VK_PAGE_UP
);
2522 case KeyboardEvent_Binding::DOM_VK_ESCAPE
:
2523 // Pressing Escape hides one level of menus only. If no menu is open,
2524 // check if a menubar is active and inform it that a menu closed. Even
2525 // though in this latter case, a menu didn't actually close, the effect
2526 // ends up being the same. Similar for the tab key below.
2527 if (aTopVisibleMenuItem
) {
2528 HidePopup(aTopVisibleMenuItem
->Element(), {HidePopupOption::IsRollup
});
2529 } else if (mActiveMenuBar
) {
2530 RefPtr menubar
= mActiveMenuBar
;
2531 menubar
->SetActive(false);
2535 case KeyboardEvent_Binding::DOM_VK_TAB
:
2537 case KeyboardEvent_Binding::DOM_VK_F10
:
2539 if (aTopVisibleMenuItem
&&
2540 !aTopVisibleMenuItem
->Frame()->PopupElement().AttrValueIs(
2541 kNameSpaceID_None
, nsGkAtoms::activateontab
, nsGkAtoms::_true
,
2543 // Close popups or deactivate menubar when Tab or F10 are pressed
2546 } else if (mActiveMenuBar
) {
2547 RefPtr menubar
= mActiveMenuBar
;
2548 menubar
->SetActive(false);
2551 // Intentional fall-through to RETURN case
2554 case KeyboardEvent_Binding::DOM_VK_RETURN
: {
2555 // If there is a popup open, check if the current item needs to be opened.
2556 // Otherwise, tell the active menubar, if any, to activate the menu. The
2557 // Enter method will return a menu if one needs to be opened as a result.
2558 WidgetEvent
* event
= aKeyEvent
->WidgetEventPtr();
2559 if (aTopVisibleMenuItem
) {
2560 aTopVisibleMenuItem
->Frame()->HandleEnterKeyPress(*event
);
2561 } else if (mActiveMenuBar
) {
2562 RefPtr menubar
= mActiveMenuBar
;
2563 menubar
->HandleEnterKeyPress(*event
);
2573 aKeyEvent
->StopPropagation();
2574 aKeyEvent
->StopCrossProcessForwarding();
2575 aKeyEvent
->PreventDefault();
2580 nsresult
nsXULPopupManager::HandleEvent(Event
* aEvent
) {
2581 RefPtr
<KeyboardEvent
> keyEvent
= aEvent
->AsKeyboardEvent();
2582 NS_ENSURE_TRUE(keyEvent
, NS_ERROR_UNEXPECTED
);
2584 // handlers shouldn't be triggered by non-trusted events.
2585 if (!keyEvent
->IsTrusted()) {
2589 nsAutoString eventType
;
2590 keyEvent
->GetType(eventType
);
2591 if (eventType
.EqualsLiteral("keyup")) {
2592 return KeyUp(keyEvent
);
2594 if (eventType
.EqualsLiteral("keydown")) {
2595 return KeyDown(keyEvent
);
2597 if (eventType
.EqualsLiteral("keypress")) {
2598 return KeyPress(keyEvent
);
2601 MOZ_ASSERT_UNREACHABLE("Unexpected eventType");
2605 nsresult
nsXULPopupManager::UpdateIgnoreKeys(bool aIgnoreKeys
) {
2606 nsMenuChainItem
* item
= GetTopVisibleMenu();
2608 item
->SetIgnoreKeys(aIgnoreKeys
? eIgnoreKeys_True
: eIgnoreKeys_Shortcuts
);
2610 UpdateKeyboardListeners();
2614 nsPopupState
nsXULPopupManager::GetPopupState(Element
* aPopupElement
) {
2615 if (mNativeMenu
&& mNativeMenu
->Element()->Contains(aPopupElement
)) {
2616 if (aPopupElement
!= mNativeMenu
->Element()) {
2617 // Submenu state is stored in mNativeMenuSubmenuStates.
2618 return mNativeMenuSubmenuStates
.MaybeGet(aPopupElement
)
2619 .valueOr(ePopupClosed
);
2621 // mNativeMenu->Element()'s state is stored in its nsMenuPopupFrame.
2624 nsMenuPopupFrame
* menuPopupFrame
=
2625 do_QueryFrame(aPopupElement
->GetPrimaryFrame());
2626 if (menuPopupFrame
) {
2627 return menuPopupFrame
->PopupState();
2629 return ePopupClosed
;
2632 nsresult
nsXULPopupManager::KeyUp(KeyboardEvent
* aKeyEvent
) {
2633 // don't do anything if a menu isn't open or a menubar isn't active
2634 if (!mActiveMenuBar
) {
2635 nsMenuChainItem
* item
= GetTopVisibleMenu();
2636 if (!item
|| item
->GetPopupType() != PopupType::Menu
) return NS_OK
;
2638 if (item
->IgnoreKeys() == eIgnoreKeys_Shortcuts
) {
2639 aKeyEvent
->StopCrossProcessForwarding();
2644 aKeyEvent
->StopPropagation();
2645 aKeyEvent
->StopCrossProcessForwarding();
2646 aKeyEvent
->PreventDefault();
2648 return NS_OK
; // I am consuming event
2651 nsresult
nsXULPopupManager::KeyDown(KeyboardEvent
* aKeyEvent
) {
2652 nsMenuChainItem
* item
= GetTopVisibleMenu();
2653 if (item
&& item
->Frame()->PopupElement().IsLocked()) {
2657 if (HandleKeyboardEventWithKeyCode(aKeyEvent
, item
)) {
2661 // don't do anything if a menu isn't open or a menubar isn't active
2662 if (!mActiveMenuBar
&& (!item
|| item
->GetPopupType() != PopupType::Menu
))
2665 // Since a menu was open, stop propagation of the event to keep other event
2666 // listeners from becoming confused.
2667 if (!item
|| item
->IgnoreKeys() != eIgnoreKeys_Shortcuts
) {
2668 aKeyEvent
->StopPropagation();
2671 // If the key just pressed is the access key (usually Alt),
2672 // dismiss and unfocus the menu.
2673 uint32_t menuAccessKey
= LookAndFeel::GetMenuAccessKey();
2674 if (menuAccessKey
) {
2675 uint32_t theChar
= aKeyEvent
->KeyCode();
2677 if (theChar
== menuAccessKey
) {
2678 bool ctrl
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_CONTROL
&&
2679 aKeyEvent
->CtrlKey());
2680 bool alt
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_ALT
&&
2681 aKeyEvent
->AltKey());
2682 bool shift
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_SHIFT
&&
2683 aKeyEvent
->ShiftKey());
2684 bool meta
= (menuAccessKey
!= KeyboardEvent_Binding::DOM_VK_META
&&
2685 aKeyEvent
->MetaKey());
2686 if (!(ctrl
|| alt
|| shift
|| meta
)) {
2687 // The access key just went down and no other
2688 // modifiers are already down.
2689 nsMenuChainItem
* item
= GetTopVisibleMenu();
2690 if (item
&& !item
->Frame()->IsMenuList()) {
2692 } else if (mActiveMenuBar
) {
2693 RefPtr menubar
= mActiveMenuBar
;
2694 menubar
->SetActive(false);
2697 // Clear the item to avoid bugs as it may have been deleted during
2701 aKeyEvent
->StopPropagation();
2702 aKeyEvent
->PreventDefault();
2706 aKeyEvent
->StopCrossProcessForwarding();
2710 nsresult
nsXULPopupManager::KeyPress(KeyboardEvent
* aKeyEvent
) {
2711 // Don't check prevent default flag -- menus always get first shot at key
2714 nsMenuChainItem
* item
= GetTopVisibleMenu();
2715 if (item
&& (item
->Frame()->PopupElement().IsLocked() ||
2716 item
->GetPopupType() != PopupType::Menu
)) {
2720 // if a menu is open or a menubar is active, it consumes the key event
2721 bool consume
= (item
|| mActiveMenuBar
);
2723 WidgetInputEvent
* evt
= aKeyEvent
->WidgetEventPtr()->AsInputEvent();
2724 bool isAccel
= evt
&& evt
->IsAccel();
2726 // When ignorekeys="shortcuts" is used, we don't call preventDefault on the
2727 // key event when the accelerator key is pressed. This allows another
2728 // listener to handle keys. For instance, this allows global shortcuts to
2729 // still apply while a menu is open.
2730 if (item
&& item
->IgnoreKeys() == eIgnoreKeys_Shortcuts
&& isAccel
) {
2734 HandleShortcutNavigation(*aKeyEvent
, nullptr);
2736 aKeyEvent
->StopCrossProcessForwarding();
2738 aKeyEvent
->StopPropagation();
2739 aKeyEvent
->PreventDefault();
2742 return NS_OK
; // I am consuming event
2746 nsXULPopupHidingEvent::Run() {
2747 RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance();
2748 Document
* document
= mPopup
->GetUncomposedDoc();
2749 if (pm
&& document
) {
2750 if (RefPtr
<nsPresContext
> presContext
= document
->GetPresContext()) {
2751 nsCOMPtr
<Element
> popup
= mPopup
;
2752 nsCOMPtr
<Element
> nextPopup
= mNextPopup
;
2753 nsCOMPtr
<Element
> lastPopup
= mLastPopup
;
2754 pm
->FirePopupHidingEvent(popup
, nextPopup
, lastPopup
, presContext
,
2755 mPopupType
, mOptions
);
2761 bool nsXULPopupPositionedEvent::DispatchIfNeeded(Element
* aPopup
) {
2762 // The popuppositioned event only fires on arrow panels for now.
2763 if (aPopup
->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::arrow
,
2765 nsCOMPtr
<nsIRunnable
> event
= new nsXULPopupPositionedEvent(aPopup
);
2766 aPopup
->OwnerDoc()->Dispatch(event
.forget());
2773 static void AlignmentPositionToString(nsMenuPopupFrame
* aFrame
,
2774 nsAString
& aString
) {
2776 int8_t position
= aFrame
->GetAlignmentPosition();
2778 case POPUPPOSITION_AFTERSTART
:
2779 return aString
.AssignLiteral("after_start");
2780 case POPUPPOSITION_AFTEREND
:
2781 return aString
.AssignLiteral("after_end");
2782 case POPUPPOSITION_BEFORESTART
:
2783 return aString
.AssignLiteral("before_start");
2784 case POPUPPOSITION_BEFOREEND
:
2785 return aString
.AssignLiteral("before_end");
2786 case POPUPPOSITION_STARTBEFORE
:
2787 return aString
.AssignLiteral("start_before");
2788 case POPUPPOSITION_ENDBEFORE
:
2789 return aString
.AssignLiteral("end_before");
2790 case POPUPPOSITION_STARTAFTER
:
2791 return aString
.AssignLiteral("start_after");
2792 case POPUPPOSITION_ENDAFTER
:
2793 return aString
.AssignLiteral("end_after");
2794 case POPUPPOSITION_OVERLAP
:
2795 return aString
.AssignLiteral("overlap");
2796 case POPUPPOSITION_AFTERPOINTER
:
2797 return aString
.AssignLiteral("after_pointer");
2798 case POPUPPOSITION_SELECTION
:
2799 return aString
.AssignLiteral("selection");
2801 // Leave as an empty string.
2806 static void PopupAlignmentToString(nsMenuPopupFrame
* aFrame
,
2807 nsAString
& aString
) {
2809 int alignment
= aFrame
->GetPopupAlignment();
2810 switch (alignment
) {
2811 case POPUPALIGNMENT_TOPLEFT
:
2812 return aString
.AssignLiteral("topleft");
2813 case POPUPALIGNMENT_TOPRIGHT
:
2814 return aString
.AssignLiteral("topright");
2815 case POPUPALIGNMENT_BOTTOMLEFT
:
2816 return aString
.AssignLiteral("bottomleft");
2817 case POPUPALIGNMENT_BOTTOMRIGHT
:
2818 return aString
.AssignLiteral("bottomright");
2819 case POPUPALIGNMENT_LEFTCENTER
:
2820 return aString
.AssignLiteral("leftcenter");
2821 case POPUPALIGNMENT_RIGHTCENTER
:
2822 return aString
.AssignLiteral("rightcenter");
2823 case POPUPALIGNMENT_TOPCENTER
:
2824 return aString
.AssignLiteral("topcenter");
2825 case POPUPALIGNMENT_BOTTOMCENTER
:
2826 return aString
.AssignLiteral("bottomcenter");
2828 // Leave as an empty string.
2834 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2835 nsXULPopupPositionedEvent::Run() {
2836 RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance();
2840 nsMenuPopupFrame
* popupFrame
= do_QueryFrame(mPopup
->GetPrimaryFrame());
2845 popupFrame
->WillDispatchPopupPositioned();
2847 // At this point, hidePopup may have been called but it currently has no
2848 // way to stop this event. However, if hidePopup was called, the popup
2849 // will now be in the hiding or closed state. If we are in the shown or
2850 // positioning state instead, we can assume that we are still clear to
2851 // open/move the popup
2852 nsPopupState state
= popupFrame
->PopupState();
2853 if (state
!= ePopupPositioning
&& state
!= ePopupShown
) {
2857 // Note that the offset might be along either the X or Y axis, but for the
2858 // sake of simplicity we use a point with only the X axis set so we can
2859 // use ToNearestPixels().
2860 int32_t popupOffset
= nsPoint(popupFrame
->GetAlignmentOffset(), 0)
2861 .ToNearestPixels(AppUnitsPerCSSPixel())
2864 PopupPositionedEventInit init
;
2865 init
.mComposed
= true;
2866 init
.mIsAnchored
= popupFrame
->IsAnchored();
2867 init
.mAlignmentOffset
= popupOffset
;
2868 AlignmentPositionToString(popupFrame
, init
.mAlignmentPosition
);
2869 PopupAlignmentToString(popupFrame
, init
.mPopupAlignment
);
2870 RefPtr
<PopupPositionedEvent
> event
=
2871 PopupPositionedEvent::Constructor(mPopup
, u
"popuppositioned"_ns
, init
);
2872 event
->SetTrusted(true);
2874 mPopup
->DispatchEvent(*event
);
2876 // Get the popup frame and make sure it is still in the positioning
2877 // state. If it isn't, someone may have tried to reshow or hide it
2878 // during the popuppositioned event.
2879 // Alternately, this event may have been fired in reponse to moving the
2880 // popup rather than opening it. In that case, we are done.
2881 popupFrame
= do_QueryFrame(mPopup
->GetPrimaryFrame());
2882 if (popupFrame
&& popupFrame
->PopupState() == ePopupPositioning
) {
2883 pm
->ShowPopupCallback(mPopup
, popupFrame
, false, false);
2890 nsXULMenuCommandEvent::Run() {
2891 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
2896 RefPtr menu
= XULButtonElement::FromNode(mMenu
);
2899 if (menu
->GetXULBoolAttr(nsGkAtoms::checked
)) {
2900 menu
->UnsetAttr(kNameSpaceID_None
, nsGkAtoms::checked
, true);
2902 menu
->SetAttr(kNameSpaceID_None
, nsGkAtoms::checked
, u
"true"_ns
, true);
2906 // The order of the nsViewManager and PresShell COM pointers is
2907 // important below. We want the pres shell to get released before the
2908 // associated view manager on exit from this function.
2910 // XXXndeakin is this still needed?
2911 RefPtr
<nsPresContext
> presContext
= menu
->OwnerDoc()->GetPresContext();
2912 RefPtr
<PresShell
> presShell
=
2913 presContext
? presContext
->PresShell() : nullptr;
2914 RefPtr
<nsViewManager
> kungFuDeathGrip
=
2915 presShell
? presShell
->GetViewManager() : nullptr;
2916 Unused
<< kungFuDeathGrip
; // Not referred to directly within this function
2918 // Deselect ourselves.
2919 if (mCloseMenuMode
!= CloseMenuMode_None
) {
2920 if (RefPtr parent
= menu
->GetMenuParent()) {
2921 if (parent
->GetActiveMenuChild() == menu
) {
2922 parent
->SetActiveMenuChild(nullptr);
2927 AutoHandlingUserInputStatePusher
userInpStatePusher(mUserInput
);
2928 nsContentUtils::DispatchXULCommand(
2929 menu
, mIsTrusted
, nullptr, presShell
, mModifiers
& MODIFIER_CONTROL
,
2930 mModifiers
& MODIFIER_ALT
, mModifiers
& MODIFIER_SHIFT
,
2931 mModifiers
& MODIFIER_META
, 0, mButton
);
2933 if (mCloseMenuMode
!= CloseMenuMode_None
) {
2934 if (RefPtr popup
= menu
->GetContainingPopupElement()) {
2935 HidePopupOptions options
{HidePopupOption::DeselectMenu
};
2936 if (mCloseMenuMode
== CloseMenuMode_Auto
) {
2937 options
+= HidePopupOption::HideChain
;
2939 pm
->HidePopup(popup
, options
);