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 "nsMenuPopupFrame.h"
8 #include "LayoutConstants.h"
9 #include "XULButtonElement.h"
10 #include "XULPopupElement.h"
11 #include "mozilla/dom/XULPopupElement.h"
12 #include "nsGkAtoms.h"
13 #include "nsIContent.h"
14 #include "nsIFrameInlines.h"
16 #include "nsPresContext.h"
17 #include "mozilla/ComputedStyle.h"
18 #include "nsCSSRendering.h"
19 #include "nsNameSpaceManager.h"
20 #include "nsIFrameInlines.h"
21 #include "nsViewManager.h"
22 #include "nsWidgetsCID.h"
23 #include "nsPIDOMWindow.h"
24 #include "nsFrameManager.h"
25 #include "mozilla/dom/Document.h"
27 #include "nsIScrollableFrame.h"
28 #include "nsIPopupContainer.h"
29 #include "nsIDocShell.h"
30 #include "nsReadableUtils.h"
31 #include "nsUnicharUtils.h"
32 #include "nsLayoutUtils.h"
33 #include "nsContentUtils.h"
34 #include "nsCSSFrameConstructor.h"
35 #include "nsPIWindowRoot.h"
36 #include "nsIReflowCallback.h"
37 #include "nsIDocShellTreeOwner.h"
38 #include "nsIBaseWindow.h"
40 #include "nsIScreenManager.h"
41 #include "nsServiceManagerUtils.h"
42 #include "nsStyleConsts.h"
43 #include "nsStyleStructInlines.h"
44 #include "nsTransitionManager.h"
45 #include "nsDisplayList.h"
46 #include "nsIDOMXULSelectCntrlEl.h"
47 #include "mozilla/widget/ScreenManager.h"
48 #include "mozilla/AnimationUtils.h"
49 #include "mozilla/BasePrincipal.h"
50 #include "mozilla/EventDispatcher.h"
51 #include "mozilla/EventStateManager.h"
52 #include "mozilla/Preferences.h"
53 #include "mozilla/LookAndFeel.h"
54 #include "mozilla/MouseEvents.h"
55 #include "mozilla/PresShell.h"
56 #include "mozilla/Services.h"
57 #include "mozilla/dom/BrowserParent.h"
58 #include "mozilla/dom/Element.h"
59 #include "mozilla/dom/Event.h"
60 #include "mozilla/dom/KeyboardEvent.h"
61 #include "mozilla/dom/KeyboardEventBinding.h"
64 #include "X11UndefineNone.h"
65 #include "nsXULPopupManager.h"
67 using namespace mozilla
;
68 using mozilla::dom::Document
;
69 using mozilla::dom::Element
;
70 using mozilla::dom::Event
;
71 using mozilla::dom::XULButtonElement
;
73 int8_t nsMenuPopupFrame::sDefaultLevelIsTop
= -1;
75 TimeStamp
nsMenuPopupFrame::sLastKeyTime
;
78 # include "mozilla/WidgetUtilsGtk.h"
79 # define IS_WAYLAND_DISPLAY() mozilla::widget::GdkIsWaylandDisplay()
80 extern mozilla::LazyLogModule gWidgetPopupLog
;
81 # define LOG_WAYLAND(...) \
82 MOZ_LOG(gWidgetPopupLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
84 # define IS_WAYLAND_DISPLAY() false
85 # define LOG_WAYLAND(...)
88 // NS_NewMenuPopupFrame
90 // Wrapper for creating a new menu popup container
92 nsIFrame
* NS_NewMenuPopupFrame(PresShell
* aPresShell
, ComputedStyle
* aStyle
) {
93 return new (aPresShell
)
94 nsMenuPopupFrame(aStyle
, aPresShell
->GetPresContext());
97 NS_IMPL_FRAMEARENA_HELPERS(nsMenuPopupFrame
)
99 NS_QUERYFRAME_HEAD(nsMenuPopupFrame
)
100 NS_QUERYFRAME_ENTRY(nsMenuPopupFrame
)
101 NS_QUERYFRAME_TAIL_INHERITING(nsBlockFrame
)
104 // nsMenuPopupFrame ctor
106 nsMenuPopupFrame::nsMenuPopupFrame(ComputedStyle
* aStyle
,
107 nsPresContext
* aPresContext
)
108 : nsBlockFrame(aStyle
, aPresContext
, kClassID
) {
109 // the preference name is backwards here. True means that the 'top' level is
110 // the default, and false means that the 'parent' level is the default.
111 if (sDefaultLevelIsTop
>= 0) return;
113 Preferences::GetBool("ui.panel.default_level_parent", false);
116 nsMenuPopupFrame::~nsMenuPopupFrame() = default;
118 static bool IsMouseTransparent(const ComputedStyle
& aStyle
) {
119 // If pointer-events: none; is set on the popup, then the widget should
120 // ignore mouse events, passing them through to the content behind.
121 return aStyle
.PointerEvents() == StylePointerEvents::None
;
124 static nsIWidget::InputRegion
ComputeInputRegion(const ComputedStyle
& aStyle
,
125 const nsPresContext
& aPc
) {
126 return {IsMouseTransparent(aStyle
),
127 (aStyle
.StyleUIReset()->mMozWindowInputRegionMargin
.ToCSSPixels() *
128 aPc
.CSSToDevPixelScale())
132 bool nsMenuPopupFrame::ShouldCreateWidgetUpfront() const {
133 if (mPopupType
!= PopupType::Menu
) {
134 // Any panel with a type attribute, such as the autocomplete popup, is
135 // always generated right away.
136 return mContent
->AsElement()->HasAttr(nsGkAtoms::type
);
139 // Generate the widget up-front if the parent menu is a <menulist> unless its
140 // sizetopopup is set to "none".
141 return ShouldExpandToInflowParentOrAnchor();
144 void nsMenuPopupFrame::Init(nsIContent
* aContent
, nsContainerFrame
* aParent
,
145 nsIFrame
* aPrevInFlow
) {
146 nsBlockFrame::Init(aContent
, aParent
, aPrevInFlow
);
150 // XXX Hack. The popup's view should float above all other views,
151 // so we use the nsView::SetFloating() to tell the view manager
152 // about that constraint.
153 nsView
* ourView
= GetView();
154 nsViewManager
* viewManager
= ourView
->GetViewManager();
155 viewManager
->SetViewFloating(ourView
, true);
157 const auto& el
= PopupElement();
158 mPopupType
= PopupType::Panel
;
160 mPopupType
= PopupType::Menu
;
161 } else if (el
.IsXULElement(nsGkAtoms::tooltip
)) {
162 mPopupType
= PopupType::Tooltip
;
165 if (PresContext()->IsChrome()) {
166 mInContentShell
= false;
169 // Support incontentshell=false attribute to allow popups to be displayed
170 // outside of the content shell. Chrome only.
171 if (el
.NodePrincipal()->IsSystemPrincipal()) {
172 if (el
.GetXULBoolAttr(nsGkAtoms::incontentshell
)) {
173 mInContentShell
= true;
174 } else if (el
.AttrValueIs(kNameSpaceID_None
, nsGkAtoms::incontentshell
,
175 nsGkAtoms::_false
, eCaseMatters
)) {
176 mInContentShell
= false;
180 // To improve performance, create the widget for the popup if needed. Popups
181 // such as menus will create their widgets later when the popup opens.
183 // FIXME(emilio): Doing this up-front for all menupopups causes a bunch of
184 // assertions, while it's supposed to be just an optimization.
185 if (!ourView
->HasWidget() && ShouldCreateWidgetUpfront()) {
186 CreateWidgetForView(ourView
);
189 AddStateBits(NS_FRAME_IN_POPUP
);
192 bool nsMenuPopupFrame::HasRemoteContent() const {
193 return !mInContentShell
&& mPopupType
== PopupType::Panel
&&
194 mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
195 nsGkAtoms::remote
, nsGkAtoms::_true
,
199 bool nsMenuPopupFrame::IsNoAutoHide() const {
200 // Panels with noautohide="true" don't hide when the mouse is clicked
201 // outside of them, or when another application is made active. Non-autohide
202 // panels cannot be used in content windows.
203 return !mInContentShell
&& mPopupType
== PopupType::Panel
&&
204 mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
205 nsGkAtoms::noautohide
,
206 nsGkAtoms::_true
, eIgnoreCase
);
209 widget::PopupLevel
nsMenuPopupFrame::GetPopupLevel(bool aIsNoAutoHide
) const {
210 // The popup level is determined as follows, in this order:
211 // 1. non-panels (menus and tooltips) are always topmost
212 // 2. any specified level attribute
213 // 3. if a titlebar attribute is set, use the 'floating' level
214 // 4. if this is a noautohide panel, use the 'parent' level
215 // 5. use the platform-specific default level
217 // If this is not a panel, this is always a top-most popup.
218 if (mPopupType
!= PopupType::Panel
) {
219 return PopupLevel::Top
;
222 // If the level attribute has been set, use that.
223 static Element::AttrValuesArray strings
[] = {nsGkAtoms::top
,
224 nsGkAtoms::parent
, nullptr};
225 switch (mContent
->AsElement()->FindAttrValueIn(
226 kNameSpaceID_None
, nsGkAtoms::level
, strings
, eCaseMatters
)) {
228 return PopupLevel::Top
;
230 return PopupLevel::Parent
;
235 // If this panel is a noautohide panel, the default is the parent level.
237 return PopupLevel::Parent
;
240 // Otherwise, the result depends on the platform.
241 return sDefaultLevelIsTop
? PopupLevel::Top
: PopupLevel::Parent
;
244 void nsMenuPopupFrame::PrepareWidget(bool aRecreate
) {
245 nsView
* ourView
= GetView();
247 if (auto* widget
= GetWidget()) {
248 // Widget's WebRender resources needs to be cleared before creating new
250 widget
->ClearCachedWebrenderResources();
252 ourView
->DestroyWidget();
254 if (!ourView
->HasWidget()) {
255 CreateWidgetForView(ourView
);
257 PropagateStyleToWidget();
261 nsresult
nsMenuPopupFrame::CreateWidgetForView(nsView
* aView
) {
262 // Create a widget for ourselves.
263 widget::InitData widgetData
;
264 widgetData
.mWindowType
= widget::WindowType::Popup
;
265 widgetData
.mBorderStyle
= widget::BorderStyle::Default
;
266 widgetData
.mClipSiblings
= true;
267 widgetData
.mPopupHint
= mPopupType
;
268 widgetData
.mNoAutoHide
= IsNoAutoHide();
270 if (!mInContentShell
) {
271 // A drag popup may be used for non-static translucent drag feedback
272 if (mPopupType
== PopupType::Panel
&&
273 mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
,
274 nsGkAtoms::drag
, eIgnoreCase
)) {
275 widgetData
.mIsDragPopup
= true;
279 bool remote
= HasRemoteContent();
281 const auto mode
= nsLayoutUtils::GetFrameTransparency(this, this);
282 widgetData
.mHasRemoteContent
= remote
;
283 widgetData
.mTransparencyMode
= mode
;
284 widgetData
.mPopupLevel
= GetPopupLevel(widgetData
.mNoAutoHide
);
286 // Panels which have a parent level need a parent widget. This allows them to
287 // always appear in front of the parent window but behind other windows that
288 // should be in front of it.
289 nsCOMPtr
<nsIWidget
> parentWidget
;
290 if (widgetData
.mPopupLevel
!= PopupLevel::Top
) {
291 nsCOMPtr
<nsIDocShellTreeItem
> dsti
= PresContext()->GetDocShell();
292 if (!dsti
) return NS_ERROR_FAILURE
;
294 nsCOMPtr
<nsIDocShellTreeOwner
> treeOwner
;
295 dsti
->GetTreeOwner(getter_AddRefs(treeOwner
));
296 if (!treeOwner
) return NS_ERROR_FAILURE
;
298 nsCOMPtr
<nsIBaseWindow
> baseWindow(do_QueryInterface(treeOwner
));
299 if (baseWindow
) baseWindow
->GetMainWidget(getter_AddRefs(parentWidget
));
302 nsresult rv
= aView
->CreateWidgetForPopup(&widgetData
, parentWidget
);
307 nsIWidget
* widget
= aView
->GetWidget();
308 widget
->SetTransparencyMode(mode
);
310 PropagateStyleToWidget();
315 void nsMenuPopupFrame::PropagateStyleToWidget(WidgetStyleFlags aFlags
) const {
316 if (aFlags
.isEmpty()) {
320 nsIWidget
* widget
= GetWidget();
325 if (aFlags
.contains(WidgetStyle::ColorScheme
)) {
326 widget
->SetColorScheme(Some(LookAndFeel::ColorSchemeForFrame(this)));
328 if (aFlags
.contains(WidgetStyle::InputRegion
)) {
329 widget
->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
331 if (aFlags
.contains(WidgetStyle::Opacity
)) {
332 widget
->SetWindowOpacity(StyleUIReset()->mWindowOpacity
);
334 if (aFlags
.contains(WidgetStyle::Shadow
)) {
335 widget
->SetWindowShadowStyle(GetShadowStyle());
337 if (aFlags
.contains(WidgetStyle::Transform
)) {
338 widget
->SetWindowTransform(ComputeWidgetTransform());
342 bool nsMenuPopupFrame::IsMouseTransparent() const {
343 return ::IsMouseTransparent(*Style());
346 WindowShadow
nsMenuPopupFrame::GetShadowStyle() const {
347 StyleWindowShadow shadow
= StyleUIReset()->mWindowShadow
;
348 if (shadow
!= StyleWindowShadow::Auto
) {
349 MOZ_ASSERT(shadow
== StyleWindowShadow::None
);
350 return WindowShadow::None
;
353 switch (StyleDisplay()->EffectiveAppearance()) {
354 case StyleAppearance::Tooltip
:
355 return WindowShadow::Tooltip
;
356 case StyleAppearance::Menupopup
:
357 return WindowShadow::Menu
;
359 return WindowShadow::Panel
;
363 void nsMenuPopupFrame::SetPopupState(nsPopupState aState
) {
364 mPopupState
= aState
;
366 // Work around https://gitlab.gnome.org/GNOME/gtk/-/issues/4166
367 if (aState
== ePopupShown
&& IS_WAYLAND_DISPLAY()) {
368 if (nsIWidget
* widget
= GetWidget()) {
369 widget
->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
374 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
375 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP
nsXULPopupShownEvent::Run() {
376 nsMenuPopupFrame
* popup
= do_QueryFrame(mPopup
->GetPrimaryFrame());
377 // Set the state to visible if the popup is still open.
378 if (popup
&& popup
->IsOpen()) {
379 popup
->SetPopupState(ePopupShown
);
382 if (!mPopup
->IsXULElement(nsGkAtoms::tooltip
)) {
383 nsCOMPtr
<nsIObserverService
> obsService
=
384 mozilla::services::GetObserverService();
386 obsService
->NotifyObservers(mPopup
, "popup-shown", nullptr);
389 WidgetMouseEvent
event(true, eXULPopupShown
, nullptr,
390 WidgetMouseEvent::eReal
);
391 return EventDispatcher::Dispatch(mPopup
, mPresContext
, &event
);
394 NS_IMETHODIMP
nsXULPopupShownEvent::HandleEvent(Event
* aEvent
) {
395 nsMenuPopupFrame
* popup
= do_QueryFrame(mPopup
->GetPrimaryFrame());
396 // Ignore events not targeted at the popup itself (ie targeted at
398 if (mPopup
!= aEvent
->GetTarget()) {
402 // ResetPopupShownDispatcher will delete the reference to this, so keep
403 // another one until Run is finished.
404 RefPtr
<nsXULPopupShownEvent
> event
= this;
405 // Only call Run if it the dispatcher was assigned. This avoids calling the
406 // Run method if the transitionend event fires multiple times.
407 if (popup
->ClearPopupShownDispatcher()) {
416 void nsXULPopupShownEvent::CancelListener() {
417 mPopup
->RemoveSystemEventListener(u
"transitionend"_ns
, this, false);
420 NS_IMPL_ISUPPORTS_INHERITED(nsXULPopupShownEvent
, Runnable
,
421 nsIDOMEventListener
);
423 void nsMenuPopupFrame::DidSetComputedStyle(ComputedStyle
* aOldStyle
) {
424 nsBlockFrame::DidSetComputedStyle(aOldStyle
);
430 WidgetStyleFlags flags
;
432 if (aOldStyle
->StyleUI()->mColorScheme
!= StyleUI()->mColorScheme
) {
433 flags
+= WidgetStyle::ColorScheme
;
436 auto& newUI
= *StyleUIReset();
437 auto& oldUI
= *aOldStyle
->StyleUIReset();
438 if (newUI
.mWindowOpacity
!= oldUI
.mWindowOpacity
) {
439 flags
+= WidgetStyle::Opacity
;
442 if (newUI
.mMozWindowTransform
!= oldUI
.mMozWindowTransform
) {
443 flags
+= WidgetStyle::Transform
;
446 if (newUI
.mWindowShadow
!= oldUI
.mWindowShadow
) {
447 flags
+= WidgetStyle::Shadow
;
450 const auto& pc
= *PresContext();
451 auto oldRegion
= ComputeInputRegion(*aOldStyle
, pc
);
452 auto newRegion
= ComputeInputRegion(*Style(), pc
);
453 if (oldRegion
.mFullyTransparent
!= newRegion
.mFullyTransparent
||
454 oldRegion
.mMargin
!= newRegion
.mMargin
) {
455 flags
+= WidgetStyle::InputRegion
;
458 PropagateStyleToWidget(flags
);
461 void nsMenuPopupFrame::TweakMinPrefISize(nscoord
& aSize
) {
462 if (!ShouldExpandToInflowParentOrAnchor()) {
465 // Make sure to accommodate for our scrollbar if needed. Do it only for
466 // menulists to match previous behavior.
468 // NOTE(emilio): This is somewhat hacky. The "right" fix (which would be
469 // using scrollbar-gutter: stable on the scroller) isn't great, because even
470 // though we want a stable gutter, we want to draw on top of the gutter when
471 // there's no scrollbar, otherwise it looks rather weird.
473 // Automatically accommodating for the scrollbar otherwise would be bug
474 // 764076, but that has its own set of problems.
475 if (nsIScrollableFrame
* sf
= GetScrollFrame()) {
476 aSize
+= sf
->GetDesiredScrollbarSizes().LeftRight();
479 nscoord menuListOrAnchorWidth
= 0;
480 if (nsIFrame
* menuList
= GetInFlowParent()) {
481 menuListOrAnchorWidth
= menuList
->GetRect().width
;
483 if (mAnchorType
== MenuPopupAnchorType_Rect
) {
484 menuListOrAnchorWidth
= std::max(menuListOrAnchorWidth
, mScreenRect
.width
);
486 // Input margin doesn't have contents, so account for it for popup sizing
488 menuListOrAnchorWidth
+=
489 2 * StyleUIReset()->mMozWindowInputRegionMargin
.ToAppUnits();
490 aSize
= std::max(aSize
, menuListOrAnchorWidth
);
493 nscoord
nsMenuPopupFrame::GetMinISize(gfxContext
* aRC
) {
494 nscoord result
= nsBlockFrame::GetMinISize(aRC
);
495 TweakMinPrefISize(result
);
499 nscoord
nsMenuPopupFrame::GetPrefISize(gfxContext
* aRC
) {
500 nscoord result
= nsBlockFrame::GetPrefISize(aRC
);
501 TweakMinPrefISize(result
);
505 void nsMenuPopupFrame::Reflow(nsPresContext
* aPresContext
,
506 ReflowOutput
& aDesiredSize
,
507 const ReflowInput
& aReflowInput
,
508 nsReflowStatus
& aStatus
) {
510 DO_GLOBAL_REFLOW_COUNT("nsMenuPopupFrame");
511 MOZ_ASSERT(aStatus
.IsEmpty(), "Caller should pass a fresh reflow status!");
513 const auto wm
= GetWritingMode();
514 // Default to preserving our bounds.
515 aDesiredSize
.SetSize(wm
, GetLogicalSize(wm
));
517 LayoutPopup(aPresContext
, aDesiredSize
, aReflowInput
, aStatus
);
519 aDesiredSize
.SetBlockStartAscent(aDesiredSize
.BSize(wm
));
520 aDesiredSize
.SetOverflowAreasToDesiredBounds();
521 FinishAndStoreOverflow(&aDesiredSize
, aReflowInput
.mStyleDisplay
);
524 void nsMenuPopupFrame::EnsureActiveMenuListItemIsVisible() {
525 if (!IsMenuList() || !IsOpen()) {
528 nsIFrame
* frame
= GetCurrentMenuItemFrame();
532 RefPtr
<mozilla::PresShell
> presShell
= PresShell();
533 presShell
->ScrollFrameIntoView(
534 frame
, Nothing(), ScrollAxis(), ScrollAxis(),
535 ScrollFlags::ScrollOverflowHidden
| ScrollFlags::ScrollFirstAncestorOnly
);
538 void nsMenuPopupFrame::LayoutPopup(nsPresContext
* aPresContext
,
539 ReflowOutput
& aDesiredSize
,
540 const ReflowInput
& aReflowInput
,
541 nsReflowStatus
& aStatus
) {
542 if (IsNativeMenu()) {
548 const bool isOpen
= IsOpen();
550 // If the popup is not open, only do layout while showing or if we're a
553 // This is needed because the SelectParent code wants to limit the height of
554 // the popup before opening it.
556 // TODO(emilio): We should consider adding a way to do that more reliably
557 // instead, but this preserves existing behavior.
558 const bool needsLayout
= mPopupState
== ePopupShowing
||
559 mPopupState
== ePopupPositioning
|| IsMenuList();
561 RemoveStateBits(NS_FRAME_FIRST_REFLOW
);
566 // Do a first reflow, with all our content, in order to find our preferred
567 // size. Then, we do a second reflow with the updated dimensions.
568 const bool needsPrefSize
= mPrefSize
== nsSize(-1, -1) || IsSubtreeDirty();
570 // Get the preferred, minimum and maximum size. If the menu is sized to the
571 // popup, then the popup's width is the menu's width.
572 ReflowOutput
preferredSize(aReflowInput
);
573 nsBlockFrame::Reflow(aPresContext
, preferredSize
, aReflowInput
, aStatus
);
574 mPrefSize
= preferredSize
.PhysicalSize();
577 // Get our desired position and final size, now that we have a preferred size.
578 auto constraints
= GetRects(mPrefSize
);
579 const auto finalSize
= constraints
.mUsedRect
.Size();
581 // We need to do an extra reflow if we haven't reflowed, our size doesn't
582 // match with our final intended size, or our bsize is unconstrained (in which
583 // case we need to specify the final size so that percentages work).
584 const bool needDefiniteReflow
=
585 aReflowInput
.ComputedBSize() == NS_UNCONSTRAINEDSIZE
|| !needsPrefSize
||
586 finalSize
!= mPrefSize
;
588 if (needDefiniteReflow
) {
589 ReflowInput
constrainedReflowInput(aReflowInput
);
590 const auto& bp
= aReflowInput
.ComputedPhysicalBorderPadding();
591 // TODO: writing-mode handling not terribly correct, but it doesn't matter.
592 const nsSize
finalContentSize(finalSize
.width
- bp
.LeftRight(),
593 finalSize
.height
- bp
.TopBottom());
594 constrainedReflowInput
.SetComputedISize(finalContentSize
.width
);
595 constrainedReflowInput
.SetComputedBSize(finalContentSize
.height
);
596 constrainedReflowInput
.SetIResize(finalSize
.width
!= mPrefSize
.width
);
597 constrainedReflowInput
.SetBResize([&] {
598 if (finalSize
.height
!= mPrefSize
.height
) {
602 aReflowInput
.ComputedBSize() == NS_UNCONSTRAINEDSIZE
&&
603 aReflowInput
.ComputedMaxBSize() == finalContentSize
.height
) {
604 // If we have measured, and maybe clamped our children via max-height,
605 // they might need to get percentages in the block axis re-resolved.
612 nsBlockFrame::Reflow(aPresContext
, aDesiredSize
, constrainedReflowInput
,
616 // Set our size, since nsAbsoluteContainingBlock won't.
617 SetRect(constraints
.mUsedRect
);
619 nsView
* view
= GetView();
621 nsViewManager
* viewManager
= view
->GetViewManager();
622 viewManager
->ResizeView(view
,
623 nsRect(nsPoint(), constraints
.mUsedRect
.Size()));
624 if (mPopupState
== ePopupOpening
) {
625 mPopupState
= ePopupVisible
;
628 viewManager
->SetViewVisibility(view
, ViewVisibility::Show
);
629 SyncFrameViewProperties(view
);
632 // Perform our move now. That will position the view and so on.
633 PerformMove(constraints
);
635 // finally, if the popup just opened, send a popupshown event
636 bool openChanged
= mIsOpenChanged
;
638 mIsOpenChanged
= false;
640 // Make sure the current selection in a menulist is visible.
641 EnsureActiveMenuListItemIsVisible();
643 // If the animate attribute is set to open, check for a transition and wait
644 // for it to finish before firing the popupshown event.
645 if (LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations
) &&
646 mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
647 nsGkAtoms::animate
, nsGkAtoms::open
,
649 AnimationUtils::HasCurrentTransitions(mContent
->AsElement(),
650 PseudoStyleType::NotPseudo
)) {
651 mPopupShownDispatcher
= new nsXULPopupShownEvent(mContent
, aPresContext
);
652 mContent
->AddSystemEventListener(u
"transitionend"_ns
,
653 mPopupShownDispatcher
, false, false);
657 // If there are no transitions, fire the popupshown event right away.
658 nsCOMPtr
<nsIRunnable
> event
=
659 new nsXULPopupShownEvent(GetContent(), aPresContext
);
660 mContent
->OwnerDoc()->Dispatch(event
.forget());
664 bool nsMenuPopupFrame::IsMenuList() const {
665 return PopupElement().IsInMenuList();
668 bool nsMenuPopupFrame::ShouldExpandToInflowParentOrAnchor() const {
669 return IsMenuList() && !mContent
->GetParent()->AsElement()->AttrValueIs(
670 kNameSpaceID_None
, nsGkAtoms::sizetopopup
,
671 nsGkAtoms::none
, eCaseMatters
);
674 nsIContent
* nsMenuPopupFrame::GetTriggerContent(
675 nsMenuPopupFrame
* aMenuPopupFrame
) {
676 while (aMenuPopupFrame
) {
677 if (aMenuPopupFrame
->mTriggerContent
) {
678 return aMenuPopupFrame
->mTriggerContent
;
681 auto* button
= XULButtonElement::FromNodeOrNull(
682 aMenuPopupFrame
->GetContent()->GetParent());
683 if (!button
|| !button
->IsMenu()) {
687 auto* popup
= button
->GetContainingPopupElement();
692 // check up the menu hierarchy until a popup with a trigger node is found
693 aMenuPopupFrame
= do_QueryFrame(popup
->GetPrimaryFrame());
699 void nsMenuPopupFrame::InitPositionFromAnchorAlign(const nsAString
& aAnchor
,
700 const nsAString
& aAlign
) {
701 mTriggerContent
= nullptr;
703 if (aAnchor
.EqualsLiteral("topleft"))
704 mPopupAnchor
= POPUPALIGNMENT_TOPLEFT
;
705 else if (aAnchor
.EqualsLiteral("topright"))
706 mPopupAnchor
= POPUPALIGNMENT_TOPRIGHT
;
707 else if (aAnchor
.EqualsLiteral("bottomleft"))
708 mPopupAnchor
= POPUPALIGNMENT_BOTTOMLEFT
;
709 else if (aAnchor
.EqualsLiteral("bottomright"))
710 mPopupAnchor
= POPUPALIGNMENT_BOTTOMRIGHT
;
711 else if (aAnchor
.EqualsLiteral("leftcenter"))
712 mPopupAnchor
= POPUPALIGNMENT_LEFTCENTER
;
713 else if (aAnchor
.EqualsLiteral("rightcenter"))
714 mPopupAnchor
= POPUPALIGNMENT_RIGHTCENTER
;
715 else if (aAnchor
.EqualsLiteral("topcenter"))
716 mPopupAnchor
= POPUPALIGNMENT_TOPCENTER
;
717 else if (aAnchor
.EqualsLiteral("bottomcenter"))
718 mPopupAnchor
= POPUPALIGNMENT_BOTTOMCENTER
;
720 mPopupAnchor
= POPUPALIGNMENT_NONE
;
722 if (aAlign
.EqualsLiteral("topleft"))
723 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
724 else if (aAlign
.EqualsLiteral("topright"))
725 mPopupAlignment
= POPUPALIGNMENT_TOPRIGHT
;
726 else if (aAlign
.EqualsLiteral("bottomleft"))
727 mPopupAlignment
= POPUPALIGNMENT_BOTTOMLEFT
;
728 else if (aAlign
.EqualsLiteral("bottomright"))
729 mPopupAlignment
= POPUPALIGNMENT_BOTTOMRIGHT
;
730 else if (aAlign
.EqualsLiteral("leftcenter"))
731 mPopupAlignment
= POPUPALIGNMENT_LEFTCENTER
;
732 else if (aAlign
.EqualsLiteral("rightcenter"))
733 mPopupAlignment
= POPUPALIGNMENT_RIGHTCENTER
;
734 else if (aAlign
.EqualsLiteral("topcenter"))
735 mPopupAlignment
= POPUPALIGNMENT_TOPCENTER
;
736 else if (aAlign
.EqualsLiteral("bottomcenter"))
737 mPopupAlignment
= POPUPALIGNMENT_BOTTOMCENTER
;
739 mPopupAlignment
= POPUPALIGNMENT_NONE
;
741 mPosition
= POPUPPOSITION_UNKNOWN
;
744 static FlipType
FlipFromAttribute(nsMenuPopupFrame
* aFrame
) {
746 aFrame
->PopupElement().GetAttr(nsGkAtoms::flip
, flip
);
747 if (flip
.EqualsLiteral("none")) {
748 return FlipType_None
;
750 if (flip
.EqualsLiteral("both")) {
751 return FlipType_Both
;
753 if (flip
.EqualsLiteral("slide")) {
754 return FlipType_Slide
;
756 return FlipType_Default
;
759 void nsMenuPopupFrame::InitializePopup(nsIContent
* aAnchorContent
,
760 nsIContent
* aTriggerContent
,
761 const nsAString
& aPosition
,
762 int32_t aXPos
, int32_t aYPos
,
763 MenuPopupAnchorType aAnchorType
,
764 bool aAttributesOverride
) {
765 auto* widget
= GetWidget();
766 bool recreateWidget
= widget
&& widget
->NeedsRecreateToReshow();
767 PrepareWidget(recreateWidget
);
769 mPopupState
= ePopupShowing
;
770 mAnchorContent
= aAnchorContent
;
771 mTriggerContent
= aTriggerContent
;
774 mIsNativeMenu
= false;
775 mIsTopLevelContextMenu
= false;
778 mConstrainedByLayout
= false;
779 mAlignmentOffset
= 0;
780 mPositionedOffset
= 0;
781 mPositionedByMoveToRect
= false;
783 mAnchorType
= aAnchorType
;
785 // if aAttributesOverride is true, then the popupanchor, popupalign and
786 // position attributes on the <menupopup> override those values passed in.
787 // If false, those attributes are only used if the values passed in are empty
788 if (aAnchorContent
|| aAnchorType
== MenuPopupAnchorType_Rect
) {
789 nsAutoString anchor
, align
, position
;
790 mContent
->AsElement()->GetAttr(nsGkAtoms::popupanchor
, anchor
);
791 mContent
->AsElement()->GetAttr(nsGkAtoms::popupalign
, align
);
792 mContent
->AsElement()->GetAttr(nsGkAtoms::position
, position
);
794 if (aAttributesOverride
) {
795 // if the attributes are set, clear the offset position. Otherwise,
796 // the offset is used to adjust the position from the anchor point
797 if (anchor
.IsEmpty() && align
.IsEmpty() && position
.IsEmpty())
798 position
.Assign(aPosition
);
801 } else if (!aPosition
.IsEmpty()) {
802 position
.Assign(aPosition
);
805 mFlip
= FlipFromAttribute(this);
807 position
.CompressWhitespace();
808 int32_t spaceIdx
= position
.FindChar(' ');
809 // if there is a space in the position, assume it is the anchor and
810 // alignment as two separate tokens.
812 InitPositionFromAnchorAlign(Substring(position
, 0, spaceIdx
),
813 Substring(position
, spaceIdx
+ 1));
814 } else if (position
.EqualsLiteral("before_start")) {
815 mPopupAnchor
= POPUPALIGNMENT_TOPLEFT
;
816 mPopupAlignment
= POPUPALIGNMENT_BOTTOMLEFT
;
817 mPosition
= POPUPPOSITION_BEFORESTART
;
818 } else if (position
.EqualsLiteral("before_end")) {
819 mPopupAnchor
= POPUPALIGNMENT_TOPRIGHT
;
820 mPopupAlignment
= POPUPALIGNMENT_BOTTOMRIGHT
;
821 mPosition
= POPUPPOSITION_BEFOREEND
;
822 } else if (position
.EqualsLiteral("after_start")) {
823 mPopupAnchor
= POPUPALIGNMENT_BOTTOMLEFT
;
824 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
825 mPosition
= POPUPPOSITION_AFTERSTART
;
826 } else if (position
.EqualsLiteral("after_end")) {
827 mPopupAnchor
= POPUPALIGNMENT_BOTTOMRIGHT
;
828 mPopupAlignment
= POPUPALIGNMENT_TOPRIGHT
;
829 mPosition
= POPUPPOSITION_AFTEREND
;
830 } else if (position
.EqualsLiteral("start_before")) {
831 mPopupAnchor
= POPUPALIGNMENT_TOPLEFT
;
832 mPopupAlignment
= POPUPALIGNMENT_TOPRIGHT
;
833 mPosition
= POPUPPOSITION_STARTBEFORE
;
834 } else if (position
.EqualsLiteral("start_after")) {
835 mPopupAnchor
= POPUPALIGNMENT_BOTTOMLEFT
;
836 mPopupAlignment
= POPUPALIGNMENT_BOTTOMRIGHT
;
837 mPosition
= POPUPPOSITION_STARTAFTER
;
838 } else if (position
.EqualsLiteral("end_before")) {
839 mPopupAnchor
= POPUPALIGNMENT_TOPRIGHT
;
840 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
841 mPosition
= POPUPPOSITION_ENDBEFORE
;
842 } else if (position
.EqualsLiteral("end_after")) {
843 mPopupAnchor
= POPUPALIGNMENT_BOTTOMRIGHT
;
844 mPopupAlignment
= POPUPALIGNMENT_BOTTOMLEFT
;
845 mPosition
= POPUPPOSITION_ENDAFTER
;
846 } else if (position
.EqualsLiteral("overlap")) {
847 mPopupAnchor
= POPUPALIGNMENT_TOPLEFT
;
848 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
849 mPosition
= POPUPPOSITION_OVERLAP
;
850 } else if (position
.EqualsLiteral("after_pointer")) {
851 mPopupAnchor
= POPUPALIGNMENT_TOPLEFT
;
852 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
853 mPosition
= POPUPPOSITION_AFTERPOINTER
;
854 // XXXndeakin this is supposed to anchor vertically after, but with the
855 // horizontal position as the mouse pointer.
857 } else if (position
.EqualsLiteral("selection")) {
858 mPopupAnchor
= POPUPALIGNMENT_BOTTOMLEFT
;
859 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
860 mPosition
= POPUPPOSITION_SELECTION
;
862 InitPositionFromAnchorAlign(anchor
, align
);
865 // When converted back to CSSIntRect it is (-1, -1, 0, 0) - as expected in
866 // nsXULPopupManager::Rollup
867 mScreenRect
= nsRect(-AppUnitsPerCSSPixel(), -AppUnitsPerCSSPixel(), 0, 0);
869 if (aAttributesOverride
) {
870 // Use |left| and |top| dimension attributes to position the popup if
871 // present, as they may have been persisted.
872 nsAutoString left
, top
;
873 mContent
->AsElement()->GetAttr(nsGkAtoms::left
, left
);
874 mContent
->AsElement()->GetAttr(nsGkAtoms::top
, top
);
877 if (!left
.IsEmpty()) {
878 int32_t x
= left
.ToInteger(&err
);
879 if (NS_SUCCEEDED(err
)) {
880 mScreenRect
.x
= CSSPixel::ToAppUnits(x
);
883 if (!top
.IsEmpty()) {
884 int32_t y
= top
.ToInteger(&err
);
885 if (NS_SUCCEEDED(err
)) {
886 mScreenRect
.y
= CSSPixel::ToAppUnits(y
);
892 void nsMenuPopupFrame::InitializePopupAtScreen(nsIContent
* aTriggerContent
,
893 int32_t aXPos
, int32_t aYPos
,
894 bool aIsContextMenu
) {
895 auto* widget
= GetWidget();
896 bool recreateWidget
= widget
&& widget
->NeedsRecreateToReshow();
897 PrepareWidget(recreateWidget
);
899 mPopupState
= ePopupShowing
;
900 mAnchorContent
= nullptr;
901 mTriggerContent
= aTriggerContent
;
903 nsRect(CSSPixel::ToAppUnits(aXPos
), CSSPixel::ToAppUnits(aYPos
), 0, 0);
906 mFlip
= FlipFromAttribute(this);
907 mPopupAnchor
= POPUPALIGNMENT_NONE
;
908 mPopupAlignment
= POPUPALIGNMENT_NONE
;
909 mPosition
= POPUPPOSITION_UNKNOWN
;
910 mIsContextMenu
= aIsContextMenu
;
911 mIsTopLevelContextMenu
= aIsContextMenu
;
912 mIsNativeMenu
= false;
913 mAnchorType
= MenuPopupAnchorType_Point
;
914 mPositionedOffset
= 0;
915 mPositionedByMoveToRect
= false;
918 void nsMenuPopupFrame::InitializePopupAsNativeContextMenu(
919 nsIContent
* aTriggerContent
, int32_t aXPos
, int32_t aYPos
) {
920 mTriggerContent
= aTriggerContent
;
921 mPopupState
= ePopupShowing
;
922 mAnchorContent
= nullptr;
924 nsRect(CSSPixel::ToAppUnits(aXPos
), CSSPixel::ToAppUnits(aYPos
), 0, 0);
927 mFlip
= FlipType_Default
;
928 mPopupAnchor
= POPUPALIGNMENT_NONE
;
929 mPopupAlignment
= POPUPALIGNMENT_NONE
;
930 mPosition
= POPUPPOSITION_UNKNOWN
;
931 mIsContextMenu
= true;
932 mIsTopLevelContextMenu
= true;
933 mIsNativeMenu
= true;
934 mAnchorType
= MenuPopupAnchorType_Point
;
935 mPositionedOffset
= 0;
936 mPositionedByMoveToRect
= false;
939 void nsMenuPopupFrame::InitializePopupAtRect(nsIContent
* aTriggerContent
,
940 const nsAString
& aPosition
,
941 const nsIntRect
& aRect
,
942 bool aAttributesOverride
) {
943 InitializePopup(nullptr, aTriggerContent
, aPosition
, 0, 0,
944 MenuPopupAnchorType_Rect
, aAttributesOverride
);
945 mScreenRect
= ToAppUnits(aRect
, AppUnitsPerCSSPixel());
948 void nsMenuPopupFrame::ShowPopup(bool aIsContextMenu
) {
949 mIsContextMenu
= aIsContextMenu
;
951 InvalidateFrameSubtree();
953 if (mPopupState
== ePopupShowing
|| mPopupState
== ePopupPositioning
) {
954 mPopupState
= ePopupOpening
;
955 mIsOpenChanged
= true;
957 // Clear mouse capture when a popup is opened.
958 if (mPopupType
== PopupType::Menu
) {
959 if (auto* activeESM
= EventStateManager::GetActiveEventStateManager()) {
960 EventStateManager::ClearGlobalActiveContent(activeESM
);
963 PresShell::ReleaseCapturingContent();
966 if (RefPtr menu
= PopupElement().GetContainingMenu()) {
970 // We skip laying out children if we're closed, so make sure that we do a
971 // full dirty reflow when opening to pick up any potential change.
972 PresShell()->FrameNeedsReflow(
973 this, IntrinsicDirty::FrameAncestorsAndDescendants
, NS_FRAME_IS_DIRTY
);
975 if (mPopupType
== PopupType::Menu
) {
976 nsCOMPtr
<nsISound
> sound(do_GetService("@mozilla.org/sound;1"));
977 if (sound
) sound
->PlayEventSound(nsISound::EVENT_MENU_POPUP
);
982 void nsMenuPopupFrame::ClearTriggerContentIncludingDocument() {
983 // clear the trigger content if the popup is being closed. But don't clear
984 // it if the popup is just being made invisible as a popuphiding or command
985 if (mTriggerContent
) {
986 // if the popup had a trigger node set, clear the global window popup node
988 Document
* doc
= mContent
->GetUncomposedDoc();
990 if (nsPIDOMWindowOuter
* win
= doc
->GetWindow()) {
991 nsCOMPtr
<nsPIWindowRoot
> root
= win
->GetTopWindowRoot();
993 root
->SetPopupNode(nullptr);
998 mTriggerContent
= nullptr;
1001 void nsMenuPopupFrame::HidePopup(bool aDeselectMenu
, nsPopupState aNewState
,
1002 bool aFromFrameDestruction
) {
1003 NS_ASSERTION(aNewState
== ePopupClosed
|| aNewState
== ePopupInvisible
,
1004 "popup being set to unexpected state");
1006 ClearPopupShownDispatcher();
1008 // don't hide the popup when it isn't open
1009 if (mPopupState
== ePopupClosed
|| mPopupState
== ePopupShowing
||
1010 mPopupState
== ePopupPositioning
) {
1014 if (aNewState
== ePopupClosed
) {
1015 // clear the trigger content if the popup is being closed. But don't clear
1016 // it if the popup is just being made invisible as a popuphiding or command
1017 // event may want to retrieve it.
1018 ClearTriggerContentIncludingDocument();
1019 mAnchorContent
= nullptr;
1022 // when invisible and about to be closed, HidePopup has already been called,
1023 // so just set the new state to closed and return
1024 if (mPopupState
== ePopupInvisible
) {
1025 if (aNewState
== ePopupClosed
) {
1026 mPopupState
= ePopupClosed
;
1031 mPopupState
= aNewState
;
1033 mIncrementalString
.Truncate();
1035 mIsOpenChanged
= false;
1036 mHFlip
= mVFlip
= false;
1037 mConstrainedByLayout
= false;
1039 if (auto* widget
= GetWidget()) {
1040 // Ideally we should call ClearCachedWebrenderResources but there are
1041 // intermittent failures (see bug 1748788), so we currently call
1042 // ClearWebrenderAnimationResources instead.
1043 widget
->ClearWebrenderAnimationResources();
1046 nsView
* view
= GetView();
1047 nsViewManager
* viewManager
= view
->GetViewManager();
1048 viewManager
->SetViewVisibility(view
, ViewVisibility::Hide
);
1050 RefPtr popup
= &PopupElement();
1051 // XXX, bug 137033, In Windows, if mouse is outside the window when the
1052 // menupopup closes, no mouse_enter/mouse_exit event will be fired to clear
1053 // current hover state, we should clear it manually. This code may not the
1054 // best solution, but we can leave it here until we find the better approach.
1055 if (!aFromFrameDestruction
&&
1056 popup
->State().HasState(dom::ElementState::HOVER
)) {
1057 EventStateManager
* esm
= PresContext()->EventStateManager();
1058 esm
->SetContentState(nullptr, dom::ElementState::HOVER
);
1060 popup
->PopupClosed(aDeselectMenu
);
1063 nsPoint
nsMenuPopupFrame::AdjustPositionForAnchorAlign(
1064 nsRect
& anchorRect
, const nsSize
& aPrefSize
, FlipStyle
& aHFlip
,
1065 FlipStyle
& aVFlip
) const {
1066 // flip the anchor and alignment for right-to-left
1067 int8_t popupAnchor(mPopupAnchor
);
1068 int8_t popupAlign(mPopupAlignment
);
1069 if (IsDirectionRTL()) {
1070 // no need to flip the centered anchor types vertically
1071 if (popupAnchor
<= POPUPALIGNMENT_LEFTCENTER
) {
1072 popupAnchor
= -popupAnchor
;
1074 popupAlign
= -popupAlign
;
1077 nsRect
originalAnchorRect(anchorRect
);
1079 // first, determine at which corner of the anchor the popup should appear
1081 switch (popupAnchor
) {
1082 case POPUPALIGNMENT_LEFTCENTER
:
1083 pnt
= nsPoint(anchorRect
.x
, anchorRect
.y
+ anchorRect
.height
/ 2);
1084 anchorRect
.y
= pnt
.y
;
1085 anchorRect
.height
= 0;
1087 case POPUPALIGNMENT_RIGHTCENTER
:
1088 pnt
= nsPoint(anchorRect
.XMost(), anchorRect
.y
+ anchorRect
.height
/ 2);
1089 anchorRect
.y
= pnt
.y
;
1090 anchorRect
.height
= 0;
1092 case POPUPALIGNMENT_TOPCENTER
:
1093 pnt
= nsPoint(anchorRect
.x
+ anchorRect
.width
/ 2, anchorRect
.y
);
1094 anchorRect
.x
= pnt
.x
;
1095 anchorRect
.width
= 0;
1097 case POPUPALIGNMENT_BOTTOMCENTER
:
1098 pnt
= nsPoint(anchorRect
.x
+ anchorRect
.width
/ 2, anchorRect
.YMost());
1099 anchorRect
.x
= pnt
.x
;
1100 anchorRect
.width
= 0;
1102 case POPUPALIGNMENT_TOPRIGHT
:
1103 pnt
= anchorRect
.TopRight();
1105 case POPUPALIGNMENT_BOTTOMLEFT
:
1106 pnt
= anchorRect
.BottomLeft();
1108 case POPUPALIGNMENT_BOTTOMRIGHT
:
1109 pnt
= anchorRect
.BottomRight();
1111 case POPUPALIGNMENT_TOPLEFT
:
1113 pnt
= anchorRect
.TopLeft();
1117 // If the alignment is on the right edge of the popup, move the popup left
1118 // by the width. Similarly, if the alignment is on the bottom edge of the
1119 // popup, move the popup up by the height. In addition, account for the
1120 // margins of the popup on the edge on which it is aligned.
1121 nsMargin margin
= GetMargin();
1122 switch (popupAlign
) {
1123 case POPUPALIGNMENT_LEFTCENTER
:
1124 pnt
.MoveBy(margin
.left
, -aPrefSize
.height
/ 2);
1126 case POPUPALIGNMENT_RIGHTCENTER
:
1127 pnt
.MoveBy(-aPrefSize
.width
- margin
.right
, -aPrefSize
.height
/ 2);
1129 case POPUPALIGNMENT_TOPCENTER
:
1130 pnt
.MoveBy(-aPrefSize
.width
/ 2, margin
.top
);
1132 case POPUPALIGNMENT_BOTTOMCENTER
:
1133 pnt
.MoveBy(-aPrefSize
.width
/ 2, -aPrefSize
.height
- margin
.bottom
);
1135 case POPUPALIGNMENT_TOPRIGHT
:
1136 pnt
.MoveBy(-aPrefSize
.width
- margin
.right
, margin
.top
);
1138 case POPUPALIGNMENT_BOTTOMLEFT
:
1139 pnt
.MoveBy(margin
.left
, -aPrefSize
.height
- margin
.bottom
);
1141 case POPUPALIGNMENT_BOTTOMRIGHT
:
1142 pnt
.MoveBy(-aPrefSize
.width
- margin
.right
,
1143 -aPrefSize
.height
- margin
.bottom
);
1145 case POPUPALIGNMENT_TOPLEFT
:
1147 pnt
.MoveBy(margin
.left
, margin
.top
);
1151 // If we aligning to the selected item in the popup, adjust the vertical
1152 // position by the height of the menulist label and the selected item's
1154 if (mPosition
== POPUPPOSITION_SELECTION
) {
1155 MOZ_ASSERT(popupAnchor
== POPUPALIGNMENT_BOTTOMLEFT
||
1156 popupAnchor
== POPUPALIGNMENT_BOTTOMRIGHT
);
1157 MOZ_ASSERT(popupAlign
== POPUPALIGNMENT_TOPLEFT
||
1158 popupAlign
== POPUPALIGNMENT_TOPRIGHT
);
1160 // Only adjust the popup if it just opened, otherwise the popup will move
1161 // around if its gets resized or the selection changed. Cache the value in
1162 // mPositionedOffset and use that instead for any future calculations.
1163 if (mIsOpenChanged
) {
1164 if (nsIFrame
* selectedItemFrame
= GetSelectedItemForAlignment()) {
1165 const nscoord itemHeight
= selectedItemFrame
->GetRect().height
;
1166 const nscoord itemOffset
=
1167 selectedItemFrame
->GetOffsetToIgnoringScrolling(this).y
;
1168 // We want to line-up the anchor rect with the selected item, but if the
1169 // selected item is outside of our bounds, we don't want to shift the
1170 // popup up in a way that our box would no longer intersect with the
1172 nscoord maxOffset
= aPrefSize
.height
- itemHeight
;
1173 if (const nsIScrollableFrame
* sf
= GetScrollFrame()) {
1174 // HACK: We ideally would want to use the offset from the bottom
1175 // bottom of our scroll-frame to the bottom of our frame (so as to
1176 // ensure that the bottom of the scrollport is inside the anchor
1179 // But at this point of the code, the scroll frame may not be laid out
1180 // with a definite size (might be overflowing us).
1182 // So, we assume the offset from the bottom is symmetric to the offset
1183 // from the top. This holds for all the popups where this matters
1184 // (menulists on macOS, effectively), and seems better than somehow
1185 // moving the popup after the fact as we used to do.
1186 const nsIFrame
* f
= do_QueryFrame(sf
);
1187 maxOffset
-= f
->GetOffsetTo(this).y
;
1190 originalAnchorRect
.height
+ std::min(itemOffset
, maxOffset
);
1194 pnt
.y
-= mPositionedOffset
;
1197 // Flipping horizontally is allowed as long as the popup is above or below
1198 // the anchor. This will happen if both the anchor and alignment are top or
1199 // both are bottom, but different values. Similarly, flipping vertically is
1200 // allowed if the popup is to the left or right of the anchor. In this case,
1201 // the values of the constants are such that both must be positive or both
1202 // must be negative. A special case, used for overlap, allows flipping
1203 // vertically as well.
1204 // If we are flipping in both directions, we want to set a flip style both
1205 // horizontally and vertically. However, we want to flip on the inside edge
1206 // of the anchor. Consider the example of a typical dropdown menu.
1207 // Vertically, we flip the popup on the outside edges of the anchor menu,
1208 // however horizontally, we want to to use the inside edges so the popup
1209 // still appears underneath the anchor menu instead of floating off the
1210 // side of the menu.
1211 switch (popupAnchor
) {
1212 case POPUPALIGNMENT_LEFTCENTER
:
1213 case POPUPALIGNMENT_RIGHTCENTER
:
1214 aHFlip
= FlipStyle_Outside
;
1215 aVFlip
= FlipStyle_Inside
;
1217 case POPUPALIGNMENT_TOPCENTER
:
1218 case POPUPALIGNMENT_BOTTOMCENTER
:
1219 aHFlip
= FlipStyle_Inside
;
1220 aVFlip
= FlipStyle_Outside
;
1223 FlipStyle anchorEdge
=
1224 mFlip
== FlipType_Both
? FlipStyle_Inside
: FlipStyle_None
;
1225 aHFlip
= (popupAnchor
== -popupAlign
) ? FlipStyle_Outside
: anchorEdge
;
1226 if (((popupAnchor
> 0) == (popupAlign
> 0)) ||
1227 (popupAnchor
== POPUPALIGNMENT_TOPLEFT
&&
1228 popupAlign
== POPUPALIGNMENT_TOPLEFT
))
1229 aVFlip
= FlipStyle_Outside
;
1231 aVFlip
= anchorEdge
;
1239 nsIFrame
* nsMenuPopupFrame::GetSelectedItemForAlignment() const {
1240 // This method adjusts a menulist's popup such that the selected item is under
1241 // the cursor, aligned with the menulist label.
1242 nsCOMPtr
<nsIDOMXULSelectControlElement
> select
;
1243 if (mAnchorContent
) {
1244 select
= mAnchorContent
->AsElement()->AsXULSelectControl();
1248 // If there isn't an anchor, then try just getting the parent of the popup.
1249 select
= mContent
->GetParent()->AsElement()->AsXULSelectControl();
1255 nsCOMPtr
<Element
> selectedElement
;
1256 select
->GetSelectedItem(getter_AddRefs(selectedElement
));
1257 return selectedElement
? selectedElement
->GetPrimaryFrame() : nullptr;
1260 nscoord
nsMenuPopupFrame::SlideOrResize(nscoord
& aScreenPoint
, nscoord aSize
,
1261 nscoord aScreenBegin
,
1263 nscoord
* aOffset
) const {
1264 // The popup may be positioned such that either the left/top or bottom/right
1265 // is outside the screen - but never both.
1267 std::max(aScreenBegin
, std::min(aScreenEnd
- aSize
, aScreenPoint
));
1268 *aOffset
= newPos
- aScreenPoint
;
1269 aScreenPoint
= newPos
;
1270 return std::min(aSize
, aScreenEnd
- aScreenPoint
);
1273 nscoord
nsMenuPopupFrame::FlipOrResize(nscoord
& aScreenPoint
, nscoord aSize
,
1274 nscoord aScreenBegin
, nscoord aScreenEnd
,
1275 nscoord aAnchorBegin
, nscoord aAnchorEnd
,
1276 nscoord aMarginBegin
, nscoord aMarginEnd
,
1277 FlipStyle aFlip
, bool aEndAligned
,
1278 bool* aFlipSide
) const {
1279 // The flip side argument will be set to true if there wasn't room and we
1280 // flipped to the opposite side.
1283 // all of the coordinates used here are in app units relative to the screen
1284 nscoord popupSize
= aSize
;
1285 if (aScreenPoint
< aScreenBegin
) {
1286 // at its current position, the popup would extend past the left or top
1287 // edge of the screen, so it will have to be moved or resized.
1289 // for inside flips, we flip on the opposite side of the anchor
1290 nscoord startpos
= aFlip
== FlipStyle_Outside
? aAnchorBegin
: aAnchorEnd
;
1291 nscoord endpos
= aFlip
== FlipStyle_Outside
? aAnchorEnd
: aAnchorBegin
;
1293 // check whether there is more room to the left and right (or top and
1294 // bottom) of the anchor and put the popup on the side with more room.
1295 if (startpos
- aScreenBegin
>= aScreenEnd
- endpos
) {
1296 aScreenPoint
= aScreenBegin
;
1297 popupSize
= startpos
- aScreenPoint
- aMarginEnd
;
1298 *aFlipSide
= !aEndAligned
;
1300 // If the newly calculated position is different than the existing
1301 // position, flip such that the popup is to the right or bottom of the
1302 // anchor point instead . However, when flipping use the same margin
1304 nscoord newScreenPoint
= endpos
+ aMarginEnd
;
1305 if (newScreenPoint
!= aScreenPoint
) {
1306 *aFlipSide
= aEndAligned
;
1307 aScreenPoint
= newScreenPoint
;
1308 // check if the new position is still off the right or bottom edge of
1309 // the screen. If so, resize the popup.
1310 if (aScreenPoint
+ aSize
> aScreenEnd
) {
1311 popupSize
= aScreenEnd
- aScreenPoint
;
1316 aScreenPoint
= aScreenBegin
;
1318 } else if (aScreenPoint
+ aSize
> aScreenEnd
) {
1319 // at its current position, the popup would extend past the right or
1320 // bottom edge of the screen, so it will have to be moved or resized.
1322 // for inside flips, we flip on the opposite side of the anchor
1323 nscoord startpos
= aFlip
== FlipStyle_Outside
? aAnchorBegin
: aAnchorEnd
;
1324 nscoord endpos
= aFlip
== FlipStyle_Outside
? aAnchorEnd
: aAnchorBegin
;
1326 // check whether there is more room to the left and right (or top and
1327 // bottom) of the anchor and put the popup on the side with more room.
1328 if (aScreenEnd
- endpos
>= startpos
- aScreenBegin
) {
1329 *aFlipSide
= aEndAligned
;
1330 if (mIsContextMenu
) {
1331 aScreenPoint
= aScreenEnd
- aSize
;
1333 aScreenPoint
= endpos
+ aMarginBegin
;
1334 popupSize
= aScreenEnd
- aScreenPoint
;
1337 // if the newly calculated position is different than the existing
1338 // position, we flip such that the popup is to the left or top of the
1339 // anchor point instead.
1340 nscoord newScreenPoint
= startpos
- aSize
- aMarginBegin
;
1341 if (newScreenPoint
!= aScreenPoint
) {
1342 *aFlipSide
= !aEndAligned
;
1343 aScreenPoint
= newScreenPoint
;
1345 // check if the new position is still off the left or top edge of the
1346 // screen. If so, resize the popup.
1347 if (aScreenPoint
< aScreenBegin
) {
1348 aScreenPoint
= aScreenBegin
;
1349 if (!mIsContextMenu
) {
1350 popupSize
= startpos
- aScreenPoint
- aMarginBegin
;
1356 aScreenPoint
= aScreenEnd
- aSize
;
1360 // Make sure that the point is within the screen boundaries and that the
1361 // size isn't off the edge of the screen. This can happen when a large
1362 // positive or negative margin is used.
1363 if (aScreenPoint
< aScreenBegin
) {
1364 aScreenPoint
= aScreenBegin
;
1366 if (aScreenPoint
> aScreenEnd
) {
1367 aScreenPoint
= aScreenEnd
- aSize
;
1370 // If popupSize ended up being negative, or the original size was actually
1371 // smaller than the calculated popup size, just use the original size instead.
1372 if (popupSize
<= 0 || aSize
< popupSize
) {
1376 return std::min(popupSize
, aScreenEnd
- aScreenPoint
);
1379 nsRect
nsMenuPopupFrame::ComputeAnchorRect(nsPresContext
* aRootPresContext
,
1380 nsIFrame
* aAnchorFrame
) const {
1381 // Get the root frame for a reference
1382 nsIFrame
* rootFrame
= aRootPresContext
->PresShell()->GetRootFrame();
1384 // The dimensions of the anchor
1385 nsRect anchorRect
= aAnchorFrame
->GetRectRelativeToSelf();
1387 // Relative to the root
1388 anchorRect
= nsLayoutUtils::TransformFrameRectToAncestor(
1389 aAnchorFrame
, anchorRect
, rootFrame
);
1390 // Relative to the screen
1391 anchorRect
.MoveBy(rootFrame
->GetScreenRectInAppUnits().TopLeft());
1393 // In its own app units
1394 return anchorRect
.ScaleToOtherAppUnitsRoundOut(
1395 aRootPresContext
->AppUnitsPerDevPixel(),
1396 PresContext()->AppUnitsPerDevPixel());
1399 static nsIFrame
* MaybeDelegatedAnchorFrame(nsIFrame
* aFrame
) {
1403 if (auto* element
= Element::FromNodeOrNull(aFrame
->GetContent())) {
1404 if (element
->HasAttr(nsGkAtoms::delegatesanchor
)) {
1405 for (nsIFrame
* f
: aFrame
->PrincipalChildList()) {
1406 if (!f
->IsPlaceholderFrame()) {
1415 auto nsMenuPopupFrame::GetRects(const nsSize
& aPrefSize
) const -> Rects
{
1416 if (NS_WARN_IF(aPrefSize
== nsSize(-1, -1))) {
1417 // Return early if the popup hasn't been laid out yet. On Windows, this can
1418 // happen when using a drag popup before it opens.
1422 nsPresContext
* pc
= PresContext();
1423 nsIFrame
* rootFrame
= pc
->PresShell()->GetRootFrame();
1424 NS_ASSERTION(rootFrame
->GetView() && GetView() &&
1425 rootFrame
->GetView() == GetView()->GetParent(),
1426 "rootFrame's view is not our view's parent???");
1428 // Indicators of whether the popup should be flipped or resized.
1429 FlipStyle hFlip
= FlipStyle_None
, vFlip
= FlipStyle_None
;
1431 const nsMargin margin
= GetMargin();
1433 // the screen rectangle of the root frame, in dev pixels.
1434 const nsRect rootScreenRect
= rootFrame
->GetScreenRectInAppUnits();
1436 const bool isNoAutoHide
= IsNoAutoHide();
1437 const PopupLevel popupLevel
= GetPopupLevel(isNoAutoHide
);
1441 // Set the popup's size to the preferred size. Below, this size will be
1442 // adjusted to fit on the screen or within the content area. If the anchor is
1443 // sized to the popup, use the anchor's width instead of the preferred width.
1444 result
.mUsedRect
= nsRect(nsPoint(), aPrefSize
);
1446 const bool anchored
= IsAnchored();
1448 // In order to deal with transforms, we need the root prescontext:
1449 nsPresContext
* rootPc
= pc
->GetRootPresContext();
1450 if (NS_WARN_IF(!rootPc
)) {
1451 // If we can't reach a root pres context, don't bother continuing.
1455 result
.mAnchorRect
= result
.mUntransformedAnchorRect
= [&] {
1456 // If anchored to a rectangle, use that rectangle. Otherwise, determine
1457 // the rectangle from the anchor.
1458 if (mAnchorType
== MenuPopupAnchorType_Rect
) {
1461 // if the frame is not specified, use the anchor node passed to OpenPopup.
1462 // If that wasn't specified either, use the root frame. Note that
1463 // mAnchorContent might be a different document so its presshell must be
1465 nsIFrame
* anchorFrame
= GetAnchorFrame();
1467 return rootScreenRect
;
1469 return ComputeAnchorRect(rootPc
, anchorFrame
);
1472 // if we are anchored, there are certain things we don't want to do when
1473 // repositioning the popup to fit on the screen, such as end up positioned
1474 // over the anchor, for instance a popup appearing over the menu label.
1475 // When doing this reposition, we want to move the popup to the side with
1476 // the most room. The combination of anchor and alignment dictate if we
1477 // readjust above/below or to the left/right.
1478 if (mAnchorContent
|| mAnchorType
== MenuPopupAnchorType_Rect
) {
1479 // move the popup according to the anchor and alignment. This will also
1480 // tell us which axis the popup is flush against in case we have to move
1481 // it around later. The AdjustPositionForAnchorAlign method accounts for
1482 // the popup's margin.
1483 result
.mUsedRect
.MoveTo(AdjustPositionForAnchorAlign(
1484 result
.mAnchorRect
, aPrefSize
, hFlip
, vFlip
));
1486 // With no anchor, the popup is positioned relative to the root frame.
1487 result
.mUsedRect
.MoveTo(result
.mAnchorRect
.TopLeft() +
1488 nsPoint(margin
.left
, margin
.top
));
1491 // mXPos and mYPos specify an additional offset passed to OpenPopup that
1492 // should be added to the position. We also add the offset to the anchor
1493 // pos so a later flip/resize takes the offset into account.
1494 // FIXME(emilio): Wayland doesn't seem to be accounting for this offset
1495 // anywhere, and it probably should.
1497 nsPoint
offset(CSSPixel::ToAppUnits(mXPos
), CSSPixel::ToAppUnits(mYPos
));
1498 if (IsDirectionRTL()) {
1499 offset
.x
= -offset
.x
;
1501 result
.mUsedRect
.MoveBy(offset
);
1502 result
.mAnchorRect
.MoveBy(offset
);
1505 // Not anchored, use mScreenRect
1506 result
.mUsedRect
.MoveTo(mScreenRect
.TopLeft());
1507 result
.mAnchorRect
= result
.mUntransformedAnchorRect
=
1508 nsRect(mScreenRect
.TopLeft(), nsSize());
1510 // Right-align RTL context menus, and apply margin and offsets as per the
1511 // platform conventions.
1512 if (mIsContextMenu
&& IsDirectionRTL()) {
1513 result
.mUsedRect
.x
-= aPrefSize
.Width();
1514 result
.mUsedRect
.MoveBy(-margin
.right
, margin
.top
);
1516 result
.mUsedRect
.MoveBy(margin
.left
, margin
.top
);
1519 // OSX tooltips follow standard flip rule but other popups flip horizontally
1521 if (mPopupType
== PopupType::Tooltip
) {
1522 vFlip
= FlipStyle_Outside
;
1524 hFlip
= FlipStyle_Outside
;
1527 // Other OS screen positioned popups can be flipped vertically but never
1529 vFlip
= FlipStyle_Outside
;
1530 #endif // #ifdef XP_MACOSX
1533 const int32_t a2d
= pc
->AppUnitsPerDevPixel();
1535 nsView
* view
= GetView();
1536 NS_ASSERTION(view
, "popup with no view");
1538 nsIWidget
* widget
= view
->GetWidget();
1540 // If a panel has flip="none", don't constrain or flip it.
1541 // Also, always do this for content shells, so that the popup doesn't extend
1542 // outside the containing frame.
1543 if (mInContentShell
|| mFlip
!= FlipType_None
) {
1544 const Maybe
<nsRect
> constraintRect
=
1545 GetConstraintRect(result
.mAnchorRect
, rootScreenRect
, popupLevel
);
1547 if (constraintRect
) {
1548 // Ensure that anchorRect is on the constraint rect.
1549 result
.mAnchorRect
= result
.mAnchorRect
.Intersect(*constraintRect
);
1550 // Shrink the popup down if it is larger than the constraint size
1551 if (result
.mUsedRect
.width
> constraintRect
->width
) {
1552 result
.mUsedRect
.width
= constraintRect
->width
;
1554 if (result
.mUsedRect
.height
> constraintRect
->height
) {
1555 result
.mUsedRect
.height
= constraintRect
->height
;
1557 result
.mConstrainedByLayout
= true;
1560 if (IS_WAYLAND_DISPLAY() && widget
) {
1561 // Shrink the popup down if it's larger than popup size received from
1562 // Wayland compositor. We don't know screen size on Wayland so this is the
1563 // only info we have there.
1564 const nsSize waylandSize
= LayoutDeviceIntRect::ToAppUnits(
1565 widget
->GetMoveToRectPopupSize(), a2d
);
1566 if (waylandSize
.width
> 0 && result
.mUsedRect
.width
> waylandSize
.width
) {
1567 LOG_WAYLAND("Wayland constraint width [%p]: %d to %d", widget
,
1568 result
.mUsedRect
.width
, waylandSize
.width
);
1569 result
.mUsedRect
.width
= waylandSize
.width
;
1571 if (waylandSize
.height
> 0 &&
1572 result
.mUsedRect
.height
> waylandSize
.height
) {
1573 LOG_WAYLAND("Wayland constraint height [%p]: %d to %d", widget
,
1574 result
.mUsedRect
.height
, waylandSize
.height
);
1575 result
.mUsedRect
.height
= waylandSize
.height
;
1577 if (RefPtr
<widget::Screen
> s
= widget
->GetWidgetScreen()) {
1578 const nsSize screenSize
=
1579 LayoutDeviceIntSize::ToAppUnits(s
->GetAvailRect().Size(), a2d
);
1580 if (result
.mUsedRect
.height
> screenSize
.height
) {
1581 LOG_WAYLAND("Wayland constraint height to screen [%p]: %d to %d",
1582 widget
, result
.mUsedRect
.height
, screenSize
.height
);
1583 result
.mUsedRect
.height
= screenSize
.height
;
1585 if (result
.mUsedRect
.width
> screenSize
.width
) {
1586 LOG_WAYLAND("Wayland constraint widthto screen [%p]: %d to %d",
1587 widget
, result
.mUsedRect
.width
, screenSize
.width
);
1588 result
.mUsedRect
.width
= screenSize
.width
;
1593 // At this point the anchor (anchorRect) is within the available screen
1594 // area (constraintRect) and the popup is known to be no larger than the
1596 if (constraintRect
) {
1597 // We might want to "slide" an arrow if the panel is of the correct type -
1598 // but we can only slide on one axis - the other axis must be "flipped or
1599 // resized" as normal.
1600 bool slideHorizontal
= false, slideVertical
= false;
1601 if (mFlip
== FlipType_Slide
) {
1602 int8_t position
= GetAlignmentPosition();
1603 slideHorizontal
= position
>= POPUPPOSITION_BEFORESTART
&&
1604 position
<= POPUPPOSITION_AFTEREND
;
1605 slideVertical
= position
>= POPUPPOSITION_STARTBEFORE
&&
1606 position
<= POPUPPOSITION_ENDAFTER
;
1609 // Next, check if there is enough space to show the popup at full size
1610 // when positioned at screenPoint. If not, flip the popups to the opposite
1611 // side of their anchor point, or resize them as necessary.
1612 if (slideHorizontal
) {
1613 result
.mUsedRect
.width
= SlideOrResize(
1614 result
.mUsedRect
.x
, result
.mUsedRect
.width
, constraintRect
->x
,
1615 constraintRect
->XMost(), &result
.mAlignmentOffset
);
1617 const bool endAligned
=
1619 ? mPopupAlignment
== POPUPALIGNMENT_TOPLEFT
||
1620 mPopupAlignment
== POPUPALIGNMENT_BOTTOMLEFT
||
1621 mPopupAlignment
== POPUPALIGNMENT_LEFTCENTER
1622 : mPopupAlignment
== POPUPALIGNMENT_TOPRIGHT
||
1623 mPopupAlignment
== POPUPALIGNMENT_BOTTOMRIGHT
||
1624 mPopupAlignment
== POPUPALIGNMENT_RIGHTCENTER
;
1625 result
.mUsedRect
.width
= FlipOrResize(
1626 result
.mUsedRect
.x
, result
.mUsedRect
.width
, constraintRect
->x
,
1627 constraintRect
->XMost(), result
.mAnchorRect
.x
,
1628 result
.mAnchorRect
.XMost(), margin
.left
, margin
.right
, hFlip
,
1629 endAligned
, &result
.mHFlip
);
1631 if (slideVertical
) {
1632 result
.mUsedRect
.height
= SlideOrResize(
1633 result
.mUsedRect
.y
, result
.mUsedRect
.height
, constraintRect
->y
,
1634 constraintRect
->YMost(), &result
.mAlignmentOffset
);
1636 bool endAligned
= mPopupAlignment
== POPUPALIGNMENT_BOTTOMLEFT
||
1637 mPopupAlignment
== POPUPALIGNMENT_BOTTOMRIGHT
||
1638 mPopupAlignment
== POPUPALIGNMENT_BOTTOMCENTER
;
1639 result
.mUsedRect
.height
= FlipOrResize(
1640 result
.mUsedRect
.y
, result
.mUsedRect
.height
, constraintRect
->y
,
1641 constraintRect
->YMost(), result
.mAnchorRect
.y
,
1642 result
.mAnchorRect
.YMost(), margin
.top
, margin
.bottom
, vFlip
,
1643 endAligned
, &result
.mVFlip
);
1647 NS_ASSERTION(constraintRect
->Contains(result
.mUsedRect
),
1648 "Popup is offscreen");
1649 if (!constraintRect
->Contains(result
.mUsedRect
)) {
1650 NS_WARNING(nsPrintfCString("Popup is offscreen (%s vs. %s)",
1651 ToString(constraintRect
).c_str(),
1652 ToString(result
.mUsedRect
).c_str())
1658 // snap the popup's position in screen coordinates to device pixels, see
1659 // bug 622507, bug 961431
1660 result
.mUsedRect
.x
= pc
->RoundAppUnitsToNearestDevPixels(result
.mUsedRect
.x
);
1661 result
.mUsedRect
.y
= pc
->RoundAppUnitsToNearestDevPixels(result
.mUsedRect
.y
);
1663 // determine the x and y position of the view by subtracting the desired
1664 // screen position from the screen position of the root frame.
1665 result
.mViewPoint
= result
.mUsedRect
.TopLeft() - rootScreenRect
.TopLeft();
1667 // Offset the position by the width and height of the borders and titlebar.
1668 // Even though GetClientOffset should return (0, 0) when there is no titlebar
1669 // or borders, we skip these calculations anyway for non-panels to save time
1670 // since they will never have a titlebar.
1671 if (mPopupType
== PopupType::Panel
&& widget
) {
1672 result
.mClientOffset
= widget
->GetClientOffset();
1673 result
.mViewPoint
+=
1674 LayoutDeviceIntPoint::ToAppUnits(result
.mClientOffset
, a2d
);
1680 void nsMenuPopupFrame::SetPopupPosition(bool aIsMove
) {
1681 if (aIsMove
&& (mPrefSize
.width
== -1 || mPrefSize
.height
== -1)) {
1685 auto rects
= GetRects(mPrefSize
);
1686 if (rects
.mUsedRect
.Size() != mRect
.Size()) {
1687 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IN_REFLOW
));
1688 // We need to resize on top of moving, trigger an actual reflow.
1689 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors
,
1696 void nsMenuPopupFrame::PerformMove(const Rects
& aRects
) {
1697 auto* ps
= PresShell();
1699 // We're just moving, sync frame position and offset as needed.
1700 ps
->GetViewManager()->MoveViewTo(GetView(), aRects
.mViewPoint
.x
,
1701 aRects
.mViewPoint
.y
);
1703 // Now that we've positioned the view, sync up the frame's origin.
1704 nsBlockFrame::SetPosition(aRects
.mViewPoint
-
1705 GetParent()->GetOffsetTo(ps
->GetRootFrame()));
1707 // If the popup is in the positioned state or if it is shown and the position
1708 // or size changed, dispatch a popuppositioned event if the popup wants it.
1709 if (mPopupState
== ePopupPositioning
||
1710 (mPopupState
== ePopupShown
&&
1711 !aRects
.mUsedRect
.IsEqualEdges(mUsedScreenRect
)) ||
1712 (mPopupState
== ePopupShown
&&
1713 aRects
.mAlignmentOffset
!= mAlignmentOffset
)) {
1714 mUsedScreenRect
= aRects
.mUsedRect
;
1715 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW
) && !mPendingPositionedEvent
) {
1716 mPendingPositionedEvent
=
1717 nsXULPopupPositionedEvent::DispatchIfNeeded(mContent
->AsElement());
1721 if (!mPositionedByMoveToRect
) {
1722 mUntransformedAnchorRect
= aRects
.mUntransformedAnchorRect
;
1725 mAlignmentOffset
= aRects
.mAlignmentOffset
;
1726 mLastClientOffset
= aRects
.mClientOffset
;
1727 mHFlip
= aRects
.mHFlip
;
1728 mVFlip
= aRects
.mVFlip
;
1729 mConstrainedByLayout
= aRects
.mConstrainedByLayout
;
1731 // If this is a noautohide popup, set the screen coordinates of the popup.
1732 // This way, the popup stays at the location where it was opened even when the
1733 // window is moved. Popups at the parent level follow the parent window as it
1734 // is moved and remained anchored, so we want to maintain the anchoring
1737 // FIXME: This suffers from issues like bug 1823552, where constraints imposed
1738 // by the anchor are lost, but this is super-old behavior.
1739 const bool fixPositionToPoint
=
1740 IsNoAutoHide() && (GetPopupLevel() != PopupLevel::Parent
||
1741 mAnchorType
== MenuPopupAnchorType_Rect
);
1742 if (fixPositionToPoint
) {
1743 // Account for the margin that will end up being added to the screen
1744 // coordinate the next time SetPopupPosition is called.
1745 const auto& margin
= GetMargin();
1746 mAnchorType
= MenuPopupAnchorType_Point
;
1747 mScreenRect
.x
= aRects
.mUsedRect
.x
- margin
.left
;
1748 mScreenRect
.y
= aRects
.mUsedRect
.y
- margin
.top
;
1751 // For anchored popups that shouldn't follow the anchor, fix the original
1753 if (IsAnchored() && !ShouldFollowAnchor() && !mUsedScreenRect
.IsEmpty() &&
1754 mAnchorType
!= MenuPopupAnchorType_Rect
) {
1755 mAnchorType
= MenuPopupAnchorType_Rect
;
1756 mScreenRect
= aRects
.mUntransformedAnchorRect
;
1759 // NOTE(emilio): This call below is kind of a workaround, but we need to do
1760 // this here because some position changes don't go through the
1761 // view system -> popup manager, like:
1763 // https://searchfox.org/mozilla-central/rev/477950cf9ca9c9bb5ff6f34e0d0f6ca4718ea798/widget/gtk/nsWindow.cpp#3847
1765 // So this might be the last chance we have to set the remote browser's
1768 // Ultimately this probably wants to get fixed in the widget size of things,
1769 // but given this is worst-case a redundant DOM traversal, and that popups
1770 // usually don't have all that much content, this is probably an ok
1772 WidgetPositionOrSizeDidChange();
1775 void nsMenuPopupFrame::WidgetPositionOrSizeDidChange() {
1776 // In the case this popup has remote contents having OOP iframes, it's
1777 // possible that OOP iframe's nsSubDocumentFrame has been already reflowed
1778 // thus, we will never have a chance to tell this parent browser's position
1779 // update to the OOP documents without notifying it explicitly.
1780 if (!HasRemoteContent()) {
1783 for (nsIContent
* content
= mContent
->GetFirstChild(); content
;
1784 content
= content
->GetNextNode(mContent
)) {
1785 if (content
->IsXULElement(nsGkAtoms::browser
) &&
1786 content
->AsElement()->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::remote
,
1787 nsGkAtoms::_true
, eIgnoreCase
)) {
1788 if (auto* browserParent
= dom::BrowserParent::GetFrom(content
)) {
1789 browserParent
->NotifyPositionUpdatedForContentsInPopup();
1795 Maybe
<nsRect
> nsMenuPopupFrame::GetConstraintRect(
1796 const nsRect
& aAnchorRect
, const nsRect
& aRootScreenRect
,
1797 PopupLevel aPopupLevel
) const {
1798 const nsPresContext
* pc
= PresContext();
1799 const int32_t a2d
= PresContext()->AppUnitsPerDevPixel();
1800 Maybe
<nsRect
> result
;
1802 auto AddConstraint
= [&result
](const nsRect
& aConstraint
) {
1804 *result
= result
->Intersect(aConstraint
);
1806 result
.emplace(aConstraint
);
1810 // Determine the available screen space. It will be reduced by the OS chrome
1811 // such as menubars. It addition, for content shells, it will be the area of
1812 // the content rather than the screen.
1813 // In Wayland we can't use the screen rect because we can't know absolute
1815 if (!IS_WAYLAND_DISPLAY()) {
1816 const DesktopToLayoutDeviceScale scale
=
1817 pc
->DeviceContext()->GetDesktopToDeviceScale();
1818 // For content shells, get the screen where the root frame is located. This
1819 // is because we need to constrain the content to this content area, so we
1820 // should use the same screen. Otherwise, use the screen where the anchor is
1822 const nsRect
& rect
= mInContentShell
? aRootScreenRect
: aAnchorRect
;
1823 auto desktopRect
= DesktopIntRect::RoundOut(
1824 LayoutDeviceRect::FromAppUnits(rect
, a2d
) / scale
);
1825 desktopRect
.width
= std::max(1, desktopRect
.width
);
1826 desktopRect
.height
= std::max(1, desktopRect
.height
);
1828 RefPtr
<nsIScreen
> screen
=
1829 widget::ScreenManager::GetSingleton().ScreenForRect(desktopRect
);
1830 MOZ_ASSERT(screen
, "We always fall back to the primary screen");
1831 // Non-top-level popups (which will always be panels) should never overlap
1833 const bool canOverlapOSBar
=
1834 aPopupLevel
== PopupLevel::Top
&&
1835 LookAndFeel::GetInt(LookAndFeel::IntID::MenusCanOverlapOSBar
) &&
1837 // Get the total screen area if the popup is allowed to overlap it.
1838 const auto screenRect
=
1839 canOverlapOSBar
? screen
->GetRect() : screen
->GetAvailRect();
1840 AddConstraint(LayoutDeviceRect::ToAppUnits(screenRect
, a2d
));
1843 if (mInContentShell
) {
1844 // For content shells, clip to the client area rather than the screen area
1845 AddConstraint(aRootScreenRect
);
1846 } else if (!mOverrideConstraintRect
.IsEmpty()) {
1847 AddConstraint(mOverrideConstraintRect
);
1848 // This is currently only used for <select> elements where we want to
1849 // constrain vertically to the screen but not horizontally, so do the
1850 // intersection and then reset the horizontal values.
1852 // FIXME(emilio): This doesn't make any sense to me...
1853 result
->x
= mOverrideConstraintRect
.x
;
1854 result
->width
= mOverrideConstraintRect
.width
;
1857 // Expand the allowable screen rect by the input margin (which can't be
1858 // interacted with).
1860 const nscoord inputMargin
=
1861 StyleUIReset()->mMozWindowInputRegionMargin
.ToAppUnits();
1862 result
->Inflate(inputMargin
);
1867 ConsumeOutsideClicksResult
nsMenuPopupFrame::ConsumeOutsideClicks() {
1868 if (mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
1869 nsGkAtoms::consumeoutsideclicks
,
1870 nsGkAtoms::_true
, eCaseMatters
)) {
1871 return ConsumeOutsideClicks_True
;
1873 if (mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
1874 nsGkAtoms::consumeoutsideclicks
,
1875 nsGkAtoms::_false
, eCaseMatters
)) {
1876 return ConsumeOutsideClicks_ParentOnly
;
1878 if (mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
1879 nsGkAtoms::consumeoutsideclicks
,
1880 nsGkAtoms::never
, eCaseMatters
)) {
1881 return ConsumeOutsideClicks_Never
;
1884 nsCOMPtr
<nsIContent
> parentContent
= mContent
->GetParent();
1885 if (parentContent
) {
1886 dom::NodeInfo
* ni
= parentContent
->NodeInfo();
1887 if (ni
->Equals(nsGkAtoms::menulist
, kNameSpaceID_XUL
)) {
1888 return ConsumeOutsideClicks_True
; // Consume outside clicks for combo
1889 // boxes on all platforms
1892 // Don't consume outside clicks for menus in Windows
1893 if (ni
->Equals(nsGkAtoms::menu
, kNameSpaceID_XUL
) ||
1894 ni
->Equals(nsGkAtoms::popupset
, kNameSpaceID_XUL
) ||
1895 ((ni
->Equals(nsGkAtoms::button
, kNameSpaceID_XUL
) ||
1896 ni
->Equals(nsGkAtoms::toolbarbutton
, kNameSpaceID_XUL
)) &&
1897 parentContent
->AsElement()->AttrValueIs(
1898 kNameSpaceID_None
, nsGkAtoms::type
, nsGkAtoms::menu
,
1900 return ConsumeOutsideClicks_Never
;
1905 return ConsumeOutsideClicks_True
;
1908 static nsIScrollableFrame
* DoGetScrollFrame(const nsIFrame
* aFrame
) {
1909 if (const nsIScrollableFrame
* sf
= do_QueryFrame(aFrame
)) {
1910 return const_cast<nsIScrollableFrame
*>(sf
);
1912 for (nsIFrame
* childFrame
: aFrame
->PrincipalChildList()) {
1913 if (auto* sf
= DoGetScrollFrame(childFrame
)) {
1920 // XXXroc this is megalame. Fossicking around for a frame of the right
1921 // type is a recipe for disaster in the long term.
1922 nsIScrollableFrame
* nsMenuPopupFrame::GetScrollFrame() const {
1923 return DoGetScrollFrame(this);
1926 void nsMenuPopupFrame::ChangeByPage(bool aIsUp
) {
1927 // Only scroll by page within menulists.
1928 if (!IsMenuList()) {
1932 nsIScrollableFrame
* scrollframe
= GetScrollFrame();
1934 RefPtr popup
= &PopupElement();
1935 XULButtonElement
* currentMenu
= popup
->GetActiveMenuChild();
1936 XULButtonElement
* newMenu
= nullptr;
1938 // If there is no current menu item, get the first item. When moving up,
1939 // just use this as the newMenu and leave currentMenu null so that no check
1940 // for a later element is performed. When moving down, set currentMenu so
1941 // that we look for one page down from the first item.
1942 newMenu
= popup
->GetFirstMenuItem();
1944 currentMenu
= newMenu
;
1948 if (currentMenu
&& currentMenu
->GetPrimaryFrame()) {
1949 const nscoord scrollHeight
=
1950 scrollframe
? scrollframe
->GetScrollPortRect().height
: mRect
.height
;
1951 const nsRect currentRect
= currentMenu
->GetPrimaryFrame()->GetRect();
1952 const XULButtonElement
* startMenu
= currentMenu
;
1954 // Get the position of the current item and add or subtract one popup's
1955 // height to or from it.
1956 const nscoord targetPos
= aIsUp
? currentRect
.YMost() - scrollHeight
1957 : currentRect
.y
+ scrollHeight
;
1958 // Look for the next child which is just past the target position. This
1959 // child will need to be selected.
1961 currentMenu
= aIsUp
? popup
->GetPrevMenuItemFrom(*currentMenu
)
1962 : popup
->GetNextMenuItemFrom(*currentMenu
)) {
1963 if (!currentMenu
->GetPrimaryFrame()) {
1966 const nsRect curRect
= currentMenu
->GetPrimaryFrame()->GetRect();
1967 const nscoord curPos
= aIsUp
? curRect
.y
: curRect
.YMost();
1968 // If the right position was found, break out. Otherwise, look for another
1970 if (aIsUp
? (curPos
< targetPos
) : (curPos
> targetPos
)) {
1971 if (!newMenu
|| newMenu
== startMenu
) {
1972 newMenu
= currentMenu
;
1977 // Assign this item to newMenu. This item will be selected in case we
1978 // don't find any more.
1979 newMenu
= currentMenu
;
1983 // Select the new menuitem.
1984 if (RefPtr newMenuRef
= newMenu
) {
1985 popup
->SetActiveMenuChild(newMenuRef
);
1989 dom::XULPopupElement
& nsMenuPopupFrame::PopupElement() const {
1990 auto* popup
= dom::XULPopupElement::FromNode(GetContent());
1991 MOZ_DIAGNOSTIC_ASSERT(popup
);
1995 XULButtonElement
* nsMenuPopupFrame::GetCurrentMenuItem() const {
1996 return PopupElement().GetActiveMenuChild();
1999 nsIFrame
* nsMenuPopupFrame::GetCurrentMenuItemFrame() const {
2000 auto* child
= GetCurrentMenuItem();
2001 return child
? child
->GetPrimaryFrame() : nullptr;
2004 void nsMenuPopupFrame::HandleEnterKeyPress(WidgetEvent
& aEvent
) {
2005 mIncrementalString
.Truncate();
2006 RefPtr popup
= &PopupElement();
2007 popup
->HandleEnterKeyPress(aEvent
);
2010 XULButtonElement
* nsMenuPopupFrame::FindMenuWithShortcut(
2011 mozilla::dom::KeyboardEvent
& aKeyEvent
, bool& aDoAction
) {
2012 uint32_t charCode
= aKeyEvent
.CharCode();
2013 uint32_t keyCode
= aKeyEvent
.KeyCode();
2017 // Enumerate over our list of frames.
2018 const bool isMenu
= !IsMenuList();
2019 TimeStamp keyTime
= aKeyEvent
.WidgetEventPtr()->mTimeStamp
;
2020 if (charCode
== 0) {
2021 if (keyCode
== dom::KeyboardEvent_Binding::DOM_VK_BACK_SPACE
) {
2022 if (!isMenu
&& !mIncrementalString
.IsEmpty()) {
2023 mIncrementalString
.SetLength(mIncrementalString
.Length() - 1);
2027 if (nsCOMPtr
<nsISound
> sound
= do_GetService("@mozilla.org/sound;1")) {
2030 #endif // #ifdef XP_WIN
2034 char16_t uniChar
= ToLowerCase(static_cast<char16_t
>(charCode
));
2036 // Menu supports only first-letter navigation
2037 mIncrementalString
= uniChar
;
2038 } else if (IsWithinIncrementalTime(keyTime
)) {
2039 mIncrementalString
.Append(uniChar
);
2041 // Interval too long, treat as new typing
2042 mIncrementalString
= uniChar
;
2045 // See bug 188199 & 192346, if all letters in incremental string are same,
2046 // just try to match the first one
2047 nsAutoString
incrementalString(mIncrementalString
);
2048 uint32_t charIndex
= 1, stringLength
= incrementalString
.Length();
2049 while (charIndex
< stringLength
&&
2050 incrementalString
[charIndex
] == incrementalString
[charIndex
- 1]) {
2053 if (charIndex
== stringLength
) {
2054 incrementalString
.Truncate(1);
2058 sLastKeyTime
= keyTime
;
2061 PopupElement().FindMenuWithShortcut(incrementalString
, aDoAction
);
2066 // If we don't match anything, rollback the last typing
2067 mIncrementalString
.SetLength(mIncrementalString
.Length() - 1);
2069 // didn't find a matching menu item
2071 // behavior on Windows - this item is in a menu popup off of the
2072 // menu bar, so beep and do nothing else
2074 if (nsCOMPtr
<nsISound
> sound
= do_GetService("@mozilla.org/sound;1")) {
2078 #endif // #ifdef XP_WIN
2083 nsIWidget
* nsMenuPopupFrame::GetWidget() const {
2084 return mView
? mView
->GetWidget() : nullptr;
2087 // helpers /////////////////////////////////////////////////////////////
2089 nsresult
nsMenuPopupFrame::AttributeChanged(int32_t aNameSpaceID
,
2095 nsBlockFrame::AttributeChanged(aNameSpaceID
, aAttribute
, aModType
);
2097 if (aAttribute
== nsGkAtoms::left
|| aAttribute
== nsGkAtoms::top
) {
2098 MoveToAttributePosition();
2101 if (aAttribute
== nsGkAtoms::remote
) {
2102 // When the remote attribute changes, we need to create a new widget to
2103 // ensure that it has the correct compositor and transparency settings to
2104 // match the new value.
2105 PrepareWidget(true);
2108 if (aAttribute
== nsGkAtoms::followanchor
) {
2109 if (nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance()) {
2110 pm
->UpdateFollowAnchor(this);
2114 if (aAttribute
== nsGkAtoms::label
) {
2115 // set the label for the titlebar
2116 nsView
* view
= GetView();
2118 nsIWidget
* widget
= view
->GetWidget();
2121 mContent
->AsElement()->GetAttr(nsGkAtoms::label
, title
);
2122 if (!title
.IsEmpty()) {
2123 widget
->SetTitle(title
);
2127 } else if (aAttribute
== nsGkAtoms::ignorekeys
) {
2128 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
2130 nsAutoString ignorekeys
;
2131 mContent
->AsElement()->GetAttr(nsGkAtoms::ignorekeys
, ignorekeys
);
2132 pm
->UpdateIgnoreKeys(ignorekeys
.EqualsLiteral("true"));
2139 void nsMenuPopupFrame::MoveToAttributePosition() {
2140 // Move the widget around when the user sets the |left| and |top| attributes.
2141 // Note that this is not the best way to move the widget, as it results in
2142 // lots of FE notifications and is likely to be slow as molasses. Use |moveTo|
2143 // on the element if possible.
2144 nsAutoString left
, top
;
2145 mContent
->AsElement()->GetAttr(nsGkAtoms::left
, left
);
2146 mContent
->AsElement()->GetAttr(nsGkAtoms::top
, top
);
2147 nsresult err1
, err2
;
2148 mozilla::CSSIntPoint
pos(left
.ToInteger(&err1
), top
.ToInteger(&err2
));
2150 if (NS_SUCCEEDED(err1
) && NS_SUCCEEDED(err2
)) MoveTo(pos
, false);
2152 PresShell()->FrameNeedsReflow(
2153 this, IntrinsicDirty::FrameAncestorsAndDescendants
, NS_FRAME_IS_DIRTY
);
2156 void nsMenuPopupFrame::Destroy(DestroyContext
& aContext
) {
2157 // XXX: Currently we don't fire popuphidden for these popups, that seems wrong
2158 // but alas, also pre-existing.
2159 HidePopup(/* aDeselectMenu = */ false, ePopupClosed
,
2160 /* aFromFrameDestruction = */ true);
2162 if (RefPtr
<nsXULPopupManager
> pm
= nsXULPopupManager::GetInstance()) {
2163 pm
->PopupDestroyed(this);
2166 nsBlockFrame::Destroy(aContext
);
2169 nsMargin
nsMenuPopupFrame::GetMargin() const {
2171 StyleMargin()->GetMargin(margin
);
2172 if (mIsTopLevelContextMenu
) {
2173 const CSSIntPoint
offset(
2174 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetHorizontal
),
2175 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetVertical
));
2176 auto auOffset
= CSSIntPoint::ToAppUnits(offset
);
2177 margin
.top
+= auOffset
.y
;
2178 margin
.bottom
+= auOffset
.y
;
2179 margin
.left
+= auOffset
.x
;
2180 margin
.right
+= auOffset
.x
;
2182 if (mPopupType
== PopupType::Tooltip
&& !IsAnchored()) {
2183 const auto auOffset
=
2184 CSSPixel::ToAppUnits(LookAndFeel::TooltipOffsetVertical());
2185 margin
.top
+= auOffset
;
2186 margin
.bottom
+= auOffset
;
2191 void nsMenuPopupFrame::MoveTo(const CSSPoint
& aPos
, bool aUpdateAttrs
,
2192 bool aByMoveToRect
) {
2193 nsIWidget
* widget
= GetWidget();
2194 nsPoint appUnitsPos
= CSSPixel::ToAppUnits(aPos
);
2196 // reposition the popup at the specified coordinates. Don't clear the anchor
2197 // and position, because the popup can be reset to its anchor position by
2198 // using (-1, -1) as coordinates.
2200 // Subtract off the margin as it will be added to the position when
2201 // SetPopupPosition is called.
2203 nsMargin margin
= GetMargin();
2204 if (mIsContextMenu
&& IsDirectionRTL()) {
2205 appUnitsPos
.x
+= margin
.right
+ mRect
.Width();
2207 appUnitsPos
.x
-= margin
.left
;
2209 appUnitsPos
.y
-= margin
.top
;
2212 if (mScreenRect
.TopLeft() == appUnitsPos
&&
2213 (!widget
|| widget
->GetClientOffset() == mLastClientOffset
)) {
2217 mPositionedByMoveToRect
= aByMoveToRect
;
2218 mScreenRect
.MoveTo(appUnitsPos
);
2219 if (mAnchorType
== MenuPopupAnchorType_Rect
) {
2220 // This ensures that the anchor width is still honored, to prevent it from
2221 // changing spuriously.
2222 mScreenRect
.height
= 0;
2223 // But we still need to make sure that our top left position ends up in
2225 mPopupAlignment
= POPUPALIGNMENT_TOPLEFT
;
2226 mPopupAnchor
= POPUPALIGNMENT_BOTTOMLEFT
;
2229 mAnchorType
= MenuPopupAnchorType_Point
;
2232 SetPopupPosition(true);
2234 RefPtr
<Element
> popup
= mContent
->AsElement();
2236 (popup
->HasAttr(nsGkAtoms::left
) || popup
->HasAttr(nsGkAtoms::top
))) {
2237 nsAutoString left
, top
;
2238 left
.AppendInt(RoundedToInt(aPos
).x
);
2239 top
.AppendInt(RoundedToInt(aPos
).y
);
2240 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::left
, left
, false);
2241 popup
->SetAttr(kNameSpaceID_None
, nsGkAtoms::top
, top
, false);
2245 void nsMenuPopupFrame::MoveToAnchor(nsIContent
* aAnchorContent
,
2246 const nsAString
& aPosition
, int32_t aXPos
,
2247 int32_t aYPos
, bool aAttributesOverride
) {
2248 NS_ASSERTION(IsVisibleOrShowing(),
2249 "popup must be visible or showing to move it");
2251 nsPopupState oldstate
= mPopupState
;
2252 InitializePopup(aAnchorContent
, mTriggerContent
, aPosition
, aXPos
, aYPos
,
2253 MenuPopupAnchorType_Node
, aAttributesOverride
);
2254 // InitializePopup changed the state so reset it.
2255 mPopupState
= oldstate
;
2257 // Pass false here so that flipping and adjusting to fit on the screen happen.
2258 SetPopupPosition(false);
2261 int8_t nsMenuPopupFrame::GetAlignmentPosition() const {
2262 // The code below handles most cases of alignment, anchor and position values.
2263 // Those that are not handled just return POPUPPOSITION_UNKNOWN.
2265 if (mPosition
== POPUPPOSITION_OVERLAP
||
2266 mPosition
== POPUPPOSITION_AFTERPOINTER
||
2267 mPosition
== POPUPPOSITION_SELECTION
) {
2271 int8_t position
= mPosition
;
2273 if (position
== POPUPPOSITION_UNKNOWN
) {
2274 switch (mPopupAnchor
) {
2275 case POPUPALIGNMENT_BOTTOMRIGHT
:
2276 case POPUPALIGNMENT_BOTTOMLEFT
:
2277 case POPUPALIGNMENT_BOTTOMCENTER
:
2278 position
= mPopupAlignment
== POPUPALIGNMENT_TOPRIGHT
2279 ? POPUPPOSITION_AFTEREND
2280 : POPUPPOSITION_AFTERSTART
;
2282 case POPUPALIGNMENT_TOPRIGHT
:
2283 case POPUPALIGNMENT_TOPLEFT
:
2284 case POPUPALIGNMENT_TOPCENTER
:
2285 position
= mPopupAlignment
== POPUPALIGNMENT_BOTTOMRIGHT
2286 ? POPUPPOSITION_BEFOREEND
2287 : POPUPPOSITION_BEFORESTART
;
2289 case POPUPALIGNMENT_LEFTCENTER
:
2290 position
= mPopupAlignment
== POPUPALIGNMENT_BOTTOMRIGHT
2291 ? POPUPPOSITION_STARTAFTER
2292 : POPUPPOSITION_STARTBEFORE
;
2294 case POPUPALIGNMENT_RIGHTCENTER
:
2295 position
= mPopupAlignment
== POPUPALIGNMENT_BOTTOMLEFT
2296 ? POPUPPOSITION_ENDAFTER
2297 : POPUPPOSITION_ENDBEFORE
;
2305 position
= POPUPPOSITION_HFLIP(position
);
2309 position
= POPUPPOSITION_VFLIP(position
);
2316 * KEEP THIS IN SYNC WITH nsIFrame::CreateView
2317 * as much as possible. Until we get rid of views finally...
2319 void nsMenuPopupFrame::CreatePopupView() {
2324 nsViewManager
* viewManager
= PresContext()->GetPresShell()->GetViewManager();
2325 NS_ASSERTION(nullptr != viewManager
, "null view manager");
2328 nsView
* parentView
= viewManager
->GetRootView();
2329 auto visibility
= ViewVisibility::Hide
;
2331 NS_ASSERTION(parentView
, "no parent view");
2334 nsView
* view
= viewManager
->CreateView(GetRect(), parentView
, visibility
);
2335 auto zIndex
= ZIndex();
2336 viewManager
->SetViewZIndex(view
, zIndex
.isNothing(), zIndex
.valueOr(0));
2337 // XXX put view last in document order until we can do better
2338 viewManager
->InsertChild(parentView
, view
, nullptr, true);
2340 // Remember our view
2344 NS_FRAME_TRACE_CALLS
,
2345 ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p", this, view
));
2348 bool nsMenuPopupFrame::ShouldFollowAnchor() const {
2349 if (mAnchorType
!= MenuPopupAnchorType_Node
|| !mAnchorContent
) {
2353 // Follow anchor mode is used when followanchor="true" is set or for arrow
2355 if (mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
2356 nsGkAtoms::followanchor
,
2357 nsGkAtoms::_true
, eCaseMatters
)) {
2361 if (mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
,
2362 nsGkAtoms::followanchor
,
2363 nsGkAtoms::_false
, eCaseMatters
)) {
2367 return mPopupType
== PopupType::Panel
&&
2368 mContent
->AsElement()->AttrValueIs(kNameSpaceID_None
, nsGkAtoms::type
,
2369 nsGkAtoms::arrow
, eCaseMatters
);
2372 bool nsMenuPopupFrame::ShouldFollowAnchor(nsRect
& aRect
) {
2373 if (!ShouldFollowAnchor()) {
2377 if (nsIFrame
* anchorFrame
= GetAnchorFrame()) {
2378 if (nsPresContext
* rootPresContext
= PresContext()->GetRootPresContext()) {
2379 aRect
= ComputeAnchorRect(rootPresContext
, anchorFrame
);
2386 bool nsMenuPopupFrame::IsDirectionRTL() const {
2387 const nsIFrame
* anchor
= GetAnchorFrame();
2388 const nsIFrame
* f
= anchor
? anchor
: this;
2389 return f
->StyleVisibility()->mDirection
== StyleDirection::Rtl
;
2392 nsIFrame
* nsMenuPopupFrame::GetAnchorFrame() const {
2393 nsIContent
* anchor
= mAnchorContent
;
2397 return MaybeDelegatedAnchorFrame(anchor
->GetPrimaryFrame());
2400 void nsMenuPopupFrame::CheckForAnchorChange(nsRect
& aRect
) {
2401 // Don't update if the popup isn't visible or we shouldn't be following the
2403 if (!IsVisible() || !ShouldFollowAnchor()) {
2407 bool shouldHide
= false;
2409 nsPresContext
* rootPresContext
= PresContext()->GetRootPresContext();
2411 // If the frame for the anchor has gone away, hide the popup.
2412 nsIFrame
* anchor
= GetAnchorFrame();
2413 if (!anchor
|| !rootPresContext
) {
2415 } else if (!anchor
->IsVisibleConsideringAncestors(
2416 VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY
)) {
2417 // If the anchor is now inside something that is invisible, hide the popup.
2420 // If the anchor is now inside a hidden parent popup, hide the popup.
2421 nsIFrame
* frame
= anchor
;
2423 nsMenuPopupFrame
* popup
= do_QueryFrame(frame
);
2424 if (popup
&& popup
->PopupState() != ePopupShown
) {
2429 frame
= frame
->GetParent();
2434 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
2436 // As the caller will be iterating over the open popups, hide
2438 pm
->HidePopup(mContent
->AsElement(),
2439 {HidePopupOption::DeselectMenu
, HidePopupOption::Async
});
2445 nsRect anchorRect
= ComputeAnchorRect(rootPresContext
, anchor
);
2447 // If the rectangles are different, move the popup.
2448 if (!anchorRect
.IsEqualEdges(aRect
)) {
2450 SetPopupPosition(true);