Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp
Warning:line 2039, column 5
Value stored to 'stringLength' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_cpp_layout_xul0.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/xul -fcoverage-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/xul -resource-dir /usr/lib/llvm-20/lib/clang/20 -include /var/lib/jenkins/workspace/firefox-scan-build/config/gcc_hidden.h -include /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D _GLIBCXX_ASSERTIONS -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /var/lib/jenkins/workspace/firefox-scan-build/layout/xul -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/xul -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /var/lib/jenkins/workspace/firefox-scan-build/ipc/chromium/src -I /var/lib/jenkins/workspace/firefox-scan-build/layout/base -I /var/lib/jenkins/workspace/firefox-scan-build/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/layout/painting -I /var/lib/jenkins/workspace/firefox-scan-build/layout/style -I /var/lib/jenkins/workspace/firefox-scan-build/dom/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/xul -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -I /usr/include/gtk-3.0 -I /usr/include/pango-1.0 -I /usr/include/glib-2.0 -I /usr/lib/x86_64-linux-gnu/glib-2.0/include -I /usr/include/sysprof-6 -I /usr/include/harfbuzz -I /usr/include/freetype2 -I /usr/include/libpng16 -I /usr/include/libmount -I /usr/include/blkid -I /usr/include/fribidi -I /usr/include/cairo -I /usr/include/pixman-1 -I /usr/include/gdk-pixbuf-2.0 -I /usr/include/x86_64-linux-gnu -I /usr/include/webp -I /usr/include/gio-unix-2.0 -I /usr/include/cloudproviders -I /usr/include/atk-1.0 -I /usr/include/at-spi2-atk/2.0 -I /usr/include/at-spi-2.0 -I /usr/include/dbus-1.0 -I /usr/lib/x86_64-linux-gnu/dbus-1.0/include -I /usr/include/gtk-3.0/unix-print -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-20/lib/clang/20/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-deprecated-this-capture -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2025-01-20-090804-167946-1 -x c++ Unified_cpp_layout_xul0.cpp
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/. */
6
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"
15#include "nsAtom.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"
26#include "nsRect.h"
27#include "nsIPopupContainer.h"
28#include "nsIDocShell.h"
29#include "nsReadableUtils.h"
30#include "nsUnicharUtils.h"
31#include "nsLayoutUtils.h"
32#include "nsContentUtils.h"
33#include "nsCSSFrameConstructor.h"
34#include "nsPIWindowRoot.h"
35#include "nsIReflowCallback.h"
36#include "nsIDocShellTreeOwner.h"
37#include "nsIBaseWindow.h"
38#include "nsISound.h"
39#include "nsIScreenManager.h"
40#include "nsServiceManagerUtils.h"
41#include "nsStyleConsts.h"
42#include "nsStyleStructInlines.h"
43#include "nsTransitionManager.h"
44#include "nsDisplayList.h"
45#include "nsIDOMXULSelectCntrlEl.h"
46#include "mozilla/widget/ScreenManager.h"
47#include "mozilla/AnimationUtils.h"
48#include "mozilla/BasePrincipal.h"
49#include "mozilla/EventDispatcher.h"
50#include "mozilla/EventStateManager.h"
51#include "mozilla/Preferences.h"
52#include "mozilla/LookAndFeel.h"
53#include "mozilla/MouseEvents.h"
54#include "mozilla/PresShell.h"
55#include "mozilla/ScrollContainerFrame.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"
62#include <algorithm>
63
64#include "X11UndefineNone.h"
65#include "nsXULPopupManager.h"
66
67using namespace mozilla;
68using mozilla::dom::Document;
69using mozilla::dom::Element;
70using mozilla::dom::Event;
71using mozilla::dom::XULButtonElement;
72
73TimeStamp nsMenuPopupFrame::sLastKeyTime;
74
75#ifdef MOZ_WAYLAND1
76# include "mozilla/WidgetUtilsGtk.h"
77# define IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() mozilla::widget::GdkIsWaylandDisplay()
78extern mozilla::LazyLogModule gWidgetPopupLog;
79# define LOG_WAYLAND(...)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, ...); } } while (
0)
\
80 MOZ_LOG(gWidgetPopupLog, mozilla::LogLevel::Debug, (__VA_ARGS__))do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, __VA_ARGS__); } }
while (0)
81#else
82# define IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() false
83# define LOG_WAYLAND(...)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, ...); } } while (
0)
84#endif
85
86// NS_NewMenuPopupFrame
87//
88// Wrapper for creating a new menu popup container
89//
90nsIFrame* NS_NewMenuPopupFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
91 return new (aPresShell)
92 nsMenuPopupFrame(aStyle, aPresShell->GetPresContext());
93}
94
95NS_IMPL_FRAMEARENA_HELPERS(nsMenuPopupFrame)void* nsMenuPopupFrame ::operator new(size_t sz, mozilla::PresShell
* aShell) { return aShell->AllocateFrame(nsQueryFrame::nsMenuPopupFrame_id
, sz); }
96
97NS_QUERYFRAME_HEAD(nsMenuPopupFrame)void* nsMenuPopupFrame ::QueryFrame(FrameIID id) const { switch
(id) {
98 NS_QUERYFRAME_ENTRY(nsMenuPopupFrame)case nsMenuPopupFrame ::kFrameIID: { static_assert( std::is_same_v
<nsMenuPopupFrame, nsMenuPopupFrame ::Has_NS_DECL_QUERYFRAME_TARGET
>, "nsMenuPopupFrame" " must declare itself as a queryframe target"
); return const_cast<nsMenuPopupFrame*>(static_cast<
const nsMenuPopupFrame*>(this)); }
99NS_QUERYFRAME_TAIL_INHERITING(nsBlockFrame)default: break; } return nsBlockFrame ::QueryFrame(id); }
100
101//
102// nsMenuPopupFrame ctor
103//
104nsMenuPopupFrame::nsMenuPopupFrame(ComputedStyle* aStyle,
105 nsPresContext* aPresContext)
106 : nsBlockFrame(aStyle, aPresContext, kClassID) {}
107
108nsMenuPopupFrame::~nsMenuPopupFrame() = default;
109
110static bool IsMouseTransparent(const ComputedStyle& aStyle) {
111 // If pointer-events: none; is set on the popup, then the widget should
112 // ignore mouse events, passing them through to the content behind.
113 return aStyle.PointerEvents() == StylePointerEvents::None;
114}
115
116static nsIWidget::InputRegion ComputeInputRegion(const ComputedStyle& aStyle,
117 const nsPresContext& aPc) {
118 return {IsMouseTransparent(aStyle),
119 (aStyle.StyleUIReset()->mMozWindowInputRegionMargin.ToCSSPixels() *
120 aPc.CSSToDevPixelScale())
121 .Truncated()};
122}
123
124bool nsMenuPopupFrame::ShouldCreateWidgetUpfront() const {
125 if (mPopupType != PopupType::Menu) {
126 // Any panel with a type attribute, such as the autocomplete popup, is
127 // always generated right away.
128 return mContent->AsElement()->HasAttr(nsGkAtoms::type);
129 }
130
131 // Generate the widget up-front if the parent menu is a <menulist> unless its
132 // sizetopopup is set to "none".
133 return ShouldExpandToInflowParentOrAnchor();
134}
135
136void nsMenuPopupFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
137 nsIFrame* aPrevInFlow) {
138 nsBlockFrame::Init(aContent, aParent, aPrevInFlow);
139
140 CreatePopupView();
141
142 nsView* ourView = GetView();
143
144 const auto& el = PopupElement();
145 mPopupType = PopupType::Panel;
146 if (el.IsMenu()) {
147 mPopupType = PopupType::Menu;
148 } else if (el.IsXULElement(nsGkAtoms::tooltip)) {
149 mPopupType = PopupType::Tooltip;
150 }
151
152 if (PresContext()->IsChrome()) {
153 mInContentShell = false;
154 }
155
156 // Support incontentshell=false attribute to allow popups to be displayed
157 // outside of the content shell. Chrome only.
158 if (el.NodePrincipal()->IsSystemPrincipal()) {
159 if (el.GetXULBoolAttr(nsGkAtoms::incontentshell)) {
160 mInContentShell = true;
161 } else if (el.AttrValueIs(kNameSpaceID_None, nsGkAtoms::incontentshell,
162 nsGkAtoms::_false, eCaseMatters)) {
163 mInContentShell = false;
164 }
165 }
166
167 // To improve performance, create the widget for the popup if needed. Popups
168 // such as menus will create their widgets later when the popup opens.
169 //
170 // FIXME(emilio): Doing this up-front for all menupopups causes a bunch of
171 // assertions, while it's supposed to be just an optimization.
172 if (!ourView->HasWidget() && ShouldCreateWidgetUpfront()) {
173 CreateWidgetForView(ourView);
174 }
175
176 AddStateBits(NS_FRAME_IN_POPUP);
177}
178
179bool nsMenuPopupFrame::HasRemoteContent() const {
180 return !mInContentShell && mPopupType == PopupType::Panel &&
181 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
182 nsGkAtoms::remote, nsGkAtoms::_true,
183 eIgnoreCase);
184}
185
186bool nsMenuPopupFrame::IsNoAutoHide() const {
187 // Panels with noautohide="true" don't hide when the mouse is clicked
188 // outside of them, or when another application is made active. Non-autohide
189 // panels cannot be used in content windows.
190 return !mInContentShell && mPopupType == PopupType::Panel &&
191 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
192 nsGkAtoms::noautohide,
193 nsGkAtoms::_true, eIgnoreCase);
194}
195
196widget::PopupLevel nsMenuPopupFrame::GetPopupLevel(bool aIsNoAutoHide) const {
197 // The popup level is determined as follows, in this order:
198 // 1. non-panels (menus and tooltips) are always topmost
199 // 2. any specified level attribute
200 // 3. if a titlebar attribute is set, use the 'floating' level
201 // 4. if this is a noautohide panel, use the 'parent' level
202 // 5. use the platform-specific default level
203
204 // If this is not a panel, this is always a top-most popup.
205 if (mPopupType != PopupType::Panel) {
206 return PopupLevel::Top;
207 }
208
209 // If the level attribute has been set, use that.
210 static Element::AttrValuesArray strings[] = {nsGkAtoms::top,
211 nsGkAtoms::parent, nullptr};
212 switch (mContent->AsElement()->FindAttrValueIn(
213 kNameSpaceID_None, nsGkAtoms::level, strings, eCaseMatters)) {
214 case 0:
215 return PopupLevel::Top;
216 case 1:
217 return PopupLevel::Parent;
218 default:
219 break;
220 }
221
222 // If this panel is a noautohide panel, the default is the parent level.
223 if (aIsNoAutoHide) {
224 return PopupLevel::Parent;
225 }
226
227 // Otherwise, the result depends on the platform.
228 return StaticPrefs::ui_panel_default_level_parent() ? PopupLevel::Parent
229 : PopupLevel::Top;
230}
231
232void nsMenuPopupFrame::PrepareWidget(bool aForceRecreate) {
233 nsView* ourView = GetView();
234 if (auto* widget = GetWidget()) {
235 nsCOMPtr<nsIWidget> parent = ComputeParentWidget();
236 if (aForceRecreate || widget->GetParent() != parent ||
237 widget->NeedsRecreateToReshow()) {
238 // Widget's WebRender resources needs to be cleared before creating new
239 // widget.
240 widget->ClearCachedWebrenderResources();
241 ourView->DestroyWidget();
242 }
243 }
244 if (!ourView->HasWidget()) {
245 CreateWidgetForView(ourView);
246 } else {
247 PropagateStyleToWidget();
248 }
249}
250
251already_AddRefed<nsIWidget> nsMenuPopupFrame::ComputeParentWidget() const {
252 auto popupLevel = GetPopupLevel(IsNoAutoHide());
253 // Panels which have a parent level need a parent widget. This allows them to
254 // always appear in front of the parent window but behind other windows that
255 // should be in front of it.
256 nsCOMPtr<nsIWidget> parentWidget;
257 if (popupLevel != PopupLevel::Top) {
258 nsCOMPtr<nsIDocShellTreeItem> dsti = PresContext()->GetDocShell();
259 if (!dsti) {
260 return nullptr;
261 }
262
263 nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
264 dsti->GetTreeOwner(getter_AddRefs(treeOwner));
265 if (!treeOwner) {
266 return nullptr;
267 }
268
269 nsCOMPtr<nsIBaseWindow> baseWindow(do_QueryInterface(treeOwner));
270 if (baseWindow) {
271 baseWindow->GetMainWidget(getter_AddRefs(parentWidget));
272 }
273 }
274 if (!parentWidget && mView && mView->GetParent()) {
275 parentWidget = mView->GetParent()->GetNearestWidget(nullptr);
276 }
277 return parentWidget.forget();
278}
279
280nsresult nsMenuPopupFrame::CreateWidgetForView(nsView* aView) {
281 // Create a widget for ourselves.
282 widget::InitData widgetData;
283 widgetData.mWindowType = widget::WindowType::Popup;
284 widgetData.mBorderStyle = widget::BorderStyle::Default;
285 widgetData.mClipSiblings = true;
286 widgetData.mPopupHint = mPopupType;
287 widgetData.mNoAutoHide = IsNoAutoHide();
288
289 if (!mInContentShell) {
290 // A drag popup may be used for non-static translucent drag feedback
291 if (mPopupType == PopupType::Panel &&
292 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
293 nsGkAtoms::drag, eIgnoreCase)) {
294 widgetData.mIsDragPopup = true;
295 }
296 }
297
298 const bool remote = HasRemoteContent();
299
300 const auto mode = nsLayoutUtils::GetFrameTransparency(this, this);
301 widgetData.mHasRemoteContent = remote;
302 widgetData.mTransparencyMode = mode;
303 widgetData.mPopupLevel = GetPopupLevel(widgetData.mNoAutoHide);
304
305 nsCOMPtr<nsIWidget> parentWidget = ComputeParentWidget();
306 if (NS_WARN_IF(!parentWidget)NS_warn_if_impl(!parentWidget, "!parentWidget", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 306)
) {
307 return NS_ERROR_FAILURE;
308 }
309
310 nsresult rv = aView->CreateWidgetForPopup(&widgetData, parentWidget);
311 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
312 return rv;
313 }
314
315 nsIWidget* widget = aView->GetWidget();
316 MOZ_ASSERT(widget->GetParent() == parentWidget)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(widget->GetParent() == parentWidget)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(widget->GetParent() == parentWidget))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("widget->GetParent() == parentWidget"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 316); AnnotateMozCrashReason("MOZ_ASSERT" "(" "widget->GetParent() == parentWidget"
")"); do { *((volatile int*)__null) = 316; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
317
318 widget->SetTransparencyMode(mode);
319 PropagateStyleToWidget();
320
321 return NS_OK;
322}
323
324void nsMenuPopupFrame::PropagateStyleToWidget(WidgetStyleFlags aFlags) const {
325 if (aFlags.isEmpty()) {
326 return;
327 }
328
329 nsIWidget* widget = GetWidget();
330 if (!widget) {
331 return;
332 }
333
334 if (aFlags.contains(WidgetStyle::ColorScheme)) {
335 widget->SetColorScheme(Some(LookAndFeel::ColorSchemeForFrame(this)));
336 }
337 if (aFlags.contains(WidgetStyle::InputRegion)) {
338 widget->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
339 }
340 if (aFlags.contains(WidgetStyle::Opacity)) {
341 widget->SetWindowOpacity(StyleUIReset()->mWindowOpacity);
342 }
343 if (aFlags.contains(WidgetStyle::Shadow)) {
344 widget->SetWindowShadowStyle(GetShadowStyle());
345 }
346 if (aFlags.contains(WidgetStyle::Transform)) {
347 widget->SetWindowTransform(ComputeWidgetTransform());
348 }
349}
350
351bool nsMenuPopupFrame::IsMouseTransparent() const {
352 return ::IsMouseTransparent(*Style());
353}
354
355WindowShadow nsMenuPopupFrame::GetShadowStyle() const {
356 StyleWindowShadow shadow = StyleUIReset()->mWindowShadow;
357 if (shadow != StyleWindowShadow::Auto) {
358 MOZ_ASSERT(shadow == StyleWindowShadow::None)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(shadow == StyleWindowShadow::None)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(shadow == StyleWindowShadow::
None))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("shadow == StyleWindowShadow::None", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 358); AnnotateMozCrashReason("MOZ_ASSERT" "(" "shadow == StyleWindowShadow::None"
")"); do { *((volatile int*)__null) = 358; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
359 return WindowShadow::None;
360 }
361
362 switch (StyleDisplay()->EffectiveAppearance()) {
363 case StyleAppearance::Tooltip:
364 return WindowShadow::Tooltip;
365 case StyleAppearance::Menupopup:
366 return WindowShadow::Menu;
367 default:
368 return WindowShadow::Panel;
369 }
370}
371
372void nsMenuPopupFrame::SetPopupState(nsPopupState aState) {
373 mPopupState = aState;
374
375 // Work around https://gitlab.gnome.org/GNOME/gtk/-/issues/4166
376 if (aState == ePopupShown && IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay()) {
377 if (nsIWidget* widget = GetWidget()) {
378 widget->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
379 }
380 }
381}
382
383// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
384MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMPnsresult nsXULPopupShownEvent::Run() {
385 nsMenuPopupFrame* popup = do_QueryFrame(mPopup->GetPrimaryFrame());
386 // Set the state to visible if the popup is still open.
387 if (popup && popup->IsOpen()) {
388 popup->SetPopupState(ePopupShown);
389 }
390
391 if (!mPopup->IsXULElement(nsGkAtoms::tooltip)) {
392 nsCOMPtr<nsIObserverService> obsService =
393 mozilla::services::GetObserverService();
394 if (obsService) {
395 obsService->NotifyObservers(mPopup, "popup-shown", nullptr);
396 }
397 }
398 WidgetMouseEvent event(true, eXULPopupShown, nullptr,
399 WidgetMouseEvent::eReal);
400 return EventDispatcher::Dispatch(mPopup, mPresContext, &event);
401}
402
403NS_IMETHODIMPnsresult nsXULPopupShownEvent::HandleEvent(Event* aEvent) {
404 nsMenuPopupFrame* popup = do_QueryFrame(mPopup->GetPrimaryFrame());
405 // Ignore events not targeted at the popup itself (ie targeted at
406 // descendants):
407 if (mPopup != aEvent->GetTarget()) {
408 return NS_OK;
409 }
410 if (popup) {
411 // ResetPopupShownDispatcher will delete the reference to this, so keep
412 // another one until Run is finished.
413 RefPtr<nsXULPopupShownEvent> event = this;
414 // Only call Run if it the dispatcher was assigned. This avoids calling the
415 // Run method if the transitionend event fires multiple times.
416 if (popup->ClearPopupShownDispatcher()) {
417 return Run();
418 }
419 }
420
421 CancelListener();
422 return NS_OK;
423}
424
425void nsXULPopupShownEvent::CancelListener() {
426 mPopup->RemoveSystemEventListener(u"transitionend"_ns, this, false);
427}
428
429NS_IMPL_ISUPPORTS_INHERITED(nsXULPopupShownEvent, Runnable,nsresult nsXULPopupShownEvent::QueryInterface(const nsIID&
aIID, void** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 430); MOZ_PretendNoReturn(); } } while (0); nsresult rv = NS_ERROR_FAILURE
; static_assert(1 > 0, "Need more arguments to NS_INTERFACE_TABLE_INHERITED"
); static const QITableEntry table[] = { {&mozilla::detail
::kImplementedIID<nsXULPopupShownEvent, nsIDOMEventListener
>, int32_t( reinterpret_cast<char*>(static_cast<nsIDOMEventListener
*>((nsXULPopupShownEvent*)0x1000)) - reinterpret_cast<char
*>((nsXULPopupShownEvent*)0x1000))}, { nullptr, 0 } } ; static_assert
(std::size(table) > 1, "need at least 1 interface"); rv = NS_TableDrivenQI
(static_cast<void*>(this), aIID, aInstancePtr, table); if
(((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1)))) return
rv; return Runnable::QueryInterface(aIID, aInstancePtr); } MozExternalRefCountType
nsXULPopupShownEvent::AddRef(void) { static_assert(!std::is_destructible_v
<nsXULPopupShownEvent>, "Reference-counted class " "nsXULPopupShownEvent"
" should not have a public destructor. " "Make this class's destructor non-public"
); nsrefcnt r = Runnable::AddRef(); if constexpr (::mozilla::
detail::ShouldLogInheritedRefcnt<nsXULPopupShownEvent>)
{ NS_LogAddRef((this), (r), ("nsXULPopupShownEvent"), (uint32_t
)(sizeof(*this))); } return r; } MozExternalRefCountType nsXULPopupShownEvent
::Release(void) { nsrefcnt r = Runnable::Release(); if constexpr
(::mozilla::detail::ShouldLogInheritedRefcnt<nsXULPopupShownEvent
>) { NS_LogRelease((this), (r), ("nsXULPopupShownEvent"));
} return r; }
430 nsIDOMEventListener)nsresult nsXULPopupShownEvent::QueryInterface(const nsIID&
aIID, void** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 430); MOZ_PretendNoReturn(); } } while (0); nsresult rv = NS_ERROR_FAILURE
; static_assert(1 > 0, "Need more arguments to NS_INTERFACE_TABLE_INHERITED"
); static const QITableEntry table[] = { {&mozilla::detail
::kImplementedIID<nsXULPopupShownEvent, nsIDOMEventListener
>, int32_t( reinterpret_cast<char*>(static_cast<nsIDOMEventListener
*>((nsXULPopupShownEvent*)0x1000)) - reinterpret_cast<char
*>((nsXULPopupShownEvent*)0x1000))}, { nullptr, 0 } } ; static_assert
(std::size(table) > 1, "need at least 1 interface"); rv = NS_TableDrivenQI
(static_cast<void*>(this), aIID, aInstancePtr, table); if
(((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1)))) return
rv; return Runnable::QueryInterface(aIID, aInstancePtr); } MozExternalRefCountType
nsXULPopupShownEvent::AddRef(void) { static_assert(!std::is_destructible_v
<nsXULPopupShownEvent>, "Reference-counted class " "nsXULPopupShownEvent"
" should not have a public destructor. " "Make this class's destructor non-public"
); nsrefcnt r = Runnable::AddRef(); if constexpr (::mozilla::
detail::ShouldLogInheritedRefcnt<nsXULPopupShownEvent>)
{ NS_LogAddRef((this), (r), ("nsXULPopupShownEvent"), (uint32_t
)(sizeof(*this))); } return r; } MozExternalRefCountType nsXULPopupShownEvent
::Release(void) { nsrefcnt r = Runnable::Release(); if constexpr
(::mozilla::detail::ShouldLogInheritedRefcnt<nsXULPopupShownEvent
>) { NS_LogRelease((this), (r), ("nsXULPopupShownEvent"));
} return r; }
;
431
432void nsMenuPopupFrame::DidSetComputedStyle(ComputedStyle* aOldStyle) {
433 nsBlockFrame::DidSetComputedStyle(aOldStyle);
434
435 if (!aOldStyle) {
436 return;
437 }
438
439 WidgetStyleFlags flags;
440
441 if (aOldStyle->StyleUI()->mColorScheme != StyleUI()->mColorScheme) {
442 flags += WidgetStyle::ColorScheme;
443 }
444
445 auto& newUI = *StyleUIReset();
446 auto& oldUI = *aOldStyle->StyleUIReset();
447 if (newUI.mWindowOpacity != oldUI.mWindowOpacity) {
448 flags += WidgetStyle::Opacity;
449 }
450
451 if (newUI.mMozWindowTransform != oldUI.mMozWindowTransform) {
452 flags += WidgetStyle::Transform;
453 }
454
455 if (newUI.mWindowShadow != oldUI.mWindowShadow) {
456 flags += WidgetStyle::Shadow;
457 }
458
459 const auto& pc = *PresContext();
460 auto oldRegion = ComputeInputRegion(*aOldStyle, pc);
461 auto newRegion = ComputeInputRegion(*Style(), pc);
462 if (oldRegion.mFullyTransparent != newRegion.mFullyTransparent ||
463 oldRegion.mMargin != newRegion.mMargin) {
464 flags += WidgetStyle::InputRegion;
465 }
466
467 PropagateStyleToWidget(flags);
468}
469
470nscoord nsMenuPopupFrame::IntrinsicISize(const IntrinsicSizeInput& aInput,
471 IntrinsicISizeType aType) {
472 nscoord iSize = nsBlockFrame::IntrinsicISize(aInput, aType);
473 if (!ShouldExpandToInflowParentOrAnchor()) {
474 return iSize;
475 }
476 // Make sure to accommodate for our scrollbar if needed. Do it only for
477 // menulists to match previous behavior.
478 //
479 // NOTE(emilio): This is somewhat hacky. The "right" fix (which would be
480 // using scrollbar-gutter: stable on the scroller) isn't great, because even
481 // though we want a stable gutter, we want to draw on top of the gutter when
482 // there's no scrollbar, otherwise it looks rather weird.
483 //
484 // Automatically accommodating for the scrollbar otherwise would be bug
485 // 764076, but that has its own set of problems.
486 if (ScrollContainerFrame* sf = GetScrollContainerFrame()) {
487 iSize += sf->GetDesiredScrollbarSizes().LeftRight();
488 }
489
490 nscoord menuListOrAnchorWidth = 0;
491 if (nsIFrame* menuList = GetInFlowParent()) {
492 menuListOrAnchorWidth = menuList->GetRect().width;
493 }
494 if (mAnchorType == MenuPopupAnchorType::Rect) {
495 menuListOrAnchorWidth = std::max(menuListOrAnchorWidth, mScreenRect.width);
496 }
497 // Input margin doesn't have contents, so account for it for popup sizing
498 // purposes.
499 menuListOrAnchorWidth +=
500 2 * StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
501
502 return std::max(iSize, menuListOrAnchorWidth);
503}
504
505void nsMenuPopupFrame::Reflow(nsPresContext* aPresContext,
506 ReflowOutput& aDesiredSize,
507 const ReflowInput& aReflowInput,
508 nsReflowStatus& aStatus) {
509 MarkInReflow();
510 DO_GLOBAL_REFLOW_COUNT("nsMenuPopupFrame")aPresContext->CountReflows(("nsMenuPopupFrame"), (nsIFrame
*)this);
;
511 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStatus.IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStatus.IsEmpty()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aStatus.IsEmpty()"
" (" "Caller should pass a fresh reflow status!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 511); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 511; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
512
513 const auto wm = GetWritingMode();
514 // Default to preserving our bounds.
515 aDesiredSize.SetSize(wm, GetLogicalSize(wm));
516
517 LayoutPopup(aPresContext, aDesiredSize, aReflowInput, aStatus);
518
519 aDesiredSize.SetBlockStartAscent(aDesiredSize.BSize(wm));
520 aDesiredSize.SetOverflowAreasToDesiredBounds();
521 FinishAndStoreOverflow(&aDesiredSize, aReflowInput.mStyleDisplay);
522}
523
524void nsMenuPopupFrame::EnsureActiveMenuListItemIsVisible() {
525 if (!IsMenuList() || !IsOpen()) {
526 return;
527 }
528 nsIFrame* frame = GetCurrentMenuItemFrame();
529 if (!frame) {
530 return;
531 }
532 RefPtr<mozilla::PresShell> presShell = PresShell();
533 presShell->ScrollFrameIntoView(
534 frame, Nothing(), ScrollAxis(), ScrollAxis(),
535 ScrollFlags::ScrollOverflowHidden | ScrollFlags::ScrollFirstAncestorOnly);
536}
537
538void nsMenuPopupFrame::LayoutPopup(nsPresContext* aPresContext,
539 ReflowOutput& aDesiredSize,
540 const ReflowInput& aReflowInput,
541 nsReflowStatus& aStatus) {
542 if (IsNativeMenu()) {
543 return;
544 }
545
546 SchedulePaint();
547
548 const bool isOpen = IsOpen();
549 if (!isOpen) {
550 // If the popup is not open, only do layout while showing or if we're a
551 // menulist.
552 //
553 // This is needed because the SelectParent code wants to limit the height of
554 // the popup before opening it.
555 //
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();
560 if (!needsLayout) {
561 RemoveStateBits(NS_FRAME_FIRST_REFLOW);
562 return;
563 }
564 }
565
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();
569 if (needsPrefSize) {
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();
575 }
576
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();
580
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;
587
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) {
599 return true;
600 }
601 if (needsPrefSize &&
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.
606 return true;
607 }
608 return false;
609 }());
610
611 aStatus.Reset();
612 nsBlockFrame::Reflow(aPresContext, aDesiredSize, constrainedReflowInput,
613 aStatus);
614 }
615
616 // Set our size, since nsAbsoluteContainingBlock won't.
617 SetRect(constraints.mUsedRect);
618
619 nsView* view = GetView();
620 if (isOpen) {
621 nsViewManager* viewManager = view->GetViewManager();
622 viewManager->ResizeView(view,
623 nsRect(nsPoint(), constraints.mUsedRect.Size()));
624 if (mPopupState == ePopupOpening) {
625 mPopupState = ePopupVisible;
626 }
627
628 viewManager->SetViewVisibility(view, ViewVisibility::Show);
629 SyncFrameViewProperties(view);
630 }
631
632 // Perform our move now. That will position the view and so on.
633 PerformMove(constraints);
634
635 // finally, if the popup just opened, send a popupshown event
636 bool openChanged = mIsOpenChanged;
637 if (openChanged) {
638 mIsOpenChanged = false;
639
640 // Make sure the current selection in a menulist is visible.
641 EnsureActiveMenuListItemIsVisible();
642
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,
648 eCaseMatters) &&
649 AnimationUtils::HasCurrentTransitions(mContent->AsElement())) {
650 mPopupShownDispatcher = new nsXULPopupShownEvent(mContent, aPresContext);
651 mContent->AddSystemEventListener(u"transitionend"_ns,
652 mPopupShownDispatcher, false, false);
653 return;
654 }
655
656 // If there are no transitions, fire the popupshown event right away.
657 nsCOMPtr<nsIRunnable> event =
658 new nsXULPopupShownEvent(GetContent(), aPresContext);
659 mContent->OwnerDoc()->Dispatch(event.forget());
660 }
661}
662
663bool nsMenuPopupFrame::IsMenuList() const {
664 return PopupElement().IsInMenuList();
665}
666
667bool nsMenuPopupFrame::ShouldExpandToInflowParentOrAnchor() const {
668 return IsMenuList() && !mContent->GetParent()->AsElement()->AttrValueIs(
669 kNameSpaceID_None, nsGkAtoms::sizetopopup,
670 nsGkAtoms::none, eCaseMatters);
671}
672
673nsIContent* nsMenuPopupFrame::GetTriggerContent(
674 nsMenuPopupFrame* aMenuPopupFrame) {
675 while (aMenuPopupFrame) {
676 if (aMenuPopupFrame->mTriggerContent) {
677 return aMenuPopupFrame->mTriggerContent;
678 }
679
680 auto* button = XULButtonElement::FromNodeOrNull(
681 aMenuPopupFrame->GetContent()->GetParent());
682 if (!button || !button->IsMenu()) {
683 break;
684 }
685
686 auto* popup = button->GetContainingPopupElement();
687 if (!popup) {
688 break;
689 }
690
691 // check up the menu hierarchy until a popup with a trigger node is found
692 aMenuPopupFrame = do_QueryFrame(popup->GetPrimaryFrame());
693 }
694
695 return nullptr;
696}
697
698void nsMenuPopupFrame::InitPositionFromAnchorAlign(const nsAString& aAnchor,
699 const nsAString& aAlign) {
700 mTriggerContent = nullptr;
701
702 if (aAnchor.EqualsLiteral("topleft")) {
703 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
704 } else if (aAnchor.EqualsLiteral("topright")) {
705 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
706 } else if (aAnchor.EqualsLiteral("bottomleft")) {
707 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
708 } else if (aAnchor.EqualsLiteral("bottomright")) {
709 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
710 } else if (aAnchor.EqualsLiteral("leftcenter")) {
711 mPopupAnchor = POPUPALIGNMENT_LEFTCENTER16;
712 } else if (aAnchor.EqualsLiteral("rightcenter")) {
713 mPopupAnchor = POPUPALIGNMENT_RIGHTCENTER-16;
714 } else if (aAnchor.EqualsLiteral("topcenter")) {
715 mPopupAnchor = POPUPALIGNMENT_TOPCENTER17;
716 } else if (aAnchor.EqualsLiteral("bottomcenter")) {
717 mPopupAnchor = POPUPALIGNMENT_BOTTOMCENTER18;
718 } else {
719 mPopupAnchor = POPUPALIGNMENT_NONE0;
720 }
721
722 if (aAlign.EqualsLiteral("topleft")) {
723 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
724 } else if (aAlign.EqualsLiteral("topright")) {
725 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
726 } else if (aAlign.EqualsLiteral("bottomleft")) {
727 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
728 } else if (aAlign.EqualsLiteral("bottomright")) {
729 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
730 } else if (aAlign.EqualsLiteral("leftcenter")) {
731 mPopupAlignment = POPUPALIGNMENT_LEFTCENTER16;
732 } else if (aAlign.EqualsLiteral("rightcenter")) {
733 mPopupAlignment = POPUPALIGNMENT_RIGHTCENTER-16;
734 } else if (aAlign.EqualsLiteral("topcenter")) {
735 mPopupAlignment = POPUPALIGNMENT_TOPCENTER17;
736 } else if (aAlign.EqualsLiteral("bottomcenter")) {
737 mPopupAlignment = POPUPALIGNMENT_BOTTOMCENTER18;
738 } else {
739 mPopupAlignment = POPUPALIGNMENT_NONE0;
740 }
741
742 mPosition = POPUPPOSITION_UNKNOWN-1;
743}
744
745static FlipType FlipFromAttribute(nsMenuPopupFrame* aFrame) {
746 nsAutoString flip;
747 aFrame->PopupElement().GetAttr(nsGkAtoms::flip, flip);
748 if (flip.EqualsLiteral("none")) {
749 return FlipType_None;
750 }
751 if (flip.EqualsLiteral("both")) {
752 return FlipType_Both;
753 }
754 if (flip.EqualsLiteral("slide")) {
755 return FlipType_Slide;
756 }
757 return FlipType_Default;
758}
759
760void nsMenuPopupFrame::InitializePopup(nsIContent* aAnchorContent,
761 nsIContent* aTriggerContent,
762 const nsAString& aPosition,
763 int32_t aXPos, int32_t aYPos,
764 MenuPopupAnchorType aAnchorType,
765 bool aAttributesOverride) {
766 PrepareWidget();
767
768 mPopupState = ePopupShowing;
769 mAnchorContent = aAnchorContent;
770 mAnchorType = aAnchorType;
771 const nscoord auPerCssPx = AppUnitsPerCSSPixel();
772 const nsPoint pos = CSSPixel::ToAppUnits(CSSIntPoint(aXPos, aYPos));
773 // When converted back to CSSIntRect it is (-1, -1, 0, 0) - as expected in
774 // nsXULPopupManager::Rollup
775 mScreenRect = nsRect(-auPerCssPx, -auPerCssPx, 0, 0);
776 mExtraMargin = pos;
777 // If we have no anchor node, anchor to the given position instead.
778 if (mAnchorType == MenuPopupAnchorType::Node && !aAnchorContent) {
779 mAnchorType = MenuPopupAnchorType::Point;
780 mScreenRect = nsRect(
781 pos + PresShell()->GetRootFrame()->GetScreenRectInAppUnits().TopLeft(),
782 nsSize());
783 mExtraMargin = {};
784 }
785 mTriggerContent = aTriggerContent;
786 mIsNativeMenu = false;
787 mIsTopLevelContextMenu = false;
788 mVFlip = false;
789 mHFlip = false;
790 mConstrainedByLayout = false;
791 mAlignmentOffset = 0;
792 mPositionedOffset = 0;
793 mPositionedByMoveToRect = false;
794
795 // if aAttributesOverride is true, then the popupanchor, popupalign and
796 // position attributes on the <menupopup> override those values passed in.
797 // If false, those attributes are only used if the values passed in are empty
798 if (aAnchorContent || aAnchorType == MenuPopupAnchorType::Rect) {
799 nsAutoString anchor, align, position;
800 mContent->AsElement()->GetAttr(nsGkAtoms::popupanchor, anchor);
801 mContent->AsElement()->GetAttr(nsGkAtoms::popupalign, align);
802 mContent->AsElement()->GetAttr(nsGkAtoms::position, position);
803
804 if (aAttributesOverride) {
805 // if the attributes are set, clear the offset position. Otherwise,
806 // the offset is used to adjust the position from the anchor point
807 if (anchor.IsEmpty() && align.IsEmpty() && position.IsEmpty()) {
808 position.Assign(aPosition);
809 }
810 } else if (!aPosition.IsEmpty()) {
811 position.Assign(aPosition);
812 }
813
814 mFlip = FlipFromAttribute(this);
815
816 position.CompressWhitespace();
817 int32_t spaceIdx = position.FindChar(' ');
818 // if there is a space in the position, assume it is the anchor and
819 // alignment as two separate tokens.
820 if (spaceIdx >= 0) {
821 InitPositionFromAnchorAlign(Substring(position, 0, spaceIdx),
822 Substring(position, spaceIdx + 1));
823 } else if (position.EqualsLiteral("before_start")) {
824 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
825 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
826 mPosition = POPUPPOSITION_BEFORESTART0;
827 } else if (position.EqualsLiteral("before_end")) {
828 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
829 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
830 mPosition = POPUPPOSITION_BEFOREEND1;
831 } else if (position.EqualsLiteral("after_start")) {
832 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
833 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
834 mPosition = POPUPPOSITION_AFTERSTART2;
835 } else if (position.EqualsLiteral("after_end")) {
836 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
837 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
838 mPosition = POPUPPOSITION_AFTEREND3;
839 } else if (position.EqualsLiteral("start_before")) {
840 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
841 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
842 mPosition = POPUPPOSITION_STARTBEFORE4;
843 } else if (position.EqualsLiteral("start_after")) {
844 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
845 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
846 mPosition = POPUPPOSITION_STARTAFTER6;
847 } else if (position.EqualsLiteral("end_before")) {
848 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
849 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
850 mPosition = POPUPPOSITION_ENDBEFORE5;
851 } else if (position.EqualsLiteral("end_after")) {
852 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
853 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
854 mPosition = POPUPPOSITION_ENDAFTER7;
855 } else if (position.EqualsLiteral("overlap")) {
856 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
857 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
858 mPosition = POPUPPOSITION_OVERLAP8;
859 } else if (position.EqualsLiteral("selection")) {
860 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
861 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
862 mPosition = POPUPPOSITION_SELECTION10;
863 } else {
864 InitPositionFromAnchorAlign(anchor, align);
865 }
866 }
867
868 if (aAttributesOverride) {
869 // Use |left| and |top| dimension attributes to position the popup if
870 // present, as they may have been persisted.
871 nsAutoString left, top;
872 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
873 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
874
875 nsresult err;
876 if (!left.IsEmpty()) {
877 int32_t x = left.ToInteger(&err);
878 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
879 mScreenRect.x = CSSPixel::ToAppUnits(x);
880 }
881 }
882 if (!top.IsEmpty()) {
883 int32_t y = top.ToInteger(&err);
884 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
885 mScreenRect.y = CSSPixel::ToAppUnits(y);
886 }
887 }
888 }
889}
890
891void nsMenuPopupFrame::InitializePopupAtScreen(nsIContent* aTriggerContent,
892 int32_t aXPos, int32_t aYPos,
893 bool aIsContextMenu) {
894 PrepareWidget();
895
896 mPopupState = ePopupShowing;
897 mAnchorContent = nullptr;
898 mTriggerContent = aTriggerContent;
899 mScreenRect =
900 nsRect(CSSPixel::ToAppUnits(CSSIntPoint(aXPos, aYPos)), nsSize());
901 mExtraMargin = {};
902 mFlip = FlipFromAttribute(this);
903 mPopupAnchor = POPUPALIGNMENT_NONE0;
904 mPopupAlignment = POPUPALIGNMENT_NONE0;
905 mPosition = POPUPPOSITION_UNKNOWN-1;
906 mIsContextMenu = aIsContextMenu;
907 mIsTopLevelContextMenu = aIsContextMenu;
908 mIsNativeMenu = false;
909 mAnchorType = MenuPopupAnchorType::Point;
910 mPositionedOffset = 0;
911 mPositionedByMoveToRect = false;
912}
913
914void nsMenuPopupFrame::InitializePopupAsNativeContextMenu(
915 nsIContent* aTriggerContent, int32_t aXPos, int32_t aYPos) {
916 mTriggerContent = aTriggerContent;
917 mPopupState = ePopupShowing;
918 mAnchorContent = nullptr;
919 mScreenRect =
920 nsRect(CSSPixel::ToAppUnits(CSSIntPoint(aXPos, aYPos)), nsSize());
921 mExtraMargin = {};
922 mFlip = FlipType_Default;
923 mPopupAnchor = POPUPALIGNMENT_NONE0;
924 mPopupAlignment = POPUPALIGNMENT_NONE0;
925 mPosition = POPUPPOSITION_UNKNOWN-1;
926 mIsContextMenu = true;
927 mIsTopLevelContextMenu = true;
928 mIsNativeMenu = true;
929 mAnchorType = MenuPopupAnchorType::Point;
930 mPositionedOffset = 0;
931 mPositionedByMoveToRect = false;
932}
933
934void nsMenuPopupFrame::InitializePopupAtRect(nsIContent* aTriggerContent,
935 const nsAString& aPosition,
936 const nsIntRect& aRect,
937 bool aAttributesOverride) {
938 InitializePopup(nullptr, aTriggerContent, aPosition, 0, 0,
939 MenuPopupAnchorType::Rect, aAttributesOverride);
940 mScreenRect = ToAppUnits(aRect, AppUnitsPerCSSPixel());
941}
942
943void nsMenuPopupFrame::ShowPopup(bool aIsContextMenu) {
944 mIsContextMenu = aIsContextMenu;
945
946 InvalidateFrameSubtree();
947
948 if (mPopupState == ePopupShowing || mPopupState == ePopupPositioning) {
949 mPopupState = ePopupOpening;
950 mIsOpenChanged = true;
951
952 // Clear mouse capture when a popup is opened.
953 if (mPopupType == PopupType::Menu) {
954 if (auto* activeESM = EventStateManager::GetActiveEventStateManager()) {
955 EventStateManager::ClearGlobalActiveContent(activeESM);
956 }
957
958 PresShell::ReleaseCapturingContent();
959 }
960
961 if (RefPtr menu = PopupElement().GetContainingMenu()) {
962 menu->PopupOpened();
963 }
964
965 // We skip laying out children if we're closed, so make sure that we do a
966 // full dirty reflow when opening to pick up any potential change.
967 PresShell()->FrameNeedsReflow(
968 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
969
970 if (mPopupType == PopupType::Menu) {
971 nsCOMPtr<nsISound> sound(do_GetService("@mozilla.org/sound;1"));
972 if (sound) {
973 sound->PlayEventSound(nsISound::EVENT_MENU_POPUP);
974 }
975 }
976 }
977}
978
979void nsMenuPopupFrame::ClearTriggerContentIncludingDocument() {
980 // clear the trigger content if the popup is being closed. But don't clear
981 // it if the popup is just being made invisible as a popuphiding or command
982 if (mTriggerContent) {
983 // if the popup had a trigger node set, clear the global window popup node
984 // as well
985 Document* doc = mContent->GetUncomposedDoc();
986 if (doc) {
987 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
988 nsCOMPtr<nsPIWindowRoot> root = win->GetTopWindowRoot();
989 if (root) {
990 root->SetPopupNode(nullptr);
991 }
992 }
993 }
994 }
995 mTriggerContent = nullptr;
996}
997
998void nsMenuPopupFrame::HidePopup(bool aDeselectMenu, nsPopupState aNewState,
999 bool aFromFrameDestruction) {
1000 NS_ASSERTION(aNewState == ePopupClosed || aNewState == ePopupInvisible,do { if (!(aNewState == ePopupClosed || aNewState == ePopupInvisible
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "popup being set to unexpected state"
, "aNewState == ePopupClosed || aNewState == ePopupInvisible"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1001); MOZ_PretendNoReturn(); } } while (0)
1001 "popup being set to unexpected state")do { if (!(aNewState == ePopupClosed || aNewState == ePopupInvisible
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "popup being set to unexpected state"
, "aNewState == ePopupClosed || aNewState == ePopupInvisible"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1001); MOZ_PretendNoReturn(); } } while (0)
;
1002
1003 ClearPopupShownDispatcher();
1004
1005 // don't hide the popup when it isn't open
1006 if (mPopupState == ePopupClosed || mPopupState == ePopupShowing ||
1007 mPopupState == ePopupPositioning) {
1008 return;
1009 }
1010
1011 if (aNewState == ePopupClosed) {
1012 // clear the trigger content if the popup is being closed. But don't clear
1013 // it if the popup is just being made invisible as a popuphiding or command
1014 // event may want to retrieve it.
1015 ClearTriggerContentIncludingDocument();
1016 mAnchorContent = nullptr;
1017 }
1018
1019 // when invisible and about to be closed, HidePopup has already been called,
1020 // so just set the new state to closed and return
1021 if (mPopupState == ePopupInvisible) {
1022 if (aNewState == ePopupClosed) {
1023 mPopupState = ePopupClosed;
1024 }
1025 return;
1026 }
1027
1028 mPopupState = aNewState;
1029
1030 mIncrementalString.Truncate();
1031
1032 mIsOpenChanged = false;
1033 mHFlip = mVFlip = false;
1034 mConstrainedByLayout = false;
1035
1036 if (auto* widget = GetWidget()) {
1037 // Ideally we should call ClearCachedWebrenderResources but there are
1038 // intermittent failures (see bug 1748788), so we currently call
1039 // ClearWebrenderAnimationResources instead.
1040 widget->ClearWebrenderAnimationResources();
1041 }
1042
1043 nsView* view = GetView();
1044 nsViewManager* viewManager = view->GetViewManager();
1045 viewManager->SetViewVisibility(view, ViewVisibility::Hide);
1046
1047 RefPtr popup = &PopupElement();
1048 // XXX, bug 137033, In Windows, if mouse is outside the window when the
1049 // menupopup closes, no mouse_enter/mouse_exit event will be fired to clear
1050 // current hover state, we should clear it manually. This code may not the
1051 // best solution, but we can leave it here until we find the better approach.
1052 if (!aFromFrameDestruction &&
1053 popup->State().HasState(dom::ElementState::HOVER)) {
1054 EventStateManager* esm = PresContext()->EventStateManager();
1055 esm->SetContentState(nullptr, dom::ElementState::HOVER);
1056 }
1057 popup->PopupClosed(aDeselectMenu);
1058}
1059
1060nsPoint nsMenuPopupFrame::AdjustPositionForAnchorAlign(
1061 nsRect& anchorRect, const nsSize& aPrefSize, FlipStyle& aHFlip,
1062 FlipStyle& aVFlip) const {
1063 // flip the anchor and alignment for right-to-left
1064 int8_t popupAnchor(mPopupAnchor);
1065 int8_t popupAlign(mPopupAlignment);
1066 if (IsDirectionRTL()) {
1067 // no need to flip the centered anchor types vertically
1068 if (popupAnchor <= POPUPALIGNMENT_LEFTCENTER16) {
1069 popupAnchor = -popupAnchor;
1070 }
1071 popupAlign = -popupAlign;
1072 }
1073
1074 nsRect originalAnchorRect(anchorRect);
1075
1076 // first, determine at which corner of the anchor the popup should appear
1077 nsPoint pnt;
1078 switch (popupAnchor) {
1079 case POPUPALIGNMENT_LEFTCENTER16:
1080 pnt = nsPoint(anchorRect.x, anchorRect.y + anchorRect.height / 2);
1081 anchorRect.y = pnt.y;
1082 anchorRect.height = 0;
1083 break;
1084 case POPUPALIGNMENT_RIGHTCENTER-16:
1085 pnt = nsPoint(anchorRect.XMost(), anchorRect.y + anchorRect.height / 2);
1086 anchorRect.y = pnt.y;
1087 anchorRect.height = 0;
1088 break;
1089 case POPUPALIGNMENT_TOPCENTER17:
1090 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.y);
1091 anchorRect.x = pnt.x;
1092 anchorRect.width = 0;
1093 break;
1094 case POPUPALIGNMENT_BOTTOMCENTER18:
1095 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.YMost());
1096 anchorRect.x = pnt.x;
1097 anchorRect.width = 0;
1098 break;
1099 case POPUPALIGNMENT_TOPRIGHT-1:
1100 pnt = anchorRect.TopRight();
1101 break;
1102 case POPUPALIGNMENT_BOTTOMLEFT2:
1103 pnt = anchorRect.BottomLeft();
1104 break;
1105 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1106 pnt = anchorRect.BottomRight();
1107 break;
1108 case POPUPALIGNMENT_TOPLEFT1:
1109 default:
1110 pnt = anchorRect.TopLeft();
1111 break;
1112 }
1113
1114 // If the alignment is on the right edge of the popup, move the popup left
1115 // by the width. Similarly, if the alignment is on the bottom edge of the
1116 // popup, move the popup up by the height. In addition, account for the
1117 // margins of the popup on the edge on which it is aligned.
1118 nsMargin margin = GetMargin();
1119 switch (popupAlign) {
1120 case POPUPALIGNMENT_LEFTCENTER16:
1121 pnt.MoveBy(margin.left, -aPrefSize.height / 2);
1122 break;
1123 case POPUPALIGNMENT_RIGHTCENTER-16:
1124 pnt.MoveBy(-aPrefSize.width - margin.right, -aPrefSize.height / 2);
1125 break;
1126 case POPUPALIGNMENT_TOPCENTER17:
1127 pnt.MoveBy(-aPrefSize.width / 2, margin.top);
1128 break;
1129 case POPUPALIGNMENT_BOTTOMCENTER18:
1130 pnt.MoveBy(-aPrefSize.width / 2, -aPrefSize.height - margin.bottom);
1131 break;
1132 case POPUPALIGNMENT_TOPRIGHT-1:
1133 pnt.MoveBy(-aPrefSize.width - margin.right, margin.top);
1134 break;
1135 case POPUPALIGNMENT_BOTTOMLEFT2:
1136 pnt.MoveBy(margin.left, -aPrefSize.height - margin.bottom);
1137 break;
1138 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1139 pnt.MoveBy(-aPrefSize.width - margin.right,
1140 -aPrefSize.height - margin.bottom);
1141 break;
1142 case POPUPALIGNMENT_TOPLEFT1:
1143 default:
1144 pnt.MoveBy(margin.left, margin.top);
1145 break;
1146 }
1147
1148 // If we aligning to the selected item in the popup, adjust the vertical
1149 // position by the height of the menulist label and the selected item's
1150 // position.
1151 if (mPosition == POPUPPOSITION_SELECTION10) {
1152 MOZ_ASSERT(popupAnchor == POPUPALIGNMENT_BOTTOMLEFT ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(popupAnchor == 2 || popupAnchor == -2)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(popupAnchor == 2 || popupAnchor == -2))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("popupAnchor == 2 || popupAnchor == -2"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1153); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1153; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1153 popupAnchor == POPUPALIGNMENT_BOTTOMRIGHT)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(popupAnchor == 2 || popupAnchor == -2)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(popupAnchor == 2 || popupAnchor == -2))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("popupAnchor == 2 || popupAnchor == -2"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1153); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1153; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1154 MOZ_ASSERT(popupAlign == POPUPALIGNMENT_TOPLEFT ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(popupAlign == 1 || popupAlign == -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(popupAlign == 1 || popupAlign
== -1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("popupAlign == 1 || popupAlign == -1", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1155); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1155; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1155 popupAlign == POPUPALIGNMENT_TOPRIGHT)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(popupAlign == 1 || popupAlign == -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(popupAlign == 1 || popupAlign
== -1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("popupAlign == 1 || popupAlign == -1", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1155); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1155; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1156
1157 // Only adjust the popup if it just opened, otherwise the popup will move
1158 // around if its gets resized or the selection changed. Cache the value in
1159 // mPositionedOffset and use that instead for any future calculations.
1160 if (mIsOpenChanged) {
1161 if (nsIFrame* selectedItemFrame = GetSelectedItemForAlignment()) {
1162 const nscoord itemHeight = selectedItemFrame->GetRect().height;
1163 const nscoord itemOffset =
1164 selectedItemFrame->GetOffsetToIgnoringScrolling(this).y;
1165 // We want to line-up the anchor rect with the selected item, but if the
1166 // selected item is outside of our bounds, we don't want to shift the
1167 // popup up in a way that our box would no longer intersect with the
1168 // anchor.
1169 nscoord maxOffset = aPrefSize.height - itemHeight;
1170 if (const ScrollContainerFrame* sf = GetScrollContainerFrame()) {
1171 // HACK: We ideally would want to use the offset from the bottom
1172 // bottom of our scroll-frame to the bottom of our frame (so as to
1173 // ensure that the bottom of the scrollport is inside the anchor
1174 // rect).
1175 //
1176 // But at this point of the code, the scroll frame may not be laid out
1177 // with a definite size (might be overflowing us).
1178 //
1179 // So, we assume the offset from the bottom is symmetric to the offset
1180 // from the top. This holds for all the popups where this matters
1181 // (menulists on macOS, effectively), and seems better than somehow
1182 // moving the popup after the fact as we used to do.
1183 maxOffset -= sf->GetOffsetTo(this).y;
1184 }
1185 mPositionedOffset =
1186 originalAnchorRect.height + std::min(itemOffset, maxOffset);
1187 }
1188 }
1189
1190 pnt.y -= mPositionedOffset;
1191 }
1192
1193 // Flipping horizontally is allowed as long as the popup is above or below
1194 // the anchor. This will happen if both the anchor and alignment are top or
1195 // both are bottom, but different values. Similarly, flipping vertically is
1196 // allowed if the popup is to the left or right of the anchor. In this case,
1197 // the values of the constants are such that both must be positive or both
1198 // must be negative. A special case, used for overlap, allows flipping
1199 // vertically as well.
1200 // If we are flipping in both directions, we want to set a flip style both
1201 // horizontally and vertically. However, we want to flip on the inside edge
1202 // of the anchor. Consider the example of a typical dropdown menu.
1203 // Vertically, we flip the popup on the outside edges of the anchor menu,
1204 // however horizontally, we want to to use the inside edges so the popup
1205 // still appears underneath the anchor menu instead of floating off the
1206 // side of the menu.
1207 switch (popupAnchor) {
1208 case POPUPALIGNMENT_LEFTCENTER16:
1209 case POPUPALIGNMENT_RIGHTCENTER-16:
1210 aHFlip = FlipStyle_Outside;
1211 aVFlip = FlipStyle_Inside;
1212 break;
1213 case POPUPALIGNMENT_TOPCENTER17:
1214 case POPUPALIGNMENT_BOTTOMCENTER18:
1215 aHFlip = FlipStyle_Inside;
1216 aVFlip = FlipStyle_Outside;
1217 break;
1218 default: {
1219 FlipStyle anchorEdge =
1220 mFlip == FlipType_Both ? FlipStyle_Inside : FlipStyle_None;
1221 aHFlip = (popupAnchor == -popupAlign) ? FlipStyle_Outside : anchorEdge;
1222 if (((popupAnchor > 0) == (popupAlign > 0)) ||
1223 (popupAnchor == POPUPALIGNMENT_TOPLEFT1 &&
1224 popupAlign == POPUPALIGNMENT_TOPLEFT1)) {
1225 aVFlip = FlipStyle_Outside;
1226 } else {
1227 aVFlip = anchorEdge;
1228 }
1229 break;
1230 }
1231 }
1232
1233 return pnt;
1234}
1235
1236nsIFrame* nsMenuPopupFrame::GetSelectedItemForAlignment() const {
1237 // This method adjusts a menulist's popup such that the selected item is under
1238 // the cursor, aligned with the menulist label.
1239 nsCOMPtr<nsIDOMXULSelectControlElement> select;
1240 if (mAnchorContent) {
1241 select = mAnchorContent->AsElement()->AsXULSelectControl();
1242 }
1243
1244 if (!select) {
1245 // If there isn't an anchor, then try just getting the parent of the popup.
1246 select = mContent->GetParent()->AsElement()->AsXULSelectControl();
1247 if (!select) {
1248 return nullptr;
1249 }
1250 }
1251
1252 nsCOMPtr<Element> selectedElement;
1253 select->GetSelectedItem(getter_AddRefs(selectedElement));
1254 return selectedElement ? selectedElement->GetPrimaryFrame() : nullptr;
1255}
1256
1257nscoord nsMenuPopupFrame::SlideOrResize(nscoord& aScreenPoint, nscoord aSize,
1258 nscoord aScreenBegin,
1259 nscoord aScreenEnd,
1260 nscoord* aOffset) const {
1261 // The popup may be positioned such that either the left/top or bottom/right
1262 // is outside the screen - but never both.
1263 nscoord newPos =
1264 std::max(aScreenBegin, std::min(aScreenEnd - aSize, aScreenPoint));
1265 *aOffset = newPos - aScreenPoint;
1266 aScreenPoint = newPos;
1267 return std::min(aSize, aScreenEnd - aScreenPoint);
1268}
1269
1270nscoord nsMenuPopupFrame::FlipOrResize(nscoord& aScreenPoint, nscoord aSize,
1271 nscoord aScreenBegin, nscoord aScreenEnd,
1272 nscoord aAnchorBegin, nscoord aAnchorEnd,
1273 nscoord aMarginBegin, nscoord aMarginEnd,
1274 FlipStyle aFlip, bool aEndAligned,
1275 bool* aFlipSide) const {
1276 // The flip side argument will be set to true if there wasn't room and we
1277 // flipped to the opposite side.
1278 *aFlipSide = false;
1279
1280 // all of the coordinates used here are in app units relative to the screen
1281 nscoord popupSize = aSize;
1282 if (aScreenPoint < aScreenBegin) {
1283 // at its current position, the popup would extend past the left or top
1284 // edge of the screen, so it will have to be moved or resized.
1285 if (aFlip) {
1286 // for inside flips, we flip on the opposite side of the anchor
1287 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1288 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1289
1290 // check whether there is more room to the left and right (or top and
1291 // bottom) of the anchor and put the popup on the side with more room.
1292 if (startpos - aScreenBegin >= aScreenEnd - endpos) {
1293 aScreenPoint = aScreenBegin;
1294 popupSize = startpos - aScreenPoint - aMarginEnd;
1295 *aFlipSide = !aEndAligned;
1296 } else {
1297 // If the newly calculated position is different than the existing
1298 // position, flip such that the popup is to the right or bottom of the
1299 // anchor point instead . However, when flipping use the same margin
1300 // size.
1301 nscoord newScreenPoint = endpos + aMarginEnd;
1302 if (newScreenPoint != aScreenPoint) {
1303 *aFlipSide = aEndAligned;
1304 aScreenPoint = newScreenPoint;
1305 // check if the new position is still off the right or bottom edge of
1306 // the screen. If so, resize the popup.
1307 if (aScreenPoint + aSize > aScreenEnd) {
1308 popupSize = aScreenEnd - aScreenPoint;
1309 }
1310 }
1311 }
1312 } else {
1313 aScreenPoint = aScreenBegin;
1314 }
1315 } else if (aScreenPoint + aSize > aScreenEnd) {
1316 // at its current position, the popup would extend past the right or
1317 // bottom edge of the screen, so it will have to be moved or resized.
1318 if (aFlip) {
1319 // for inside flips, we flip on the opposite side of the anchor
1320 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1321 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1322
1323 // check whether there is more room to the left and right (or top and
1324 // bottom) of the anchor and put the popup on the side with more room.
1325 if (aScreenEnd - endpos >= startpos - aScreenBegin) {
1326 *aFlipSide = aEndAligned;
1327 if (mIsContextMenu) {
1328 aScreenPoint = aScreenEnd - aSize;
1329 } else {
1330 aScreenPoint = endpos + aMarginBegin;
1331 popupSize = aScreenEnd - aScreenPoint;
1332 }
1333 } else {
1334 // if the newly calculated position is different than the existing
1335 // position, we flip such that the popup is to the left or top of the
1336 // anchor point instead.
1337 nscoord newScreenPoint = startpos - aSize - aMarginBegin;
1338 if (newScreenPoint != aScreenPoint) {
1339 *aFlipSide = !aEndAligned;
1340 aScreenPoint = newScreenPoint;
1341
1342 // check if the new position is still off the left or top edge of the
1343 // screen. If so, resize the popup.
1344 if (aScreenPoint < aScreenBegin) {
1345 aScreenPoint = aScreenBegin;
1346 if (!mIsContextMenu) {
1347 popupSize = startpos - aScreenPoint - aMarginBegin;
1348 }
1349 }
1350 }
1351 }
1352 } else {
1353 aScreenPoint = aScreenEnd - aSize;
1354 }
1355 }
1356
1357 // Make sure that the point is within the screen boundaries and that the
1358 // size isn't off the edge of the screen. This can happen when a large
1359 // positive or negative margin is used.
1360 if (aScreenPoint < aScreenBegin) {
1361 aScreenPoint = aScreenBegin;
1362 }
1363 if (aScreenPoint > aScreenEnd) {
1364 aScreenPoint = aScreenEnd - aSize;
1365 }
1366
1367 // If popupSize ended up being negative, or the original size was actually
1368 // smaller than the calculated popup size, just use the original size instead.
1369 if (popupSize <= 0 || aSize < popupSize) {
1370 popupSize = aSize;
1371 }
1372
1373 return std::min(popupSize, aScreenEnd - aScreenPoint);
1374}
1375
1376nsRect nsMenuPopupFrame::ComputeAnchorRect(nsPresContext* aRootPresContext,
1377 nsIFrame* aAnchorFrame) const {
1378 // Get the root frame for a reference
1379 nsIFrame* rootFrame = aRootPresContext->PresShell()->GetRootFrame();
1380
1381 // The dimensions of the anchor
1382 nsRect anchorRect = aAnchorFrame->GetRectRelativeToSelf();
1383
1384 // Relative to the root
1385 anchorRect = nsLayoutUtils::TransformFrameRectToAncestor(
1386 aAnchorFrame, anchorRect, rootFrame);
1387 // Relative to the screen
1388 anchorRect.MoveBy(rootFrame->GetScreenRectInAppUnits().TopLeft());
1389
1390 // In its own app units
1391 return anchorRect.ScaleToOtherAppUnitsRoundOut(
1392 aRootPresContext->AppUnitsPerDevPixel(),
1393 PresContext()->AppUnitsPerDevPixel());
1394}
1395
1396static nsIFrame* MaybeDelegatedAnchorFrame(nsIFrame* aFrame) {
1397 if (!aFrame) {
1398 return nullptr;
1399 }
1400 if (auto* element = Element::FromNodeOrNull(aFrame->GetContent())) {
1401 if (element->HasAttr(nsGkAtoms::delegatesanchor)) {
1402 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1403 if (!f->IsPlaceholderFrame()) {
1404 return f;
1405 }
1406 }
1407 }
1408 }
1409 return aFrame;
1410}
1411
1412auto nsMenuPopupFrame::GetRects(const nsSize& aPrefSize) const -> Rects {
1413 if (NS_WARN_IF(aPrefSize == nsSize(-1, -1))NS_warn_if_impl(aPrefSize == nsSize(-1, -1), "aPrefSize == nsSize(-1, -1)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1413)
) {
1414 // Return early if the popup hasn't been laid out yet. On Windows, this can
1415 // happen when using a drag popup before it opens.
1416 return {};
1417 }
1418
1419 nsPresContext* pc = PresContext();
1420 nsIFrame* rootFrame = pc->PresShell()->GetRootFrame();
1421 NS_ASSERTION(rootFrame->GetView() && GetView() &&do { if (!(rootFrame->GetView() && GetView() &&
rootFrame->GetView() == GetView()->GetParent())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "rootFrame's view is not our view's parent???"
, "rootFrame->GetView() && GetView() && rootFrame->GetView() == GetView()->GetParent()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1423); MOZ_PretendNoReturn(); } } while (0)
1422 rootFrame->GetView() == GetView()->GetParent(),do { if (!(rootFrame->GetView() && GetView() &&
rootFrame->GetView() == GetView()->GetParent())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "rootFrame's view is not our view's parent???"
, "rootFrame->GetView() && GetView() && rootFrame->GetView() == GetView()->GetParent()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1423); MOZ_PretendNoReturn(); } } while (0)
1423 "rootFrame's view is not our view's parent???")do { if (!(rootFrame->GetView() && GetView() &&
rootFrame->GetView() == GetView()->GetParent())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "rootFrame's view is not our view's parent???"
, "rootFrame->GetView() && GetView() && rootFrame->GetView() == GetView()->GetParent()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1423); MOZ_PretendNoReturn(); } } while (0)
;
1424
1425 // Indicators of whether the popup should be flipped or resized.
1426 FlipStyle hFlip = FlipStyle_None, vFlip = FlipStyle_None;
1427
1428 const nsMargin margin = GetMargin();
1429
1430 // the screen rectangle of the root frame, in dev pixels.
1431 const nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
1432
1433 const bool isNoAutoHide = IsNoAutoHide();
1434 const PopupLevel popupLevel = GetPopupLevel(isNoAutoHide);
1435
1436 Rects result;
1437
1438 // Set the popup's size to the preferred size. Below, this size will be
1439 // adjusted to fit on the screen or within the content area. If the anchor is
1440 // sized to the popup, use the anchor's width instead of the preferred width.
1441 result.mUsedRect = nsRect(nsPoint(), aPrefSize);
1442
1443 const bool anchored = IsAnchored();
1444 if (anchored) {
1445 // In order to deal with transforms, we need the root prescontext:
1446 nsPresContext* rootPc = pc->GetRootPresContext();
1447 if (NS_WARN_IF(!rootPc)NS_warn_if_impl(!rootPc, "!rootPc", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1447)
) {
1448 // If we can't reach a root pres context, don't bother continuing.
1449 return result;
1450 }
1451
1452 result.mAnchorRect = result.mUntransformedAnchorRect = [&] {
1453 // If anchored to a rectangle, use that rectangle. Otherwise, determine
1454 // the rectangle from the anchor.
1455 if (mAnchorType == MenuPopupAnchorType::Rect) {
1456 return mScreenRect;
1457 }
1458 // if the frame is not specified, use the anchor node passed to OpenPopup.
1459 // If that wasn't specified either, use the root frame. Note that
1460 // mAnchorContent might be a different document so its presshell must be
1461 // used.
1462 nsIFrame* anchorFrame = GetAnchorFrame();
1463 if (!anchorFrame) {
1464 return rootScreenRect;
1465 }
1466 return ComputeAnchorRect(rootPc, anchorFrame);
1467 }();
1468
1469 // if we are anchored, there are certain things we don't want to do when
1470 // repositioning the popup to fit on the screen, such as end up positioned
1471 // over the anchor, for instance a popup appearing over the menu label.
1472 // When doing this reposition, we want to move the popup to the side with
1473 // the most room. The combination of anchor and alignment dictate if we
1474 // readjust above/below or to the left/right.
1475 if (mAnchorContent || mAnchorType == MenuPopupAnchorType::Rect) {
1476 // move the popup according to the anchor and alignment. This will also
1477 // tell us which axis the popup is flush against in case we have to move
1478 // it around later. The AdjustPositionForAnchorAlign method accounts for
1479 // the popup's margin.
1480 result.mUsedRect.MoveTo(AdjustPositionForAnchorAlign(
1481 result.mAnchorRect, aPrefSize, hFlip, vFlip));
1482 } else {
1483 // With no anchor, the popup is positioned relative to the root frame.
1484 result.mUsedRect.MoveTo(result.mAnchorRect.TopLeft() +
1485 nsPoint(margin.left, margin.top));
1486 }
1487 } else {
1488 // Not anchored, use mScreenRect
1489 result.mUsedRect.MoveTo(mScreenRect.TopLeft());
1490 result.mAnchorRect = result.mUntransformedAnchorRect =
1491 nsRect(mScreenRect.TopLeft(), nsSize());
1492
1493 // Right-align RTL context menus, and apply margin and offsets as per the
1494 // platform conventions.
1495 if (mIsContextMenu && IsDirectionRTL()) {
1496 result.mUsedRect.x -= aPrefSize.Width();
1497 result.mUsedRect.MoveBy(-margin.right, margin.top);
1498 } else {
1499 result.mUsedRect.MoveBy(margin.left, margin.top);
1500 }
1501#ifdef XP_MACOSX
1502 // OSX tooltips follow standard flip rule but other popups flip horizontally
1503 // not vertically
1504 if (mPopupType == PopupType::Tooltip) {
1505 vFlip = FlipStyle_Outside;
1506 } else {
1507 hFlip = FlipStyle_Outside;
1508 }
1509#else
1510 // Other OS screen positioned popups can be flipped vertically but never
1511 // horizontally
1512 vFlip = FlipStyle_Outside;
1513#endif // #ifdef XP_MACOSX
1514 }
1515
1516 const int32_t a2d = pc->AppUnitsPerDevPixel();
1517
1518 nsView* view = GetView();
1519 NS_ASSERTION(view, "popup with no view")do { if (!(view)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "popup with no view"
, "view", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1519); MOZ_PretendNoReturn(); } } while (0)
;
1520
1521 nsIWidget* widget = view->GetWidget();
1522
1523 // If a panel has flip="none", don't constrain or flip it.
1524 // Also, always do this for content shells, so that the popup doesn't extend
1525 // outside the containing frame.
1526 if (mInContentShell || mFlip != FlipType_None) {
1527 const Maybe<nsRect> constraintRect =
1528 GetConstraintRect(result.mAnchorRect, rootScreenRect, popupLevel);
1529
1530 if (constraintRect) {
1531 // Ensure that anchorRect is on the constraint rect.
1532 result.mAnchorRect = result.mAnchorRect.Intersect(*constraintRect);
1533 // Shrink the popup down if it is larger than the constraint size
1534 if (result.mUsedRect.width > constraintRect->width) {
1535 result.mUsedRect.width = constraintRect->width;
1536 }
1537 if (result.mUsedRect.height > constraintRect->height) {
1538 result.mUsedRect.height = constraintRect->height;
1539 }
1540 result.mConstrainedByLayout = true;
1541 }
1542
1543 if (IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() && widget) {
1544 // Shrink the popup down if it's larger than popup size received from
1545 // Wayland compositor. We don't know screen size on Wayland so this is the
1546 // only info we have there.
1547 const nsSize waylandSize = LayoutDeviceIntRect::ToAppUnits(
1548 widget->GetMoveToRectPopupSize(), a2d);
1549 if (waylandSize.width > 0 && result.mUsedRect.width > waylandSize.width) {
1550 LOG_WAYLAND("Wayland constraint width [%p]: %d to %d", widget,do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint width [%p]: %d to %d"
, widget, result.mUsedRect.width, waylandSize.width); } } while
(0)
1551 result.mUsedRect.width, waylandSize.width)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint width [%p]: %d to %d"
, widget, result.mUsedRect.width, waylandSize.width); } } while
(0)
;
1552 result.mUsedRect.width = waylandSize.width;
1553 }
1554 if (waylandSize.height > 0 &&
1555 result.mUsedRect.height > waylandSize.height) {
1556 LOG_WAYLAND("Wayland constraint height [%p]: %d to %d", widget,do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint height [%p]: %d to %d"
, widget, result.mUsedRect.height, waylandSize.height); } } while
(0)
1557 result.mUsedRect.height, waylandSize.height)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint height [%p]: %d to %d"
, widget, result.mUsedRect.height, waylandSize.height); } } while
(0)
;
1558 result.mUsedRect.height = waylandSize.height;
1559 }
1560 if (RefPtr<widget::Screen> s = widget->GetWidgetScreen()) {
1561 const nsSize screenSize =
1562 LayoutDeviceIntSize::ToAppUnits(s->GetAvailRect().Size(), a2d);
1563 if (result.mUsedRect.height > screenSize.height) {
1564 LOG_WAYLAND("Wayland constraint height to screen [%p]: %d to %d",do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint height to screen [%p]: %d to %d"
, widget, result.mUsedRect.height, screenSize.height); } } while
(0)
1565 widget, result.mUsedRect.height, screenSize.height)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint height to screen [%p]: %d to %d"
, widget, result.mUsedRect.height, screenSize.height); } } while
(0)
;
1566 result.mUsedRect.height = screenSize.height;
1567 }
1568 if (result.mUsedRect.width > screenSize.width) {
1569 LOG_WAYLAND("Wayland constraint widthto screen [%p]: %d to %d",do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint widthto screen [%p]: %d to %d"
, widget, result.mUsedRect.width, screenSize.width); } } while
(0)
1570 widget, result.mUsedRect.width, screenSize.width)do { const ::mozilla::LogModule* moz_real_module = gWidgetPopupLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, mozilla::LogLevel::Debug)), 0))) { mozilla::detail::log_print
(moz_real_module, mozilla::LogLevel::Debug, "Wayland constraint widthto screen [%p]: %d to %d"
, widget, result.mUsedRect.width, screenSize.width); } } while
(0)
;
1571 result.mUsedRect.width = screenSize.width;
1572 }
1573 }
1574 }
1575
1576 // At this point the anchor (anchorRect) is within the available screen
1577 // area (constraintRect) and the popup is known to be no larger than the
1578 // screen.
1579 if (constraintRect) {
1580 // We might want to "slide" an arrow if the panel is of the correct type -
1581 // but we can only slide on one axis - the other axis must be "flipped or
1582 // resized" as normal.
1583 bool slideHorizontal = false, slideVertical = false;
1584 if (mFlip == FlipType_Slide) {
1585 int8_t position = GetAlignmentPosition();
1586 slideHorizontal = position >= POPUPPOSITION_BEFORESTART0 &&
1587 position <= POPUPPOSITION_AFTEREND3;
1588 slideVertical = position >= POPUPPOSITION_STARTBEFORE4 &&
1589 position <= POPUPPOSITION_ENDAFTER7;
1590 }
1591
1592 // Next, check if there is enough space to show the popup at full size
1593 // when positioned at screenPoint. If not, flip the popups to the opposite
1594 // side of their anchor point, or resize them as necessary.
1595 if (slideHorizontal) {
1596 result.mUsedRect.width = SlideOrResize(
1597 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1598 constraintRect->XMost(), &result.mAlignmentOffset);
1599 } else {
1600 const bool endAligned =
1601 IsDirectionRTL()
1602 ? mPopupAlignment == POPUPALIGNMENT_TOPLEFT1 ||
1603 mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1604 mPopupAlignment == POPUPALIGNMENT_LEFTCENTER16
1605 : mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1 ||
1606 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1607 mPopupAlignment == POPUPALIGNMENT_RIGHTCENTER-16;
1608 result.mUsedRect.width = FlipOrResize(
1609 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1610 constraintRect->XMost(), result.mAnchorRect.x,
1611 result.mAnchorRect.XMost(), margin.left, margin.right, hFlip,
1612 endAligned, &result.mHFlip);
1613 }
1614 if (slideVertical) {
1615 result.mUsedRect.height = SlideOrResize(
1616 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1617 constraintRect->YMost(), &result.mAlignmentOffset);
1618 } else {
1619 bool endAligned = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1620 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1621 mPopupAlignment == POPUPALIGNMENT_BOTTOMCENTER18;
1622 result.mUsedRect.height = FlipOrResize(
1623 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1624 constraintRect->YMost(), result.mAnchorRect.y,
1625 result.mAnchorRect.YMost(), margin.top, margin.bottom, vFlip,
1626 endAligned, &result.mVFlip);
1627 }
1628
1629#ifdef DEBUG1
1630 NS_ASSERTION(constraintRect->Contains(result.mUsedRect),do { if (!(constraintRect->Contains(result.mUsedRect))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Popup is offscreen", "constraintRect->Contains(result.mUsedRect)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1631); MOZ_PretendNoReturn(); } } while (0)
1631 "Popup is offscreen")do { if (!(constraintRect->Contains(result.mUsedRect))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Popup is offscreen", "constraintRect->Contains(result.mUsedRect)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1631); MOZ_PretendNoReturn(); } } while (0)
;
1632 if (!constraintRect->Contains(result.mUsedRect)) {
1633 NS_WARNING(nsPrintfCString("Popup is offscreen (%s vs. %s)",NS_DebugBreak(NS_DEBUG_WARNING, nsPrintfCString("Popup is offscreen (%s vs. %s)"
, ToString(constraintRect).c_str(), ToString(result.mUsedRect
).c_str()) .get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1636)
1634 ToString(constraintRect).c_str(),NS_DebugBreak(NS_DEBUG_WARNING, nsPrintfCString("Popup is offscreen (%s vs. %s)"
, ToString(constraintRect).c_str(), ToString(result.mUsedRect
).c_str()) .get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1636)
1635 ToString(result.mUsedRect).c_str())NS_DebugBreak(NS_DEBUG_WARNING, nsPrintfCString("Popup is offscreen (%s vs. %s)"
, ToString(constraintRect).c_str(), ToString(result.mUsedRect
).c_str()) .get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1636)
1636 .get())NS_DebugBreak(NS_DEBUG_WARNING, nsPrintfCString("Popup is offscreen (%s vs. %s)"
, ToString(constraintRect).c_str(), ToString(result.mUsedRect
).c_str()) .get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1636)
;
1637 }
1638#endif
1639 }
1640 }
1641 // snap the popup's position in screen coordinates to device pixels, see
1642 // bug 622507, bug 961431
1643 result.mUsedRect.x = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.x);
1644 result.mUsedRect.y = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.y);
1645
1646 // determine the x and y position of the view by subtracting the desired
1647 // screen position from the screen position of the root frame.
1648 result.mViewPoint = result.mUsedRect.TopLeft() - rootScreenRect.TopLeft();
1649
1650 // Offset the position by the width and height of the borders and titlebar.
1651 // Even though GetClientOffset should return (0, 0) when there is no titlebar
1652 // or borders, we skip these calculations anyway for non-panels to save time
1653 // since they will never have a titlebar.
1654 if (mPopupType == PopupType::Panel && widget) {
1655 result.mClientOffset = widget->GetClientOffset();
1656 result.mViewPoint +=
1657 LayoutDeviceIntPoint::ToAppUnits(result.mClientOffset, a2d);
1658 }
1659
1660 return result;
1661}
1662
1663void nsMenuPopupFrame::SetPopupPosition(bool aIsMove) {
1664 if (aIsMove && (mPrefSize.width == -1 || mPrefSize.height == -1)) {
1665 return;
1666 }
1667
1668 auto rects = GetRects(mPrefSize);
1669 if (rects.mUsedRect.Size() != mRect.Size()) {
1670 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IN_REFLOW))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IN_REFLOW))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasAnyStateBits(NS_FRAME_IN_REFLOW
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAnyStateBits(NS_FRAME_IN_REFLOW)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1670); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IN_REFLOW)"
")"); do { *((volatile int*)__null) = 1670; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1671 // We need to resize on top of moving, trigger an actual reflow.
1672 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
1673 NS_FRAME_IS_DIRTY);
1674 return;
1675 }
1676 PerformMove(rects);
1677}
1678
1679void nsMenuPopupFrame::PerformMove(const Rects& aRects) {
1680 auto* ps = PresShell();
1681
1682 // We're just moving, sync frame position and offset as needed.
1683 ps->GetViewManager()->MoveViewTo(GetView(), aRects.mViewPoint.x,
1684 aRects.mViewPoint.y);
1685
1686 // Now that we've positioned the view, sync up the frame's origin.
1687 nsBlockFrame::SetPosition(aRects.mViewPoint -
1688 GetParent()->GetOffsetTo(ps->GetRootFrame()));
1689
1690 // If the popup is in the positioned state or if it is shown and the position
1691 // or size changed, dispatch a popuppositioned event if the popup wants it.
1692 if (mPopupState == ePopupPositioning ||
1693 (mPopupState == ePopupShown &&
1694 !aRects.mUsedRect.IsEqualEdges(mUsedScreenRect)) ||
1695 (mPopupState == ePopupShown &&
1696 aRects.mAlignmentOffset != mAlignmentOffset)) {
1697 mUsedScreenRect = aRects.mUsedRect;
1698 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && !mPendingPositionedEvent) {
1699 mPendingPositionedEvent =
1700 nsXULPopupPositionedEvent::DispatchIfNeeded(mContent->AsElement());
1701 }
1702 }
1703
1704 if (!mPositionedByMoveToRect) {
1705 mUntransformedAnchorRect = aRects.mUntransformedAnchorRect;
1706 }
1707
1708 mAlignmentOffset = aRects.mAlignmentOffset;
1709 mLastClientOffset = aRects.mClientOffset;
1710 mHFlip = aRects.mHFlip;
1711 mVFlip = aRects.mVFlip;
1712 mConstrainedByLayout = aRects.mConstrainedByLayout;
1713
1714 // If this is a noautohide popup, set the screen coordinates of the popup.
1715 // This way, the popup stays at the location where it was opened even when the
1716 // window is moved. Popups at the parent level follow the parent window as it
1717 // is moved and remained anchored, so we want to maintain the anchoring
1718 // instead.
1719 //
1720 // FIXME: This suffers from issues like bug 1823552, where constraints imposed
1721 // by the anchor are lost, but this is super-old behavior.
1722 const bool fixPositionToPoint =
1723 IsNoAutoHide() && (GetPopupLevel() != PopupLevel::Parent ||
1724 mAnchorType == MenuPopupAnchorType::Rect);
1725 if (fixPositionToPoint) {
1726 // Account for the margin that will end up being added to the screen
1727 // coordinate the next time SetPopupPosition is called.
1728 const auto& margin = GetMargin();
1729 mAnchorType = MenuPopupAnchorType::Point;
1730 mScreenRect.x = aRects.mUsedRect.x - margin.left;
1731 mScreenRect.y = aRects.mUsedRect.y - margin.top;
1732 }
1733
1734 // For anchored popups that shouldn't follow the anchor, fix the original
1735 // anchor rect.
1736 if (IsAnchored() && !ShouldFollowAnchor() && !mUsedScreenRect.IsEmpty() &&
1737 mAnchorType != MenuPopupAnchorType::Rect) {
1738 mAnchorType = MenuPopupAnchorType::Rect;
1739 mScreenRect = aRects.mUntransformedAnchorRect;
1740 }
1741
1742 // NOTE(emilio): This call below is kind of a workaround, but we need to do
1743 // this here because some position changes don't go through the
1744 // view system -> popup manager, like:
1745 //
1746 // https://searchfox.org/mozilla-central/rev/477950cf9ca9c9bb5ff6f34e0d0f6ca4718ea798/widget/gtk/nsWindow.cpp#3847
1747 //
1748 // So this might be the last chance we have to set the remote browser's
1749 // position.
1750 //
1751 // Ultimately this probably wants to get fixed in the widget size of things,
1752 // but given this is worst-case a redundant DOM traversal, and that popups
1753 // usually don't have all that much content, this is probably an ok
1754 // workaround.
1755 WidgetPositionOrSizeDidChange();
1756}
1757
1758void nsMenuPopupFrame::WidgetPositionOrSizeDidChange() {
1759 // In the case this popup has remote contents having OOP iframes, it's
1760 // possible that OOP iframe's nsSubDocumentFrame has been already reflowed
1761 // thus, we will never have a chance to tell this parent browser's position
1762 // update to the OOP documents without notifying it explicitly.
1763 if (!HasRemoteContent()) {
1764 return;
1765 }
1766 for (nsIContent* content = mContent->GetFirstChild(); content;
1767 content = content->GetNextNode(mContent)) {
1768 if (content->IsXULElement(nsGkAtoms::browser) &&
1769 content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
1770 nsGkAtoms::_true, eIgnoreCase)) {
1771 if (auto* browserParent = dom::BrowserParent::GetFrom(content)) {
1772 browserParent->NotifyPositionUpdatedForContentsInPopup();
1773 }
1774 }
1775 }
1776}
1777
1778Maybe<nsRect> nsMenuPopupFrame::GetConstraintRect(
1779 const nsRect& aAnchorRect, const nsRect& aRootScreenRect,
1780 PopupLevel aPopupLevel) const {
1781 const nsPresContext* pc = PresContext();
1782 const int32_t a2d = PresContext()->AppUnitsPerDevPixel();
1783 Maybe<nsRect> result;
1784
1785 auto AddConstraint = [&result](const nsRect& aConstraint) {
1786 if (result) {
1787 *result = result->Intersect(aConstraint);
1788 } else {
1789 result.emplace(aConstraint);
1790 }
1791 };
1792
1793 // Determine the available screen space. It will be reduced by the OS chrome
1794 // such as menubars. It addition, for content shells, it will be the area of
1795 // the content rather than the screen.
1796 // In Wayland we can't use the screen rect because we can't know absolute
1797 // window position.
1798 if (!IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay()) {
1799 const DesktopToLayoutDeviceScale scale =
1800 pc->DeviceContext()->GetDesktopToDeviceScale();
1801 // For content shells, get the screen where the root frame is located. This
1802 // is because we need to constrain the content to this content area, so we
1803 // should use the same screen. Otherwise, use the screen where the anchor is
1804 // located.
1805 const nsRect& rect = mInContentShell ? aRootScreenRect : aAnchorRect;
1806 auto desktopRect = DesktopIntRect::RoundOut(
1807 LayoutDeviceRect::FromAppUnits(rect, a2d) / scale);
1808 desktopRect.width = std::max(1, desktopRect.width);
1809 desktopRect.height = std::max(1, desktopRect.height);
1810
1811 RefPtr<nsIScreen> screen =
1812 widget::ScreenManager::GetSingleton().ScreenForRect(desktopRect);
1813 MOZ_ASSERT(screen, "We always fall back to the primary screen")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(screen)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(screen))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("screen" " (" "We always fall back to the primary screen"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1813); AnnotateMozCrashReason("MOZ_ASSERT" "(" "screen" ") ("
"We always fall back to the primary screen" ")"); do { *((volatile
int*)__null) = 1813; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
1814 // Non-top-level popups (which will always be panels) should never overlap
1815 // the OS bar.
1816 const bool canOverlapOSBar =
1817 aPopupLevel == PopupLevel::Top &&
1818 LookAndFeel::GetInt(LookAndFeel::IntID::MenusCanOverlapOSBar) &&
1819 !mInContentShell;
1820 // Get the total screen area if the popup is allowed to overlap it.
1821 const auto screenRect =
1822 canOverlapOSBar ? screen->GetRect() : screen->GetAvailRect();
1823 AddConstraint(LayoutDeviceRect::ToAppUnits(screenRect, a2d));
1824 }
1825
1826 if (mInContentShell) {
1827 // For content shells, clip to the client area rather than the screen area
1828 AddConstraint(aRootScreenRect);
1829 } else if (!mOverrideConstraintRect.IsEmpty()) {
1830 AddConstraint(mOverrideConstraintRect);
1831 // This is currently only used for <select> elements where we want to
1832 // constrain vertically to the screen but not horizontally, so do the
1833 // intersection and then reset the horizontal values.
1834 //
1835 // FIXME(emilio): This doesn't make any sense to me...
1836 result->x = mOverrideConstraintRect.x;
1837 result->width = mOverrideConstraintRect.width;
1838 }
1839
1840 // Expand the allowable screen rect by the input margin (which can't be
1841 // interacted with).
1842 if (result) {
1843 const nscoord inputMargin =
1844 StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
1845 result->Inflate(inputMargin);
1846 }
1847 return result;
1848}
1849
1850ConsumeOutsideClicksResult nsMenuPopupFrame::ConsumeOutsideClicks() {
1851 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1852 nsGkAtoms::consumeoutsideclicks,
1853 nsGkAtoms::_true, eCaseMatters)) {
1854 return ConsumeOutsideClicks_True;
1855 }
1856 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1857 nsGkAtoms::consumeoutsideclicks,
1858 nsGkAtoms::_false, eCaseMatters)) {
1859 return ConsumeOutsideClicks_ParentOnly;
1860 }
1861 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1862 nsGkAtoms::consumeoutsideclicks,
1863 nsGkAtoms::never, eCaseMatters)) {
1864 return ConsumeOutsideClicks_Never;
1865 }
1866
1867 nsCOMPtr<nsIContent> parentContent = mContent->GetParent();
1868 if (parentContent) {
1869 dom::NodeInfo* ni = parentContent->NodeInfo();
1870 if (ni->Equals(nsGkAtoms::menulist, kNameSpaceID_XUL8)) {
1871 return ConsumeOutsideClicks_True; // Consume outside clicks for combo
1872 // boxes on all platforms
1873 }
1874#if defined(XP_WIN)
1875 // Don't consume outside clicks for menus in Windows
1876 if (ni->Equals(nsGkAtoms::menu, kNameSpaceID_XUL8) ||
1877 ni->Equals(nsGkAtoms::popupset, kNameSpaceID_XUL8) ||
1878 ((ni->Equals(nsGkAtoms::button, kNameSpaceID_XUL8) ||
1879 ni->Equals(nsGkAtoms::toolbarbutton, kNameSpaceID_XUL8)) &&
1880 parentContent->AsElement()->AttrValueIs(
1881 kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::menu,
1882 eCaseMatters))) {
1883 return ConsumeOutsideClicks_Never;
1884 }
1885#endif
1886 }
1887
1888 return ConsumeOutsideClicks_True;
1889}
1890
1891static ScrollContainerFrame* DoGetScrollContainerFrame(const nsIFrame* aFrame) {
1892 if (const ScrollContainerFrame* sf = do_QueryFrame(aFrame)) {
1893 return const_cast<ScrollContainerFrame*>(sf);
1894 }
1895 for (nsIFrame* childFrame : aFrame->PrincipalChildList()) {
1896 if (auto* sf = DoGetScrollContainerFrame(childFrame)) {
1897 return sf;
1898 }
1899 }
1900 return nullptr;
1901}
1902
1903// XXXroc this is megalame. Fossicking around for a frame of the right
1904// type is a recipe for disaster in the long term.
1905ScrollContainerFrame* nsMenuPopupFrame::GetScrollContainerFrame() const {
1906 return DoGetScrollContainerFrame(this);
1907}
1908
1909void nsMenuPopupFrame::ChangeByPage(bool aIsUp) {
1910 // Only scroll by page within menulists.
1911 if (!IsMenuList()) {
1912 return;
1913 }
1914
1915 ScrollContainerFrame* scrollContainerFrame = GetScrollContainerFrame();
1916
1917 RefPtr popup = &PopupElement();
1918 XULButtonElement* currentMenu = popup->GetActiveMenuChild();
1919 XULButtonElement* newMenu = nullptr;
1920 if (!currentMenu) {
1921 // If there is no current menu item, get the first item. When moving up,
1922 // just use this as the newMenu and leave currentMenu null so that no check
1923 // for a later element is performed. When moving down, set currentMenu so
1924 // that we look for one page down from the first item.
1925 newMenu = popup->GetFirstMenuItem();
1926 if (!aIsUp) {
1927 currentMenu = newMenu;
1928 }
1929 }
1930
1931 if (currentMenu && currentMenu->GetPrimaryFrame()) {
1932 const nscoord scrollHeight =
1933 scrollContainerFrame ? scrollContainerFrame->GetScrollPortRect().height
1934 : mRect.height;
1935 const nsRect currentRect = currentMenu->GetPrimaryFrame()->GetRect();
1936 const XULButtonElement* startMenu = currentMenu;
1937
1938 // Get the position of the current item and add or subtract one popup's
1939 // height to or from it.
1940 const nscoord targetPos = aIsUp ? currentRect.YMost() - scrollHeight
1941 : currentRect.y + scrollHeight;
1942 // Look for the next child which is just past the target position. This
1943 // child will need to be selected.
1944 for (; currentMenu;
1945 currentMenu = aIsUp ? popup->GetPrevMenuItemFrom(*currentMenu)
1946 : popup->GetNextMenuItemFrom(*currentMenu)) {
1947 if (!currentMenu->GetPrimaryFrame()) {
1948 continue;
1949 }
1950 const nsRect curRect = currentMenu->GetPrimaryFrame()->GetRect();
1951 const nscoord curPos = aIsUp ? curRect.y : curRect.YMost();
1952 // If the right position was found, break out. Otherwise, look for another
1953 // item.
1954 if (aIsUp ? (curPos < targetPos) : (curPos > targetPos)) {
1955 if (!newMenu || newMenu == startMenu) {
1956 newMenu = currentMenu;
1957 }
1958 break;
1959 }
1960
1961 // Assign this item to newMenu. This item will be selected in case we
1962 // don't find any more.
1963 newMenu = currentMenu;
1964 }
1965 }
1966
1967 // Select the new menuitem.
1968 if (RefPtr newMenuRef = newMenu) {
1969 popup->SetActiveMenuChild(newMenuRef);
1970 }
1971}
1972
1973dom::XULPopupElement& nsMenuPopupFrame::PopupElement() const {
1974 auto* popup = dom::XULPopupElement::FromNode(GetContent());
1975 MOZ_DIAGNOSTIC_ASSERT(popup)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(popup)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(popup))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("popup", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1975); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "popup"
")"); do { *((volatile int*)__null) = 1975; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1976 return *popup;
1977}
1978
1979XULButtonElement* nsMenuPopupFrame::GetCurrentMenuItem() const {
1980 return PopupElement().GetActiveMenuChild();
1981}
1982
1983nsIFrame* nsMenuPopupFrame::GetCurrentMenuItemFrame() const {
1984 auto* child = GetCurrentMenuItem();
1985 return child ? child->GetPrimaryFrame() : nullptr;
1986}
1987
1988void nsMenuPopupFrame::HandleEnterKeyPress(WidgetEvent& aEvent) {
1989 mIncrementalString.Truncate();
1990 RefPtr popup = &PopupElement();
1991 popup->HandleEnterKeyPress(aEvent);
1992}
1993
1994XULButtonElement* nsMenuPopupFrame::FindMenuWithShortcut(
1995 mozilla::dom::KeyboardEvent& aKeyEvent, bool& aDoAction) {
1996 uint32_t charCode = aKeyEvent.CharCode();
1997 uint32_t keyCode = aKeyEvent.KeyCode();
1998
1999 aDoAction = false;
2000
2001 // Enumerate over our list of frames.
2002 const bool isMenu = !IsMenuList();
2003 TimeStamp keyTime = aKeyEvent.WidgetEventPtr()->mTimeStamp;
2004 if (charCode == 0) {
2005 if (keyCode == dom::KeyboardEvent_Binding::DOM_VK_BACK_SPACE) {
2006 if (!isMenu && !mIncrementalString.IsEmpty()) {
2007 mIncrementalString.SetLength(mIncrementalString.Length() - 1);
2008 return nullptr;
2009 }
2010#ifdef XP_WIN
2011 if (nsCOMPtr<nsISound> sound = do_GetService("@mozilla.org/sound;1")) {
2012 sound->Beep();
2013 }
2014#endif // #ifdef XP_WIN
2015 }
2016 return nullptr;
2017 }
2018 char16_t uniChar = ToLowerCase(static_cast<char16_t>(charCode));
2019 if (isMenu) {
2020 // Menu supports only first-letter navigation
2021 mIncrementalString = uniChar;
2022 } else if (IsWithinIncrementalTime(keyTime)) {
2023 mIncrementalString.Append(uniChar);
2024 } else {
2025 // Interval too long, treat as new typing
2026 mIncrementalString = uniChar;
2027 }
2028
2029 // See bug 188199 & 192346, if all letters in incremental string are same,
2030 // just try to match the first one
2031 nsAutoString incrementalString(mIncrementalString);
2032 uint32_t charIndex = 1, stringLength = incrementalString.Length();
2033 while (charIndex < stringLength &&
2034 incrementalString[charIndex] == incrementalString[charIndex - 1]) {
2035 charIndex++;
2036 }
2037 if (charIndex == stringLength) {
2038 incrementalString.Truncate(1);
2039 stringLength = 1;
Value stored to 'stringLength' is never read
2040 }
2041
2042 sLastKeyTime = keyTime;
2043
2044 auto* item =
2045 PopupElement().FindMenuWithShortcut(incrementalString, aDoAction);
2046 if (item) {
2047 return item;
2048 }
2049
2050 // If we don't match anything, rollback the last typing
2051 mIncrementalString.SetLength(mIncrementalString.Length() - 1);
2052
2053 // didn't find a matching menu item
2054#ifdef XP_WIN
2055 // behavior on Windows - this item is in a menu popup off of the
2056 // menu bar, so beep and do nothing else
2057 if (isMenu) {
2058 if (nsCOMPtr<nsISound> sound = do_GetService("@mozilla.org/sound;1")) {
2059 sound->Beep();
2060 }
2061 }
2062#endif // #ifdef XP_WIN
2063
2064 return nullptr;
2065}
2066
2067nsIWidget* nsMenuPopupFrame::GetWidget() const {
2068 return mView ? mView->GetWidget() : nullptr;
2069}
2070
2071// helpers /////////////////////////////////////////////////////////////
2072
2073nsresult nsMenuPopupFrame::AttributeChanged(int32_t aNameSpaceID,
2074 nsAtom* aAttribute,
2075 int32_t aModType)
2076
2077{
2078 nsresult rv =
2079 nsBlockFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
2080
2081 if (aAttribute == nsGkAtoms::left || aAttribute == nsGkAtoms::top) {
2082 MoveToAttributePosition();
2083 }
2084
2085 if (aAttribute == nsGkAtoms::remote && GetWidget()) {
2086 // When the remote attribute changes, we need to create a new widget to
2087 // ensure that it has the correct compositor and transparency settings to
2088 // match the new value. Do that only if we already have a widget.
2089 // TODO(emilio): We should consider doing it only when we get re-shown or
2090 // so.
2091 PrepareWidget(true);
2092 }
2093
2094 if (aAttribute == nsGkAtoms::followanchor) {
2095 if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
2096 pm->UpdateFollowAnchor(this);
2097 }
2098 }
2099
2100 if (aAttribute == nsGkAtoms::label) {
2101 // set the label for the titlebar
2102 nsView* view = GetView();
2103 if (view) {
2104 nsIWidget* widget = view->GetWidget();
2105 if (widget) {
2106 nsAutoString title;
2107 mContent->AsElement()->GetAttr(nsGkAtoms::label, title);
2108 if (!title.IsEmpty()) {
2109 widget->SetTitle(title);
2110 }
2111 }
2112 }
2113 } else if (aAttribute == nsGkAtoms::ignorekeys) {
2114 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2115 if (pm) {
2116 nsAutoString ignorekeys;
2117 mContent->AsElement()->GetAttr(nsGkAtoms::ignorekeys, ignorekeys);
2118 pm->UpdateIgnoreKeys(ignorekeys.EqualsLiteral("true"));
2119 }
2120 }
2121
2122 return rv;
2123}
2124
2125void nsMenuPopupFrame::MoveToAttributePosition() {
2126 // Move the widget around when the user sets the |left| and |top| attributes.
2127 // Note that this is not the best way to move the widget, as it results in
2128 // lots of FE notifications and is likely to be slow as molasses. Use |moveTo|
2129 // on the element if possible.
2130 nsAutoString left, top;
2131 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
2132 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
2133 nsresult err1, err2;
2134 const CSSIntPoint pos(left.ToInteger(&err1), top.ToInteger(&err2));
2135 if (NS_SUCCEEDED(err1)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err1)), 1))) && NS_SUCCEEDED(err2)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err2)), 1)))) {
2136 MoveTo(pos, false);
2137 }
2138
2139 PresShell()->FrameNeedsReflow(
2140 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
2141}
2142
2143void nsMenuPopupFrame::Destroy(DestroyContext& aContext) {
2144 // XXX: Currently we don't fire popuphidden for these popups, that seems wrong
2145 // but alas, also pre-existing.
2146 HidePopup(/* aDeselectMenu = */ false, ePopupClosed,
2147 /* aFromFrameDestruction = */ true);
2148
2149 if (RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance()) {
2150 pm->PopupDestroyed(this);
2151 }
2152
2153 nsBlockFrame::Destroy(aContext);
2154}
2155
2156nsMargin nsMenuPopupFrame::GetMargin() const {
2157 nsMargin margin;
2158 StyleMargin()->GetMargin(margin);
2159 if (mIsTopLevelContextMenu) {
2160 const CSSIntPoint offset(
2161 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetHorizontal),
2162 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetVertical));
2163 auto auOffset = CSSIntPoint::ToAppUnits(offset);
2164 margin.top += auOffset.y;
2165 margin.bottom += auOffset.y;
2166 margin.left += auOffset.x;
2167 margin.right += auOffset.x;
2168 }
2169 if (mPopupType == PopupType::Tooltip && !IsAnchored()) {
2170 const auto auOffset =
2171 CSSPixel::ToAppUnits(LookAndFeel::TooltipOffsetVertical());
2172 margin.top += auOffset;
2173 margin.bottom += auOffset;
2174 }
2175 // TODO(emilio): We should consider make these properly mirrored (that is,
2176 // changing -= to += here, and removing the rtl special case), but some tests
2177 // rely on the old behavior of the anchor moving physically regardless of
2178 // alignment...
2179 margin.top += mExtraMargin.y;
2180 margin.bottom -= mExtraMargin.y;
2181 if (IsDirectionRTL()) {
2182 margin.left -= mExtraMargin.x;
2183 margin.right += mExtraMargin.x;
2184 } else {
2185 margin.left += mExtraMargin.x;
2186 margin.right -= mExtraMargin.x;
2187 }
2188 return margin;
2189}
2190
2191void nsMenuPopupFrame::MoveTo(const CSSPoint& aPos, bool aUpdateAttrs,
2192 bool aByMoveToRect) {
2193 nsIWidget* widget = GetWidget();
2194 nsPoint appUnitsPos = CSSPixel::ToAppUnits(aPos);
2195
2196 const bool rtl = IsDirectionRTL();
2197
2198 // reposition the popup at the specified coordinates. Don't clear the anchor
2199 // and position, because the popup can be reset to its anchor position by
2200 // using (-1, -1) as coordinates.
2201 //
2202 // Subtract off the margin as it will be added to the position when
2203 // SetPopupPosition is called.
2204 {
2205 nsMargin margin = GetMargin();
2206 if (rtl && mIsContextMenu) {
2207 appUnitsPos.x += margin.right + mRect.Width();
2208 } else {
2209 appUnitsPos.x -= margin.left;
2210 }
2211 appUnitsPos.y -= margin.top;
2212 }
2213
2214 if (mScreenRect.TopLeft() == appUnitsPos &&
2215 (!widget || widget->GetClientOffset() == mLastClientOffset)) {
2216 return;
2217 }
2218
2219 mPositionedByMoveToRect = aByMoveToRect;
2220 mScreenRect.MoveTo(appUnitsPos);
2221 if (mAnchorType == MenuPopupAnchorType::Rect) {
2222 // This ensures that the anchor width is still honored, to prevent it from
2223 // changing spuriously.
2224 mScreenRect.height = 0;
2225 // But we still need to make sure that our top left position ends up in
2226 // appUnitsPos.
2227 mPopupAlignment = rtl ? POPUPALIGNMENT_TOPRIGHT-1 : POPUPALIGNMENT_TOPLEFT1;
2228 mPopupAnchor = rtl ? POPUPALIGNMENT_BOTTOMRIGHT-2 : POPUPALIGNMENT_BOTTOMLEFT2;
2229 } else {
2230 mAnchorType = MenuPopupAnchorType::Point;
2231 }
2232
2233 SetPopupPosition(true);
2234
2235 RefPtr<Element> popup = mContent->AsElement();
2236 if (aUpdateAttrs &&
2237 (popup->HasAttr(nsGkAtoms::left) || popup->HasAttr(nsGkAtoms::top))) {
2238 nsAutoString left, top;
2239 left.AppendInt(RoundedToInt(aPos).x);
2240 top.AppendInt(RoundedToInt(aPos).y);
2241 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::left, left, false);
2242 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::top, top, false);
2243 }
2244}
2245
2246void nsMenuPopupFrame::MoveToAnchor(nsIContent* aAnchorContent,
2247 const nsAString& aPosition, int32_t aXPos,
2248 int32_t aYPos, bool aAttributesOverride) {
2249 NS_ASSERTION(IsVisibleOrShowing(),do { if (!(IsVisibleOrShowing())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "popup must be visible or showing to move it", "IsVisibleOrShowing()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 2250); MOZ_PretendNoReturn(); } } while (0)
2250 "popup must be visible or showing to move it")do { if (!(IsVisibleOrShowing())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "popup must be visible or showing to move it", "IsVisibleOrShowing()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 2250); MOZ_PretendNoReturn(); } } while (0)
;
2251
2252 nsPopupState oldstate = mPopupState;
2253 InitializePopup(aAnchorContent, mTriggerContent, aPosition, aXPos, aYPos,
2254 MenuPopupAnchorType::Node, aAttributesOverride);
2255 // InitializePopup changed the state so reset it.
2256 mPopupState = oldstate;
2257
2258 // Pass false here so that flipping and adjusting to fit on the screen happen.
2259 SetPopupPosition(false);
2260}
2261
2262int8_t nsMenuPopupFrame::GetAlignmentPosition() const {
2263 // The code below handles most cases of alignment, anchor and position values.
2264 // Those that are not handled just return POPUPPOSITION_UNKNOWN.
2265
2266 if (mPosition == POPUPPOSITION_OVERLAP8 ||
2267 mPosition == POPUPPOSITION_AFTERPOINTER9 ||
2268 mPosition == POPUPPOSITION_SELECTION10) {
2269 return mPosition;
2270 }
2271
2272 int8_t position = mPosition;
2273
2274 if (position == POPUPPOSITION_UNKNOWN-1) {
2275 switch (mPopupAnchor) {
2276 case POPUPALIGNMENT_BOTTOMRIGHT-2:
2277 case POPUPALIGNMENT_BOTTOMLEFT2:
2278 case POPUPALIGNMENT_BOTTOMCENTER18:
2279 position = mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1
2280 ? POPUPPOSITION_AFTEREND3
2281 : POPUPPOSITION_AFTERSTART2;
2282 break;
2283 case POPUPALIGNMENT_TOPRIGHT-1:
2284 case POPUPALIGNMENT_TOPLEFT1:
2285 case POPUPALIGNMENT_TOPCENTER17:
2286 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2287 ? POPUPPOSITION_BEFOREEND1
2288 : POPUPPOSITION_BEFORESTART0;
2289 break;
2290 case POPUPALIGNMENT_LEFTCENTER16:
2291 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2292 ? POPUPPOSITION_STARTAFTER6
2293 : POPUPPOSITION_STARTBEFORE4;
2294 break;
2295 case POPUPALIGNMENT_RIGHTCENTER-16:
2296 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2
2297 ? POPUPPOSITION_ENDAFTER7
2298 : POPUPPOSITION_ENDBEFORE5;
2299 break;
2300 default:
2301 break;
2302 }
2303 }
2304
2305 if (mHFlip) {
2306 position = POPUPPOSITION_HFLIP(position)(position ^ 1);
2307 }
2308
2309 if (mVFlip) {
2310 position = POPUPPOSITION_VFLIP(position)(position ^ 2);
2311 }
2312
2313 return position;
2314}
2315
2316/**
2317 * KEEP THIS IN SYNC WITH nsIFrame::CreateView
2318 * as much as possible. Until we get rid of views finally...
2319 */
2320void nsMenuPopupFrame::CreatePopupView() {
2321 if (HasView()) {
2322 return;
2323 }
2324
2325 nsViewManager* viewManager = PresContext()->GetPresShell()->GetViewManager();
2326 NS_ASSERTION(nullptr != viewManager, "null view manager")do { if (!(nullptr != viewManager)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "null view manager", "nullptr != viewManager", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 2326); MOZ_PretendNoReturn(); } } while (0)
;
2327
2328 // Create a view
2329 nsView* parentView = viewManager->GetRootView();
2330 auto visibility = ViewVisibility::Hide;
2331
2332 NS_ASSERTION(parentView, "no parent view")do { if (!(parentView)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "no parent view"
, "parentView", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 2332); MOZ_PretendNoReturn(); } } while (0)
;
2333
2334 // Create a view
2335 nsView* view = viewManager->CreateView(GetRect(), parentView, visibility);
2336 // XXX put view last in document order until we can do better
2337 viewManager->InsertChild(parentView, view, nullptr, true);
2338
2339 // Remember our view
2340 SetView(view);
2341
2342 NS_FRAME_LOG(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
2343 NS_FRAME_TRACE_CALLS,do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
2344 ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p", this, view))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
;
2345}
2346
2347bool nsMenuPopupFrame::ShouldFollowAnchor() const {
2348 if (mAnchorType != MenuPopupAnchorType::Node || !mAnchorContent) {
2349 return false;
2350 }
2351
2352 // Follow anchor mode is used when followanchor="true" is set or for arrow
2353 // panels.
2354 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2355 nsGkAtoms::followanchor,
2356 nsGkAtoms::_true, eCaseMatters)) {
2357 return true;
2358 }
2359
2360 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2361 nsGkAtoms::followanchor,
2362 nsGkAtoms::_false, eCaseMatters)) {
2363 return false;
2364 }
2365
2366 return mPopupType == PopupType::Panel &&
2367 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
2368 nsGkAtoms::arrow, eCaseMatters);
2369}
2370
2371bool nsMenuPopupFrame::ShouldFollowAnchor(nsRect& aRect) {
2372 if (!ShouldFollowAnchor()) {
2373 return false;
2374 }
2375
2376 if (nsIFrame* anchorFrame = GetAnchorFrame()) {
2377 if (nsPresContext* rootPresContext = PresContext()->GetRootPresContext()) {
2378 aRect = ComputeAnchorRect(rootPresContext, anchorFrame);
2379 }
2380 }
2381
2382 return true;
2383}
2384
2385bool nsMenuPopupFrame::IsDirectionRTL() const {
2386 const nsIFrame* anchor = GetAnchorFrame();
2387 const nsIFrame* f = anchor ? anchor : this;
2388 return f->StyleVisibility()->mDirection == StyleDirection::Rtl;
2389}
2390
2391nsIFrame* nsMenuPopupFrame::GetAnchorFrame() const {
2392 nsIContent* anchor = mAnchorContent;
2393 if (!anchor) {
2394 return nullptr;
2395 }
2396 return MaybeDelegatedAnchorFrame(anchor->GetPrimaryFrame());
2397}
2398
2399void nsMenuPopupFrame::CheckForAnchorChange(nsRect& aRect) {
2400 // Don't update if the popup isn't visible or we shouldn't be following the
2401 // anchor.
2402 if (!IsVisible() || !ShouldFollowAnchor()) {
2403 return;
2404 }
2405
2406 bool shouldHide = false;
2407
2408 nsPresContext* rootPresContext = PresContext()->GetRootPresContext();
2409
2410 // If the frame for the anchor has gone away, hide the popup.
2411 nsIFrame* anchor = GetAnchorFrame();
2412 if (!anchor || !rootPresContext) {
2413 shouldHide = true;
2414 } else if (!anchor->IsVisibleConsideringAncestors(
2415 VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) {
2416 // If the anchor is now inside something that is invisible, hide the popup.
2417 shouldHide = true;
2418 } else {
2419 // If the anchor is now inside a hidden parent popup, hide the popup.
2420 nsIFrame* frame = anchor;
2421 while (frame) {
2422 nsMenuPopupFrame* popup = do_QueryFrame(frame);
2423 if (popup && popup->PopupState() != ePopupShown) {
2424 shouldHide = true;
2425 break;
2426 }
2427
2428 frame = frame->GetParent();
2429 }
2430 }
2431
2432 if (shouldHide) {
2433 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2434 if (pm) {
2435 // As the caller will be iterating over the open popups, hide
2436 // asyncronously.
2437 pm->HidePopup(mContent->AsElement(),
2438 {HidePopupOption::DeselectMenu, HidePopupOption::Async});
2439 }
2440
2441 return;
2442 }
2443
2444 nsRect anchorRect = ComputeAnchorRect(rootPresContext, anchor);
2445
2446 // If the rectangles are different, move the popup.
2447 if (!anchorRect.IsEqualEdges(aRect)) {
2448 aRect = anchorRect;
2449 SetPopupPosition(true);
2450 }
2451}