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-18/lib/clang/18 -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 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-18/lib/clang/18/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 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -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-2024-07-30-004816-4182763-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
73int8_t nsMenuPopupFrame::sDefaultLevelIsTop = -1;
74
75TimeStamp nsMenuPopupFrame::sLastKeyTime;
76
77#ifdef MOZ_WAYLAND1
78# include "mozilla/WidgetUtilsGtk.h"
79# define IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() mozilla::widget::GdkIsWaylandDisplay()
80extern mozilla::LazyLogModule gWidgetPopupLog;
81# 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)
\
82 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)
83#else
84# define IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() false
85# 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)
86#endif
87
88// NS_NewMenuPopupFrame
89//
90// Wrapper for creating a new menu popup container
91//
92nsIFrame* NS_NewMenuPopupFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
93 return new (aPresShell)
94 nsMenuPopupFrame(aStyle, aPresShell->GetPresContext());
95}
96
97NS_IMPL_FRAMEARENA_HELPERS(nsMenuPopupFrame)void* nsMenuPopupFrame ::operator new(size_t sz, mozilla::PresShell
* aShell) { return aShell->AllocateFrame(nsQueryFrame::nsMenuPopupFrame_id
, sz); }
98
99NS_QUERYFRAME_HEAD(nsMenuPopupFrame)void* nsMenuPopupFrame ::QueryFrame(FrameIID id) const { switch
(id) {
100 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)); }
101NS_QUERYFRAME_TAIL_INHERITING(nsBlockFrame)default: break; } return nsBlockFrame ::QueryFrame(id); }
102
103//
104// nsMenuPopupFrame ctor
105//
106nsMenuPopupFrame::nsMenuPopupFrame(ComputedStyle* aStyle,
107 nsPresContext* aPresContext)
108 : nsBlockFrame(aStyle, aPresContext, kClassID) {
109 // the preference name is backwards here. True means that the 'top' level is
110 // the default, and false means that the 'parent' level is the default.
111 if (sDefaultLevelIsTop >= 0) return;
112 sDefaultLevelIsTop =
113 Preferences::GetBool("ui.panel.default_level_parent", false);
114} // ctor
115
116nsMenuPopupFrame::~nsMenuPopupFrame() = default;
117
118static bool IsMouseTransparent(const ComputedStyle& aStyle) {
119 // If pointer-events: none; is set on the popup, then the widget should
120 // ignore mouse events, passing them through to the content behind.
121 return aStyle.PointerEvents() == StylePointerEvents::None;
122}
123
124static nsIWidget::InputRegion ComputeInputRegion(const ComputedStyle& aStyle,
125 const nsPresContext& aPc) {
126 return {IsMouseTransparent(aStyle),
127 (aStyle.StyleUIReset()->mMozWindowInputRegionMargin.ToCSSPixels() *
128 aPc.CSSToDevPixelScale())
129 .Truncated()};
130}
131
132bool nsMenuPopupFrame::ShouldCreateWidgetUpfront() const {
133 if (mPopupType != PopupType::Menu) {
134 // Any panel with a type attribute, such as the autocomplete popup, is
135 // always generated right away.
136 return mContent->AsElement()->HasAttr(nsGkAtoms::type);
137 }
138
139 // Generate the widget up-front if the parent menu is a <menulist> unless its
140 // sizetopopup is set to "none".
141 return ShouldExpandToInflowParentOrAnchor();
142}
143
144void nsMenuPopupFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
145 nsIFrame* aPrevInFlow) {
146 nsBlockFrame::Init(aContent, aParent, aPrevInFlow);
147
148 CreatePopupView();
149
150 // XXX Hack. The popup's view should float above all other views,
151 // so we use the nsView::SetFloating() to tell the view manager
152 // about that constraint.
153 nsView* ourView = GetView();
154 nsViewManager* viewManager = ourView->GetViewManager();
155 viewManager->SetViewFloating(ourView, true);
156
157 const auto& el = PopupElement();
158 mPopupType = PopupType::Panel;
159 if (el.IsMenu()) {
160 mPopupType = PopupType::Menu;
161 } else if (el.IsXULElement(nsGkAtoms::tooltip)) {
162 mPopupType = PopupType::Tooltip;
163 }
164
165 if (PresContext()->IsChrome()) {
166 mInContentShell = false;
167 }
168
169 // Support incontentshell=false attribute to allow popups to be displayed
170 // outside of the content shell. Chrome only.
171 if (el.NodePrincipal()->IsSystemPrincipal()) {
172 if (el.GetXULBoolAttr(nsGkAtoms::incontentshell)) {
173 mInContentShell = true;
174 } else if (el.AttrValueIs(kNameSpaceID_None, nsGkAtoms::incontentshell,
175 nsGkAtoms::_false, eCaseMatters)) {
176 mInContentShell = false;
177 }
178 }
179
180 // To improve performance, create the widget for the popup if needed. Popups
181 // such as menus will create their widgets later when the popup opens.
182 //
183 // FIXME(emilio): Doing this up-front for all menupopups causes a bunch of
184 // assertions, while it's supposed to be just an optimization.
185 if (!ourView->HasWidget() && ShouldCreateWidgetUpfront()) {
186 CreateWidgetForView(ourView);
187 }
188
189 AddStateBits(NS_FRAME_IN_POPUP);
190}
191
192bool nsMenuPopupFrame::HasRemoteContent() const {
193 return !mInContentShell && mPopupType == PopupType::Panel &&
194 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
195 nsGkAtoms::remote, nsGkAtoms::_true,
196 eIgnoreCase);
197}
198
199bool nsMenuPopupFrame::IsNoAutoHide() const {
200 // Panels with noautohide="true" don't hide when the mouse is clicked
201 // outside of them, or when another application is made active. Non-autohide
202 // panels cannot be used in content windows.
203 return !mInContentShell && mPopupType == PopupType::Panel &&
204 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
205 nsGkAtoms::noautohide,
206 nsGkAtoms::_true, eIgnoreCase);
207}
208
209widget::PopupLevel nsMenuPopupFrame::GetPopupLevel(bool aIsNoAutoHide) const {
210 // The popup level is determined as follows, in this order:
211 // 1. non-panels (menus and tooltips) are always topmost
212 // 2. any specified level attribute
213 // 3. if a titlebar attribute is set, use the 'floating' level
214 // 4. if this is a noautohide panel, use the 'parent' level
215 // 5. use the platform-specific default level
216
217 // If this is not a panel, this is always a top-most popup.
218 if (mPopupType != PopupType::Panel) {
219 return PopupLevel::Top;
220 }
221
222 // If the level attribute has been set, use that.
223 static Element::AttrValuesArray strings[] = {nsGkAtoms::top,
224 nsGkAtoms::parent, nullptr};
225 switch (mContent->AsElement()->FindAttrValueIn(
226 kNameSpaceID_None, nsGkAtoms::level, strings, eCaseMatters)) {
227 case 0:
228 return PopupLevel::Top;
229 case 1:
230 return PopupLevel::Parent;
231 default:
232 break;
233 }
234
235 // If this panel is a noautohide panel, the default is the parent level.
236 if (aIsNoAutoHide) {
237 return PopupLevel::Parent;
238 }
239
240 // Otherwise, the result depends on the platform.
241 return sDefaultLevelIsTop ? PopupLevel::Top : PopupLevel::Parent;
242}
243
244void nsMenuPopupFrame::PrepareWidget(bool aRecreate) {
245 nsView* ourView = GetView();
246 if (aRecreate) {
247 if (auto* widget = GetWidget()) {
248 // Widget's WebRender resources needs to be cleared before creating new
249 // widget.
250 widget->ClearCachedWebrenderResources();
251 }
252 ourView->DestroyWidget();
253 }
254 if (!ourView->HasWidget()) {
255 CreateWidgetForView(ourView);
256 } else {
257 PropagateStyleToWidget();
258 }
259}
260
261nsresult nsMenuPopupFrame::CreateWidgetForView(nsView* aView) {
262 // Create a widget for ourselves.
263 widget::InitData widgetData;
264 widgetData.mWindowType = widget::WindowType::Popup;
265 widgetData.mBorderStyle = widget::BorderStyle::Default;
266 widgetData.mClipSiblings = true;
267 widgetData.mPopupHint = mPopupType;
268 widgetData.mNoAutoHide = IsNoAutoHide();
269
270 if (!mInContentShell) {
271 // A drag popup may be used for non-static translucent drag feedback
272 if (mPopupType == PopupType::Panel &&
273 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
274 nsGkAtoms::drag, eIgnoreCase)) {
275 widgetData.mIsDragPopup = true;
276 }
277 }
278
279 bool remote = HasRemoteContent();
280
281 const auto mode = nsLayoutUtils::GetFrameTransparency(this, this);
282 widgetData.mHasRemoteContent = remote;
283 widgetData.mTransparencyMode = mode;
284 widgetData.mPopupLevel = GetPopupLevel(widgetData.mNoAutoHide);
285
286 // Panels which have a parent level need a parent widget. This allows them to
287 // always appear in front of the parent window but behind other windows that
288 // should be in front of it.
289 nsCOMPtr<nsIWidget> parentWidget;
290 if (widgetData.mPopupLevel != PopupLevel::Top) {
291 nsCOMPtr<nsIDocShellTreeItem> dsti = PresContext()->GetDocShell();
292 if (!dsti) return NS_ERROR_FAILURE;
293
294 nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
295 dsti->GetTreeOwner(getter_AddRefs(treeOwner));
296 if (!treeOwner) return NS_ERROR_FAILURE;
297
298 nsCOMPtr<nsIBaseWindow> baseWindow(do_QueryInterface(treeOwner));
299 if (baseWindow) baseWindow->GetMainWidget(getter_AddRefs(parentWidget));
300 }
301
302 nsresult rv = aView->CreateWidgetForPopup(&widgetData, parentWidget);
303 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
304 return rv;
305 }
306
307 nsIWidget* widget = aView->GetWidget();
308 widget->SetTransparencyMode(mode);
309
310 PropagateStyleToWidget();
311
312 return NS_OK;
313}
314
315void nsMenuPopupFrame::PropagateStyleToWidget(WidgetStyleFlags aFlags) const {
316 if (aFlags.isEmpty()) {
317 return;
318 }
319
320 nsIWidget* widget = GetWidget();
321 if (!widget) {
322 return;
323 }
324
325 if (aFlags.contains(WidgetStyle::ColorScheme)) {
326 widget->SetColorScheme(Some(LookAndFeel::ColorSchemeForFrame(this)));
327 }
328 if (aFlags.contains(WidgetStyle::InputRegion)) {
329 widget->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
330 }
331 if (aFlags.contains(WidgetStyle::Opacity)) {
332 widget->SetWindowOpacity(StyleUIReset()->mWindowOpacity);
333 }
334 if (aFlags.contains(WidgetStyle::Shadow)) {
335 widget->SetWindowShadowStyle(GetShadowStyle());
336 }
337 if (aFlags.contains(WidgetStyle::Transform)) {
338 widget->SetWindowTransform(ComputeWidgetTransform());
339 }
340}
341
342bool nsMenuPopupFrame::IsMouseTransparent() const {
343 return ::IsMouseTransparent(*Style());
344}
345
346WindowShadow nsMenuPopupFrame::GetShadowStyle() const {
347 StyleWindowShadow shadow = StyleUIReset()->mWindowShadow;
348 if (shadow != StyleWindowShadow::Auto) {
349 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"
, 349); AnnotateMozCrashReason("MOZ_ASSERT" "(" "shadow == StyleWindowShadow::None"
")"); do { *((volatile int*)__null) = 349; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
350 return WindowShadow::None;
351 }
352
353 switch (StyleDisplay()->EffectiveAppearance()) {
354 case StyleAppearance::Tooltip:
355 return WindowShadow::Tooltip;
356 case StyleAppearance::Menupopup:
357 return WindowShadow::Menu;
358 default:
359 return WindowShadow::Panel;
360 }
361}
362
363void nsMenuPopupFrame::SetPopupState(nsPopupState aState) {
364 mPopupState = aState;
365
366 // Work around https://gitlab.gnome.org/GNOME/gtk/-/issues/4166
367 if (aState == ePopupShown && IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay()) {
368 if (nsIWidget* widget = GetWidget()) {
369 widget->SetInputRegion(ComputeInputRegion(*Style(), *PresContext()));
370 }
371 }
372}
373
374// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
375MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMPnsresult nsXULPopupShownEvent::Run() {
376 nsMenuPopupFrame* popup = do_QueryFrame(mPopup->GetPrimaryFrame());
377 // Set the state to visible if the popup is still open.
378 if (popup && popup->IsOpen()) {
379 popup->SetPopupState(ePopupShown);
380 }
381
382 if (!mPopup->IsXULElement(nsGkAtoms::tooltip)) {
383 nsCOMPtr<nsIObserverService> obsService =
384 mozilla::services::GetObserverService();
385 if (obsService) {
386 obsService->NotifyObservers(mPopup, "popup-shown", nullptr);
387 }
388 }
389 WidgetMouseEvent event(true, eXULPopupShown, nullptr,
390 WidgetMouseEvent::eReal);
391 return EventDispatcher::Dispatch(mPopup, mPresContext, &event);
392}
393
394NS_IMETHODIMPnsresult nsXULPopupShownEvent::HandleEvent(Event* aEvent) {
395 nsMenuPopupFrame* popup = do_QueryFrame(mPopup->GetPrimaryFrame());
396 // Ignore events not targeted at the popup itself (ie targeted at
397 // descendants):
398 if (mPopup != aEvent->GetTarget()) {
399 return NS_OK;
400 }
401 if (popup) {
402 // ResetPopupShownDispatcher will delete the reference to this, so keep
403 // another one until Run is finished.
404 RefPtr<nsXULPopupShownEvent> event = this;
405 // Only call Run if it the dispatcher was assigned. This avoids calling the
406 // Run method if the transitionend event fires multiple times.
407 if (popup->ClearPopupShownDispatcher()) {
408 return Run();
409 }
410 }
411
412 CancelListener();
413 return NS_OK;
414}
415
416void nsXULPopupShownEvent::CancelListener() {
417 mPopup->RemoveSystemEventListener(u"transitionend"_ns, this, false);
418}
419
420NS_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"
, 421); 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
((sizeof(table) / sizeof(table[0])) > 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; }
421 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"
, 421); 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
((sizeof(table) / sizeof(table[0])) > 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; }
;
422
423void nsMenuPopupFrame::DidSetComputedStyle(ComputedStyle* aOldStyle) {
424 nsBlockFrame::DidSetComputedStyle(aOldStyle);
425
426 if (!aOldStyle) {
427 return;
428 }
429
430 WidgetStyleFlags flags;
431
432 if (aOldStyle->StyleUI()->mColorScheme != StyleUI()->mColorScheme) {
433 flags += WidgetStyle::ColorScheme;
434 }
435
436 auto& newUI = *StyleUIReset();
437 auto& oldUI = *aOldStyle->StyleUIReset();
438 if (newUI.mWindowOpacity != oldUI.mWindowOpacity) {
439 flags += WidgetStyle::Opacity;
440 }
441
442 if (newUI.mMozWindowTransform != oldUI.mMozWindowTransform) {
443 flags += WidgetStyle::Transform;
444 }
445
446 if (newUI.mWindowShadow != oldUI.mWindowShadow) {
447 flags += WidgetStyle::Shadow;
448 }
449
450 const auto& pc = *PresContext();
451 auto oldRegion = ComputeInputRegion(*aOldStyle, pc);
452 auto newRegion = ComputeInputRegion(*Style(), pc);
453 if (oldRegion.mFullyTransparent != newRegion.mFullyTransparent ||
454 oldRegion.mMargin != newRegion.mMargin) {
455 flags += WidgetStyle::InputRegion;
456 }
457
458 PropagateStyleToWidget(flags);
459}
460
461nscoord nsMenuPopupFrame::IntrinsicISize(gfxContext* aContext,
462 IntrinsicISizeType aType) {
463 nscoord iSize = nsBlockFrame::IntrinsicISize(aContext, aType);
464 if (!ShouldExpandToInflowParentOrAnchor()) {
465 return iSize;
466 }
467 // Make sure to accommodate for our scrollbar if needed. Do it only for
468 // menulists to match previous behavior.
469 //
470 // NOTE(emilio): This is somewhat hacky. The "right" fix (which would be
471 // using scrollbar-gutter: stable on the scroller) isn't great, because even
472 // though we want a stable gutter, we want to draw on top of the gutter when
473 // there's no scrollbar, otherwise it looks rather weird.
474 //
475 // Automatically accommodating for the scrollbar otherwise would be bug
476 // 764076, but that has its own set of problems.
477 if (ScrollContainerFrame* sf = GetScrollContainerFrame()) {
478 iSize += sf->GetDesiredScrollbarSizes().LeftRight();
479 }
480
481 nscoord menuListOrAnchorWidth = 0;
482 if (nsIFrame* menuList = GetInFlowParent()) {
483 menuListOrAnchorWidth = menuList->GetRect().width;
484 }
485 if (mAnchorType == MenuPopupAnchorType::Rect) {
486 menuListOrAnchorWidth = std::max(menuListOrAnchorWidth, mScreenRect.width);
487 }
488 // Input margin doesn't have contents, so account for it for popup sizing
489 // purposes.
490 menuListOrAnchorWidth +=
491 2 * StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
492
493 return std::max(iSize, menuListOrAnchorWidth);
494}
495
496void nsMenuPopupFrame::Reflow(nsPresContext* aPresContext,
497 ReflowOutput& aDesiredSize,
498 const ReflowInput& aReflowInput,
499 nsReflowStatus& aStatus) {
500 MarkInReflow();
501 DO_GLOBAL_REFLOW_COUNT("nsMenuPopupFrame")aPresContext->CountReflows(("nsMenuPopupFrame"), (nsIFrame
*)this);
;
502 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"
, 502); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 502; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
503
504 const auto wm = GetWritingMode();
505 // Default to preserving our bounds.
506 aDesiredSize.SetSize(wm, GetLogicalSize(wm));
507
508 LayoutPopup(aPresContext, aDesiredSize, aReflowInput, aStatus);
509
510 aDesiredSize.SetBlockStartAscent(aDesiredSize.BSize(wm));
511 aDesiredSize.SetOverflowAreasToDesiredBounds();
512 FinishAndStoreOverflow(&aDesiredSize, aReflowInput.mStyleDisplay);
513}
514
515void nsMenuPopupFrame::EnsureActiveMenuListItemIsVisible() {
516 if (!IsMenuList() || !IsOpen()) {
517 return;
518 }
519 nsIFrame* frame = GetCurrentMenuItemFrame();
520 if (!frame) {
521 return;
522 }
523 RefPtr<mozilla::PresShell> presShell = PresShell();
524 presShell->ScrollFrameIntoView(
525 frame, Nothing(), ScrollAxis(), ScrollAxis(),
526 ScrollFlags::ScrollOverflowHidden | ScrollFlags::ScrollFirstAncestorOnly);
527}
528
529void nsMenuPopupFrame::LayoutPopup(nsPresContext* aPresContext,
530 ReflowOutput& aDesiredSize,
531 const ReflowInput& aReflowInput,
532 nsReflowStatus& aStatus) {
533 if (IsNativeMenu()) {
534 return;
535 }
536
537 SchedulePaint();
538
539 const bool isOpen = IsOpen();
540 if (!isOpen) {
541 // If the popup is not open, only do layout while showing or if we're a
542 // menulist.
543 //
544 // This is needed because the SelectParent code wants to limit the height of
545 // the popup before opening it.
546 //
547 // TODO(emilio): We should consider adding a way to do that more reliably
548 // instead, but this preserves existing behavior.
549 const bool needsLayout = mPopupState == ePopupShowing ||
550 mPopupState == ePopupPositioning || IsMenuList();
551 if (!needsLayout) {
552 RemoveStateBits(NS_FRAME_FIRST_REFLOW);
553 return;
554 }
555 }
556
557 // Do a first reflow, with all our content, in order to find our preferred
558 // size. Then, we do a second reflow with the updated dimensions.
559 const bool needsPrefSize = mPrefSize == nsSize(-1, -1) || IsSubtreeDirty();
560 if (needsPrefSize) {
561 // Get the preferred, minimum and maximum size. If the menu is sized to the
562 // popup, then the popup's width is the menu's width.
563 ReflowOutput preferredSize(aReflowInput);
564 nsBlockFrame::Reflow(aPresContext, preferredSize, aReflowInput, aStatus);
565 mPrefSize = preferredSize.PhysicalSize();
566 }
567
568 // Get our desired position and final size, now that we have a preferred size.
569 auto constraints = GetRects(mPrefSize);
570 const auto finalSize = constraints.mUsedRect.Size();
571
572 // We need to do an extra reflow if we haven't reflowed, our size doesn't
573 // match with our final intended size, or our bsize is unconstrained (in which
574 // case we need to specify the final size so that percentages work).
575 const bool needDefiniteReflow =
576 aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE || !needsPrefSize ||
577 finalSize != mPrefSize;
578
579 if (needDefiniteReflow) {
580 ReflowInput constrainedReflowInput(aReflowInput);
581 const auto& bp = aReflowInput.ComputedPhysicalBorderPadding();
582 // TODO: writing-mode handling not terribly correct, but it doesn't matter.
583 const nsSize finalContentSize(finalSize.width - bp.LeftRight(),
584 finalSize.height - bp.TopBottom());
585 constrainedReflowInput.SetComputedISize(finalContentSize.width);
586 constrainedReflowInput.SetComputedBSize(finalContentSize.height);
587 constrainedReflowInput.SetIResize(finalSize.width != mPrefSize.width);
588 constrainedReflowInput.SetBResize([&] {
589 if (finalSize.height != mPrefSize.height) {
590 return true;
591 }
592 if (needsPrefSize &&
593 aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE &&
594 aReflowInput.ComputedMaxBSize() == finalContentSize.height) {
595 // If we have measured, and maybe clamped our children via max-height,
596 // they might need to get percentages in the block axis re-resolved.
597 return true;
598 }
599 return false;
600 }());
601
602 aStatus.Reset();
603 nsBlockFrame::Reflow(aPresContext, aDesiredSize, constrainedReflowInput,
604 aStatus);
605 }
606
607 // Set our size, since nsAbsoluteContainingBlock won't.
608 SetRect(constraints.mUsedRect);
609
610 nsView* view = GetView();
611 if (isOpen) {
612 nsViewManager* viewManager = view->GetViewManager();
613 viewManager->ResizeView(view,
614 nsRect(nsPoint(), constraints.mUsedRect.Size()));
615 if (mPopupState == ePopupOpening) {
616 mPopupState = ePopupVisible;
617 }
618
619 viewManager->SetViewVisibility(view, ViewVisibility::Show);
620 SyncFrameViewProperties(view);
621 }
622
623 // Perform our move now. That will position the view and so on.
624 PerformMove(constraints);
625
626 // finally, if the popup just opened, send a popupshown event
627 bool openChanged = mIsOpenChanged;
628 if (openChanged) {
629 mIsOpenChanged = false;
630
631 // Make sure the current selection in a menulist is visible.
632 EnsureActiveMenuListItemIsVisible();
633
634 // If the animate attribute is set to open, check for a transition and wait
635 // for it to finish before firing the popupshown event.
636 if (LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations) &&
637 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
638 nsGkAtoms::animate, nsGkAtoms::open,
639 eCaseMatters) &&
640 AnimationUtils::HasCurrentTransitions(mContent->AsElement(),
641 PseudoStyleType::NotPseudo)) {
642 mPopupShownDispatcher = new nsXULPopupShownEvent(mContent, aPresContext);
643 mContent->AddSystemEventListener(u"transitionend"_ns,
644 mPopupShownDispatcher, false, false);
645 return;
646 }
647
648 // If there are no transitions, fire the popupshown event right away.
649 nsCOMPtr<nsIRunnable> event =
650 new nsXULPopupShownEvent(GetContent(), aPresContext);
651 mContent->OwnerDoc()->Dispatch(event.forget());
652 }
653}
654
655bool nsMenuPopupFrame::IsMenuList() const {
656 return PopupElement().IsInMenuList();
657}
658
659bool nsMenuPopupFrame::ShouldExpandToInflowParentOrAnchor() const {
660 return IsMenuList() && !mContent->GetParent()->AsElement()->AttrValueIs(
661 kNameSpaceID_None, nsGkAtoms::sizetopopup,
662 nsGkAtoms::none, eCaseMatters);
663}
664
665nsIContent* nsMenuPopupFrame::GetTriggerContent(
666 nsMenuPopupFrame* aMenuPopupFrame) {
667 while (aMenuPopupFrame) {
668 if (aMenuPopupFrame->mTriggerContent) {
669 return aMenuPopupFrame->mTriggerContent;
670 }
671
672 auto* button = XULButtonElement::FromNodeOrNull(
673 aMenuPopupFrame->GetContent()->GetParent());
674 if (!button || !button->IsMenu()) {
675 break;
676 }
677
678 auto* popup = button->GetContainingPopupElement();
679 if (!popup) {
680 break;
681 }
682
683 // check up the menu hierarchy until a popup with a trigger node is found
684 aMenuPopupFrame = do_QueryFrame(popup->GetPrimaryFrame());
685 }
686
687 return nullptr;
688}
689
690void nsMenuPopupFrame::InitPositionFromAnchorAlign(const nsAString& aAnchor,
691 const nsAString& aAlign) {
692 mTriggerContent = nullptr;
693
694 if (aAnchor.EqualsLiteral("topleft"))
695 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
696 else if (aAnchor.EqualsLiteral("topright"))
697 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
698 else if (aAnchor.EqualsLiteral("bottomleft"))
699 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
700 else if (aAnchor.EqualsLiteral("bottomright"))
701 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
702 else if (aAnchor.EqualsLiteral("leftcenter"))
703 mPopupAnchor = POPUPALIGNMENT_LEFTCENTER16;
704 else if (aAnchor.EqualsLiteral("rightcenter"))
705 mPopupAnchor = POPUPALIGNMENT_RIGHTCENTER-16;
706 else if (aAnchor.EqualsLiteral("topcenter"))
707 mPopupAnchor = POPUPALIGNMENT_TOPCENTER17;
708 else if (aAnchor.EqualsLiteral("bottomcenter"))
709 mPopupAnchor = POPUPALIGNMENT_BOTTOMCENTER18;
710 else
711 mPopupAnchor = POPUPALIGNMENT_NONE0;
712
713 if (aAlign.EqualsLiteral("topleft"))
714 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
715 else if (aAlign.EqualsLiteral("topright"))
716 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
717 else if (aAlign.EqualsLiteral("bottomleft"))
718 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
719 else if (aAlign.EqualsLiteral("bottomright"))
720 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
721 else if (aAlign.EqualsLiteral("leftcenter"))
722 mPopupAlignment = POPUPALIGNMENT_LEFTCENTER16;
723 else if (aAlign.EqualsLiteral("rightcenter"))
724 mPopupAlignment = POPUPALIGNMENT_RIGHTCENTER-16;
725 else if (aAlign.EqualsLiteral("topcenter"))
726 mPopupAlignment = POPUPALIGNMENT_TOPCENTER17;
727 else if (aAlign.EqualsLiteral("bottomcenter"))
728 mPopupAlignment = POPUPALIGNMENT_BOTTOMCENTER18;
729 else
730 mPopupAlignment = POPUPALIGNMENT_NONE0;
731
732 mPosition = POPUPPOSITION_UNKNOWN-1;
733}
734
735static FlipType FlipFromAttribute(nsMenuPopupFrame* aFrame) {
736 nsAutoString flip;
737 aFrame->PopupElement().GetAttr(nsGkAtoms::flip, flip);
738 if (flip.EqualsLiteral("none")) {
739 return FlipType_None;
740 }
741 if (flip.EqualsLiteral("both")) {
742 return FlipType_Both;
743 }
744 if (flip.EqualsLiteral("slide")) {
745 return FlipType_Slide;
746 }
747 return FlipType_Default;
748}
749
750void nsMenuPopupFrame::InitializePopup(nsIContent* aAnchorContent,
751 nsIContent* aTriggerContent,
752 const nsAString& aPosition,
753 int32_t aXPos, int32_t aYPos,
754 MenuPopupAnchorType aAnchorType,
755 bool aAttributesOverride) {
756 auto* widget = GetWidget();
757 bool recreateWidget = widget && widget->NeedsRecreateToReshow();
758 PrepareWidget(recreateWidget);
759
760 mPopupState = ePopupShowing;
761 mAnchorContent = aAnchorContent;
762 mTriggerContent = aTriggerContent;
763 mXPos = aXPos;
764 mYPos = aYPos;
765 mIsNativeMenu = false;
766 mIsTopLevelContextMenu = false;
767 mVFlip = false;
768 mHFlip = false;
769 mConstrainedByLayout = false;
770 mAlignmentOffset = 0;
771 mPositionedOffset = 0;
772 mPositionedByMoveToRect = false;
773
774 mAnchorType = aAnchorType;
775
776 // if aAttributesOverride is true, then the popupanchor, popupalign and
777 // position attributes on the <menupopup> override those values passed in.
778 // If false, those attributes are only used if the values passed in are empty
779 if (aAnchorContent || aAnchorType == MenuPopupAnchorType::Rect) {
780 nsAutoString anchor, align, position;
781 mContent->AsElement()->GetAttr(nsGkAtoms::popupanchor, anchor);
782 mContent->AsElement()->GetAttr(nsGkAtoms::popupalign, align);
783 mContent->AsElement()->GetAttr(nsGkAtoms::position, position);
784
785 if (aAttributesOverride) {
786 // if the attributes are set, clear the offset position. Otherwise,
787 // the offset is used to adjust the position from the anchor point
788 if (anchor.IsEmpty() && align.IsEmpty() && position.IsEmpty())
789 position.Assign(aPosition);
790 else
791 mXPos = mYPos = 0;
792 } else if (!aPosition.IsEmpty()) {
793 position.Assign(aPosition);
794 }
795
796 mFlip = FlipFromAttribute(this);
797
798 position.CompressWhitespace();
799 int32_t spaceIdx = position.FindChar(' ');
800 // if there is a space in the position, assume it is the anchor and
801 // alignment as two separate tokens.
802 if (spaceIdx >= 0) {
803 InitPositionFromAnchorAlign(Substring(position, 0, spaceIdx),
804 Substring(position, spaceIdx + 1));
805 } else if (position.EqualsLiteral("before_start")) {
806 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
807 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
808 mPosition = POPUPPOSITION_BEFORESTART0;
809 } else if (position.EqualsLiteral("before_end")) {
810 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
811 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
812 mPosition = POPUPPOSITION_BEFOREEND1;
813 } else if (position.EqualsLiteral("after_start")) {
814 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
815 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
816 mPosition = POPUPPOSITION_AFTERSTART2;
817 } else if (position.EqualsLiteral("after_end")) {
818 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
819 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
820 mPosition = POPUPPOSITION_AFTEREND3;
821 } else if (position.EqualsLiteral("start_before")) {
822 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
823 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
824 mPosition = POPUPPOSITION_STARTBEFORE4;
825 } else if (position.EqualsLiteral("start_after")) {
826 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
827 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
828 mPosition = POPUPPOSITION_STARTAFTER6;
829 } else if (position.EqualsLiteral("end_before")) {
830 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
831 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
832 mPosition = POPUPPOSITION_ENDBEFORE5;
833 } else if (position.EqualsLiteral("end_after")) {
834 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
835 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
836 mPosition = POPUPPOSITION_ENDAFTER7;
837 } else if (position.EqualsLiteral("overlap")) {
838 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
839 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
840 mPosition = POPUPPOSITION_OVERLAP8;
841 } else if (position.EqualsLiteral("selection")) {
842 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
843 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
844 mPosition = POPUPPOSITION_SELECTION10;
845 } else {
846 InitPositionFromAnchorAlign(anchor, align);
847 }
848 }
849 // When converted back to CSSIntRect it is (-1, -1, 0, 0) - as expected in
850 // nsXULPopupManager::Rollup
851 mScreenRect = nsRect(-AppUnitsPerCSSPixel(), -AppUnitsPerCSSPixel(), 0, 0);
852
853 if (aAttributesOverride) {
854 // Use |left| and |top| dimension attributes to position the popup if
855 // present, as they may have been persisted.
856 nsAutoString left, top;
857 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
858 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
859
860 nsresult err;
861 if (!left.IsEmpty()) {
862 int32_t x = left.ToInteger(&err);
863 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
864 mScreenRect.x = CSSPixel::ToAppUnits(x);
865 }
866 }
867 if (!top.IsEmpty()) {
868 int32_t y = top.ToInteger(&err);
869 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
870 mScreenRect.y = CSSPixel::ToAppUnits(y);
871 }
872 }
873 }
874}
875
876void nsMenuPopupFrame::InitializePopupAtScreen(nsIContent* aTriggerContent,
877 int32_t aXPos, int32_t aYPos,
878 bool aIsContextMenu) {
879 auto* widget = GetWidget();
880 bool recreateWidget = widget && widget->NeedsRecreateToReshow();
881 PrepareWidget(recreateWidget);
882
883 mPopupState = ePopupShowing;
884 mAnchorContent = nullptr;
885 mTriggerContent = aTriggerContent;
886 mScreenRect =
887 nsRect(CSSPixel::ToAppUnits(aXPos), CSSPixel::ToAppUnits(aYPos), 0, 0);
888 mXPos = 0;
889 mYPos = 0;
890 mFlip = FlipFromAttribute(this);
891 mPopupAnchor = POPUPALIGNMENT_NONE0;
892 mPopupAlignment = POPUPALIGNMENT_NONE0;
893 mPosition = POPUPPOSITION_UNKNOWN-1;
894 mIsContextMenu = aIsContextMenu;
895 mIsTopLevelContextMenu = aIsContextMenu;
896 mIsNativeMenu = false;
897 mAnchorType = MenuPopupAnchorType::Point;
898 mPositionedOffset = 0;
899 mPositionedByMoveToRect = false;
900}
901
902void nsMenuPopupFrame::InitializePopupAsNativeContextMenu(
903 nsIContent* aTriggerContent, int32_t aXPos, int32_t aYPos) {
904 mTriggerContent = aTriggerContent;
905 mPopupState = ePopupShowing;
906 mAnchorContent = nullptr;
907 mScreenRect =
908 nsRect(CSSPixel::ToAppUnits(aXPos), CSSPixel::ToAppUnits(aYPos), 0, 0);
909 mXPos = 0;
910 mYPos = 0;
911 mFlip = FlipType_Default;
912 mPopupAnchor = POPUPALIGNMENT_NONE0;
913 mPopupAlignment = POPUPALIGNMENT_NONE0;
914 mPosition = POPUPPOSITION_UNKNOWN-1;
915 mIsContextMenu = true;
916 mIsTopLevelContextMenu = true;
917 mIsNativeMenu = true;
918 mAnchorType = MenuPopupAnchorType::Point;
919 mPositionedOffset = 0;
920 mPositionedByMoveToRect = false;
921}
922
923void nsMenuPopupFrame::InitializePopupAtRect(nsIContent* aTriggerContent,
924 const nsAString& aPosition,
925 const nsIntRect& aRect,
926 bool aAttributesOverride) {
927 InitializePopup(nullptr, aTriggerContent, aPosition, 0, 0,
928 MenuPopupAnchorType::Rect, aAttributesOverride);
929 mScreenRect = ToAppUnits(aRect, AppUnitsPerCSSPixel());
930}
931
932void nsMenuPopupFrame::ShowPopup(bool aIsContextMenu) {
933 mIsContextMenu = aIsContextMenu;
934
935 InvalidateFrameSubtree();
936
937 if (mPopupState == ePopupShowing || mPopupState == ePopupPositioning) {
938 mPopupState = ePopupOpening;
939 mIsOpenChanged = true;
940
941 // Clear mouse capture when a popup is opened.
942 if (mPopupType == PopupType::Menu) {
943 if (auto* activeESM = EventStateManager::GetActiveEventStateManager()) {
944 EventStateManager::ClearGlobalActiveContent(activeESM);
945 }
946
947 PresShell::ReleaseCapturingContent();
948 }
949
950 if (RefPtr menu = PopupElement().GetContainingMenu()) {
951 menu->PopupOpened();
952 }
953
954 // We skip laying out children if we're closed, so make sure that we do a
955 // full dirty reflow when opening to pick up any potential change.
956 PresShell()->FrameNeedsReflow(
957 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
958
959 if (mPopupType == PopupType::Menu) {
960 nsCOMPtr<nsISound> sound(do_GetService("@mozilla.org/sound;1"));
961 if (sound) sound->PlayEventSound(nsISound::EVENT_MENU_POPUP);
962 }
963 }
964}
965
966void nsMenuPopupFrame::ClearTriggerContentIncludingDocument() {
967 // clear the trigger content if the popup is being closed. But don't clear
968 // it if the popup is just being made invisible as a popuphiding or command
969 if (mTriggerContent) {
970 // if the popup had a trigger node set, clear the global window popup node
971 // as well
972 Document* doc = mContent->GetUncomposedDoc();
973 if (doc) {
974 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
975 nsCOMPtr<nsPIWindowRoot> root = win->GetTopWindowRoot();
976 if (root) {
977 root->SetPopupNode(nullptr);
978 }
979 }
980 }
981 }
982 mTriggerContent = nullptr;
983}
984
985void nsMenuPopupFrame::HidePopup(bool aDeselectMenu, nsPopupState aNewState,
986 bool aFromFrameDestruction) {
987 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"
, 988); MOZ_PretendNoReturn(); } } while (0)
988 "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"
, 988); MOZ_PretendNoReturn(); } } while (0)
;
989
990 ClearPopupShownDispatcher();
991
992 // don't hide the popup when it isn't open
993 if (mPopupState == ePopupClosed || mPopupState == ePopupShowing ||
994 mPopupState == ePopupPositioning) {
995 return;
996 }
997
998 if (aNewState == ePopupClosed) {
999 // clear the trigger content if the popup is being closed. But don't clear
1000 // it if the popup is just being made invisible as a popuphiding or command
1001 // event may want to retrieve it.
1002 ClearTriggerContentIncludingDocument();
1003 mAnchorContent = nullptr;
1004 }
1005
1006 // when invisible and about to be closed, HidePopup has already been called,
1007 // so just set the new state to closed and return
1008 if (mPopupState == ePopupInvisible) {
1009 if (aNewState == ePopupClosed) {
1010 mPopupState = ePopupClosed;
1011 }
1012 return;
1013 }
1014
1015 mPopupState = aNewState;
1016
1017 mIncrementalString.Truncate();
1018
1019 mIsOpenChanged = false;
1020 mHFlip = mVFlip = false;
1021 mConstrainedByLayout = false;
1022
1023 if (auto* widget = GetWidget()) {
1024 // Ideally we should call ClearCachedWebrenderResources but there are
1025 // intermittent failures (see bug 1748788), so we currently call
1026 // ClearWebrenderAnimationResources instead.
1027 widget->ClearWebrenderAnimationResources();
1028 }
1029
1030 nsView* view = GetView();
1031 nsViewManager* viewManager = view->GetViewManager();
1032 viewManager->SetViewVisibility(view, ViewVisibility::Hide);
1033
1034 RefPtr popup = &PopupElement();
1035 // XXX, bug 137033, In Windows, if mouse is outside the window when the
1036 // menupopup closes, no mouse_enter/mouse_exit event will be fired to clear
1037 // current hover state, we should clear it manually. This code may not the
1038 // best solution, but we can leave it here until we find the better approach.
1039 if (!aFromFrameDestruction &&
1040 popup->State().HasState(dom::ElementState::HOVER)) {
1041 EventStateManager* esm = PresContext()->EventStateManager();
1042 esm->SetContentState(nullptr, dom::ElementState::HOVER);
1043 }
1044 popup->PopupClosed(aDeselectMenu);
1045}
1046
1047nsPoint nsMenuPopupFrame::AdjustPositionForAnchorAlign(
1048 nsRect& anchorRect, const nsSize& aPrefSize, FlipStyle& aHFlip,
1049 FlipStyle& aVFlip) const {
1050 // flip the anchor and alignment for right-to-left
1051 int8_t popupAnchor(mPopupAnchor);
1052 int8_t popupAlign(mPopupAlignment);
1053 if (IsDirectionRTL()) {
1054 // no need to flip the centered anchor types vertically
1055 if (popupAnchor <= POPUPALIGNMENT_LEFTCENTER16) {
1056 popupAnchor = -popupAnchor;
1057 }
1058 popupAlign = -popupAlign;
1059 }
1060
1061 nsRect originalAnchorRect(anchorRect);
1062
1063 // first, determine at which corner of the anchor the popup should appear
1064 nsPoint pnt;
1065 switch (popupAnchor) {
1066 case POPUPALIGNMENT_LEFTCENTER16:
1067 pnt = nsPoint(anchorRect.x, anchorRect.y + anchorRect.height / 2);
1068 anchorRect.y = pnt.y;
1069 anchorRect.height = 0;
1070 break;
1071 case POPUPALIGNMENT_RIGHTCENTER-16:
1072 pnt = nsPoint(anchorRect.XMost(), anchorRect.y + anchorRect.height / 2);
1073 anchorRect.y = pnt.y;
1074 anchorRect.height = 0;
1075 break;
1076 case POPUPALIGNMENT_TOPCENTER17:
1077 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.y);
1078 anchorRect.x = pnt.x;
1079 anchorRect.width = 0;
1080 break;
1081 case POPUPALIGNMENT_BOTTOMCENTER18:
1082 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.YMost());
1083 anchorRect.x = pnt.x;
1084 anchorRect.width = 0;
1085 break;
1086 case POPUPALIGNMENT_TOPRIGHT-1:
1087 pnt = anchorRect.TopRight();
1088 break;
1089 case POPUPALIGNMENT_BOTTOMLEFT2:
1090 pnt = anchorRect.BottomLeft();
1091 break;
1092 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1093 pnt = anchorRect.BottomRight();
1094 break;
1095 case POPUPALIGNMENT_TOPLEFT1:
1096 default:
1097 pnt = anchorRect.TopLeft();
1098 break;
1099 }
1100
1101 // If the alignment is on the right edge of the popup, move the popup left
1102 // by the width. Similarly, if the alignment is on the bottom edge of the
1103 // popup, move the popup up by the height. In addition, account for the
1104 // margins of the popup on the edge on which it is aligned.
1105 nsMargin margin = GetMargin();
1106 switch (popupAlign) {
1107 case POPUPALIGNMENT_LEFTCENTER16:
1108 pnt.MoveBy(margin.left, -aPrefSize.height / 2);
1109 break;
1110 case POPUPALIGNMENT_RIGHTCENTER-16:
1111 pnt.MoveBy(-aPrefSize.width - margin.right, -aPrefSize.height / 2);
1112 break;
1113 case POPUPALIGNMENT_TOPCENTER17:
1114 pnt.MoveBy(-aPrefSize.width / 2, margin.top);
1115 break;
1116 case POPUPALIGNMENT_BOTTOMCENTER18:
1117 pnt.MoveBy(-aPrefSize.width / 2, -aPrefSize.height - margin.bottom);
1118 break;
1119 case POPUPALIGNMENT_TOPRIGHT-1:
1120 pnt.MoveBy(-aPrefSize.width - margin.right, margin.top);
1121 break;
1122 case POPUPALIGNMENT_BOTTOMLEFT2:
1123 pnt.MoveBy(margin.left, -aPrefSize.height - margin.bottom);
1124 break;
1125 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1126 pnt.MoveBy(-aPrefSize.width - margin.right,
1127 -aPrefSize.height - margin.bottom);
1128 break;
1129 case POPUPALIGNMENT_TOPLEFT1:
1130 default:
1131 pnt.MoveBy(margin.left, margin.top);
1132 break;
1133 }
1134
1135 // If we aligning to the selected item in the popup, adjust the vertical
1136 // position by the height of the menulist label and the selected item's
1137 // position.
1138 if (mPosition == POPUPPOSITION_SELECTION10) {
1139 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"
, 1140); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1140; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1140 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"
, 1140); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1140; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1141 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"
, 1142); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1142; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1142 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"
, 1142); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1142; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1143
1144 // Only adjust the popup if it just opened, otherwise the popup will move
1145 // around if its gets resized or the selection changed. Cache the value in
1146 // mPositionedOffset and use that instead for any future calculations.
1147 if (mIsOpenChanged) {
1148 if (nsIFrame* selectedItemFrame = GetSelectedItemForAlignment()) {
1149 const nscoord itemHeight = selectedItemFrame->GetRect().height;
1150 const nscoord itemOffset =
1151 selectedItemFrame->GetOffsetToIgnoringScrolling(this).y;
1152 // We want to line-up the anchor rect with the selected item, but if the
1153 // selected item is outside of our bounds, we don't want to shift the
1154 // popup up in a way that our box would no longer intersect with the
1155 // anchor.
1156 nscoord maxOffset = aPrefSize.height - itemHeight;
1157 if (const ScrollContainerFrame* sf = GetScrollContainerFrame()) {
1158 // HACK: We ideally would want to use the offset from the bottom
1159 // bottom of our scroll-frame to the bottom of our frame (so as to
1160 // ensure that the bottom of the scrollport is inside the anchor
1161 // rect).
1162 //
1163 // But at this point of the code, the scroll frame may not be laid out
1164 // with a definite size (might be overflowing us).
1165 //
1166 // So, we assume the offset from the bottom is symmetric to the offset
1167 // from the top. This holds for all the popups where this matters
1168 // (menulists on macOS, effectively), and seems better than somehow
1169 // moving the popup after the fact as we used to do.
1170 maxOffset -= sf->GetOffsetTo(this).y;
1171 }
1172 mPositionedOffset =
1173 originalAnchorRect.height + std::min(itemOffset, maxOffset);
1174 }
1175 }
1176
1177 pnt.y -= mPositionedOffset;
1178 }
1179
1180 // Flipping horizontally is allowed as long as the popup is above or below
1181 // the anchor. This will happen if both the anchor and alignment are top or
1182 // both are bottom, but different values. Similarly, flipping vertically is
1183 // allowed if the popup is to the left or right of the anchor. In this case,
1184 // the values of the constants are such that both must be positive or both
1185 // must be negative. A special case, used for overlap, allows flipping
1186 // vertically as well.
1187 // If we are flipping in both directions, we want to set a flip style both
1188 // horizontally and vertically. However, we want to flip on the inside edge
1189 // of the anchor. Consider the example of a typical dropdown menu.
1190 // Vertically, we flip the popup on the outside edges of the anchor menu,
1191 // however horizontally, we want to to use the inside edges so the popup
1192 // still appears underneath the anchor menu instead of floating off the
1193 // side of the menu.
1194 switch (popupAnchor) {
1195 case POPUPALIGNMENT_LEFTCENTER16:
1196 case POPUPALIGNMENT_RIGHTCENTER-16:
1197 aHFlip = FlipStyle_Outside;
1198 aVFlip = FlipStyle_Inside;
1199 break;
1200 case POPUPALIGNMENT_TOPCENTER17:
1201 case POPUPALIGNMENT_BOTTOMCENTER18:
1202 aHFlip = FlipStyle_Inside;
1203 aVFlip = FlipStyle_Outside;
1204 break;
1205 default: {
1206 FlipStyle anchorEdge =
1207 mFlip == FlipType_Both ? FlipStyle_Inside : FlipStyle_None;
1208 aHFlip = (popupAnchor == -popupAlign) ? FlipStyle_Outside : anchorEdge;
1209 if (((popupAnchor > 0) == (popupAlign > 0)) ||
1210 (popupAnchor == POPUPALIGNMENT_TOPLEFT1 &&
1211 popupAlign == POPUPALIGNMENT_TOPLEFT1))
1212 aVFlip = FlipStyle_Outside;
1213 else
1214 aVFlip = anchorEdge;
1215 break;
1216 }
1217 }
1218
1219 return pnt;
1220}
1221
1222nsIFrame* nsMenuPopupFrame::GetSelectedItemForAlignment() const {
1223 // This method adjusts a menulist's popup such that the selected item is under
1224 // the cursor, aligned with the menulist label.
1225 nsCOMPtr<nsIDOMXULSelectControlElement> select;
1226 if (mAnchorContent) {
1227 select = mAnchorContent->AsElement()->AsXULSelectControl();
1228 }
1229
1230 if (!select) {
1231 // If there isn't an anchor, then try just getting the parent of the popup.
1232 select = mContent->GetParent()->AsElement()->AsXULSelectControl();
1233 if (!select) {
1234 return nullptr;
1235 }
1236 }
1237
1238 nsCOMPtr<Element> selectedElement;
1239 select->GetSelectedItem(getter_AddRefs(selectedElement));
1240 return selectedElement ? selectedElement->GetPrimaryFrame() : nullptr;
1241}
1242
1243nscoord nsMenuPopupFrame::SlideOrResize(nscoord& aScreenPoint, nscoord aSize,
1244 nscoord aScreenBegin,
1245 nscoord aScreenEnd,
1246 nscoord* aOffset) const {
1247 // The popup may be positioned such that either the left/top or bottom/right
1248 // is outside the screen - but never both.
1249 nscoord newPos =
1250 std::max(aScreenBegin, std::min(aScreenEnd - aSize, aScreenPoint));
1251 *aOffset = newPos - aScreenPoint;
1252 aScreenPoint = newPos;
1253 return std::min(aSize, aScreenEnd - aScreenPoint);
1254}
1255
1256nscoord nsMenuPopupFrame::FlipOrResize(nscoord& aScreenPoint, nscoord aSize,
1257 nscoord aScreenBegin, nscoord aScreenEnd,
1258 nscoord aAnchorBegin, nscoord aAnchorEnd,
1259 nscoord aMarginBegin, nscoord aMarginEnd,
1260 FlipStyle aFlip, bool aEndAligned,
1261 bool* aFlipSide) const {
1262 // The flip side argument will be set to true if there wasn't room and we
1263 // flipped to the opposite side.
1264 *aFlipSide = false;
1265
1266 // all of the coordinates used here are in app units relative to the screen
1267 nscoord popupSize = aSize;
1268 if (aScreenPoint < aScreenBegin) {
1269 // at its current position, the popup would extend past the left or top
1270 // edge of the screen, so it will have to be moved or resized.
1271 if (aFlip) {
1272 // for inside flips, we flip on the opposite side of the anchor
1273 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1274 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1275
1276 // check whether there is more room to the left and right (or top and
1277 // bottom) of the anchor and put the popup on the side with more room.
1278 if (startpos - aScreenBegin >= aScreenEnd - endpos) {
1279 aScreenPoint = aScreenBegin;
1280 popupSize = startpos - aScreenPoint - aMarginEnd;
1281 *aFlipSide = !aEndAligned;
1282 } else {
1283 // If the newly calculated position is different than the existing
1284 // position, flip such that the popup is to the right or bottom of the
1285 // anchor point instead . However, when flipping use the same margin
1286 // size.
1287 nscoord newScreenPoint = endpos + aMarginEnd;
1288 if (newScreenPoint != aScreenPoint) {
1289 *aFlipSide = aEndAligned;
1290 aScreenPoint = newScreenPoint;
1291 // check if the new position is still off the right or bottom edge of
1292 // the screen. If so, resize the popup.
1293 if (aScreenPoint + aSize > aScreenEnd) {
1294 popupSize = aScreenEnd - aScreenPoint;
1295 }
1296 }
1297 }
1298 } else {
1299 aScreenPoint = aScreenBegin;
1300 }
1301 } else if (aScreenPoint + aSize > aScreenEnd) {
1302 // at its current position, the popup would extend past the right or
1303 // bottom edge of the screen, so it will have to be moved or resized.
1304 if (aFlip) {
1305 // for inside flips, we flip on the opposite side of the anchor
1306 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1307 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1308
1309 // check whether there is more room to the left and right (or top and
1310 // bottom) of the anchor and put the popup on the side with more room.
1311 if (aScreenEnd - endpos >= startpos - aScreenBegin) {
1312 *aFlipSide = aEndAligned;
1313 if (mIsContextMenu) {
1314 aScreenPoint = aScreenEnd - aSize;
1315 } else {
1316 aScreenPoint = endpos + aMarginBegin;
1317 popupSize = aScreenEnd - aScreenPoint;
1318 }
1319 } else {
1320 // if the newly calculated position is different than the existing
1321 // position, we flip such that the popup is to the left or top of the
1322 // anchor point instead.
1323 nscoord newScreenPoint = startpos - aSize - aMarginBegin;
1324 if (newScreenPoint != aScreenPoint) {
1325 *aFlipSide = !aEndAligned;
1326 aScreenPoint = newScreenPoint;
1327
1328 // check if the new position is still off the left or top edge of the
1329 // screen. If so, resize the popup.
1330 if (aScreenPoint < aScreenBegin) {
1331 aScreenPoint = aScreenBegin;
1332 if (!mIsContextMenu) {
1333 popupSize = startpos - aScreenPoint - aMarginBegin;
1334 }
1335 }
1336 }
1337 }
1338 } else {
1339 aScreenPoint = aScreenEnd - aSize;
1340 }
1341 }
1342
1343 // Make sure that the point is within the screen boundaries and that the
1344 // size isn't off the edge of the screen. This can happen when a large
1345 // positive or negative margin is used.
1346 if (aScreenPoint < aScreenBegin) {
1347 aScreenPoint = aScreenBegin;
1348 }
1349 if (aScreenPoint > aScreenEnd) {
1350 aScreenPoint = aScreenEnd - aSize;
1351 }
1352
1353 // If popupSize ended up being negative, or the original size was actually
1354 // smaller than the calculated popup size, just use the original size instead.
1355 if (popupSize <= 0 || aSize < popupSize) {
1356 popupSize = aSize;
1357 }
1358
1359 return std::min(popupSize, aScreenEnd - aScreenPoint);
1360}
1361
1362nsRect nsMenuPopupFrame::ComputeAnchorRect(nsPresContext* aRootPresContext,
1363 nsIFrame* aAnchorFrame) const {
1364 // Get the root frame for a reference
1365 nsIFrame* rootFrame = aRootPresContext->PresShell()->GetRootFrame();
1366
1367 // The dimensions of the anchor
1368 nsRect anchorRect = aAnchorFrame->GetRectRelativeToSelf();
1369
1370 // Relative to the root
1371 anchorRect = nsLayoutUtils::TransformFrameRectToAncestor(
1372 aAnchorFrame, anchorRect, rootFrame);
1373 // Relative to the screen
1374 anchorRect.MoveBy(rootFrame->GetScreenRectInAppUnits().TopLeft());
1375
1376 // In its own app units
1377 return anchorRect.ScaleToOtherAppUnitsRoundOut(
1378 aRootPresContext->AppUnitsPerDevPixel(),
1379 PresContext()->AppUnitsPerDevPixel());
1380}
1381
1382static nsIFrame* MaybeDelegatedAnchorFrame(nsIFrame* aFrame) {
1383 if (!aFrame) {
1384 return nullptr;
1385 }
1386 if (auto* element = Element::FromNodeOrNull(aFrame->GetContent())) {
1387 if (element->HasAttr(nsGkAtoms::delegatesanchor)) {
1388 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1389 if (!f->IsPlaceholderFrame()) {
1390 return f;
1391 }
1392 }
1393 }
1394 }
1395 return aFrame;
1396}
1397
1398auto nsMenuPopupFrame::GetRects(const nsSize& aPrefSize) const -> Rects {
1399 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"
, 1399)
) {
1400 // Return early if the popup hasn't been laid out yet. On Windows, this can
1401 // happen when using a drag popup before it opens.
1402 return {};
1403 }
1404
1405 nsPresContext* pc = PresContext();
1406 nsIFrame* rootFrame = pc->PresShell()->GetRootFrame();
1407 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"
, 1409); MOZ_PretendNoReturn(); } } while (0)
1408 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"
, 1409); MOZ_PretendNoReturn(); } } while (0)
1409 "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"
, 1409); MOZ_PretendNoReturn(); } } while (0)
;
1410
1411 // Indicators of whether the popup should be flipped or resized.
1412 FlipStyle hFlip = FlipStyle_None, vFlip = FlipStyle_None;
1413
1414 const nsMargin margin = GetMargin();
1415
1416 // the screen rectangle of the root frame, in dev pixels.
1417 const nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
1418
1419 const bool isNoAutoHide = IsNoAutoHide();
1420 const PopupLevel popupLevel = GetPopupLevel(isNoAutoHide);
1421
1422 Rects result;
1423
1424 // Set the popup's size to the preferred size. Below, this size will be
1425 // adjusted to fit on the screen or within the content area. If the anchor is
1426 // sized to the popup, use the anchor's width instead of the preferred width.
1427 result.mUsedRect = nsRect(nsPoint(), aPrefSize);
1428
1429 const bool anchored = IsAnchored();
1430 if (anchored) {
1431 // In order to deal with transforms, we need the root prescontext:
1432 nsPresContext* rootPc = pc->GetRootPresContext();
1433 if (NS_WARN_IF(!rootPc)NS_warn_if_impl(!rootPc, "!rootPc", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1433)
) {
1434 // If we can't reach a root pres context, don't bother continuing.
1435 return result;
1436 }
1437
1438 result.mAnchorRect = result.mUntransformedAnchorRect = [&] {
1439 // If anchored to a rectangle, use that rectangle. Otherwise, determine
1440 // the rectangle from the anchor.
1441 if (mAnchorType == MenuPopupAnchorType::Rect) {
1442 return mScreenRect;
1443 }
1444 // if the frame is not specified, use the anchor node passed to OpenPopup.
1445 // If that wasn't specified either, use the root frame. Note that
1446 // mAnchorContent might be a different document so its presshell must be
1447 // used.
1448 nsIFrame* anchorFrame = GetAnchorFrame();
1449 if (!anchorFrame) {
1450 return rootScreenRect;
1451 }
1452 return ComputeAnchorRect(rootPc, anchorFrame);
1453 }();
1454
1455 // if we are anchored, there are certain things we don't want to do when
1456 // repositioning the popup to fit on the screen, such as end up positioned
1457 // over the anchor, for instance a popup appearing over the menu label.
1458 // When doing this reposition, we want to move the popup to the side with
1459 // the most room. The combination of anchor and alignment dictate if we
1460 // readjust above/below or to the left/right.
1461 if (mAnchorContent || mAnchorType == MenuPopupAnchorType::Rect) {
1462 // move the popup according to the anchor and alignment. This will also
1463 // tell us which axis the popup is flush against in case we have to move
1464 // it around later. The AdjustPositionForAnchorAlign method accounts for
1465 // the popup's margin.
1466 result.mUsedRect.MoveTo(AdjustPositionForAnchorAlign(
1467 result.mAnchorRect, aPrefSize, hFlip, vFlip));
1468 } else {
1469 // With no anchor, the popup is positioned relative to the root frame.
1470 result.mUsedRect.MoveTo(result.mAnchorRect.TopLeft() +
1471 nsPoint(margin.left, margin.top));
1472 }
1473
1474 // mXPos and mYPos specify an additional offset passed to OpenPopup that
1475 // should be added to the position. We also add the offset to the anchor
1476 // pos so a later flip/resize takes the offset into account.
1477 // FIXME(emilio): Wayland doesn't seem to be accounting for this offset
1478 // anywhere, and it probably should.
1479 {
1480 nsPoint offset(CSSPixel::ToAppUnits(mXPos), CSSPixel::ToAppUnits(mYPos));
1481 if (IsDirectionRTL()) {
1482 offset.x = -offset.x;
1483 }
1484 result.mUsedRect.MoveBy(offset);
1485 result.mAnchorRect.MoveBy(offset);
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) {
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.
2089 PrepareWidget(true);
2090 }
2091
2092 if (aAttribute == nsGkAtoms::followanchor) {
2093 if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
2094 pm->UpdateFollowAnchor(this);
2095 }
2096 }
2097
2098 if (aAttribute == nsGkAtoms::label) {
2099 // set the label for the titlebar
2100 nsView* view = GetView();
2101 if (view) {
2102 nsIWidget* widget = view->GetWidget();
2103 if (widget) {
2104 nsAutoString title;
2105 mContent->AsElement()->GetAttr(nsGkAtoms::label, title);
2106 if (!title.IsEmpty()) {
2107 widget->SetTitle(title);
2108 }
2109 }
2110 }
2111 } else if (aAttribute == nsGkAtoms::ignorekeys) {
2112 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2113 if (pm) {
2114 nsAutoString ignorekeys;
2115 mContent->AsElement()->GetAttr(nsGkAtoms::ignorekeys, ignorekeys);
2116 pm->UpdateIgnoreKeys(ignorekeys.EqualsLiteral("true"));
2117 }
2118 }
2119
2120 return rv;
2121}
2122
2123void nsMenuPopupFrame::MoveToAttributePosition() {
2124 // Move the widget around when the user sets the |left| and |top| attributes.
2125 // Note that this is not the best way to move the widget, as it results in
2126 // lots of FE notifications and is likely to be slow as molasses. Use |moveTo|
2127 // on the element if possible.
2128 nsAutoString left, top;
2129 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
2130 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
2131 nsresult err1, err2;
2132 const CSSIntPoint pos(left.ToInteger(&err1), top.ToInteger(&err2));
2133 if (NS_SUCCEEDED(err1)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err1)), 1))) && NS_SUCCEEDED(err2)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err2)), 1)))) {
2134 MoveTo(pos, false);
2135 }
2136
2137 PresShell()->FrameNeedsReflow(
2138 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
2139}
2140
2141void nsMenuPopupFrame::Destroy(DestroyContext& aContext) {
2142 // XXX: Currently we don't fire popuphidden for these popups, that seems wrong
2143 // but alas, also pre-existing.
2144 HidePopup(/* aDeselectMenu = */ false, ePopupClosed,
2145 /* aFromFrameDestruction = */ true);
2146
2147 if (RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance()) {
2148 pm->PopupDestroyed(this);
2149 }
2150
2151 nsBlockFrame::Destroy(aContext);
2152}
2153
2154nsMargin nsMenuPopupFrame::GetMargin() const {
2155 nsMargin margin;
2156 StyleMargin()->GetMargin(margin);
2157 if (mIsTopLevelContextMenu) {
2158 const CSSIntPoint offset(
2159 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetHorizontal),
2160 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetVertical));
2161 auto auOffset = CSSIntPoint::ToAppUnits(offset);
2162 margin.top += auOffset.y;
2163 margin.bottom += auOffset.y;
2164 margin.left += auOffset.x;
2165 margin.right += auOffset.x;
2166 }
2167 if (mPopupType == PopupType::Tooltip && !IsAnchored()) {
2168 const auto auOffset =
2169 CSSPixel::ToAppUnits(LookAndFeel::TooltipOffsetVertical());
2170 margin.top += auOffset;
2171 margin.bottom += auOffset;
2172 }
2173 return margin;
2174}
2175
2176void nsMenuPopupFrame::MoveTo(const CSSPoint& aPos, bool aUpdateAttrs,
2177 bool aByMoveToRect) {
2178 nsIWidget* widget = GetWidget();
2179 nsPoint appUnitsPos = CSSPixel::ToAppUnits(aPos);
2180
2181 // reposition the popup at the specified coordinates. Don't clear the anchor
2182 // and position, because the popup can be reset to its anchor position by
2183 // using (-1, -1) as coordinates.
2184 //
2185 // Subtract off the margin as it will be added to the position when
2186 // SetPopupPosition is called.
2187 {
2188 nsMargin margin = GetMargin();
2189 if (mIsContextMenu && IsDirectionRTL()) {
2190 appUnitsPos.x += margin.right + mRect.Width();
2191 } else {
2192 appUnitsPos.x -= margin.left;
2193 }
2194 appUnitsPos.y -= margin.top;
2195 }
2196
2197 if (mScreenRect.TopLeft() == appUnitsPos &&
2198 (!widget || widget->GetClientOffset() == mLastClientOffset)) {
2199 return;
2200 }
2201
2202 mPositionedByMoveToRect = aByMoveToRect;
2203 mScreenRect.MoveTo(appUnitsPos);
2204 if (mAnchorType == MenuPopupAnchorType::Rect) {
2205 // This ensures that the anchor width is still honored, to prevent it from
2206 // changing spuriously.
2207 mScreenRect.height = 0;
2208 // But we still need to make sure that our top left position ends up in
2209 // appUnitsPos.
2210 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
2211 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
2212 mXPos = mYPos = 0;
2213 } else {
2214 mAnchorType = MenuPopupAnchorType::Point;
2215 }
2216
2217 SetPopupPosition(true);
2218
2219 RefPtr<Element> popup = mContent->AsElement();
2220 if (aUpdateAttrs &&
2221 (popup->HasAttr(nsGkAtoms::left) || popup->HasAttr(nsGkAtoms::top))) {
2222 nsAutoString left, top;
2223 left.AppendInt(RoundedToInt(aPos).x);
2224 top.AppendInt(RoundedToInt(aPos).y);
2225 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::left, left, false);
2226 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::top, top, false);
2227 }
2228}
2229
2230void nsMenuPopupFrame::MoveToAnchor(nsIContent* aAnchorContent,
2231 const nsAString& aPosition, int32_t aXPos,
2232 int32_t aYPos, bool aAttributesOverride) {
2233 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"
, 2234); MOZ_PretendNoReturn(); } } while (0)
2234 "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"
, 2234); MOZ_PretendNoReturn(); } } while (0)
;
2235
2236 nsPopupState oldstate = mPopupState;
2237 InitializePopup(aAnchorContent, mTriggerContent, aPosition, aXPos, aYPos,
2238 MenuPopupAnchorType::Node, aAttributesOverride);
2239 // InitializePopup changed the state so reset it.
2240 mPopupState = oldstate;
2241
2242 // Pass false here so that flipping and adjusting to fit on the screen happen.
2243 SetPopupPosition(false);
2244}
2245
2246int8_t nsMenuPopupFrame::GetAlignmentPosition() const {
2247 // The code below handles most cases of alignment, anchor and position values.
2248 // Those that are not handled just return POPUPPOSITION_UNKNOWN.
2249
2250 if (mPosition == POPUPPOSITION_OVERLAP8 ||
2251 mPosition == POPUPPOSITION_AFTERPOINTER9 ||
2252 mPosition == POPUPPOSITION_SELECTION10) {
2253 return mPosition;
2254 }
2255
2256 int8_t position = mPosition;
2257
2258 if (position == POPUPPOSITION_UNKNOWN-1) {
2259 switch (mPopupAnchor) {
2260 case POPUPALIGNMENT_BOTTOMRIGHT-2:
2261 case POPUPALIGNMENT_BOTTOMLEFT2:
2262 case POPUPALIGNMENT_BOTTOMCENTER18:
2263 position = mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1
2264 ? POPUPPOSITION_AFTEREND3
2265 : POPUPPOSITION_AFTERSTART2;
2266 break;
2267 case POPUPALIGNMENT_TOPRIGHT-1:
2268 case POPUPALIGNMENT_TOPLEFT1:
2269 case POPUPALIGNMENT_TOPCENTER17:
2270 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2271 ? POPUPPOSITION_BEFOREEND1
2272 : POPUPPOSITION_BEFORESTART0;
2273 break;
2274 case POPUPALIGNMENT_LEFTCENTER16:
2275 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2276 ? POPUPPOSITION_STARTAFTER6
2277 : POPUPPOSITION_STARTBEFORE4;
2278 break;
2279 case POPUPALIGNMENT_RIGHTCENTER-16:
2280 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2
2281 ? POPUPPOSITION_ENDAFTER7
2282 : POPUPPOSITION_ENDBEFORE5;
2283 break;
2284 default:
2285 break;
2286 }
2287 }
2288
2289 if (mHFlip) {
2290 position = POPUPPOSITION_HFLIP(position)(position ^ 1);
2291 }
2292
2293 if (mVFlip) {
2294 position = POPUPPOSITION_VFLIP(position)(position ^ 2);
2295 }
2296
2297 return position;
2298}
2299
2300/**
2301 * KEEP THIS IN SYNC WITH nsIFrame::CreateView
2302 * as much as possible. Until we get rid of views finally...
2303 */
2304void nsMenuPopupFrame::CreatePopupView() {
2305 if (HasView()) {
2306 return;
2307 }
2308
2309 nsViewManager* viewManager = PresContext()->GetPresShell()->GetViewManager();
2310 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"
, 2310); MOZ_PretendNoReturn(); } } while (0)
;
2311
2312 // Create a view
2313 nsView* parentView = viewManager->GetRootView();
2314 auto visibility = ViewVisibility::Hide;
2315
2316 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"
, 2316); MOZ_PretendNoReturn(); } } while (0)
;
2317
2318 // Create a view
2319 nsView* view = viewManager->CreateView(GetRect(), parentView, visibility);
2320 // XXX put view last in document order until we can do better
2321 viewManager->InsertChild(parentView, view, nullptr, true);
2322
2323 // Remember our view
2324 SetView(view);
2325
2326 NS_FRAME_LOG(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
2327 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)
2328 ("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)
;
2329}
2330
2331bool nsMenuPopupFrame::ShouldFollowAnchor() const {
2332 if (mAnchorType != MenuPopupAnchorType::Node || !mAnchorContent) {
2333 return false;
2334 }
2335
2336 // Follow anchor mode is used when followanchor="true" is set or for arrow
2337 // panels.
2338 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2339 nsGkAtoms::followanchor,
2340 nsGkAtoms::_true, eCaseMatters)) {
2341 return true;
2342 }
2343
2344 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2345 nsGkAtoms::followanchor,
2346 nsGkAtoms::_false, eCaseMatters)) {
2347 return false;
2348 }
2349
2350 return mPopupType == PopupType::Panel &&
2351 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
2352 nsGkAtoms::arrow, eCaseMatters);
2353}
2354
2355bool nsMenuPopupFrame::ShouldFollowAnchor(nsRect& aRect) {
2356 if (!ShouldFollowAnchor()) {
2357 return false;
2358 }
2359
2360 if (nsIFrame* anchorFrame = GetAnchorFrame()) {
2361 if (nsPresContext* rootPresContext = PresContext()->GetRootPresContext()) {
2362 aRect = ComputeAnchorRect(rootPresContext, anchorFrame);
2363 }
2364 }
2365
2366 return true;
2367}
2368
2369bool nsMenuPopupFrame::IsDirectionRTL() const {
2370 const nsIFrame* anchor = GetAnchorFrame();
2371 const nsIFrame* f = anchor ? anchor : this;
2372 return f->StyleVisibility()->mDirection == StyleDirection::Rtl;
2373}
2374
2375nsIFrame* nsMenuPopupFrame::GetAnchorFrame() const {
2376 nsIContent* anchor = mAnchorContent;
2377 if (!anchor) {
2378 return nullptr;
2379 }
2380 return MaybeDelegatedAnchorFrame(anchor->GetPrimaryFrame());
2381}
2382
2383void nsMenuPopupFrame::CheckForAnchorChange(nsRect& aRect) {
2384 // Don't update if the popup isn't visible or we shouldn't be following the
2385 // anchor.
2386 if (!IsVisible() || !ShouldFollowAnchor()) {
2387 return;
2388 }
2389
2390 bool shouldHide = false;
2391
2392 nsPresContext* rootPresContext = PresContext()->GetRootPresContext();
2393
2394 // If the frame for the anchor has gone away, hide the popup.
2395 nsIFrame* anchor = GetAnchorFrame();
2396 if (!anchor || !rootPresContext) {
2397 shouldHide = true;
2398 } else if (!anchor->IsVisibleConsideringAncestors(
2399 VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) {
2400 // If the anchor is now inside something that is invisible, hide the popup.
2401 shouldHide = true;
2402 } else {
2403 // If the anchor is now inside a hidden parent popup, hide the popup.
2404 nsIFrame* frame = anchor;
2405 while (frame) {
2406 nsMenuPopupFrame* popup = do_QueryFrame(frame);
2407 if (popup && popup->PopupState() != ePopupShown) {
2408 shouldHide = true;
2409 break;
2410 }
2411
2412 frame = frame->GetParent();
2413 }
2414 }
2415
2416 if (shouldHide) {
2417 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2418 if (pm) {
2419 // As the caller will be iterating over the open popups, hide
2420 // asyncronously.
2421 pm->HidePopup(mContent->AsElement(),
2422 {HidePopupOption::DeselectMenu, HidePopupOption::Async});
2423 }
2424
2425 return;
2426 }
2427
2428 nsRect anchorRect = ComputeAnchorRect(rootPresContext, anchor);
2429
2430 // If the rectangles are different, move the popup.
2431 if (!anchorRect.IsEqualEdges(aRect)) {
2432 aRect = anchorRect;
2433 SetPopupPosition(true);
2434 }
2435}