Bug 1833854 - Part 6: Round requested nursery before checking range when changing...
[gecko.git] / layout / xul / nsXULPopupManager.cpp
blobfe12c70326f01ea8e2247dc6257296daa088d324
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"
13 #include "nsISound.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 "nsGlobalWindow.h"
21 #include "nsIContentInlines.h"
22 #include "nsLayoutUtils.h"
23 #include "nsViewManager.h"
24 #include "nsITimer.h"
25 #include "nsFocusManager.h"
26 #include "nsIDocShell.h"
27 #include "nsPIDOMWindow.h"
28 #include "nsIInterfaceRequestorUtils.h"
29 #include "nsIBaseWindow.h"
30 #include "nsCaret.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) {
111 InitMousePoint();
114 void PendingPopup::InitMousePoint() {
115 // get the event coordinates relative to the root frame of the document
116 // containing the popup.
117 if (!mEvent) {
118 return;
121 WidgetEvent* event = mEvent->WidgetEventPtr();
122 WidgetInputEvent* inputEvent = event->AsInputEvent();
123 if (inputEvent) {
124 mModifiers = inputEvent->mModifiers;
126 Document* doc = mPopup->GetUncomposedDoc();
127 if (!doc) {
128 return;
131 PresShell* presShell = doc->GetPresShell();
132 nsPresContext* presContext;
133 if (presShell && (presContext = presShell->GetPresContext())) {
134 nsPresContext* rootDocPresContext = presContext->GetRootPresContext();
135 if (!rootDocPresContext) {
136 return;
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});
162 mMousePoint =
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 {
176 if (mEvent) {
177 mozilla::WidgetMouseEventBase* mouseEvent =
178 mEvent->WidgetEventPtr()->AsMouseEventBase();
179 if (mouseEvent) {
180 return mouseEvent->mInputSource;
183 RefPtr<XULCommandEvent> commandEvent = mEvent->AsXULCommandEvent();
184 if (commandEvent) {
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);
198 if (mParent) {
199 mParent->mChild = this;
203 UniquePtr<nsMenuChainItem> nsMenuChainItem::Detach() {
204 if (mParent) {
205 MOZ_ASSERT(mParent->mChild == this,
206 "Unexpected - parent's child not set to this");
207 mParent->mChild = nullptr;
209 return std::move(mParent);
212 void nsXULPopupManager::RemoveMenuChainItem(nsMenuChainItem* aItem) {
213 auto parent = aItem->Detach();
214 if (auto* child = aItem->GetChild()) {
215 MOZ_ASSERT(aItem != mPopups,
216 "Unexpected - popup with child at end of chain");
217 // This will kill aItem by changing child's mParent pointer.
218 child->SetParent(std::move(parent));
219 } else {
220 // An item without a child should be the first item in the chain, so set
221 // the first item pointer, pointed to by aRoot, to the parent.
222 MOZ_ASSERT(aItem == mPopups,
223 "Unexpected - popup with no child not at end of chain");
224 mPopups = std::move(parent);
228 void nsMenuChainItem::UpdateFollowAnchor() {
229 mFollowAnchor = mFrame->ShouldFollowAnchor(mCurrentRect);
232 void nsMenuChainItem::CheckForAnchorChange() {
233 if (mFollowAnchor) {
234 mFrame->CheckForAnchorChange(mCurrentRect);
238 NS_IMPL_ISUPPORTS(nsXULPopupManager, nsIDOMEventListener, nsIObserver)
240 nsXULPopupManager::nsXULPopupManager()
241 : mActiveMenuBar(nullptr), mPopups(nullptr), mPendingPopup(nullptr) {
242 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
243 if (obs) {
244 obs->AddObserver(this, "xpcom-shutdown", false);
248 nsXULPopupManager::~nsXULPopupManager() {
249 NS_ASSERTION(!mPopups, "XUL popups still open");
251 if (mNativeMenu) {
252 mNativeMenu->RemoveObserver(this);
256 nsresult nsXULPopupManager::Init() {
257 sInstance = new nsXULPopupManager();
258 NS_ENSURE_TRUE(sInstance, NS_ERROR_OUT_OF_MEMORY);
259 NS_ADDREF(sInstance);
260 return NS_OK;
263 void nsXULPopupManager::Shutdown() { NS_IF_RELEASE(sInstance); }
265 NS_IMETHODIMP
266 nsXULPopupManager::Observe(nsISupports* aSubject, const char* aTopic,
267 const char16_t* aData) {
268 if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) {
269 if (mKeyListener) {
270 mKeyListener->RemoveEventListener(u"keypress"_ns, this, true);
271 mKeyListener->RemoveEventListener(u"keydown"_ns, this, true);
272 mKeyListener->RemoveEventListener(u"keyup"_ns, this, true);
273 mKeyListener = nullptr;
275 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
276 if (obs) {
277 obs->RemoveObserver(this, "xpcom-shutdown");
281 return NS_OK;
284 nsXULPopupManager* nsXULPopupManager::GetInstance() {
285 MOZ_ASSERT(sInstance);
286 return sInstance;
289 bool nsXULPopupManager::RollupTooltips() {
290 return RollupInternal(RollupKind::Tooltip, {}, nullptr);
293 bool nsXULPopupManager::Rollup(const RollupOptions& aOptions,
294 nsIContent** aLastRolledUp) {
295 return RollupInternal(RollupKind::Menu, aOptions, aLastRolledUp);
298 bool nsXULPopupManager::RollupNativeMenu() {
299 if (mNativeMenu) {
300 RefPtr<NativeMenu> menu = mNativeMenu;
301 return menu->Close();
303 return false;
306 bool nsXULPopupManager::RollupInternal(RollupKind aKind,
307 const RollupOptions& aOptions,
308 nsIContent** aLastRolledUp) {
309 if (aLastRolledUp) {
310 *aLastRolledUp = nullptr;
313 // We can disable the autohide behavior via a pref to ease debugging.
314 if (StaticPrefs::ui_popup_disable_autohide()) {
315 // Required on linux to allow events to work on other targets.
316 if (mWidget) {
317 mWidget->CaptureRollupEvents(false);
319 return false;
322 nsMenuChainItem* item = GetRollupItem(aKind);
323 if (!item) {
324 return false;
326 if (aLastRolledUp) {
327 // We need to get the popup that will be closed last, so that widget can
328 // keep track of it so it doesn't reopen if a mousedown event is going to
329 // processed. Keep going up the menu chain to get the first level menu of
330 // the same type. If a different type is encountered it means we have,
331 // for example, a menulist or context menu inside a panel, and we want to
332 // treat these as distinct. It's possible that this menu doesn't end up
333 // closing because the popuphiding event was cancelled, but in that case
334 // we don't need to deal with the menu reopening as it will already still
335 // be open.
336 nsMenuChainItem* first = item;
337 while (first->GetParent()) {
338 nsMenuChainItem* parent = first->GetParent();
339 if (first->Frame()->GetPopupType() != parent->Frame()->GetPopupType() ||
340 first->IsContextMenu() != parent->IsContextMenu()) {
341 break;
343 first = parent;
346 *aLastRolledUp = first->Element();
349 ConsumeOutsideClicksResult consumeResult =
350 item->Frame()->ConsumeOutsideClicks();
351 bool consume = consumeResult == ConsumeOutsideClicks_True;
352 bool rollup = true;
354 // If norolluponanchor is true, then don't rollup when clicking the anchor.
355 // This would be used to allow adjusting the caret position in an
356 // autocomplete field without hiding the popup for example.
357 bool noRollupOnAnchor =
358 (!consume && aOptions.mPoint &&
359 item->Frame()->GetContent()->AsElement()->AttrValueIs(
360 kNameSpaceID_None, nsGkAtoms::norolluponanchor, nsGkAtoms::_true,
361 eCaseMatters));
363 // When ConsumeOutsideClicks_ParentOnly is used, always consume the click
364 // when the click was over the anchor. This way, clicking on a menu doesn't
365 // reopen the menu.
366 if ((consumeResult == ConsumeOutsideClicks_ParentOnly || noRollupOnAnchor) &&
367 aOptions.mPoint) {
368 nsMenuPopupFrame* popupFrame = item->Frame();
369 CSSIntRect anchorRect = [&] {
370 if (popupFrame->IsAnchored()) {
371 // Check if the popup has an anchor rectangle set. If not, get the
372 // rectangle from the anchor element.
373 auto r = popupFrame->GetScreenAnchorRect();
374 if (r.x != -1 && r.y != -1) {
375 // Prefer the untransformed anchor rect, so as to account for Wayland
376 // properly. Note we still need to check GetScreenAnchorRect() tho, so
377 // as to detect whether the anchor came from the popup opening call,
378 // or from an element (in which case we want to take the code-path
379 // below)..
380 auto untransformed = popupFrame->GetUntransformedAnchorRect();
381 if (!untransformed.IsEmpty()) {
382 return CSSIntRect::FromAppUnitsRounded(untransformed);
384 return r;
388 auto* anchor = Element::FromNodeOrNull(popupFrame->GetAnchor());
389 if (!anchor) {
390 return CSSIntRect();
393 // Check if the anchor has indicated another node to use for checking
394 // for roll-up. That way, we can anchor a popup on anonymous content
395 // or an individual icon, while clicking elsewhere within a button or
396 // other container doesn't result in us re-opening the popup.
397 nsAutoString consumeAnchor;
398 anchor->GetAttr(nsGkAtoms::consumeanchor, consumeAnchor);
399 if (!consumeAnchor.IsEmpty()) {
400 if (Element* newAnchor =
401 anchor->OwnerDoc()->GetElementById(consumeAnchor)) {
402 anchor = newAnchor;
406 nsIFrame* f = anchor->GetPrimaryFrame();
407 if (!f) {
408 return CSSIntRect();
410 return f->GetScreenRect();
411 }();
413 // It's possible that some other element is above the anchor at the same
414 // position, but the only thing that would happen is that the mouse
415 // event will get consumed, so here only a quick coordinates check is
416 // done rather than a slower complete check of what is at that location.
417 nsPresContext* presContext = item->Frame()->PresContext();
418 CSSIntPoint posCSSPixels =
419 presContext->DevPixelsToIntCSSPixels(*aOptions.mPoint);
420 if (anchorRect.Contains(posCSSPixels)) {
421 if (consumeResult == ConsumeOutsideClicks_ParentOnly) {
422 consume = true;
425 if (noRollupOnAnchor) {
426 rollup = false;
431 if (!rollup) {
432 return false;
435 // If a number of popups to close has been specified, determine the last
436 // popup to close.
437 Element* lastPopup = nullptr;
438 uint32_t count = aOptions.mCount;
439 if (count && count != UINT32_MAX) {
440 nsMenuChainItem* last = item;
441 while (--count && last->GetParent()) {
442 last = last->GetParent();
444 if (last) {
445 lastPopup = last->Element();
449 nsPresContext* presContext = item->Frame()->PresContext();
450 RefPtr<nsViewManager> viewManager =
451 presContext->PresShell()->GetViewManager();
453 HidePopupOptions options{HidePopupOption::HideChain,
454 HidePopupOption::DeselectMenu,
455 HidePopupOption::IsRollup};
456 if (aOptions.mAllowAnimations == AllowAnimations::No) {
457 options += HidePopupOption::DisableAnimations;
460 HidePopup(item->Element(), options, lastPopup);
462 if (aOptions.mFlush == FlushViews::Yes) {
463 // The popup's visibility doesn't update until the minimize animation
464 // has finished, so call UpdateWidgetGeometry to update it right away.
465 viewManager->UpdateWidgetGeometry();
468 return consume;
471 ////////////////////////////////////////////////////////////////////////
472 bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent() {
473 // should rollup only for autocomplete widgets
474 // XXXndeakin this should really be something the popup has more control over
476 nsMenuChainItem* item = GetTopVisibleMenu();
477 if (!item) {
478 return false;
481 nsIContent* content = item->Frame()->GetContent();
482 if (!content || !content->IsElement()) return false;
484 Element* element = content->AsElement();
485 if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
486 nsGkAtoms::_true, eCaseMatters))
487 return true;
489 if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
490 nsGkAtoms::_false, eCaseMatters))
491 return false;
493 nsAutoString value;
494 element->GetAttr(kNameSpaceID_None, nsGkAtoms::type, value);
495 return StringBeginsWith(value, u"autocomplete"_ns);
498 bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent() {
499 nsMenuChainItem* item = GetTopVisibleMenu();
500 if (!item) {
501 return false;
504 nsMenuPopupFrame* frame = item->Frame();
505 if (frame->GetPopupType() != PopupType::Panel) return true;
507 return !frame->GetContent()->AsElement()->AttrValueIs(
508 kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::arrow, eCaseMatters);
511 // a menu should not roll up if activated by a mouse activate message (eg.
512 // X-mouse)
513 bool nsXULPopupManager::ShouldRollupOnMouseActivate() { return false; }
515 uint32_t nsXULPopupManager::GetSubmenuWidgetChain(
516 nsTArray<nsIWidget*>* aWidgetChain) {
517 // this method is used by the widget code to determine the list of popups
518 // that are open. If a mouse click occurs outside one of these popups, the
519 // panels will roll up. If the click is inside a popup, they will not roll up
520 uint32_t count = 0, sameTypeCount = 0;
522 NS_ASSERTION(aWidgetChain, "null parameter");
523 nsMenuChainItem* item = GetTopVisibleMenu();
524 while (item) {
525 nsMenuChainItem* parent = item->GetParent();
526 if (!item->IsNoAutoHide()) {
527 nsCOMPtr<nsIWidget> widget = item->Frame()->GetWidget();
528 NS_ASSERTION(widget, "open popup has no widget");
529 if (widget) {
530 aWidgetChain->AppendElement(widget.get());
531 // In the case when a menulist inside a panel is open, clicking in the
532 // panel should still roll up the menu, so if a different type is found,
533 // stop scanning.
534 if (!sameTypeCount) {
535 count++;
536 if (!parent ||
537 item->Frame()->GetPopupType() !=
538 parent->Frame()->GetPopupType() ||
539 item->IsContextMenu() != parent->IsContextMenu()) {
540 sameTypeCount = count;
545 item = parent;
548 return sameTypeCount;
551 nsIWidget* nsXULPopupManager::GetRollupWidget() {
552 nsMenuChainItem* item = GetTopVisibleMenu();
553 return item ? item->Frame()->GetWidget() : nullptr;
556 void nsXULPopupManager::AdjustPopupsOnWindowChange(
557 nsPIDOMWindowOuter* aWindow) {
558 // When the parent window is moved, adjust any child popups. Dismissable
559 // menus and panels are expected to roll up when a window is moved, so there
560 // is no need to check these popups, only the noautohide popups.
562 // The items are added to a list so that they can be adjusted bottom to top.
563 nsTArray<nsMenuPopupFrame*> list;
565 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
566 // only move popups that are within the same window and where auto
567 // positioning has not been disabled
568 if (!item->IsNoAutoHide()) {
569 continue;
571 nsMenuPopupFrame* frame = item->Frame();
572 nsIContent* popup = frame->GetContent();
573 if (!popup) {
574 continue;
576 Document* document = popup->GetUncomposedDoc();
577 if (!document) {
578 continue;
580 nsPIDOMWindowOuter* window = document->GetWindow();
581 if (!window) {
582 continue;
584 window = window->GetPrivateRoot();
585 if (window == aWindow) {
586 list.AppendElement(frame);
590 for (int32_t l = list.Length() - 1; l >= 0; l--) {
591 list[l]->SetPopupPosition(true);
595 void nsXULPopupManager::AdjustPopupsOnWindowChange(PresShell* aPresShell) {
596 if (aPresShell->GetDocument()) {
597 AdjustPopupsOnWindowChange(aPresShell->GetDocument()->GetWindow());
601 static nsMenuPopupFrame* GetPopupToMoveOrResize(nsIFrame* aFrame) {
602 nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(aFrame);
603 if (!menuPopupFrame) return nullptr;
605 // no point moving or resizing hidden popups
606 if (!menuPopupFrame->IsVisible()) return nullptr;
608 nsIWidget* widget = menuPopupFrame->GetWidget();
609 if (widget && !widget->IsVisible()) return nullptr;
611 return menuPopupFrame;
614 void nsXULPopupManager::PopupMoved(nsIFrame* aFrame,
615 const LayoutDeviceIntPoint& aPoint,
616 bool aByMoveToRect) {
617 nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
618 if (!menuPopupFrame) {
619 return;
622 nsView* view = menuPopupFrame->GetView();
623 if (!view) {
624 return;
627 menuPopupFrame->WidgetPositionOrSizeDidChange();
629 // Don't do anything if the popup is already at the specified location. This
630 // prevents recursive calls when a popup is positioned.
631 LayoutDeviceIntRect curDevBounds = view->RecalcWidgetBounds();
632 nsIWidget* widget = menuPopupFrame->GetWidget();
633 if (curDevBounds.TopLeft() == aPoint &&
634 (!widget ||
635 widget->GetClientOffset() == menuPopupFrame->GetLastClientOffset())) {
636 return;
639 // Update the popup's position using SetPopupPosition if the popup is
640 // anchored and at the parent level as these maintain their position
641 // relative to the parent window (except if positioned by move to rect, in
642 // which case we better make sure that layout matches that). Otherwise, just
643 // update the popup to the specified screen coordinates.
644 if (menuPopupFrame->IsAnchored() &&
645 menuPopupFrame->GetPopupLevel() == widget::PopupLevel::Parent &&
646 !aByMoveToRect) {
647 menuPopupFrame->SetPopupPosition(true);
648 } else {
649 CSSPoint cssPos =
650 aPoint / menuPopupFrame->PresContext()->CSSToDevPixelScale();
651 menuPopupFrame->MoveTo(cssPos, false, aByMoveToRect);
655 void nsXULPopupManager::PopupResized(nsIFrame* aFrame,
656 const LayoutDeviceIntSize& aSize) {
657 nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
658 if (!menuPopupFrame) {
659 return;
662 menuPopupFrame->WidgetPositionOrSizeDidChange();
664 nsView* view = menuPopupFrame->GetView();
665 if (!view) {
666 return;
669 const LayoutDeviceIntRect curDevBounds = view->RecalcWidgetBounds();
670 // If the size is what we think it is, we have nothing to do.
671 if (curDevBounds.Size() == aSize) {
672 return;
675 Element* popup = menuPopupFrame->GetContent()->AsElement();
677 // Only set the width and height if the popup already has these attributes.
678 if (!popup->HasAttr(nsGkAtoms::width) || !popup->HasAttr(nsGkAtoms::height)) {
679 return;
682 // The size is different. Convert the actual size to css pixels and store it
683 // as 'width' and 'height' attributes on the popup.
684 nsPresContext* presContext = menuPopupFrame->PresContext();
686 CSSIntSize newCSS(presContext->DevPixelsToIntCSSPixels(aSize.width),
687 presContext->DevPixelsToIntCSSPixels(aSize.height));
689 nsAutoString width, height;
690 width.AppendInt(newCSS.width);
691 height.AppendInt(newCSS.height);
692 // FIXME(emilio): aNotify should be consistent (probably true in the two calls
693 // below?).
694 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::width, width, false);
695 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::height, height, true);
698 nsMenuPopupFrame* nsXULPopupManager::GetPopupFrameForContent(
699 nsIContent* aContent, bool aShouldFlush) {
700 if (aShouldFlush) {
701 Document* document = aContent->GetUncomposedDoc();
702 if (document) {
703 if (RefPtr<PresShell> presShell = document->GetPresShell()) {
704 presShell->FlushPendingNotifications(FlushType::Layout);
709 return do_QueryFrame(aContent->GetPrimaryFrame());
712 nsMenuChainItem* nsXULPopupManager::GetRollupItem(RollupKind aKind) {
713 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
714 if (item->Frame()->PopupState() == ePopupInvisible) {
715 continue;
717 MOZ_ASSERT_IF(item->Frame()->GetPopupType() == PopupType::Tooltip,
718 item->IsNoAutoHide());
719 const bool valid = aKind == RollupKind::Tooltip
720 ? item->Frame()->GetPopupType() == PopupType::Tooltip
721 : !item->IsNoAutoHide();
722 if (valid) {
723 return item;
726 return nullptr;
729 void nsXULPopupManager::SetActiveMenuBar(XULMenuBarElement* aMenuBar,
730 bool aActivate) {
731 if (aActivate) {
732 mActiveMenuBar = aMenuBar;
733 } else if (mActiveMenuBar == aMenuBar) {
734 mActiveMenuBar = nullptr;
736 UpdateKeyboardListeners();
739 static CloseMenuMode GetCloseMenuMode(nsIContent* aMenu) {
740 if (!aMenu->IsElement()) {
741 return CloseMenuMode_Auto;
744 static Element::AttrValuesArray strings[] = {nsGkAtoms::none,
745 nsGkAtoms::single, nullptr};
746 switch (aMenu->AsElement()->FindAttrValueIn(
747 kNameSpaceID_None, nsGkAtoms::closemenu, strings, eCaseMatters)) {
748 case 0:
749 return CloseMenuMode_None;
750 case 1:
751 return CloseMenuMode_Single;
752 default:
753 return CloseMenuMode_Auto;
757 auto nsXULPopupManager::MayShowMenu(nsIContent* aMenu) -> MayShowMenuResult {
758 if (mNativeMenu && aMenu->IsElement() &&
759 mNativeMenu->Element()->Contains(aMenu)) {
760 return {true};
763 auto* menu = XULButtonElement::FromNode(aMenu);
764 if (!menu) {
765 return {};
768 nsMenuPopupFrame* popupFrame = menu->GetMenuPopup(FlushType::None);
769 if (!popupFrame || !MayShowPopup(popupFrame)) {
770 return {};
772 return {false, menu, popupFrame};
775 void nsXULPopupManager::ShowMenu(nsIContent* aMenu, bool aSelectFirstItem) {
776 auto mayShowResult = MayShowMenu(aMenu);
777 if (NS_WARN_IF(!mayShowResult)) {
778 return;
781 if (mayShowResult.mIsNative) {
782 mNativeMenu->OpenSubmenu(aMenu->AsElement());
783 return;
786 nsMenuPopupFrame* popupFrame = mayShowResult.mMenuPopupFrame;
788 // inherit whether or not we're a context menu from the parent
789 const bool onMenuBar = mayShowResult.mMenuButton->IsOnMenuBar();
790 const bool onmenu = mayShowResult.mMenuButton->IsOnMenu();
791 const bool parentIsContextMenu = mayShowResult.mMenuButton->IsOnContextMenu();
793 nsAutoString position;
795 #ifdef XP_MACOSX
796 if (aMenu->IsXULElement(nsGkAtoms::menulist)) {
797 position.AssignLiteral("selection");
798 } else
799 #endif
801 if (onMenuBar || !onmenu)
802 position.AssignLiteral("after_start");
803 else
804 position.AssignLiteral("end_before");
806 // there is no trigger event for menus
807 popupFrame->InitializePopup(aMenu, nullptr, position, 0, 0,
808 MenuPopupAnchorType_Node, true);
809 PendingPopup pendingPopup(&popupFrame->PopupElement(), nullptr);
810 BeginShowingPopup(pendingPopup, parentIsContextMenu, aSelectFirstItem);
813 static bool ShouldUseNativeContextMenus() {
814 #ifdef HAS_NATIVE_MENU_SUPPORT
815 return mozilla::widget::NativeMenuSupport::ShouldUseNativeContextMenus();
816 #else
817 return false;
818 #endif
821 void nsXULPopupManager::ShowPopup(Element* aPopup, nsIContent* aAnchorContent,
822 const nsAString& aPosition, int32_t aXPos,
823 int32_t aYPos, bool aIsContextMenu,
824 bool aAttributesOverride,
825 bool aSelectFirstItem, Event* aTriggerEvent) {
826 #ifdef XP_MACOSX
827 // On Mac, use a native menu if possible since the non-native menu looks out
828 // of place. Native menus for anchored popups are not currently implemented,
829 // so fall back to the non-native path below if `aAnchorContent` is given. We
830 // also fall back if the position string is not empty so we don't break tests
831 // that either themselves call or test app features that call
832 // `openPopup(null, "position")`.
833 if (!aAnchorContent && aPosition.IsEmpty() && ShouldUseNativeContextMenus() &&
834 aPopup->IsAnyOfXULElements(nsGkAtoms::menu, nsGkAtoms::menupopup) &&
835 ShowPopupAsNativeMenu(aPopup, aXPos, aYPos, aIsContextMenu,
836 aTriggerEvent)) {
837 return;
839 #endif
841 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
842 if (!popupFrame || !MayShowPopup(popupFrame)) {
843 return;
846 PendingPopup pendingPopup(aPopup, aTriggerEvent);
847 nsCOMPtr<nsIContent> triggerContent = pendingPopup.GetTriggerContent();
849 popupFrame->InitializePopup(aAnchorContent, triggerContent, aPosition, aXPos,
850 aYPos, MenuPopupAnchorType_Node,
851 aAttributesOverride);
853 BeginShowingPopup(pendingPopup, aIsContextMenu, aSelectFirstItem);
856 void nsXULPopupManager::ShowPopupAtScreen(Element* aPopup, int32_t aXPos,
857 int32_t aYPos, bool aIsContextMenu,
858 Event* aTriggerEvent) {
859 if (aIsContextMenu && ShouldUseNativeContextMenus() &&
860 ShowPopupAsNativeMenu(aPopup, aXPos, aYPos, aIsContextMenu,
861 aTriggerEvent)) {
862 return;
865 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
866 if (!popupFrame || !MayShowPopup(popupFrame)) return;
868 PendingPopup pendingPopup(aPopup, aTriggerEvent);
869 nsCOMPtr<nsIContent> triggerContent = pendingPopup.GetTriggerContent();
871 popupFrame->InitializePopupAtScreen(triggerContent, aXPos, aYPos,
872 aIsContextMenu);
873 BeginShowingPopup(pendingPopup, aIsContextMenu, false);
876 bool nsXULPopupManager::ShowPopupAsNativeMenu(Element* aPopup, int32_t aXPos,
877 int32_t aYPos,
878 bool aIsContextMenu,
879 Event* aTriggerEvent) {
880 if (mNativeMenu) {
881 NS_WARNING("Native menu still open when trying to open another");
882 RefPtr<NativeMenu> menu = mNativeMenu;
883 (void)menu->Close();
884 menu->RemoveObserver(this);
885 mNativeMenu = nullptr;
888 RefPtr<NativeMenu> menu;
889 #ifdef HAS_NATIVE_MENU_SUPPORT
890 menu = mozilla::widget::NativeMenuSupport::CreateNativeContextMenu(aPopup);
891 #endif
893 if (!menu) {
894 return false;
897 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
898 if (!popupFrame) {
899 return true;
902 // Hide the menu from our accessibility code so that we don't dispatch custom
903 // accessibility notifications which would conflict with the system ones.
904 aPopup->SetAttr(kNameSpaceID_None, nsGkAtoms::aria_hidden, u"true"_ns, true);
906 PendingPopup pendingPopup(aPopup, aTriggerEvent);
907 nsCOMPtr<nsIContent> triggerContent = pendingPopup.GetTriggerContent();
909 popupFrame->InitializePopupAsNativeContextMenu(triggerContent, aXPos, aYPos);
911 RefPtr<nsPresContext> presContext = popupFrame->PresContext();
912 nsEventStatus status = FirePopupShowingEvent(pendingPopup, presContext);
914 // if the event was cancelled, don't open the popup, reset its state back
915 // to closed and clear its trigger content.
916 if (status == nsEventStatus_eConsumeNoDefault) {
917 if ((popupFrame = GetPopupFrameForContent(aPopup, true))) {
918 popupFrame->SetPopupState(ePopupClosed);
919 popupFrame->ClearTriggerContent();
921 return true;
924 mNativeMenu = menu;
925 mNativeMenu->AddObserver(this);
926 nsIFrame* frame = presContext->PresShell()->GetCurrentEventFrame();
927 if (!frame) {
928 frame = presContext->PresShell()->GetRootFrame();
930 mNativeMenu->ShowAsContextMenu(frame, CSSIntPoint(aXPos, aYPos),
931 aIsContextMenu);
933 // While the native menu is open, it consumes mouseup events.
934 // Clear any :active state, mouse capture state and drag tracking now.
935 EventStateManager* activeESM = static_cast<EventStateManager*>(
936 EventStateManager::GetActiveEventStateManager());
937 if (activeESM) {
938 EventStateManager::ClearGlobalActiveContent(activeESM);
939 activeESM->StopTrackingDragGesture(true);
941 PresShell::ReleaseCapturingContent();
943 return true;
946 void nsXULPopupManager::OnNativeMenuOpened() {
947 if (!mNativeMenu) {
948 return;
951 RefPtr<nsXULPopupManager> kungFuDeathGrip(this);
953 nsCOMPtr<nsIContent> popup = mNativeMenu->Element();
954 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(popup, true);
955 if (popupFrame) {
956 popupFrame->SetPopupState(ePopupShown);
960 void nsXULPopupManager::OnNativeMenuClosed() {
961 if (!mNativeMenu) {
962 return;
965 RefPtr<nsXULPopupManager> kungFuDeathGrip(this);
967 bool shouldHideChain =
968 mNativeMenuActivatedItemCloseMenuMode == Some(CloseMenuMode_Auto);
970 nsCOMPtr<nsIContent> popup = mNativeMenu->Element();
971 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(popup, true);
972 if (popupFrame) {
973 popupFrame->ClearTriggerContentIncludingDocument();
974 popupFrame->SetPopupState(ePopupClosed);
976 mNativeMenu->RemoveObserver(this);
977 mNativeMenu = nullptr;
978 mNativeMenuActivatedItemCloseMenuMode = Nothing();
979 mNativeMenuSubmenuStates.Clear();
981 // Stop hiding the menu from accessibility code, in case it gets opened as a
982 // non-native menu in the future.
983 popup->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::aria_hidden,
984 true);
986 if (shouldHideChain && mPopups &&
987 mPopups->GetPopupType() == PopupType::Menu) {
988 // A menu item was activated before this menu closed, and the item requested
989 // the entire popup chain to be closed, which includes any open non-native
990 // menus.
991 // Close the non-native menus now. This matches the HidePopup call in
992 // nsXULMenuCommandEvent::Run.
993 HidePopup(mPopups->Element(), {HidePopupOption::HideChain});
997 void nsXULPopupManager::OnNativeSubMenuWillOpen(
998 mozilla::dom::Element* aPopupElement) {
999 mNativeMenuSubmenuStates.InsertOrUpdate(aPopupElement, ePopupShowing);
1002 void nsXULPopupManager::OnNativeSubMenuDidOpen(
1003 mozilla::dom::Element* aPopupElement) {
1004 mNativeMenuSubmenuStates.InsertOrUpdate(aPopupElement, ePopupShown);
1007 void nsXULPopupManager::OnNativeSubMenuClosed(
1008 mozilla::dom::Element* aPopupElement) {
1009 mNativeMenuSubmenuStates.Remove(aPopupElement);
1012 void nsXULPopupManager::OnNativeMenuWillActivateItem(
1013 mozilla::dom::Element* aMenuItemElement) {
1014 if (!mNativeMenu) {
1015 return;
1018 CloseMenuMode cmm = GetCloseMenuMode(aMenuItemElement);
1019 mNativeMenuActivatedItemCloseMenuMode = Some(cmm);
1021 if (cmm == CloseMenuMode_Auto) {
1022 // If any non-native menus are visible (for example because the context menu
1023 // was opened on a non-native menu item, e.g. in a bookmarks folder), hide
1024 // the non-native menus before executing the item.
1025 HideOpenMenusBeforeExecutingMenu(CloseMenuMode_Auto);
1029 void nsXULPopupManager::ShowPopupAtScreenRect(
1030 Element* aPopup, const nsAString& aPosition, const nsIntRect& aRect,
1031 bool aIsContextMenu, bool aAttributesOverride, Event* aTriggerEvent) {
1032 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
1033 if (!popupFrame || !MayShowPopup(popupFrame)) return;
1035 PendingPopup pendingPopup(aPopup, aTriggerEvent);
1036 nsCOMPtr<nsIContent> triggerContent = pendingPopup.GetTriggerContent();
1038 popupFrame->InitializePopupAtRect(triggerContent, aPosition, aRect,
1039 aAttributesOverride);
1041 BeginShowingPopup(pendingPopup, aIsContextMenu, false);
1044 void nsXULPopupManager::ShowTooltipAtScreen(
1045 Element* aPopup, nsIContent* aTriggerContent,
1046 const LayoutDeviceIntPoint& aScreenPoint) {
1047 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
1048 if (!popupFrame || !MayShowPopup(popupFrame)) {
1049 return;
1052 PendingPopup pendingPopup(aPopup, nullptr);
1054 nsPresContext* pc = popupFrame->PresContext();
1055 pendingPopup.SetMousePoint([&] {
1056 // Event coordinates are relative to the root widget
1057 if (nsPresContext* rootPresContext = pc->GetRootPresContext()) {
1058 if (nsCOMPtr<nsIWidget> rootWidget = rootPresContext->GetRootWidget()) {
1059 return aScreenPoint - rootWidget->WidgetToScreenOffset();
1062 return aScreenPoint;
1063 }());
1065 auto screenCSSPoint =
1066 CSSIntPoint::Round(aScreenPoint / pc->CSSToDevPixelScale());
1067 popupFrame->InitializePopupAtScreen(aTriggerContent, screenCSSPoint.x,
1068 screenCSSPoint.y, false);
1070 BeginShowingPopup(pendingPopup, false, false);
1073 static void CheckCaretDrawingState() {
1074 // There is 1 caret per document, we need to find the focused
1075 // document and erase its caret.
1076 nsFocusManager* fm = nsFocusManager::GetFocusManager();
1077 if (fm) {
1078 nsCOMPtr<mozIDOMWindowProxy> window;
1079 fm->GetFocusedWindow(getter_AddRefs(window));
1080 if (!window) return;
1082 auto* piWindow = nsPIDOMWindowOuter::From(window);
1083 MOZ_ASSERT(piWindow);
1085 nsCOMPtr<Document> focusedDoc = piWindow->GetDoc();
1086 if (!focusedDoc) return;
1088 PresShell* presShell = focusedDoc->GetPresShell();
1089 if (!presShell) {
1090 return;
1093 RefPtr<nsCaret> caret = presShell->GetCaret();
1094 if (!caret) return;
1095 caret->SchedulePaint();
1099 void nsXULPopupManager::ShowPopupCallback(Element* aPopup,
1100 nsMenuPopupFrame* aPopupFrame,
1101 bool aIsContextMenu,
1102 bool aSelectFirstItem) {
1103 PopupType popupType = aPopupFrame->GetPopupType();
1104 const bool isMenu = popupType == PopupType::Menu;
1106 // Popups normally hide when an outside click occurs. Panels may use
1107 // the noautohide attribute to disable this behaviour. It is expected
1108 // that the application will hide these popups manually. The tooltip
1109 // listener will handle closing the tooltip also.
1110 bool isNoAutoHide =
1111 aPopupFrame->IsNoAutoHide() || popupType == PopupType::Tooltip;
1113 auto item = MakeUnique<nsMenuChainItem>(aPopupFrame, isNoAutoHide,
1114 aIsContextMenu, popupType);
1116 // install keyboard event listeners for navigating menus. For panels, the
1117 // escape key may be used to close the panel. However, the ignorekeys
1118 // attribute may be used to disable adding these event listeners for popups
1119 // that want to handle their own keyboard events.
1120 nsAutoString ignorekeys;
1121 aPopup->GetAttr(kNameSpaceID_None, nsGkAtoms::ignorekeys, ignorekeys);
1122 if (ignorekeys.EqualsLiteral("true")) {
1123 item->SetIgnoreKeys(eIgnoreKeys_True);
1124 } else if (ignorekeys.EqualsLiteral("shortcuts")) {
1125 item->SetIgnoreKeys(eIgnoreKeys_Shortcuts);
1128 if (isMenu) {
1129 // if the menu is on a menubar, use the menubar's listener instead
1130 if (auto* menu = aPopupFrame->PopupElement().GetContainingMenu()) {
1131 item->SetOnMenuBar(menu->IsOnMenuBar());
1135 // use a weak frame as the popup will set an open attribute if it is a menu
1136 AutoWeakFrame weakFrame(aPopupFrame);
1137 aPopupFrame->ShowPopup(aIsContextMenu);
1138 NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
1140 item->UpdateFollowAnchor();
1142 // popups normally hide when an outside click occurs. Panels may use
1143 // the noautohide attribute to disable this behaviour. It is expected
1144 // that the application will hide these popups manually. The tooltip
1145 // listener will handle closing the tooltip also.
1146 nsIContent* oldmenu = nullptr;
1147 if (mPopups) {
1148 oldmenu = mPopups->Element();
1150 item->SetParent(std::move(mPopups));
1151 mPopups = std::move(item);
1152 SetCaptureState(oldmenu);
1153 NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
1155 RefPtr popup = &aPopupFrame->PopupElement();
1156 popup->PopupOpened(aSelectFirstItem);
1158 if (isMenu) {
1159 UpdateMenuItems(aPopup);
1162 // Caret visibility may have been affected, ensure that
1163 // the caret isn't now drawn when it shouldn't be.
1164 CheckCaretDrawingState();
1167 nsMenuChainItem* nsXULPopupManager::FindPopup(Element* aPopup) const {
1168 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1169 if (item->Frame()->GetContent() == aPopup) {
1170 return item;
1173 return nullptr;
1176 void nsXULPopupManager::HidePopup(Element* aPopup, HidePopupOptions aOptions,
1177 Element* aLastPopup) {
1178 if (mNativeMenu && mNativeMenu->Element() == aPopup) {
1179 RefPtr<NativeMenu> menu = mNativeMenu;
1180 (void)menu->Close();
1181 return;
1184 nsMenuPopupFrame* popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
1185 if (!popupFrame) {
1186 return;
1189 nsMenuChainItem* foundPopup = FindPopup(aPopup);
1191 RefPtr<Element> popupToHide, nextPopup, lastPopup;
1193 if (foundPopup) {
1194 if (foundPopup->IsNoAutoHide()) {
1195 // If this is a noautohide panel, remove it but don't close any other
1196 // panels.
1197 popupToHide = aPopup;
1198 // XXX This preserves behavior but why is it the right thing to do?
1199 aOptions -= HidePopupOption::DeselectMenu;
1200 } else {
1201 // At this point, foundPopup will be set to the found item in the list. If
1202 // foundPopup is the topmost menu, the one to remove, then there are no
1203 // other popups to hide. If foundPopup is not the topmost menu, then there
1204 // may be open submenus below it. In this case, we need to make sure that
1205 // those submenus are closed up first. To do this, we scan up the menu
1206 // list to find the topmost popup with only menus between it and
1207 // foundPopup and close that menu first. In synchronous mode, the
1208 // FirePopupHidingEvent method will be called which in turn calls
1209 // HidePopupCallback to close up the next popup in the chain. These two
1210 // methods will be called in sequence recursively to close up all the
1211 // necessary popups. In asynchronous mode, a similar process occurs except
1212 // that the FirePopupHidingEvent method is called asynchronously. In
1213 // either case, nextPopup is set to the content node of the next popup to
1214 // close, and lastPopup is set to the last popup in the chain to close,
1215 // which will be aPopup, or null to close up all menus.
1217 nsMenuChainItem* topMenu = foundPopup;
1218 // Use IsMenu to ensure that foundPopup is a menu and scan down the child
1219 // list until a non-menu is found. If foundPopup isn't a menu at all,
1220 // don't scan and just close up this menu.
1221 if (foundPopup->IsMenu()) {
1222 nsMenuChainItem* child = foundPopup->GetChild();
1223 while (child && child->IsMenu()) {
1224 topMenu = child;
1225 child = child->GetChild();
1229 popupToHide = topMenu->Element();
1230 popupFrame = topMenu->Frame();
1232 const bool hideChain = aOptions.contains(HidePopupOption::HideChain);
1234 // Close up another popup if there is one, and we are either hiding the
1235 // entire chain or the item to hide isn't the topmost popup.
1236 nsMenuChainItem* parent = topMenu->GetParent();
1237 if (parent && (hideChain || topMenu != foundPopup)) {
1238 while (parent && parent->IsNoAutoHide()) {
1239 parent = parent->GetParent();
1242 if (parent) {
1243 nextPopup = parent->Element();
1247 lastPopup = aLastPopup ? aLastPopup : (hideChain ? nullptr : aPopup);
1249 } else if (popupFrame->PopupState() == ePopupPositioning) {
1250 // When the popup is in the popuppositioning state, it will not be in the
1251 // mPopups list. We need another way to find it and make sure it does not
1252 // continue the popup showing process.
1253 popupToHide = aPopup;
1256 if (!popupToHide) {
1257 return;
1260 nsPopupState state = popupFrame->PopupState();
1261 // If the popup is already being hidden, don't attempt to hide it again
1262 if (state == ePopupHiding) {
1263 return;
1266 // Change the popup state to hiding. Don't set the hiding state if the
1267 // popup is invisible, otherwise nsMenuPopupFrame::HidePopup will
1268 // run again. In the invisible state, we just want the events to fire.
1269 if (state != ePopupInvisible) {
1270 popupFrame->SetPopupState(ePopupHiding);
1273 // For menus, popupToHide is always the frontmost item in the list to hide.
1274 if (aOptions.contains(HidePopupOption::Async)) {
1275 nsCOMPtr<nsIRunnable> event =
1276 new nsXULPopupHidingEvent(popupToHide, nextPopup, lastPopup,
1277 popupFrame->GetPopupType(), aOptions);
1278 aPopup->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
1279 } else {
1280 RefPtr<nsPresContext> presContext = popupFrame->PresContext();
1281 FirePopupHidingEvent(popupToHide, nextPopup, lastPopup, presContext,
1282 popupFrame->GetPopupType(), aOptions);
1286 void nsXULPopupManager::HideMenu(nsIContent* aMenu) {
1287 if (mNativeMenu && aMenu->IsElement() &&
1288 mNativeMenu->Element()->Contains(aMenu)) {
1289 mNativeMenu->CloseSubmenu(aMenu->AsElement());
1290 return;
1293 auto* button = XULButtonElement::FromNode(aMenu);
1294 if (!button || !button->IsMenu()) {
1295 return;
1297 auto* popup = button->GetMenuPopupContent();
1298 if (!popup) {
1299 return;
1301 HidePopup(popup, {HidePopupOption::DeselectMenu});
1304 // This is used to hide the popup after a transition finishes.
1305 class TransitionEnder final : public nsIDOMEventListener {
1306 private:
1307 // Effectively const but is cycle collected
1308 MOZ_KNOWN_LIVE RefPtr<Element> mElement;
1310 protected:
1311 virtual ~TransitionEnder() = default;
1313 public:
1314 HidePopupOptions mOptions;
1316 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
1317 NS_DECL_CYCLE_COLLECTION_CLASS(TransitionEnder)
1319 TransitionEnder(Element* aElement, HidePopupOptions aOptions)
1320 : mElement(aElement), mOptions(aOptions) {}
1322 MOZ_CAN_RUN_SCRIPT NS_IMETHOD HandleEvent(Event* aEvent) override {
1323 mElement->RemoveSystemEventListener(u"transitionend"_ns, this, false);
1325 nsMenuPopupFrame* popupFrame = do_QueryFrame(mElement->GetPrimaryFrame());
1326 if (!popupFrame) {
1327 return NS_OK;
1330 // Now hide the popup. There could be other properties transitioning, but
1331 // we'll assume they all end at the same time and just hide the popup upon
1332 // the first one ending.
1333 if (RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance()) {
1334 pm->HidePopupCallback(mElement, popupFrame, nullptr, nullptr,
1335 popupFrame->GetPopupType(), mOptions);
1338 return NS_OK;
1342 NS_IMPL_CYCLE_COLLECTING_ADDREF(TransitionEnder)
1343 NS_IMPL_CYCLE_COLLECTING_RELEASE(TransitionEnder)
1344 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TransitionEnder)
1345 NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
1346 NS_INTERFACE_MAP_ENTRY(nsISupports)
1347 NS_INTERFACE_MAP_END
1349 NS_IMPL_CYCLE_COLLECTION(TransitionEnder, mElement);
1350 void nsXULPopupManager::HidePopupCallback(
1351 Element* aPopup, nsMenuPopupFrame* aPopupFrame, Element* aNextPopup,
1352 Element* aLastPopup, PopupType aPopupType, HidePopupOptions aOptions) {
1353 if (mCloseTimer && mTimerMenu == aPopupFrame) {
1354 mCloseTimer->Cancel();
1355 mCloseTimer = nullptr;
1356 mTimerMenu = nullptr;
1359 // The popup to hide is aPopup. Search the list again to find the item that
1360 // corresponds to the popup to hide aPopup. This is done because it's
1361 // possible someone added another item (attempted to open another popup)
1362 // or removed a popup frame during the event processing so the item isn't at
1363 // the front anymore.
1364 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1365 if (item->Element() == aPopup) {
1366 RemoveMenuChainItem(item);
1367 SetCaptureState(aPopup);
1368 break;
1372 AutoWeakFrame weakFrame(aPopupFrame);
1373 aPopupFrame->HidePopup(aOptions.contains(HidePopupOption::DeselectMenu),
1374 ePopupClosed);
1375 NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
1377 // send the popuphidden event synchronously. This event has no default
1378 // behaviour.
1379 nsEventStatus status = nsEventStatus_eIgnore;
1380 WidgetMouseEvent event(true, eXULPopupHidden, nullptr,
1381 WidgetMouseEvent::eReal);
1382 RefPtr<nsPresContext> presContext = aPopupFrame->PresContext();
1383 EventDispatcher::Dispatch(aPopup, presContext, &event, nullptr, &status);
1384 NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
1386 // Force any popups that might be anchored on elements within this popup to
1387 // update.
1388 UpdatePopupPositions(presContext->RefreshDriver());
1390 // if there are more popups to close, look for the next one
1391 if (aNextPopup && aPopup != aLastPopup) {
1392 nsMenuChainItem* foundMenu = FindPopup(aNextPopup);
1394 // continue hiding the chain of popups until the last popup aLastPopup
1395 // is reached, or until a popup of a different type is reached. This
1396 // last check is needed so that a menulist inside a non-menu panel only
1397 // closes the menu and not the panel as well.
1398 if (foundMenu && (aLastPopup || aPopupType == foundMenu->GetPopupType())) {
1399 nsCOMPtr<Element> popupToHide = foundMenu->Element();
1400 nsMenuChainItem* parent = foundMenu->GetParent();
1402 nsCOMPtr<Element> nextPopup;
1403 if (parent && popupToHide != aLastPopup) nextPopup = parent->Element();
1405 nsMenuPopupFrame* popupFrame = foundMenu->Frame();
1406 nsPopupState state = popupFrame->PopupState();
1407 if (state == ePopupHiding) return;
1408 if (state != ePopupInvisible) popupFrame->SetPopupState(ePopupHiding);
1410 RefPtr<nsPresContext> presContext = popupFrame->PresContext();
1411 FirePopupHidingEvent(popupToHide, nextPopup, aLastPopup, presContext,
1412 foundMenu->GetPopupType(), aOptions);
1417 void nsXULPopupManager::HidePopupAfterDelay(nsMenuPopupFrame* aPopup,
1418 int32_t aDelay) {
1419 // Don't close up immediately.
1420 // Kick off a close timer.
1421 KillMenuTimer();
1423 // Kick off the timer.
1424 nsIEventTarget* target =
1425 aPopup->PopupElement().OwnerDoc()->EventTargetFor(TaskCategory::Other);
1426 NS_NewTimerWithFuncCallback(
1427 getter_AddRefs(mCloseTimer),
1428 [](nsITimer* aTimer, void* aClosure) {
1429 if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
1430 pm->KillMenuTimer();
1433 nullptr, aDelay, nsITimer::TYPE_ONE_SHOT, "KillMenuTimer", target);
1434 // the popup will call PopupDestroyed if it is destroyed, which checks if it
1435 // is set to mTimerMenu, so it should be safe to keep a reference to it
1436 mTimerMenu = aPopup;
1439 void nsXULPopupManager::HidePopupsInList(
1440 const nsTArray<nsMenuPopupFrame*>& aFrames) {
1441 // Create a weak frame list. This is done in a separate array with the
1442 // right capacity predetermined to avoid multiple allocations.
1443 nsTArray<WeakFrame> weakPopups(aFrames.Length());
1444 uint32_t f;
1445 for (f = 0; f < aFrames.Length(); f++) {
1446 WeakFrame* wframe = weakPopups.AppendElement();
1447 if (wframe) *wframe = aFrames[f];
1450 for (f = 0; f < weakPopups.Length(); f++) {
1451 // check to ensure that the frame is still alive before hiding it.
1452 if (weakPopups[f].IsAlive()) {
1453 auto* frame = static_cast<nsMenuPopupFrame*>(weakPopups[f].GetFrame());
1454 frame->HidePopup(true, ePopupInvisible);
1458 SetCaptureState(nullptr);
1461 bool nsXULPopupManager::IsChildOfDocShell(Document* aDoc,
1462 nsIDocShellTreeItem* aExpected) {
1463 nsCOMPtr<nsIDocShellTreeItem> docShellItem(aDoc->GetDocShell());
1464 while (docShellItem) {
1465 if (docShellItem == aExpected) return true;
1467 nsCOMPtr<nsIDocShellTreeItem> parent;
1468 docShellItem->GetInProcessParent(getter_AddRefs(parent));
1469 docShellItem = parent;
1472 return false;
1475 void nsXULPopupManager::HidePopupsInDocShell(
1476 nsIDocShellTreeItem* aDocShellToHide) {
1477 nsTArray<nsMenuPopupFrame*> popupsToHide;
1479 // Iterate to get the set of popup frames to hide
1480 nsMenuChainItem* item = mPopups.get();
1481 while (item) {
1482 // Get the parent before calling detach so that we can keep iterating.
1483 nsMenuChainItem* parent = item->GetParent();
1484 if (item->Frame()->PopupState() != ePopupInvisible &&
1485 IsChildOfDocShell(item->Element()->OwnerDoc(), aDocShellToHide)) {
1486 nsMenuPopupFrame* frame = item->Frame();
1487 RemoveMenuChainItem(item);
1488 popupsToHide.AppendElement(frame);
1490 item = parent;
1493 HidePopupsInList(popupsToHide);
1496 void nsXULPopupManager::UpdatePopupPositions(nsRefreshDriver* aRefreshDriver) {
1497 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1498 if (item->Frame()->PresContext()->RefreshDriver() == aRefreshDriver) {
1499 item->CheckForAnchorChange();
1504 void nsXULPopupManager::UpdateFollowAnchor(nsMenuPopupFrame* aPopup) {
1505 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1506 if (item->Frame() == aPopup) {
1507 item->UpdateFollowAnchor();
1508 break;
1513 void nsXULPopupManager::HideOpenMenusBeforeExecutingMenu(CloseMenuMode aMode) {
1514 if (aMode == CloseMenuMode_None) {
1515 return;
1518 // When a menuitem is selected to be executed, first hide all the open
1519 // popups, but don't remove them yet. This is needed when a menu command
1520 // opens a modal dialog. The views associated with the popups needed to be
1521 // hidden and the accesibility events fired before the command executes, but
1522 // the popuphiding/popuphidden events are fired afterwards.
1523 nsTArray<nsMenuPopupFrame*> popupsToHide;
1524 nsMenuChainItem* item = GetTopVisibleMenu();
1525 while (item) {
1526 // if it isn't a <menupopup>, don't close it automatically
1527 if (!item->IsMenu()) {
1528 break;
1531 nsMenuChainItem* next = item->GetParent();
1532 popupsToHide.AppendElement(item->Frame());
1533 if (aMode == CloseMenuMode_Single) {
1534 // only close one level of menu
1535 break;
1537 item = next;
1540 // Now hide the popups. If the closemenu mode is auto, deselect the menu,
1541 // otherwise only one popup is closing, so keep the parent menu selected.
1542 HidePopupsInList(popupsToHide);
1545 void nsXULPopupManager::ExecuteMenu(nsIContent* aMenu,
1546 nsXULMenuCommandEvent* aEvent) {
1547 CloseMenuMode cmm = GetCloseMenuMode(aMenu);
1548 HideOpenMenusBeforeExecutingMenu(cmm);
1549 aEvent->SetCloseMenuMode(cmm);
1550 nsCOMPtr<nsIRunnable> event = aEvent;
1551 aMenu->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
1554 bool nsXULPopupManager::ActivateNativeMenuItem(nsIContent* aItem,
1555 mozilla::Modifiers aModifiers,
1556 int16_t aButton,
1557 mozilla::ErrorResult& aRv) {
1558 if (mNativeMenu && aItem->IsElement() &&
1559 mNativeMenu->Element()->Contains(aItem)) {
1560 mNativeMenu->ActivateItem(aItem->AsElement(), aModifiers, aButton, aRv);
1561 return true;
1563 return false;
1566 nsEventStatus nsXULPopupManager::FirePopupShowingEvent(
1567 const PendingPopup& aPendingPopup, nsPresContext* aPresContext) {
1568 // Cache the pending popup so that the trigger node and other properties can
1569 // be retrieved during the popupshowing event. It will be cleared below after
1570 // the event has fired.
1571 AutoRestore<const PendingPopup*> restorePendingPopup(mPendingPopup);
1572 mPendingPopup = &aPendingPopup;
1574 nsEventStatus status = nsEventStatus_eIgnore;
1575 WidgetMouseEvent event(true, eXULPopupShowing, nullptr,
1576 WidgetMouseEvent::eReal);
1578 // coordinates are relative to the root widget
1579 nsPresContext* rootPresContext = aPresContext->GetRootPresContext();
1580 if (rootPresContext) {
1581 event.mWidget =
1582 rootPresContext->PresShell()->GetViewManager()->GetRootWidget();
1583 } else {
1584 event.mWidget = nullptr;
1587 event.mInputSource = aPendingPopup.MouseInputSource();
1588 event.mRefPoint = aPendingPopup.mMousePoint;
1589 event.mModifiers = aPendingPopup.mModifiers;
1590 RefPtr<nsIContent> popup = aPendingPopup.mPopup;
1591 EventDispatcher::Dispatch(popup, aPresContext, &event, nullptr, &status);
1593 return status;
1596 void nsXULPopupManager::BeginShowingPopup(const PendingPopup& aPendingPopup,
1597 bool aIsContextMenu,
1598 bool aSelectFirstItem) {
1599 RefPtr<Element> popup = aPendingPopup.mPopup;
1601 nsMenuPopupFrame* popupFrame = do_QueryFrame(popup->GetPrimaryFrame());
1602 if (NS_WARN_IF(!popupFrame)) {
1603 return;
1606 RefPtr<nsPresContext> presContext = popupFrame->PresContext();
1607 RefPtr<PresShell> presShell = presContext->PresShell();
1608 presShell->FrameNeedsReflow(popupFrame, IntrinsicDirty::FrameAndAncestors,
1609 NS_FRAME_IS_DIRTY);
1611 PopupType popupType = popupFrame->GetPopupType();
1613 nsEventStatus status = FirePopupShowingEvent(aPendingPopup, presContext);
1615 // if a panel, blur whatever has focus so that the panel can take the focus.
1616 // This is done after the popupshowing event in case that event is cancelled.
1617 // Using noautofocus="true" will disable this behaviour, which is needed for
1618 // the autocomplete widget as it manages focus itself.
1619 if (popupType == PopupType::Panel &&
1620 !popup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
1621 nsGkAtoms::_true, eCaseMatters)) {
1622 if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
1623 Document* doc = popup->GetUncomposedDoc();
1625 // Only remove the focus if the currently focused item is ouside the
1626 // popup. It isn't a big deal if the current focus is in a child popup
1627 // inside the popup as that shouldn't be visible. This check ensures that
1628 // a node inside the popup that is focused during a popupshowing event
1629 // remains focused.
1630 RefPtr<Element> currentFocus = fm->GetFocusedElement();
1631 if (doc && currentFocus &&
1632 !nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus, popup)) {
1633 nsCOMPtr<nsPIDOMWindowOuter> outerWindow = doc->GetWindow();
1634 fm->ClearFocus(outerWindow);
1639 popup->OwnerDoc()->FlushPendingNotifications(FlushType::Frames);
1641 // get the frame again in case it went away
1642 popupFrame = do_QueryFrame(popup->GetPrimaryFrame());
1643 if (!popupFrame) {
1644 return;
1646 // if the event was cancelled or the popup was closed in the mean time, don't
1647 // open the popup, reset its state back to closed and clear its trigger
1648 // content.
1649 if (popupFrame->PopupState() == ePopupClosed ||
1650 status == nsEventStatus_eConsumeNoDefault) {
1651 popupFrame->SetPopupState(ePopupClosed);
1652 popupFrame->ClearTriggerContent();
1653 return;
1655 // Now check if we need to fire the popuppositioned event. If not, call
1656 // ShowPopupCallback directly.
1657 // The popuppositioned event only fires on arrow panels for now.
1658 if (popup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::arrow,
1659 eCaseMatters)) {
1660 popupFrame->ShowWithPositionedEvent();
1661 presShell->FrameNeedsReflow(popupFrame, IntrinsicDirty::FrameAndAncestors,
1662 NS_FRAME_HAS_DIRTY_CHILDREN);
1663 } else {
1664 ShowPopupCallback(popup, popupFrame, aIsContextMenu, aSelectFirstItem);
1668 void nsXULPopupManager::FirePopupHidingEvent(Element* aPopup,
1669 Element* aNextPopup,
1670 Element* aLastPopup,
1671 nsPresContext* aPresContext,
1672 PopupType aPopupType,
1673 HidePopupOptions aOptions) {
1674 nsCOMPtr<nsIContent> popup = aPopup;
1675 RefPtr<PresShell> presShell = aPresContext->PresShell();
1676 Unused << presShell; // This presShell may be keeping things alive
1677 // on non GTK platforms
1679 nsEventStatus status = nsEventStatus_eIgnore;
1680 WidgetMouseEvent event(true, eXULPopupHiding, nullptr,
1681 WidgetMouseEvent::eReal);
1682 EventDispatcher::Dispatch(aPopup, aPresContext, &event, nullptr, &status);
1684 // when a panel is closed, blur whatever has focus inside the popup
1685 if (aPopupType == PopupType::Panel &&
1686 (!aPopup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
1687 nsGkAtoms::_true, eCaseMatters))) {
1688 if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
1689 Document* doc = aPopup->GetUncomposedDoc();
1691 // Remove the focus from the focused node only if it is inside the popup.
1692 RefPtr<Element> currentFocus = fm->GetFocusedElement();
1693 if (doc && currentFocus &&
1694 nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus, aPopup)) {
1695 nsCOMPtr<nsPIDOMWindowOuter> outerWindow = doc->GetWindow();
1696 fm->ClearFocus(outerWindow);
1701 aPopup->OwnerDoc()->FlushPendingNotifications(FlushType::Frames);
1703 // get frame again in case it went away
1704 nsMenuPopupFrame* popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
1705 if (!popupFrame) {
1706 return;
1709 // If the event was cancelled, don't hide the popup, and reset its
1710 // state back to open. Only popups in chrome shells can prevent a popup
1711 // from hiding.
1712 if (status == nsEventStatus_eConsumeNoDefault &&
1713 !popupFrame->IsInContentShell()) {
1714 // XXXndeakin
1715 // If an attempt was made to hide this popup before the popupshown event
1716 // fired, then ePopupShown is set here even though it should be
1717 // ePopupVisible. This probably isn't worth the hassle of handling.
1718 popupFrame->SetPopupState(ePopupShown);
1719 return;
1722 const bool shouldAnimate = [&] {
1723 if (!LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations)) {
1724 // Animations are not supported by the platform, avoid transitioning.
1725 return false;
1727 if (aOptions.contains(HidePopupOption::DisableAnimations)) {
1728 // Animations are not allowed by our caller.
1729 return false;
1731 if (aNextPopup) {
1732 // If there is a next popup, indicating that mutliple popups are rolling
1733 // up, don't wait and hide the popup right away since the effect would
1734 // likely be undesirable.
1735 return false;
1737 nsAutoString animate;
1738 if (!aPopup->GetAttr(nsGkAtoms::animate, animate)) {
1739 return false;
1741 // If animate="false" then don't transition at all.
1742 if (animate.EqualsLiteral("false")) {
1743 return false;
1745 // If animate="cancel", only show the transition if cancelling the popup
1746 // or rolling up.
1747 if (animate.EqualsLiteral("cancel") &&
1748 !aOptions.contains(HidePopupOption::IsRollup)) {
1749 return false;
1751 return true;
1752 }();
1753 // If we should animate the popup, check if it has a closing transition
1754 // and wait for it to finish.
1755 // The transition would still occur either way, but if we don't wait the
1756 // view will be hidden and you won't be able to see it.
1757 if (shouldAnimate && AnimationUtils::HasCurrentTransitions(
1758 aPopup, PseudoStyleType::NotPseudo)) {
1759 RefPtr<TransitionEnder> ender = new TransitionEnder(aPopup, aOptions);
1760 aPopup->AddSystemEventListener(u"transitionend"_ns, ender, false, false);
1761 return;
1764 HidePopupCallback(aPopup, popupFrame, aNextPopup, aLastPopup, aPopupType,
1765 aOptions);
1768 bool nsXULPopupManager::IsPopupOpen(Element* aPopup) {
1769 if (mNativeMenu && mNativeMenu->Element() == aPopup) {
1770 return true;
1773 // a popup is open if it is in the open list. The assertions ensure that the
1774 // frame is in the correct state. If the popup is in the hiding or invisible
1775 // state, it will still be in the open popup list until it is closed.
1776 if (nsMenuChainItem* item = FindPopup(aPopup)) {
1777 NS_ASSERTION(item->Frame()->IsOpen() ||
1778 item->Frame()->PopupState() == ePopupHiding ||
1779 item->Frame()->PopupState() == ePopupInvisible,
1780 "popup in open list not actually open");
1781 Unused << item;
1782 return true;
1784 return false;
1787 nsIFrame* nsXULPopupManager::GetTopPopup(PopupType aType) {
1788 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1789 if (item->Frame()->IsVisible() &&
1790 (item->GetPopupType() == aType || aType == PopupType::Any)) {
1791 return item->Frame();
1794 return nullptr;
1797 nsIContent* nsXULPopupManager::GetTopActiveMenuItemContent() {
1798 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1799 if (!item->Frame()->IsVisible()) {
1800 continue;
1802 if (auto* content = item->Frame()->PopupElement().GetActiveMenuChild()) {
1803 return content;
1806 return nullptr;
1809 void nsXULPopupManager::GetVisiblePopups(nsTArray<nsIFrame*>& aPopups) {
1810 aPopups.Clear();
1811 for (nsMenuChainItem* item = mPopups.get(); item; item = item->GetParent()) {
1812 // Skip panels which are not visible as well as popups that are transparent
1813 // to mouse events.
1814 if (item->Frame()->IsVisible() && !item->Frame()->IsMouseTransparent()) {
1815 aPopups.AppendElement(item->Frame());
1820 already_AddRefed<nsINode> nsXULPopupManager::GetLastTriggerNode(
1821 Document* aDocument, bool aIsTooltip) {
1822 if (!aDocument) return nullptr;
1824 RefPtr<nsINode> node;
1826 // If a pending popup is set, it means that a popupshowing event is being
1827 // fired. In this case, just use the cached node, as the popup is not yet in
1828 // the list of open popups.
1829 RefPtr<nsIContent> openingPopup =
1830 mPendingPopup ? mPendingPopup->mPopup : nullptr;
1831 if (openingPopup && openingPopup->GetUncomposedDoc() == aDocument &&
1832 aIsTooltip == openingPopup->IsXULElement(nsGkAtoms::tooltip)) {
1833 node = nsMenuPopupFrame::GetTriggerContent(
1834 GetPopupFrameForContent(openingPopup, false));
1835 } else if (mNativeMenu && !aIsTooltip) {
1836 RefPtr<dom::Element> popup = mNativeMenu->Element();
1837 if (popup->GetUncomposedDoc() == aDocument) {
1838 nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(popup, false);
1839 node = nsMenuPopupFrame::GetTriggerContent(popupFrame);
1841 } else {
1842 for (nsMenuChainItem* item = mPopups.get(); item;
1843 item = item->GetParent()) {
1844 // look for a popup of the same type and document.
1845 if ((item->GetPopupType() == PopupType::Tooltip) == aIsTooltip &&
1846 item->Element()->GetUncomposedDoc() == aDocument) {
1847 node = nsMenuPopupFrame::GetTriggerContent(item->Frame());
1848 if (node) {
1849 break;
1855 return node.forget();
1858 bool nsXULPopupManager::MayShowPopup(nsMenuPopupFrame* aPopup) {
1859 // if a popup's IsOpen method returns true, then the popup must always be in
1860 // the popup chain scanned in IsPopupOpen.
1861 NS_ASSERTION(!aPopup->IsOpen() || IsPopupOpen(&aPopup->PopupElement()),
1862 "popup frame state doesn't match XULPopupManager open state");
1864 nsPopupState state = aPopup->PopupState();
1866 // if the popup is not in the open popup chain, then it must have a state that
1867 // is either closed, in the process of being shown, or invisible.
1868 NS_ASSERTION(IsPopupOpen(&aPopup->PopupElement()) || state == ePopupClosed ||
1869 state == ePopupShowing || state == ePopupPositioning ||
1870 state == ePopupInvisible,
1871 "popup not in XULPopupManager open list is open");
1873 // don't show popups unless they are closed or invisible
1874 if (state != ePopupClosed && state != ePopupInvisible) return false;
1876 // Don't show popups that we already have in our popup chain
1877 if (IsPopupOpen(&aPopup->PopupElement())) {
1878 NS_WARNING("Refusing to show duplicate popup");
1879 return false;
1882 // if the popup was just rolled up, don't reopen it
1883 if (mozilla::widget::nsAutoRollup::GetLastRollup() == aPopup->GetContent()) {
1884 return false;
1887 nsCOMPtr<nsIDocShell> docShell = aPopup->PresContext()->GetDocShell();
1889 nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(docShell);
1890 if (!baseWin) {
1891 return false;
1894 nsCOMPtr<nsIDocShellTreeItem> root;
1895 docShell->GetInProcessRootTreeItem(getter_AddRefs(root));
1896 if (!root) {
1897 return false;
1900 nsCOMPtr<nsPIDOMWindowOuter> rootWin = root->GetWindow();
1902 MOZ_RELEASE_ASSERT(XRE_IsParentProcess(),
1903 "Cannot have XUL in content process showing popups.");
1905 // chrome shells can always open popups, but other types of shells can only
1906 // open popups when they are focused and visible
1907 if (docShell->ItemType() != nsIDocShellTreeItem::typeChrome) {
1908 // only allow popups in active windows
1909 nsFocusManager* fm = nsFocusManager::GetFocusManager();
1910 if (!fm || !rootWin) {
1911 return false;
1914 nsCOMPtr<nsPIDOMWindowOuter> activeWindow = fm->GetActiveWindow();
1915 if (activeWindow != rootWin) {
1916 return false;
1919 // only allow popups in visible frames
1920 // TODO: This visibility check should be replaced with a check of
1921 // bc->IsActive(). It is okay for now since this is only called
1922 // in the parent process. Bug 1698533.
1923 bool visible;
1924 baseWin->GetVisibility(&visible);
1925 if (!visible) {
1926 return false;
1930 // platforms respond differently when an popup is opened in a minimized
1931 // window, so this is always disabled.
1932 nsCOMPtr<nsIWidget> mainWidget;
1933 baseWin->GetMainWidget(getter_AddRefs(mainWidget));
1934 if (mainWidget && mainWidget->SizeMode() == nsSizeMode_Minimized) {
1935 return false;
1938 #ifdef XP_MACOSX
1939 if (rootWin) {
1940 auto globalWin = nsGlobalWindowOuter::Cast(rootWin.get());
1941 if (globalWin->IsInModalState()) {
1942 return false;
1945 #endif
1947 // cannot open a popup that is a submenu of a menupopup that isn't open.
1948 if (auto* menu = aPopup->PopupElement().GetContainingMenu()) {
1949 if (auto* parent = XULPopupElement::FromNodeOrNull(menu->GetMenuParent())) {
1950 nsMenuPopupFrame* f = do_QueryFrame(parent->GetPrimaryFrame());
1951 if (f && !f->IsOpen()) {
1952 return false;
1957 return true;
1960 void nsXULPopupManager::PopupDestroyed(nsMenuPopupFrame* aPopup) {
1961 // when a popup frame is destroyed, just unhook it from the list of popups
1962 CancelMenuTimer(aPopup);
1964 nsMenuChainItem* item = FindPopup(&aPopup->PopupElement());
1965 if (!item) {
1966 return;
1969 nsTArray<nsMenuPopupFrame*> popupsToHide;
1970 // XXXndeakin shouldn't this only happen for menus?
1971 if (!item->IsNoAutoHide() && item->Frame()->PopupState() != ePopupInvisible) {
1972 // Iterate through any child menus and hide them as well, since the
1973 // parent is going away. We won't remove them from the list yet, just
1974 // hide them, as they will be removed from the list when this function
1975 // gets called for that child frame.
1976 for (auto* child = item->GetChild(); child; child = child->GetChild()) {
1977 // If the popup is a child frame of the menu that was destroyed, add it
1978 // to the list of popups to hide. Don't bother with the events since the
1979 // frames are going away. If the child menu is not a child frame, for
1980 // example, a context menu, use HidePopup instead, but call it
1981 // asynchronously since we are in the middle of frame destruction.
1982 if (nsLayoutUtils::IsProperAncestorFrame(item->Frame(), child->Frame())) {
1983 popupsToHide.AppendElement(child->Frame());
1984 } else {
1985 // HidePopup will take care of hiding any of its children, so
1986 // break out afterwards
1987 HidePopup(child->Element(), {HidePopupOption::Async});
1988 break;
1993 RemoveMenuChainItem(item);
1994 HidePopupsInList(popupsToHide);
1997 bool nsXULPopupManager::HasContextMenu(nsMenuPopupFrame* aPopup) {
1998 nsMenuChainItem* item = GetTopVisibleMenu();
1999 while (item && item->Frame() != aPopup) {
2000 if (item->IsContextMenu()) return true;
2001 item = item->GetParent();
2004 return false;
2007 void nsXULPopupManager::SetCaptureState(nsIContent* aOldPopup) {
2008 nsMenuChainItem* item = GetTopVisibleMenu();
2009 if (item && aOldPopup == item->Element()) return;
2011 if (mWidget) {
2012 mWidget->CaptureRollupEvents(false);
2013 mWidget = nullptr;
2016 if (item) {
2017 nsMenuPopupFrame* popup = item->Frame();
2018 mWidget = popup->GetWidget();
2019 if (mWidget) {
2020 mWidget->CaptureRollupEvents(true);
2024 UpdateKeyboardListeners();
2027 void nsXULPopupManager::UpdateKeyboardListeners() {
2028 nsCOMPtr<EventTarget> newTarget;
2029 bool isForMenu = false;
2030 if (nsMenuChainItem* item = GetTopVisibleMenu()) {
2031 if (item->IgnoreKeys() != eIgnoreKeys_True) {
2032 newTarget = item->Element()->GetComposedDoc();
2034 isForMenu = item->GetPopupType() == PopupType::Menu;
2035 } else if (mActiveMenuBar && mActiveMenuBar->IsActiveByKeyboard()) {
2036 // Only listen for key events iff menubar is activated via key, see
2037 // bug 1818241.
2038 newTarget = mActiveMenuBar->GetComposedDoc();
2039 isForMenu = true;
2042 if (mKeyListener != newTarget) {
2043 OwningNonNull<nsXULPopupManager> kungFuDeathGrip(*this);
2044 if (mKeyListener) {
2045 mKeyListener->RemoveEventListener(u"keypress"_ns, this, true);
2046 mKeyListener->RemoveEventListener(u"keydown"_ns, this, true);
2047 mKeyListener->RemoveEventListener(u"keyup"_ns, this, true);
2048 mKeyListener = nullptr;
2049 nsContentUtils::NotifyInstalledMenuKeyboardListener(false);
2052 if (newTarget) {
2053 newTarget->AddEventListener(u"keypress"_ns, this, true);
2054 newTarget->AddEventListener(u"keydown"_ns, this, true);
2055 newTarget->AddEventListener(u"keyup"_ns, this, true);
2056 nsContentUtils::NotifyInstalledMenuKeyboardListener(isForMenu);
2057 mKeyListener = newTarget;
2062 void nsXULPopupManager::UpdateMenuItems(Element* aPopup) {
2063 // Walk all of the menu's children, checking to see if any of them has a
2064 // command attribute. If so, then several attributes must potentially be
2065 // updated.
2067 nsCOMPtr<Document> document = aPopup->GetUncomposedDoc();
2068 if (!document) {
2069 return;
2072 // When a menu is opened, make sure that command updating is unlocked first.
2073 nsCOMPtr<nsIDOMXULCommandDispatcher> commandDispatcher =
2074 document->GetCommandDispatcher();
2075 if (commandDispatcher) {
2076 commandDispatcher->Unlock();
2079 for (nsCOMPtr<nsIContent> grandChild = aPopup->GetFirstChild(); grandChild;
2080 grandChild = grandChild->GetNextSibling()) {
2081 if (grandChild->IsXULElement(nsGkAtoms::menugroup)) {
2082 if (grandChild->GetChildCount() == 0) {
2083 continue;
2085 grandChild = grandChild->GetFirstChild();
2087 if (grandChild->IsXULElement(nsGkAtoms::menuitem)) {
2088 // See if we have a command attribute.
2089 Element* grandChildElement = grandChild->AsElement();
2090 nsAutoString command;
2091 grandChildElement->GetAttr(kNameSpaceID_None, nsGkAtoms::command,
2092 command);
2093 if (!command.IsEmpty()) {
2094 // We do! Look it up in our document
2095 RefPtr<dom::Element> commandElement = document->GetElementById(command);
2096 if (commandElement) {
2097 nsAutoString commandValue;
2098 // The menu's disabled state needs to be updated to match the command.
2099 if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::disabled,
2100 commandValue))
2101 grandChildElement->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled,
2102 commandValue, true);
2103 else
2104 grandChildElement->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled,
2105 true);
2107 // The menu's label, accesskey checked and hidden states need to be
2108 // updated to match the command. Note that unlike the disabled state
2109 // if the command has *no* value, we assume the menu is supplying its
2110 // own.
2111 if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::label,
2112 commandValue))
2113 grandChildElement->SetAttr(kNameSpaceID_None, nsGkAtoms::label,
2114 commandValue, true);
2116 if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey,
2117 commandValue))
2118 grandChildElement->SetAttr(kNameSpaceID_None, nsGkAtoms::accesskey,
2119 commandValue, true);
2121 if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::checked,
2122 commandValue))
2123 grandChildElement->SetAttr(kNameSpaceID_None, nsGkAtoms::checked,
2124 commandValue, true);
2126 if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::hidden,
2127 commandValue))
2128 grandChildElement->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden,
2129 commandValue, true);
2133 if (!grandChild->GetNextSibling() &&
2134 grandChild->GetParent()->IsXULElement(nsGkAtoms::menugroup)) {
2135 grandChild = grandChild->GetParent();
2140 // Notify
2142 // The item selection timer has fired, we might have to readjust the
2143 // selected item. There are two cases here that we are trying to deal with:
2144 // (1) diagonal movement from a parent menu to a submenu passing briefly over
2145 // other items, and
2146 // (2) moving out from a submenu to a parent or grandparent menu.
2147 // In both cases, |mTimerMenu| is the menu item that might have an open submenu
2148 // and the first item in |mPopups| is the item the mouse is currently over,
2149 // which could be none of them.
2151 // case (1):
2152 // As the mouse moves from the parent item of a submenu (we'll call 'A')
2153 // diagonally into the submenu, it probably passes through one or more
2154 // sibilings (B). As the mouse passes through B, it becomes the current menu
2155 // item and the timer is set and mTimerMenu is set to A. Before the timer
2156 // fires, the mouse leaves the menu containing A and B and enters the submenus.
2157 // Now when the timer fires, |mPopups| is null (!= |mTimerMenu|) so we have to
2158 // see if anything in A's children is selected (recall that even disabled items
2159 // are selected, the style just doesn't show it). If that is the case, we need
2160 // to set the selected item back to A.
2162 // case (2);
2163 // Item A has an open submenu, and in it there is an item (B) which also has an
2164 // open submenu (so there are 3 menus displayed right now). The mouse then
2165 // leaves B's child submenu and selects an item that is a sibling of A, call it
2166 // C. When the mouse enters C, the timer is set and |mTimerMenu| is A and
2167 // |mPopups| is C. As the timer fires, the mouse is still within C. The correct
2168 // behavior is to set the current item to C and close up the chain parented at
2169 // A.
2171 // This brings up the question of is the logic of case (1) enough? The answer
2172 // is no, and is discussed in bugzilla bug 29400. Case (1) asks if A's submenu
2173 // has a selected child, and if it does, set the selected item to A. Because B
2174 // has a submenu open, it is selected and as a result, A is set to be the
2175 // selected item even though the mouse rests in C -- very wrong.
2177 // The solution is to use the same idea, but instead of only checking one
2178 // level, drill all the way down to the deepest open submenu and check if it
2179 // has something selected. Since the mouse is in a grandparent, it won't, and
2180 // we know that we can safely close up A and all its children.
2182 // The code below melds the two cases together.
2184 void nsXULPopupManager::KillMenuTimer() {
2185 if (mCloseTimer && mTimerMenu) {
2186 mCloseTimer->Cancel();
2187 mCloseTimer = nullptr;
2189 if (mTimerMenu->IsOpen()) {
2190 HidePopup(&mTimerMenu->PopupElement(), {HidePopupOption::Async});
2194 mTimerMenu = nullptr;
2197 void nsXULPopupManager::CancelMenuTimer(nsMenuPopupFrame* aMenu) {
2198 if (mCloseTimer && mTimerMenu == aMenu) {
2199 mCloseTimer->Cancel();
2200 mCloseTimer = nullptr;
2201 mTimerMenu = nullptr;
2205 bool nsXULPopupManager::HandleShortcutNavigation(KeyboardEvent& aKeyEvent,
2206 nsMenuPopupFrame* aFrame) {
2207 // On Windows, don't check shortcuts when the accelerator key is down.
2208 #ifdef XP_WIN
2209 WidgetInputEvent* evt = aKeyEvent.WidgetEventPtr()->AsInputEvent();
2210 if (evt && evt->IsAccel()) {
2211 return false;
2213 #endif
2215 if (!aFrame) {
2216 if (nsMenuChainItem* item = GetTopVisibleMenu()) {
2217 aFrame = item->Frame();
2221 if (aFrame) {
2222 bool action = false;
2223 RefPtr result = aFrame->FindMenuWithShortcut(aKeyEvent, action);
2224 if (!result) {
2225 return false;
2227 RefPtr popup = &aFrame->PopupElement();
2228 popup->SetActiveMenuChild(result, XULMenuParentElement::ByKey::Yes);
2229 if (action) {
2230 WidgetEvent* evt = aKeyEvent.WidgetEventPtr();
2231 result->HandleEnterKeyPress(*evt);
2233 return true;
2236 // Only do shortcut navigation when the menubar is activated via keyboard.
2237 if (mActiveMenuBar) {
2238 RefPtr menubar = mActiveMenuBar;
2239 if (RefPtr result = menubar->FindMenuWithShortcut(aKeyEvent)) {
2240 result->OpenMenuPopup(true);
2241 return true;
2243 #ifdef XP_WIN
2244 // Behavior on Windows - this item is on the menu bar, beep and deactivate
2245 // the menu bar.
2246 // TODO(emilio): This is rather odd, and I cannot get the beep to work,
2247 // but this matches what old code was doing...
2248 if (nsCOMPtr<nsISound> sound = do_GetService("@mozilla.org/sound;1")) {
2249 sound->Beep();
2251 menubar->SetActive(false);
2252 #endif
2254 return false;
2257 bool nsXULPopupManager::HandleKeyboardNavigation(uint32_t aKeyCode) {
2258 if (nsMenuChainItem* nextitem = GetTopVisibleMenu()) {
2259 nextitem->Element()->OwnerDoc()->FlushPendingNotifications(
2260 FlushType::Frames);
2263 // navigate up through the open menus, looking for the topmost one
2264 // in the same hierarchy
2265 nsMenuChainItem* item = nullptr;
2266 nsMenuChainItem* nextitem = GetTopVisibleMenu();
2267 while (nextitem) {
2268 item = nextitem;
2269 nextitem = item->GetParent();
2271 if (!nextitem) {
2272 break;
2274 // stop if the parent isn't a menu
2275 if (!nextitem->IsMenu()) {
2276 break;
2279 // Check to make sure that the parent is actually the parent menu. It won't
2280 // be if the parent is in a different frame hierarchy, for example, for a
2281 // context menu opened on another menu.
2282 XULPopupElement& expectedParent = nextitem->Frame()->PopupElement();
2283 auto* menu = item->Frame()->PopupElement().GetContainingMenu();
2284 if (!menu || menu->GetMenuParent() != &expectedParent) {
2285 break;
2289 nsIFrame* itemFrame;
2290 if (item) {
2291 itemFrame = item->Frame();
2292 } else if (mActiveMenuBar) {
2293 itemFrame = mActiveMenuBar->GetPrimaryFrame();
2294 if (!itemFrame) {
2295 return false;
2297 } else {
2298 return false;
2301 nsNavigationDirection theDirection;
2302 NS_ASSERTION(aKeyCode >= KeyboardEvent_Binding::DOM_VK_END &&
2303 aKeyCode <= KeyboardEvent_Binding::DOM_VK_DOWN,
2304 "Illegal key code");
2305 theDirection = NS_DIRECTION_FROM_KEY_CODE(itemFrame, aKeyCode);
2307 bool selectFirstItem = true;
2308 #ifdef MOZ_WIDGET_GTK
2310 XULButtonElement* currentItem = nullptr;
2311 if (item && mActiveMenuBar && NS_DIRECTION_IS_INLINE(theDirection)) {
2312 currentItem = item->Frame()->PopupElement().GetActiveMenuChild();
2313 // If nothing is selected in the menu and we have a menubar, let it
2314 // handle the movement not to steal focus from it.
2315 if (!currentItem) {
2316 item = nullptr;
2319 // On menu change, only select first item if an item is already selected.
2320 selectFirstItem = !!currentItem;
2322 #endif
2324 // if a popup is open, first check for navigation within the popup
2325 if (item && HandleKeyboardNavigationInPopup(item, theDirection)) {
2326 return true;
2329 // no popup handled the key, so check the active menubar, if any
2330 if (!mActiveMenuBar) {
2331 return false;
2333 RefPtr menubar = mActiveMenuBar;
2334 if (NS_DIRECTION_IS_INLINE(theDirection)) {
2335 RefPtr prevActiveItem = menubar->GetActiveMenuChild();
2336 const bool open = prevActiveItem && prevActiveItem->IsMenuPopupOpen();
2337 RefPtr nextItem = theDirection == eNavigationDirection_End
2338 ? menubar->GetNextMenuItem()
2339 : menubar->GetPrevMenuItem();
2340 menubar->SetActiveMenuChild(nextItem, XULMenuParentElement::ByKey::Yes);
2341 if (open && nextItem) {
2342 nextItem->OpenMenuPopup(selectFirstItem);
2344 return true;
2346 if (NS_DIRECTION_IS_BLOCK(theDirection)) {
2347 // Open the menu and select its first item.
2348 if (RefPtr currentMenu = menubar->GetActiveMenuChild()) {
2349 ShowMenu(currentMenu, selectFirstItem);
2351 return true;
2353 return false;
2356 bool nsXULPopupManager::HandleKeyboardNavigationInPopup(
2357 nsMenuChainItem* item, nsMenuPopupFrame* aFrame,
2358 nsNavigationDirection aDir) {
2359 NS_ASSERTION(aFrame, "aFrame is null");
2360 NS_ASSERTION(!item || item->Frame() == aFrame,
2361 "aFrame is expected to be equal to item->Frame()");
2363 using Wrap = XULMenuParentElement::Wrap;
2364 RefPtr<XULPopupElement> menu = &aFrame->PopupElement();
2366 aFrame->ClearIncrementalString();
2367 RefPtr currentItem = aFrame->GetCurrentMenuItem();
2369 // This method only gets called if we're open.
2370 if (!currentItem && NS_DIRECTION_IS_INLINE(aDir)) {
2371 // We've been opened, but we haven't had anything selected.
2372 // We can handle End, but our parent handles Start.
2373 if (aDir == eNavigationDirection_End) {
2374 if (RefPtr nextItem = menu->GetNextMenuItem(Wrap::No)) {
2375 menu->SetActiveMenuChild(nextItem, XULMenuParentElement::ByKey::Yes);
2376 return true;
2379 return false;
2382 const bool isContainer = currentItem && !currentItem->IsMenuItem();
2383 const bool isOpen = currentItem && currentItem->IsMenuPopupOpen();
2384 if (isOpen) {
2385 // For an open popup, have the child process the event
2386 nsMenuChainItem* child = item ? item->GetChild() : nullptr;
2387 if (child && HandleKeyboardNavigationInPopup(child, aDir)) {
2388 return true;
2390 } else if (aDir == eNavigationDirection_End && isContainer &&
2391 !currentItem->IsDisabled()) {
2392 currentItem->OpenMenuPopup(true);
2393 return true;
2396 // For block progression, we can move in either direction
2397 if (NS_DIRECTION_IS_BLOCK(aDir) || NS_DIRECTION_IS_BLOCK_TO_EDGE(aDir)) {
2398 RefPtr<XULButtonElement> nextItem = nullptr;
2400 if (aDir == eNavigationDirection_Before ||
2401 aDir == eNavigationDirection_After) {
2402 // Cursor navigation does not wrap on Mac or for menulists on Windows.
2403 auto wrap =
2404 #ifdef XP_WIN
2405 aFrame->IsMenuList() ? Wrap::No : Wrap::Yes;
2406 #elif defined XP_MACOSX
2407 Wrap::No;
2408 #else
2409 Wrap::Yes;
2410 #endif
2412 if (aDir == eNavigationDirection_Before) {
2413 nextItem = menu->GetPrevMenuItem(wrap);
2414 } else {
2415 nextItem = menu->GetNextMenuItem(wrap);
2417 } else if (aDir == eNavigationDirection_First) {
2418 nextItem = menu->GetFirstMenuItem();
2419 } else {
2420 nextItem = menu->GetLastMenuItem();
2423 if (nextItem) {
2424 menu->SetActiveMenuChild(nextItem, XULMenuParentElement::ByKey::Yes);
2425 return true;
2427 } else if (currentItem && isOpen && aDir == eNavigationDirection_Start) {
2428 // close a submenu when Left is pressed
2429 if (nsMenuPopupFrame* popupFrame =
2430 currentItem->GetMenuPopup(FlushType::None)) {
2431 HidePopup(&popupFrame->PopupElement(), {});
2433 return true;
2436 return false;
2439 bool nsXULPopupManager::HandleKeyboardEventWithKeyCode(
2440 KeyboardEvent* aKeyEvent, nsMenuChainItem* aTopVisibleMenuItem) {
2441 uint32_t keyCode = aKeyEvent->KeyCode();
2443 // Escape should close panels, but the other keys should have no effect.
2444 if (aTopVisibleMenuItem &&
2445 aTopVisibleMenuItem->GetPopupType() != PopupType::Menu) {
2446 if (keyCode == KeyboardEvent_Binding::DOM_VK_ESCAPE) {
2447 HidePopup(aTopVisibleMenuItem->Element(), {HidePopupOption::IsRollup});
2448 aKeyEvent->StopPropagation();
2449 aKeyEvent->StopCrossProcessForwarding();
2450 aKeyEvent->PreventDefault();
2452 return true;
2455 bool consume = (aTopVisibleMenuItem || mActiveMenuBar);
2456 switch (keyCode) {
2457 case KeyboardEvent_Binding::DOM_VK_UP:
2458 case KeyboardEvent_Binding::DOM_VK_DOWN:
2459 #ifndef XP_MACOSX
2460 // roll up the popup when alt+up/down are pressed within a menulist.
2461 if (aKeyEvent->AltKey() && aTopVisibleMenuItem &&
2462 aTopVisibleMenuItem->Frame()->IsMenuList()) {
2463 Rollup({});
2464 break;
2466 [[fallthrough]];
2467 #endif
2469 case KeyboardEvent_Binding::DOM_VK_LEFT:
2470 case KeyboardEvent_Binding::DOM_VK_RIGHT:
2471 case KeyboardEvent_Binding::DOM_VK_HOME:
2472 case KeyboardEvent_Binding::DOM_VK_END:
2473 HandleKeyboardNavigation(keyCode);
2474 break;
2476 case KeyboardEvent_Binding::DOM_VK_PAGE_DOWN:
2477 case KeyboardEvent_Binding::DOM_VK_PAGE_UP:
2478 if (aTopVisibleMenuItem) {
2479 aTopVisibleMenuItem->Frame()->ChangeByPage(
2480 keyCode == KeyboardEvent_Binding::DOM_VK_PAGE_UP);
2482 break;
2484 case KeyboardEvent_Binding::DOM_VK_ESCAPE:
2485 // Pressing Escape hides one level of menus only. If no menu is open,
2486 // check if a menubar is active and inform it that a menu closed. Even
2487 // though in this latter case, a menu didn't actually close, the effect
2488 // ends up being the same. Similar for the tab key below.
2489 if (aTopVisibleMenuItem) {
2490 HidePopup(aTopVisibleMenuItem->Element(), {HidePopupOption::IsRollup});
2491 } else if (mActiveMenuBar) {
2492 RefPtr menubar = mActiveMenuBar;
2493 menubar->SetActive(false);
2495 break;
2497 case KeyboardEvent_Binding::DOM_VK_TAB:
2498 #ifndef XP_MACOSX
2499 case KeyboardEvent_Binding::DOM_VK_F10:
2500 #endif
2501 if (aTopVisibleMenuItem &&
2502 !aTopVisibleMenuItem->Frame()->PopupElement().AttrValueIs(
2503 kNameSpaceID_None, nsGkAtoms::activateontab, nsGkAtoms::_true,
2504 eCaseMatters)) {
2505 // Close popups or deactivate menubar when Tab or F10 are pressed
2506 Rollup({});
2507 break;
2508 } else if (mActiveMenuBar) {
2509 RefPtr menubar = mActiveMenuBar;
2510 menubar->SetActive(false);
2511 break;
2513 // Intentional fall-through to RETURN case
2514 [[fallthrough]];
2516 case KeyboardEvent_Binding::DOM_VK_RETURN: {
2517 // If there is a popup open, check if the current item needs to be opened.
2518 // Otherwise, tell the active menubar, if any, to activate the menu. The
2519 // Enter method will return a menu if one needs to be opened as a result.
2520 WidgetEvent* event = aKeyEvent->WidgetEventPtr();
2521 if (aTopVisibleMenuItem) {
2522 aTopVisibleMenuItem->Frame()->HandleEnterKeyPress(*event);
2523 } else if (mActiveMenuBar) {
2524 RefPtr menubar = mActiveMenuBar;
2525 menubar->HandleEnterKeyPress(*event);
2527 break;
2530 default:
2531 return false;
2534 if (consume) {
2535 aKeyEvent->StopPropagation();
2536 aKeyEvent->StopCrossProcessForwarding();
2537 aKeyEvent->PreventDefault();
2539 return true;
2542 nsresult nsXULPopupManager::HandleEvent(Event* aEvent) {
2543 RefPtr<KeyboardEvent> keyEvent = aEvent->AsKeyboardEvent();
2544 NS_ENSURE_TRUE(keyEvent, NS_ERROR_UNEXPECTED);
2546 // handlers shouldn't be triggered by non-trusted events.
2547 if (!keyEvent->IsTrusted()) {
2548 return NS_OK;
2551 nsAutoString eventType;
2552 keyEvent->GetType(eventType);
2553 if (eventType.EqualsLiteral("keyup")) {
2554 return KeyUp(keyEvent);
2556 if (eventType.EqualsLiteral("keydown")) {
2557 return KeyDown(keyEvent);
2559 if (eventType.EqualsLiteral("keypress")) {
2560 return KeyPress(keyEvent);
2563 MOZ_ASSERT_UNREACHABLE("Unexpected eventType");
2564 return NS_OK;
2567 nsresult nsXULPopupManager::UpdateIgnoreKeys(bool aIgnoreKeys) {
2568 nsMenuChainItem* item = GetTopVisibleMenu();
2569 if (item) {
2570 item->SetIgnoreKeys(aIgnoreKeys ? eIgnoreKeys_True : eIgnoreKeys_Shortcuts);
2572 UpdateKeyboardListeners();
2573 return NS_OK;
2576 nsPopupState nsXULPopupManager::GetPopupState(Element* aPopupElement) {
2577 if (mNativeMenu && mNativeMenu->Element()->Contains(aPopupElement)) {
2578 if (aPopupElement != mNativeMenu->Element()) {
2579 // Submenu state is stored in mNativeMenuSubmenuStates.
2580 return mNativeMenuSubmenuStates.MaybeGet(aPopupElement)
2581 .valueOr(ePopupClosed);
2583 // mNativeMenu->Element()'s state is stored in its nsMenuPopupFrame.
2586 nsMenuPopupFrame* menuPopupFrame =
2587 do_QueryFrame(aPopupElement->GetPrimaryFrame());
2588 if (menuPopupFrame) {
2589 return menuPopupFrame->PopupState();
2591 return ePopupClosed;
2594 nsresult nsXULPopupManager::KeyUp(KeyboardEvent* aKeyEvent) {
2595 // don't do anything if a menu isn't open or a menubar isn't active
2596 if (!mActiveMenuBar) {
2597 nsMenuChainItem* item = GetTopVisibleMenu();
2598 if (!item || item->GetPopupType() != PopupType::Menu) return NS_OK;
2600 if (item->IgnoreKeys() == eIgnoreKeys_Shortcuts) {
2601 aKeyEvent->StopCrossProcessForwarding();
2602 return NS_OK;
2606 aKeyEvent->StopPropagation();
2607 aKeyEvent->StopCrossProcessForwarding();
2608 aKeyEvent->PreventDefault();
2610 return NS_OK; // I am consuming event
2613 nsresult nsXULPopupManager::KeyDown(KeyboardEvent* aKeyEvent) {
2614 nsMenuChainItem* item = GetTopVisibleMenu();
2615 if (item && item->Frame()->PopupElement().IsLocked()) {
2616 return NS_OK;
2619 if (HandleKeyboardEventWithKeyCode(aKeyEvent, item)) {
2620 return NS_OK;
2623 // don't do anything if a menu isn't open or a menubar isn't active
2624 if (!mActiveMenuBar && (!item || item->GetPopupType() != PopupType::Menu))
2625 return NS_OK;
2627 // Since a menu was open, stop propagation of the event to keep other event
2628 // listeners from becoming confused.
2629 if (!item || item->IgnoreKeys() != eIgnoreKeys_Shortcuts) {
2630 aKeyEvent->StopPropagation();
2633 // If the key just pressed is the access key (usually Alt),
2634 // dismiss and unfocus the menu.
2635 uint32_t menuAccessKey = LookAndFeel::GetMenuAccessKey();
2636 if (menuAccessKey) {
2637 uint32_t theChar = aKeyEvent->KeyCode();
2639 if (theChar == menuAccessKey) {
2640 bool ctrl = (menuAccessKey != KeyboardEvent_Binding::DOM_VK_CONTROL &&
2641 aKeyEvent->CtrlKey());
2642 bool alt = (menuAccessKey != KeyboardEvent_Binding::DOM_VK_ALT &&
2643 aKeyEvent->AltKey());
2644 bool shift = (menuAccessKey != KeyboardEvent_Binding::DOM_VK_SHIFT &&
2645 aKeyEvent->ShiftKey());
2646 bool meta = (menuAccessKey != KeyboardEvent_Binding::DOM_VK_META &&
2647 aKeyEvent->MetaKey());
2648 if (!(ctrl || alt || shift || meta)) {
2649 // The access key just went down and no other
2650 // modifiers are already down.
2651 nsMenuChainItem* item = GetTopVisibleMenu();
2652 if (item && !item->Frame()->IsMenuList()) {
2653 Rollup({});
2654 } else if (mActiveMenuBar) {
2655 RefPtr menubar = mActiveMenuBar;
2656 menubar->SetActive(false);
2659 // Clear the item to avoid bugs as it may have been deleted during
2660 // rollup.
2661 item = nullptr;
2663 aKeyEvent->StopPropagation();
2664 aKeyEvent->PreventDefault();
2668 aKeyEvent->StopCrossProcessForwarding();
2669 return NS_OK;
2672 nsresult nsXULPopupManager::KeyPress(KeyboardEvent* aKeyEvent) {
2673 // Don't check prevent default flag -- menus always get first shot at key
2674 // events.
2676 nsMenuChainItem* item = GetTopVisibleMenu();
2677 if (item && (item->Frame()->PopupElement().IsLocked() ||
2678 item->GetPopupType() != PopupType::Menu)) {
2679 return NS_OK;
2682 // if a menu is open or a menubar is active, it consumes the key event
2683 bool consume = (item || mActiveMenuBar);
2685 WidgetInputEvent* evt = aKeyEvent->WidgetEventPtr()->AsInputEvent();
2686 bool isAccel = evt && evt->IsAccel();
2688 // When ignorekeys="shortcuts" is used, we don't call preventDefault on the
2689 // key event when the accelerator key is pressed. This allows another
2690 // listener to handle keys. For instance, this allows global shortcuts to
2691 // still apply while a menu is open.
2692 if (item && item->IgnoreKeys() == eIgnoreKeys_Shortcuts && isAccel) {
2693 consume = false;
2696 HandleShortcutNavigation(*aKeyEvent, nullptr);
2698 aKeyEvent->StopCrossProcessForwarding();
2699 if (consume) {
2700 aKeyEvent->StopPropagation();
2701 aKeyEvent->PreventDefault();
2704 return NS_OK; // I am consuming event
2707 NS_IMETHODIMP
2708 nsXULPopupHidingEvent::Run() {
2709 RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance();
2710 Document* document = mPopup->GetUncomposedDoc();
2711 if (pm && document) {
2712 if (RefPtr<nsPresContext> presContext = document->GetPresContext()) {
2713 nsCOMPtr<Element> popup = mPopup;
2714 nsCOMPtr<Element> nextPopup = mNextPopup;
2715 nsCOMPtr<Element> lastPopup = mLastPopup;
2716 pm->FirePopupHidingEvent(popup, nextPopup, lastPopup, presContext,
2717 mPopupType, mOptions);
2720 return NS_OK;
2723 bool nsXULPopupPositionedEvent::DispatchIfNeeded(Element* aPopup) {
2724 // The popuppositioned event only fires on arrow panels for now.
2725 if (aPopup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::arrow,
2726 eCaseMatters)) {
2727 nsCOMPtr<nsIRunnable> event = new nsXULPopupPositionedEvent(aPopup);
2728 aPopup->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
2729 return true;
2732 return false;
2735 static void AlignmentPositionToString(nsMenuPopupFrame* aFrame,
2736 nsAString& aString) {
2737 aString.Truncate();
2738 int8_t position = aFrame->GetAlignmentPosition();
2739 switch (position) {
2740 case POPUPPOSITION_AFTERSTART:
2741 return aString.AssignLiteral("after_start");
2742 case POPUPPOSITION_AFTEREND:
2743 return aString.AssignLiteral("after_end");
2744 case POPUPPOSITION_BEFORESTART:
2745 return aString.AssignLiteral("before_start");
2746 case POPUPPOSITION_BEFOREEND:
2747 return aString.AssignLiteral("before_end");
2748 case POPUPPOSITION_STARTBEFORE:
2749 return aString.AssignLiteral("start_before");
2750 case POPUPPOSITION_ENDBEFORE:
2751 return aString.AssignLiteral("end_before");
2752 case POPUPPOSITION_STARTAFTER:
2753 return aString.AssignLiteral("start_after");
2754 case POPUPPOSITION_ENDAFTER:
2755 return aString.AssignLiteral("end_after");
2756 case POPUPPOSITION_OVERLAP:
2757 return aString.AssignLiteral("overlap");
2758 case POPUPPOSITION_AFTERPOINTER:
2759 return aString.AssignLiteral("after_pointer");
2760 case POPUPPOSITION_SELECTION:
2761 return aString.AssignLiteral("selection");
2762 default:
2763 // Leave as an empty string.
2764 break;
2768 NS_IMETHODIMP
2769 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2770 nsXULPopupPositionedEvent::Run() {
2771 RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance();
2772 if (!pm) {
2773 return NS_OK;
2775 nsMenuPopupFrame* popupFrame = do_QueryFrame(mPopup->GetPrimaryFrame());
2776 if (!popupFrame) {
2777 return NS_OK;
2780 popupFrame->WillDispatchPopupPositioned();
2782 // At this point, hidePopup may have been called but it currently has no
2783 // way to stop this event. However, if hidePopup was called, the popup
2784 // will now be in the hiding or closed state. If we are in the shown or
2785 // positioning state instead, we can assume that we are still clear to
2786 // open/move the popup
2787 nsPopupState state = popupFrame->PopupState();
2788 if (state != ePopupPositioning && state != ePopupShown) {
2789 return NS_OK;
2792 // Note that the offset might be along either the X or Y axis, but for the
2793 // sake of simplicity we use a point with only the X axis set so we can
2794 // use ToNearestPixels().
2795 int32_t popupOffset = nsPoint(popupFrame->GetAlignmentOffset(), 0)
2796 .ToNearestPixels(AppUnitsPerCSSPixel())
2799 PopupPositionedEventInit init;
2800 init.mComposed = true;
2801 init.mIsAnchored = popupFrame->IsAnchored();
2802 init.mAlignmentOffset = popupOffset;
2803 AlignmentPositionToString(popupFrame, init.mAlignmentPosition);
2804 RefPtr<PopupPositionedEvent> event =
2805 PopupPositionedEvent::Constructor(mPopup, u"popuppositioned"_ns, init);
2806 event->SetTrusted(true);
2808 mPopup->DispatchEvent(*event);
2810 // Get the popup frame and make sure it is still in the positioning
2811 // state. If it isn't, someone may have tried to reshow or hide it
2812 // during the popuppositioned event.
2813 // Alternately, this event may have been fired in reponse to moving the
2814 // popup rather than opening it. In that case, we are done.
2815 popupFrame = do_QueryFrame(mPopup->GetPrimaryFrame());
2816 if (popupFrame && popupFrame->PopupState() == ePopupPositioning) {
2817 pm->ShowPopupCallback(mPopup, popupFrame, false, false);
2820 return NS_OK;
2823 NS_IMETHODIMP
2824 nsXULMenuCommandEvent::Run() {
2825 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2826 if (!pm) {
2827 return NS_OK;
2830 RefPtr menu = XULButtonElement::FromNode(mMenu);
2831 MOZ_ASSERT(menu);
2832 if (mFlipChecked) {
2833 if (menu->GetXULBoolAttr(nsGkAtoms::checked)) {
2834 menu->UnsetAttr(kNameSpaceID_None, nsGkAtoms::checked, true);
2835 } else {
2836 menu->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, u"true"_ns, true);
2840 // The order of the nsViewManager and PresShell COM pointers is
2841 // important below. We want the pres shell to get released before the
2842 // associated view manager on exit from this function.
2843 // See bug 54233.
2844 // XXXndeakin is this still needed?
2845 RefPtr<nsPresContext> presContext = menu->OwnerDoc()->GetPresContext();
2846 RefPtr<PresShell> presShell =
2847 presContext ? presContext->PresShell() : nullptr;
2848 RefPtr<nsViewManager> kungFuDeathGrip =
2849 presShell ? presShell->GetViewManager() : nullptr;
2850 Unused << kungFuDeathGrip; // Not referred to directly within this function
2852 // Deselect ourselves.
2853 if (mCloseMenuMode != CloseMenuMode_None) {
2854 if (RefPtr parent = menu->GetMenuParent()) {
2855 if (parent->GetActiveMenuChild() == menu) {
2856 parent->SetActiveMenuChild(nullptr);
2861 AutoHandlingUserInputStatePusher userInpStatePusher(mUserInput);
2862 nsContentUtils::DispatchXULCommand(
2863 menu, mIsTrusted, nullptr, presShell, mModifiers & MODIFIER_CONTROL,
2864 mModifiers & MODIFIER_ALT, mModifiers & MODIFIER_SHIFT,
2865 mModifiers & MODIFIER_META, 0, mButton);
2867 if (mCloseMenuMode != CloseMenuMode_None) {
2868 if (RefPtr popup = menu->GetContainingPopupElement()) {
2869 HidePopupOptions options{HidePopupOption::DeselectMenu};
2870 if (mCloseMenuMode == CloseMenuMode_Auto) {
2871 options += HidePopupOption::HideChain;
2873 pm->HidePopup(popup, options);
2877 return NS_OK;