Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp
Warning:line 2055, 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-27-022226-2793976-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
461void nsMenuPopupFrame::TweakMinPrefISize(nscoord& aSize) {
462 if (!ShouldExpandToInflowParentOrAnchor()) {
463 return;
464 }
465 // Make sure to accommodate for our scrollbar if needed. Do it only for
466 // menulists to match previous behavior.
467 //
468 // NOTE(emilio): This is somewhat hacky. The "right" fix (which would be
469 // using scrollbar-gutter: stable on the scroller) isn't great, because even
470 // though we want a stable gutter, we want to draw on top of the gutter when
471 // there's no scrollbar, otherwise it looks rather weird.
472 //
473 // Automatically accommodating for the scrollbar otherwise would be bug
474 // 764076, but that has its own set of problems.
475 if (ScrollContainerFrame* sf = GetScrollContainerFrame()) {
476 aSize += sf->GetDesiredScrollbarSizes().LeftRight();
477 }
478
479 nscoord menuListOrAnchorWidth = 0;
480 if (nsIFrame* menuList = GetInFlowParent()) {
481 menuListOrAnchorWidth = menuList->GetRect().width;
482 }
483 if (mAnchorType == MenuPopupAnchorType_Rect) {
484 menuListOrAnchorWidth = std::max(menuListOrAnchorWidth, mScreenRect.width);
485 }
486 // Input margin doesn't have contents, so account for it for popup sizing
487 // purposes.
488 menuListOrAnchorWidth +=
489 2 * StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
490 aSize = std::max(aSize, menuListOrAnchorWidth);
491}
492
493nscoord nsMenuPopupFrame::GetMinISize(gfxContext* aRC) {
494 nscoord result = nsBlockFrame::GetMinISize(aRC);
495 TweakMinPrefISize(result);
496 return result;
497}
498
499nscoord nsMenuPopupFrame::GetPrefISize(gfxContext* aRC) {
500 nscoord result = nsBlockFrame::GetPrefISize(aRC);
501 TweakMinPrefISize(result);
502 return result;
503}
504
505void nsMenuPopupFrame::Reflow(nsPresContext* aPresContext,
506 ReflowOutput& aDesiredSize,
507 const ReflowInput& aReflowInput,
508 nsReflowStatus& aStatus) {
509 MarkInReflow();
510 DO_GLOBAL_REFLOW_COUNT("nsMenuPopupFrame")aPresContext->CountReflows(("nsMenuPopupFrame"), (nsIFrame
*)this);
;
511 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStatus.IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStatus.IsEmpty()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aStatus.IsEmpty()"
" (" "Caller should pass a fresh reflow status!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 511); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 511; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
512
513 const auto wm = GetWritingMode();
514 // Default to preserving our bounds.
515 aDesiredSize.SetSize(wm, GetLogicalSize(wm));
516
517 LayoutPopup(aPresContext, aDesiredSize, aReflowInput, aStatus);
518
519 aDesiredSize.SetBlockStartAscent(aDesiredSize.BSize(wm));
520 aDesiredSize.SetOverflowAreasToDesiredBounds();
521 FinishAndStoreOverflow(&aDesiredSize, aReflowInput.mStyleDisplay);
522}
523
524void nsMenuPopupFrame::EnsureActiveMenuListItemIsVisible() {
525 if (!IsMenuList() || !IsOpen()) {
526 return;
527 }
528 nsIFrame* frame = GetCurrentMenuItemFrame();
529 if (!frame) {
530 return;
531 }
532 RefPtr<mozilla::PresShell> presShell = PresShell();
533 presShell->ScrollFrameIntoView(
534 frame, Nothing(), ScrollAxis(), ScrollAxis(),
535 ScrollFlags::ScrollOverflowHidden | ScrollFlags::ScrollFirstAncestorOnly);
536}
537
538void nsMenuPopupFrame::LayoutPopup(nsPresContext* aPresContext,
539 ReflowOutput& aDesiredSize,
540 const ReflowInput& aReflowInput,
541 nsReflowStatus& aStatus) {
542 if (IsNativeMenu()) {
543 return;
544 }
545
546 SchedulePaint();
547
548 const bool isOpen = IsOpen();
549 if (!isOpen) {
550 // If the popup is not open, only do layout while showing or if we're a
551 // menulist.
552 //
553 // This is needed because the SelectParent code wants to limit the height of
554 // the popup before opening it.
555 //
556 // TODO(emilio): We should consider adding a way to do that more reliably
557 // instead, but this preserves existing behavior.
558 const bool needsLayout = mPopupState == ePopupShowing ||
559 mPopupState == ePopupPositioning || IsMenuList();
560 if (!needsLayout) {
561 RemoveStateBits(NS_FRAME_FIRST_REFLOW);
562 return;
563 }
564 }
565
566 // Do a first reflow, with all our content, in order to find our preferred
567 // size. Then, we do a second reflow with the updated dimensions.
568 const bool needsPrefSize = mPrefSize == nsSize(-1, -1) || IsSubtreeDirty();
569 if (needsPrefSize) {
570 // Get the preferred, minimum and maximum size. If the menu is sized to the
571 // popup, then the popup's width is the menu's width.
572 ReflowOutput preferredSize(aReflowInput);
573 nsBlockFrame::Reflow(aPresContext, preferredSize, aReflowInput, aStatus);
574 mPrefSize = preferredSize.PhysicalSize();
575 }
576
577 // Get our desired position and final size, now that we have a preferred size.
578 auto constraints = GetRects(mPrefSize);
579 const auto finalSize = constraints.mUsedRect.Size();
580
581 // We need to do an extra reflow if we haven't reflowed, our size doesn't
582 // match with our final intended size, or our bsize is unconstrained (in which
583 // case we need to specify the final size so that percentages work).
584 const bool needDefiniteReflow =
585 aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE || !needsPrefSize ||
586 finalSize != mPrefSize;
587
588 if (needDefiniteReflow) {
589 ReflowInput constrainedReflowInput(aReflowInput);
590 const auto& bp = aReflowInput.ComputedPhysicalBorderPadding();
591 // TODO: writing-mode handling not terribly correct, but it doesn't matter.
592 const nsSize finalContentSize(finalSize.width - bp.LeftRight(),
593 finalSize.height - bp.TopBottom());
594 constrainedReflowInput.SetComputedISize(finalContentSize.width);
595 constrainedReflowInput.SetComputedBSize(finalContentSize.height);
596 constrainedReflowInput.SetIResize(finalSize.width != mPrefSize.width);
597 constrainedReflowInput.SetBResize([&] {
598 if (finalSize.height != mPrefSize.height) {
599 return true;
600 }
601 if (needsPrefSize &&
602 aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE &&
603 aReflowInput.ComputedMaxBSize() == finalContentSize.height) {
604 // If we have measured, and maybe clamped our children via max-height,
605 // they might need to get percentages in the block axis re-resolved.
606 return true;
607 }
608 return false;
609 }());
610
611 aStatus.Reset();
612 nsBlockFrame::Reflow(aPresContext, aDesiredSize, constrainedReflowInput,
613 aStatus);
614 }
615
616 // Set our size, since nsAbsoluteContainingBlock won't.
617 SetRect(constraints.mUsedRect);
618
619 nsView* view = GetView();
620 if (isOpen) {
621 nsViewManager* viewManager = view->GetViewManager();
622 viewManager->ResizeView(view,
623 nsRect(nsPoint(), constraints.mUsedRect.Size()));
624 if (mPopupState == ePopupOpening) {
625 mPopupState = ePopupVisible;
626 }
627
628 viewManager->SetViewVisibility(view, ViewVisibility::Show);
629 SyncFrameViewProperties(view);
630 }
631
632 // Perform our move now. That will position the view and so on.
633 PerformMove(constraints);
634
635 // finally, if the popup just opened, send a popupshown event
636 bool openChanged = mIsOpenChanged;
637 if (openChanged) {
638 mIsOpenChanged = false;
639
640 // Make sure the current selection in a menulist is visible.
641 EnsureActiveMenuListItemIsVisible();
642
643 // If the animate attribute is set to open, check for a transition and wait
644 // for it to finish before firing the popupshown event.
645 if (LookAndFeel::GetInt(LookAndFeel::IntID::PanelAnimations) &&
646 mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
647 nsGkAtoms::animate, nsGkAtoms::open,
648 eCaseMatters) &&
649 AnimationUtils::HasCurrentTransitions(mContent->AsElement(),
650 PseudoStyleType::NotPseudo)) {
651 mPopupShownDispatcher = new nsXULPopupShownEvent(mContent, aPresContext);
652 mContent->AddSystemEventListener(u"transitionend"_ns,
653 mPopupShownDispatcher, false, false);
654 return;
655 }
656
657 // If there are no transitions, fire the popupshown event right away.
658 nsCOMPtr<nsIRunnable> event =
659 new nsXULPopupShownEvent(GetContent(), aPresContext);
660 mContent->OwnerDoc()->Dispatch(event.forget());
661 }
662}
663
664bool nsMenuPopupFrame::IsMenuList() const {
665 return PopupElement().IsInMenuList();
666}
667
668bool nsMenuPopupFrame::ShouldExpandToInflowParentOrAnchor() const {
669 return IsMenuList() && !mContent->GetParent()->AsElement()->AttrValueIs(
670 kNameSpaceID_None, nsGkAtoms::sizetopopup,
671 nsGkAtoms::none, eCaseMatters);
672}
673
674nsIContent* nsMenuPopupFrame::GetTriggerContent(
675 nsMenuPopupFrame* aMenuPopupFrame) {
676 while (aMenuPopupFrame) {
677 if (aMenuPopupFrame->mTriggerContent) {
678 return aMenuPopupFrame->mTriggerContent;
679 }
680
681 auto* button = XULButtonElement::FromNodeOrNull(
682 aMenuPopupFrame->GetContent()->GetParent());
683 if (!button || !button->IsMenu()) {
684 break;
685 }
686
687 auto* popup = button->GetContainingPopupElement();
688 if (!popup) {
689 break;
690 }
691
692 // check up the menu hierarchy until a popup with a trigger node is found
693 aMenuPopupFrame = do_QueryFrame(popup->GetPrimaryFrame());
694 }
695
696 return nullptr;
697}
698
699void nsMenuPopupFrame::InitPositionFromAnchorAlign(const nsAString& aAnchor,
700 const nsAString& aAlign) {
701 mTriggerContent = nullptr;
702
703 if (aAnchor.EqualsLiteral("topleft"))
704 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
705 else if (aAnchor.EqualsLiteral("topright"))
706 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
707 else if (aAnchor.EqualsLiteral("bottomleft"))
708 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
709 else if (aAnchor.EqualsLiteral("bottomright"))
710 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
711 else if (aAnchor.EqualsLiteral("leftcenter"))
712 mPopupAnchor = POPUPALIGNMENT_LEFTCENTER16;
713 else if (aAnchor.EqualsLiteral("rightcenter"))
714 mPopupAnchor = POPUPALIGNMENT_RIGHTCENTER-16;
715 else if (aAnchor.EqualsLiteral("topcenter"))
716 mPopupAnchor = POPUPALIGNMENT_TOPCENTER17;
717 else if (aAnchor.EqualsLiteral("bottomcenter"))
718 mPopupAnchor = POPUPALIGNMENT_BOTTOMCENTER18;
719 else
720 mPopupAnchor = POPUPALIGNMENT_NONE0;
721
722 if (aAlign.EqualsLiteral("topleft"))
723 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
724 else if (aAlign.EqualsLiteral("topright"))
725 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
726 else if (aAlign.EqualsLiteral("bottomleft"))
727 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
728 else if (aAlign.EqualsLiteral("bottomright"))
729 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
730 else if (aAlign.EqualsLiteral("leftcenter"))
731 mPopupAlignment = POPUPALIGNMENT_LEFTCENTER16;
732 else if (aAlign.EqualsLiteral("rightcenter"))
733 mPopupAlignment = POPUPALIGNMENT_RIGHTCENTER-16;
734 else if (aAlign.EqualsLiteral("topcenter"))
735 mPopupAlignment = POPUPALIGNMENT_TOPCENTER17;
736 else if (aAlign.EqualsLiteral("bottomcenter"))
737 mPopupAlignment = POPUPALIGNMENT_BOTTOMCENTER18;
738 else
739 mPopupAlignment = POPUPALIGNMENT_NONE0;
740
741 mPosition = POPUPPOSITION_UNKNOWN-1;
742}
743
744static FlipType FlipFromAttribute(nsMenuPopupFrame* aFrame) {
745 nsAutoString flip;
746 aFrame->PopupElement().GetAttr(nsGkAtoms::flip, flip);
747 if (flip.EqualsLiteral("none")) {
748 return FlipType_None;
749 }
750 if (flip.EqualsLiteral("both")) {
751 return FlipType_Both;
752 }
753 if (flip.EqualsLiteral("slide")) {
754 return FlipType_Slide;
755 }
756 return FlipType_Default;
757}
758
759void nsMenuPopupFrame::InitializePopup(nsIContent* aAnchorContent,
760 nsIContent* aTriggerContent,
761 const nsAString& aPosition,
762 int32_t aXPos, int32_t aYPos,
763 MenuPopupAnchorType aAnchorType,
764 bool aAttributesOverride) {
765 auto* widget = GetWidget();
766 bool recreateWidget = widget && widget->NeedsRecreateToReshow();
767 PrepareWidget(recreateWidget);
768
769 mPopupState = ePopupShowing;
770 mAnchorContent = aAnchorContent;
771 mTriggerContent = aTriggerContent;
772 mXPos = aXPos;
773 mYPos = aYPos;
774 mIsNativeMenu = false;
775 mIsTopLevelContextMenu = false;
776 mVFlip = false;
777 mHFlip = false;
778 mConstrainedByLayout = false;
779 mAlignmentOffset = 0;
780 mPositionedOffset = 0;
781 mPositionedByMoveToRect = false;
782
783 mAnchorType = aAnchorType;
784
785 // if aAttributesOverride is true, then the popupanchor, popupalign and
786 // position attributes on the <menupopup> override those values passed in.
787 // If false, those attributes are only used if the values passed in are empty
788 if (aAnchorContent || aAnchorType == MenuPopupAnchorType_Rect) {
789 nsAutoString anchor, align, position;
790 mContent->AsElement()->GetAttr(nsGkAtoms::popupanchor, anchor);
791 mContent->AsElement()->GetAttr(nsGkAtoms::popupalign, align);
792 mContent->AsElement()->GetAttr(nsGkAtoms::position, position);
793
794 if (aAttributesOverride) {
795 // if the attributes are set, clear the offset position. Otherwise,
796 // the offset is used to adjust the position from the anchor point
797 if (anchor.IsEmpty() && align.IsEmpty() && position.IsEmpty())
798 position.Assign(aPosition);
799 else
800 mXPos = mYPos = 0;
801 } else if (!aPosition.IsEmpty()) {
802 position.Assign(aPosition);
803 }
804
805 mFlip = FlipFromAttribute(this);
806
807 position.CompressWhitespace();
808 int32_t spaceIdx = position.FindChar(' ');
809 // if there is a space in the position, assume it is the anchor and
810 // alignment as two separate tokens.
811 if (spaceIdx >= 0) {
812 InitPositionFromAnchorAlign(Substring(position, 0, spaceIdx),
813 Substring(position, spaceIdx + 1));
814 } else if (position.EqualsLiteral("before_start")) {
815 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
816 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
817 mPosition = POPUPPOSITION_BEFORESTART0;
818 } else if (position.EqualsLiteral("before_end")) {
819 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
820 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
821 mPosition = POPUPPOSITION_BEFOREEND1;
822 } else if (position.EqualsLiteral("after_start")) {
823 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
824 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
825 mPosition = POPUPPOSITION_AFTERSTART2;
826 } else if (position.EqualsLiteral("after_end")) {
827 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
828 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
829 mPosition = POPUPPOSITION_AFTEREND3;
830 } else if (position.EqualsLiteral("start_before")) {
831 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
832 mPopupAlignment = POPUPALIGNMENT_TOPRIGHT-1;
833 mPosition = POPUPPOSITION_STARTBEFORE4;
834 } else if (position.EqualsLiteral("start_after")) {
835 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
836 mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT-2;
837 mPosition = POPUPPOSITION_STARTAFTER6;
838 } else if (position.EqualsLiteral("end_before")) {
839 mPopupAnchor = POPUPALIGNMENT_TOPRIGHT-1;
840 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
841 mPosition = POPUPPOSITION_ENDBEFORE5;
842 } else if (position.EqualsLiteral("end_after")) {
843 mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT-2;
844 mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT2;
845 mPosition = POPUPPOSITION_ENDAFTER7;
846 } else if (position.EqualsLiteral("overlap")) {
847 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
848 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
849 mPosition = POPUPPOSITION_OVERLAP8;
850 } else if (position.EqualsLiteral("after_pointer")) {
851 mPopupAnchor = POPUPALIGNMENT_TOPLEFT1;
852 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
853 mPosition = POPUPPOSITION_AFTERPOINTER9;
854 // XXXndeakin this is supposed to anchor vertically after, but with the
855 // horizontal position as the mouse pointer.
856 mYPos += 21;
857 } else if (position.EqualsLiteral("selection")) {
858 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
859 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
860 mPosition = POPUPPOSITION_SELECTION10;
861 } else {
862 InitPositionFromAnchorAlign(anchor, align);
863 }
864 }
865 // When converted back to CSSIntRect it is (-1, -1, 0, 0) - as expected in
866 // nsXULPopupManager::Rollup
867 mScreenRect = nsRect(-AppUnitsPerCSSPixel(), -AppUnitsPerCSSPixel(), 0, 0);
868
869 if (aAttributesOverride) {
870 // Use |left| and |top| dimension attributes to position the popup if
871 // present, as they may have been persisted.
872 nsAutoString left, top;
873 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
874 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
875
876 nsresult err;
877 if (!left.IsEmpty()) {
878 int32_t x = left.ToInteger(&err);
879 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
880 mScreenRect.x = CSSPixel::ToAppUnits(x);
881 }
882 }
883 if (!top.IsEmpty()) {
884 int32_t y = top.ToInteger(&err);
885 if (NS_SUCCEEDED(err)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err)), 1)))) {
886 mScreenRect.y = CSSPixel::ToAppUnits(y);
887 }
888 }
889 }
890}
891
892void nsMenuPopupFrame::InitializePopupAtScreen(nsIContent* aTriggerContent,
893 int32_t aXPos, int32_t aYPos,
894 bool aIsContextMenu) {
895 auto* widget = GetWidget();
896 bool recreateWidget = widget && widget->NeedsRecreateToReshow();
897 PrepareWidget(recreateWidget);
898
899 mPopupState = ePopupShowing;
900 mAnchorContent = nullptr;
901 mTriggerContent = aTriggerContent;
902 mScreenRect =
903 nsRect(CSSPixel::ToAppUnits(aXPos), CSSPixel::ToAppUnits(aYPos), 0, 0);
904 mXPos = 0;
905 mYPos = 0;
906 mFlip = FlipFromAttribute(this);
907 mPopupAnchor = POPUPALIGNMENT_NONE0;
908 mPopupAlignment = POPUPALIGNMENT_NONE0;
909 mPosition = POPUPPOSITION_UNKNOWN-1;
910 mIsContextMenu = aIsContextMenu;
911 mIsTopLevelContextMenu = aIsContextMenu;
912 mIsNativeMenu = false;
913 mAnchorType = MenuPopupAnchorType_Point;
914 mPositionedOffset = 0;
915 mPositionedByMoveToRect = false;
916}
917
918void nsMenuPopupFrame::InitializePopupAsNativeContextMenu(
919 nsIContent* aTriggerContent, int32_t aXPos, int32_t aYPos) {
920 mTriggerContent = aTriggerContent;
921 mPopupState = ePopupShowing;
922 mAnchorContent = nullptr;
923 mScreenRect =
924 nsRect(CSSPixel::ToAppUnits(aXPos), CSSPixel::ToAppUnits(aYPos), 0, 0);
925 mXPos = 0;
926 mYPos = 0;
927 mFlip = FlipType_Default;
928 mPopupAnchor = POPUPALIGNMENT_NONE0;
929 mPopupAlignment = POPUPALIGNMENT_NONE0;
930 mPosition = POPUPPOSITION_UNKNOWN-1;
931 mIsContextMenu = true;
932 mIsTopLevelContextMenu = true;
933 mIsNativeMenu = true;
934 mAnchorType = MenuPopupAnchorType_Point;
935 mPositionedOffset = 0;
936 mPositionedByMoveToRect = false;
937}
938
939void nsMenuPopupFrame::InitializePopupAtRect(nsIContent* aTriggerContent,
940 const nsAString& aPosition,
941 const nsIntRect& aRect,
942 bool aAttributesOverride) {
943 InitializePopup(nullptr, aTriggerContent, aPosition, 0, 0,
944 MenuPopupAnchorType_Rect, aAttributesOverride);
945 mScreenRect = ToAppUnits(aRect, AppUnitsPerCSSPixel());
946}
947
948void nsMenuPopupFrame::ShowPopup(bool aIsContextMenu) {
949 mIsContextMenu = aIsContextMenu;
950
951 InvalidateFrameSubtree();
952
953 if (mPopupState == ePopupShowing || mPopupState == ePopupPositioning) {
954 mPopupState = ePopupOpening;
955 mIsOpenChanged = true;
956
957 // Clear mouse capture when a popup is opened.
958 if (mPopupType == PopupType::Menu) {
959 if (auto* activeESM = EventStateManager::GetActiveEventStateManager()) {
960 EventStateManager::ClearGlobalActiveContent(activeESM);
961 }
962
963 PresShell::ReleaseCapturingContent();
964 }
965
966 if (RefPtr menu = PopupElement().GetContainingMenu()) {
967 menu->PopupOpened();
968 }
969
970 // We skip laying out children if we're closed, so make sure that we do a
971 // full dirty reflow when opening to pick up any potential change.
972 PresShell()->FrameNeedsReflow(
973 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
974
975 if (mPopupType == PopupType::Menu) {
976 nsCOMPtr<nsISound> sound(do_GetService("@mozilla.org/sound;1"));
977 if (sound) sound->PlayEventSound(nsISound::EVENT_MENU_POPUP);
978 }
979 }
980}
981
982void nsMenuPopupFrame::ClearTriggerContentIncludingDocument() {
983 // clear the trigger content if the popup is being closed. But don't clear
984 // it if the popup is just being made invisible as a popuphiding or command
985 if (mTriggerContent) {
986 // if the popup had a trigger node set, clear the global window popup node
987 // as well
988 Document* doc = mContent->GetUncomposedDoc();
989 if (doc) {
990 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
991 nsCOMPtr<nsPIWindowRoot> root = win->GetTopWindowRoot();
992 if (root) {
993 root->SetPopupNode(nullptr);
994 }
995 }
996 }
997 }
998 mTriggerContent = nullptr;
999}
1000
1001void nsMenuPopupFrame::HidePopup(bool aDeselectMenu, nsPopupState aNewState,
1002 bool aFromFrameDestruction) {
1003 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"
, 1004); MOZ_PretendNoReturn(); } } while (0)
1004 "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"
, 1004); MOZ_PretendNoReturn(); } } while (0)
;
1005
1006 ClearPopupShownDispatcher();
1007
1008 // don't hide the popup when it isn't open
1009 if (mPopupState == ePopupClosed || mPopupState == ePopupShowing ||
1010 mPopupState == ePopupPositioning) {
1011 return;
1012 }
1013
1014 if (aNewState == ePopupClosed) {
1015 // clear the trigger content if the popup is being closed. But don't clear
1016 // it if the popup is just being made invisible as a popuphiding or command
1017 // event may want to retrieve it.
1018 ClearTriggerContentIncludingDocument();
1019 mAnchorContent = nullptr;
1020 }
1021
1022 // when invisible and about to be closed, HidePopup has already been called,
1023 // so just set the new state to closed and return
1024 if (mPopupState == ePopupInvisible) {
1025 if (aNewState == ePopupClosed) {
1026 mPopupState = ePopupClosed;
1027 }
1028 return;
1029 }
1030
1031 mPopupState = aNewState;
1032
1033 mIncrementalString.Truncate();
1034
1035 mIsOpenChanged = false;
1036 mHFlip = mVFlip = false;
1037 mConstrainedByLayout = false;
1038
1039 if (auto* widget = GetWidget()) {
1040 // Ideally we should call ClearCachedWebrenderResources but there are
1041 // intermittent failures (see bug 1748788), so we currently call
1042 // ClearWebrenderAnimationResources instead.
1043 widget->ClearWebrenderAnimationResources();
1044 }
1045
1046 nsView* view = GetView();
1047 nsViewManager* viewManager = view->GetViewManager();
1048 viewManager->SetViewVisibility(view, ViewVisibility::Hide);
1049
1050 RefPtr popup = &PopupElement();
1051 // XXX, bug 137033, In Windows, if mouse is outside the window when the
1052 // menupopup closes, no mouse_enter/mouse_exit event will be fired to clear
1053 // current hover state, we should clear it manually. This code may not the
1054 // best solution, but we can leave it here until we find the better approach.
1055 if (!aFromFrameDestruction &&
1056 popup->State().HasState(dom::ElementState::HOVER)) {
1057 EventStateManager* esm = PresContext()->EventStateManager();
1058 esm->SetContentState(nullptr, dom::ElementState::HOVER);
1059 }
1060 popup->PopupClosed(aDeselectMenu);
1061}
1062
1063nsPoint nsMenuPopupFrame::AdjustPositionForAnchorAlign(
1064 nsRect& anchorRect, const nsSize& aPrefSize, FlipStyle& aHFlip,
1065 FlipStyle& aVFlip) const {
1066 // flip the anchor and alignment for right-to-left
1067 int8_t popupAnchor(mPopupAnchor);
1068 int8_t popupAlign(mPopupAlignment);
1069 if (IsDirectionRTL()) {
1070 // no need to flip the centered anchor types vertically
1071 if (popupAnchor <= POPUPALIGNMENT_LEFTCENTER16) {
1072 popupAnchor = -popupAnchor;
1073 }
1074 popupAlign = -popupAlign;
1075 }
1076
1077 nsRect originalAnchorRect(anchorRect);
1078
1079 // first, determine at which corner of the anchor the popup should appear
1080 nsPoint pnt;
1081 switch (popupAnchor) {
1082 case POPUPALIGNMENT_LEFTCENTER16:
1083 pnt = nsPoint(anchorRect.x, anchorRect.y + anchorRect.height / 2);
1084 anchorRect.y = pnt.y;
1085 anchorRect.height = 0;
1086 break;
1087 case POPUPALIGNMENT_RIGHTCENTER-16:
1088 pnt = nsPoint(anchorRect.XMost(), anchorRect.y + anchorRect.height / 2);
1089 anchorRect.y = pnt.y;
1090 anchorRect.height = 0;
1091 break;
1092 case POPUPALIGNMENT_TOPCENTER17:
1093 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.y);
1094 anchorRect.x = pnt.x;
1095 anchorRect.width = 0;
1096 break;
1097 case POPUPALIGNMENT_BOTTOMCENTER18:
1098 pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.YMost());
1099 anchorRect.x = pnt.x;
1100 anchorRect.width = 0;
1101 break;
1102 case POPUPALIGNMENT_TOPRIGHT-1:
1103 pnt = anchorRect.TopRight();
1104 break;
1105 case POPUPALIGNMENT_BOTTOMLEFT2:
1106 pnt = anchorRect.BottomLeft();
1107 break;
1108 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1109 pnt = anchorRect.BottomRight();
1110 break;
1111 case POPUPALIGNMENT_TOPLEFT1:
1112 default:
1113 pnt = anchorRect.TopLeft();
1114 break;
1115 }
1116
1117 // If the alignment is on the right edge of the popup, move the popup left
1118 // by the width. Similarly, if the alignment is on the bottom edge of the
1119 // popup, move the popup up by the height. In addition, account for the
1120 // margins of the popup on the edge on which it is aligned.
1121 nsMargin margin = GetMargin();
1122 switch (popupAlign) {
1123 case POPUPALIGNMENT_LEFTCENTER16:
1124 pnt.MoveBy(margin.left, -aPrefSize.height / 2);
1125 break;
1126 case POPUPALIGNMENT_RIGHTCENTER-16:
1127 pnt.MoveBy(-aPrefSize.width - margin.right, -aPrefSize.height / 2);
1128 break;
1129 case POPUPALIGNMENT_TOPCENTER17:
1130 pnt.MoveBy(-aPrefSize.width / 2, margin.top);
1131 break;
1132 case POPUPALIGNMENT_BOTTOMCENTER18:
1133 pnt.MoveBy(-aPrefSize.width / 2, -aPrefSize.height - margin.bottom);
1134 break;
1135 case POPUPALIGNMENT_TOPRIGHT-1:
1136 pnt.MoveBy(-aPrefSize.width - margin.right, margin.top);
1137 break;
1138 case POPUPALIGNMENT_BOTTOMLEFT2:
1139 pnt.MoveBy(margin.left, -aPrefSize.height - margin.bottom);
1140 break;
1141 case POPUPALIGNMENT_BOTTOMRIGHT-2:
1142 pnt.MoveBy(-aPrefSize.width - margin.right,
1143 -aPrefSize.height - margin.bottom);
1144 break;
1145 case POPUPALIGNMENT_TOPLEFT1:
1146 default:
1147 pnt.MoveBy(margin.left, margin.top);
1148 break;
1149 }
1150
1151 // If we aligning to the selected item in the popup, adjust the vertical
1152 // position by the height of the menulist label and the selected item's
1153 // position.
1154 if (mPosition == POPUPPOSITION_SELECTION10) {
1155 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"
, 1156); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1156; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1156 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"
, 1156); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAnchor == 2 || popupAnchor == -2"
")"); do { *((volatile int*)__null) = 1156; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1157 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"
, 1158); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1158; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1158 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"
, 1158); AnnotateMozCrashReason("MOZ_ASSERT" "(" "popupAlign == 1 || popupAlign == -1"
")"); do { *((volatile int*)__null) = 1158; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1159
1160 // Only adjust the popup if it just opened, otherwise the popup will move
1161 // around if its gets resized or the selection changed. Cache the value in
1162 // mPositionedOffset and use that instead for any future calculations.
1163 if (mIsOpenChanged) {
1164 if (nsIFrame* selectedItemFrame = GetSelectedItemForAlignment()) {
1165 const nscoord itemHeight = selectedItemFrame->GetRect().height;
1166 const nscoord itemOffset =
1167 selectedItemFrame->GetOffsetToIgnoringScrolling(this).y;
1168 // We want to line-up the anchor rect with the selected item, but if the
1169 // selected item is outside of our bounds, we don't want to shift the
1170 // popup up in a way that our box would no longer intersect with the
1171 // anchor.
1172 nscoord maxOffset = aPrefSize.height - itemHeight;
1173 if (const ScrollContainerFrame* sf = GetScrollContainerFrame()) {
1174 // HACK: We ideally would want to use the offset from the bottom
1175 // bottom of our scroll-frame to the bottom of our frame (so as to
1176 // ensure that the bottom of the scrollport is inside the anchor
1177 // rect).
1178 //
1179 // But at this point of the code, the scroll frame may not be laid out
1180 // with a definite size (might be overflowing us).
1181 //
1182 // So, we assume the offset from the bottom is symmetric to the offset
1183 // from the top. This holds for all the popups where this matters
1184 // (menulists on macOS, effectively), and seems better than somehow
1185 // moving the popup after the fact as we used to do.
1186 maxOffset -= sf->GetOffsetTo(this).y;
1187 }
1188 mPositionedOffset =
1189 originalAnchorRect.height + std::min(itemOffset, maxOffset);
1190 }
1191 }
1192
1193 pnt.y -= mPositionedOffset;
1194 }
1195
1196 // Flipping horizontally is allowed as long as the popup is above or below
1197 // the anchor. This will happen if both the anchor and alignment are top or
1198 // both are bottom, but different values. Similarly, flipping vertically is
1199 // allowed if the popup is to the left or right of the anchor. In this case,
1200 // the values of the constants are such that both must be positive or both
1201 // must be negative. A special case, used for overlap, allows flipping
1202 // vertically as well.
1203 // If we are flipping in both directions, we want to set a flip style both
1204 // horizontally and vertically. However, we want to flip on the inside edge
1205 // of the anchor. Consider the example of a typical dropdown menu.
1206 // Vertically, we flip the popup on the outside edges of the anchor menu,
1207 // however horizontally, we want to to use the inside edges so the popup
1208 // still appears underneath the anchor menu instead of floating off the
1209 // side of the menu.
1210 switch (popupAnchor) {
1211 case POPUPALIGNMENT_LEFTCENTER16:
1212 case POPUPALIGNMENT_RIGHTCENTER-16:
1213 aHFlip = FlipStyle_Outside;
1214 aVFlip = FlipStyle_Inside;
1215 break;
1216 case POPUPALIGNMENT_TOPCENTER17:
1217 case POPUPALIGNMENT_BOTTOMCENTER18:
1218 aHFlip = FlipStyle_Inside;
1219 aVFlip = FlipStyle_Outside;
1220 break;
1221 default: {
1222 FlipStyle anchorEdge =
1223 mFlip == FlipType_Both ? FlipStyle_Inside : FlipStyle_None;
1224 aHFlip = (popupAnchor == -popupAlign) ? FlipStyle_Outside : anchorEdge;
1225 if (((popupAnchor > 0) == (popupAlign > 0)) ||
1226 (popupAnchor == POPUPALIGNMENT_TOPLEFT1 &&
1227 popupAlign == POPUPALIGNMENT_TOPLEFT1))
1228 aVFlip = FlipStyle_Outside;
1229 else
1230 aVFlip = anchorEdge;
1231 break;
1232 }
1233 }
1234
1235 return pnt;
1236}
1237
1238nsIFrame* nsMenuPopupFrame::GetSelectedItemForAlignment() const {
1239 // This method adjusts a menulist's popup such that the selected item is under
1240 // the cursor, aligned with the menulist label.
1241 nsCOMPtr<nsIDOMXULSelectControlElement> select;
1242 if (mAnchorContent) {
1243 select = mAnchorContent->AsElement()->AsXULSelectControl();
1244 }
1245
1246 if (!select) {
1247 // If there isn't an anchor, then try just getting the parent of the popup.
1248 select = mContent->GetParent()->AsElement()->AsXULSelectControl();
1249 if (!select) {
1250 return nullptr;
1251 }
1252 }
1253
1254 nsCOMPtr<Element> selectedElement;
1255 select->GetSelectedItem(getter_AddRefs(selectedElement));
1256 return selectedElement ? selectedElement->GetPrimaryFrame() : nullptr;
1257}
1258
1259nscoord nsMenuPopupFrame::SlideOrResize(nscoord& aScreenPoint, nscoord aSize,
1260 nscoord aScreenBegin,
1261 nscoord aScreenEnd,
1262 nscoord* aOffset) const {
1263 // The popup may be positioned such that either the left/top or bottom/right
1264 // is outside the screen - but never both.
1265 nscoord newPos =
1266 std::max(aScreenBegin, std::min(aScreenEnd - aSize, aScreenPoint));
1267 *aOffset = newPos - aScreenPoint;
1268 aScreenPoint = newPos;
1269 return std::min(aSize, aScreenEnd - aScreenPoint);
1270}
1271
1272nscoord nsMenuPopupFrame::FlipOrResize(nscoord& aScreenPoint, nscoord aSize,
1273 nscoord aScreenBegin, nscoord aScreenEnd,
1274 nscoord aAnchorBegin, nscoord aAnchorEnd,
1275 nscoord aMarginBegin, nscoord aMarginEnd,
1276 FlipStyle aFlip, bool aEndAligned,
1277 bool* aFlipSide) const {
1278 // The flip side argument will be set to true if there wasn't room and we
1279 // flipped to the opposite side.
1280 *aFlipSide = false;
1281
1282 // all of the coordinates used here are in app units relative to the screen
1283 nscoord popupSize = aSize;
1284 if (aScreenPoint < aScreenBegin) {
1285 // at its current position, the popup would extend past the left or top
1286 // edge of the screen, so it will have to be moved or resized.
1287 if (aFlip) {
1288 // for inside flips, we flip on the opposite side of the anchor
1289 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1290 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1291
1292 // check whether there is more room to the left and right (or top and
1293 // bottom) of the anchor and put the popup on the side with more room.
1294 if (startpos - aScreenBegin >= aScreenEnd - endpos) {
1295 aScreenPoint = aScreenBegin;
1296 popupSize = startpos - aScreenPoint - aMarginEnd;
1297 *aFlipSide = !aEndAligned;
1298 } else {
1299 // If the newly calculated position is different than the existing
1300 // position, flip such that the popup is to the right or bottom of the
1301 // anchor point instead . However, when flipping use the same margin
1302 // size.
1303 nscoord newScreenPoint = endpos + aMarginEnd;
1304 if (newScreenPoint != aScreenPoint) {
1305 *aFlipSide = aEndAligned;
1306 aScreenPoint = newScreenPoint;
1307 // check if the new position is still off the right or bottom edge of
1308 // the screen. If so, resize the popup.
1309 if (aScreenPoint + aSize > aScreenEnd) {
1310 popupSize = aScreenEnd - aScreenPoint;
1311 }
1312 }
1313 }
1314 } else {
1315 aScreenPoint = aScreenBegin;
1316 }
1317 } else if (aScreenPoint + aSize > aScreenEnd) {
1318 // at its current position, the popup would extend past the right or
1319 // bottom edge of the screen, so it will have to be moved or resized.
1320 if (aFlip) {
1321 // for inside flips, we flip on the opposite side of the anchor
1322 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1323 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1324
1325 // check whether there is more room to the left and right (or top and
1326 // bottom) of the anchor and put the popup on the side with more room.
1327 if (aScreenEnd - endpos >= startpos - aScreenBegin) {
1328 *aFlipSide = aEndAligned;
1329 if (mIsContextMenu) {
1330 aScreenPoint = aScreenEnd - aSize;
1331 } else {
1332 aScreenPoint = endpos + aMarginBegin;
1333 popupSize = aScreenEnd - aScreenPoint;
1334 }
1335 } else {
1336 // if the newly calculated position is different than the existing
1337 // position, we flip such that the popup is to the left or top of the
1338 // anchor point instead.
1339 nscoord newScreenPoint = startpos - aSize - aMarginBegin;
1340 if (newScreenPoint != aScreenPoint) {
1341 *aFlipSide = !aEndAligned;
1342 aScreenPoint = newScreenPoint;
1343
1344 // check if the new position is still off the left or top edge of the
1345 // screen. If so, resize the popup.
1346 if (aScreenPoint < aScreenBegin) {
1347 aScreenPoint = aScreenBegin;
1348 if (!mIsContextMenu) {
1349 popupSize = startpos - aScreenPoint - aMarginBegin;
1350 }
1351 }
1352 }
1353 }
1354 } else {
1355 aScreenPoint = aScreenEnd - aSize;
1356 }
1357 }
1358
1359 // Make sure that the point is within the screen boundaries and that the
1360 // size isn't off the edge of the screen. This can happen when a large
1361 // positive or negative margin is used.
1362 if (aScreenPoint < aScreenBegin) {
1363 aScreenPoint = aScreenBegin;
1364 }
1365 if (aScreenPoint > aScreenEnd) {
1366 aScreenPoint = aScreenEnd - aSize;
1367 }
1368
1369 // If popupSize ended up being negative, or the original size was actually
1370 // smaller than the calculated popup size, just use the original size instead.
1371 if (popupSize <= 0 || aSize < popupSize) {
1372 popupSize = aSize;
1373 }
1374
1375 return std::min(popupSize, aScreenEnd - aScreenPoint);
1376}
1377
1378nsRect nsMenuPopupFrame::ComputeAnchorRect(nsPresContext* aRootPresContext,
1379 nsIFrame* aAnchorFrame) const {
1380 // Get the root frame for a reference
1381 nsIFrame* rootFrame = aRootPresContext->PresShell()->GetRootFrame();
1382
1383 // The dimensions of the anchor
1384 nsRect anchorRect = aAnchorFrame->GetRectRelativeToSelf();
1385
1386 // Relative to the root
1387 anchorRect = nsLayoutUtils::TransformFrameRectToAncestor(
1388 aAnchorFrame, anchorRect, rootFrame);
1389 // Relative to the screen
1390 anchorRect.MoveBy(rootFrame->GetScreenRectInAppUnits().TopLeft());
1391
1392 // In its own app units
1393 return anchorRect.ScaleToOtherAppUnitsRoundOut(
1394 aRootPresContext->AppUnitsPerDevPixel(),
1395 PresContext()->AppUnitsPerDevPixel());
1396}
1397
1398static nsIFrame* MaybeDelegatedAnchorFrame(nsIFrame* aFrame) {
1399 if (!aFrame) {
1400 return nullptr;
1401 }
1402 if (auto* element = Element::FromNodeOrNull(aFrame->GetContent())) {
1403 if (element->HasAttr(nsGkAtoms::delegatesanchor)) {
1404 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1405 if (!f->IsPlaceholderFrame()) {
1406 return f;
1407 }
1408 }
1409 }
1410 }
1411 return aFrame;
1412}
1413
1414auto nsMenuPopupFrame::GetRects(const nsSize& aPrefSize) const -> Rects {
1415 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"
, 1415)
) {
1416 // Return early if the popup hasn't been laid out yet. On Windows, this can
1417 // happen when using a drag popup before it opens.
1418 return {};
1419 }
1420
1421 nsPresContext* pc = PresContext();
1422 nsIFrame* rootFrame = pc->PresShell()->GetRootFrame();
1423 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"
, 1425); MOZ_PretendNoReturn(); } } while (0)
1424 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"
, 1425); MOZ_PretendNoReturn(); } } while (0)
1425 "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"
, 1425); MOZ_PretendNoReturn(); } } while (0)
;
1426
1427 // Indicators of whether the popup should be flipped or resized.
1428 FlipStyle hFlip = FlipStyle_None, vFlip = FlipStyle_None;
1429
1430 const nsMargin margin = GetMargin();
1431
1432 // the screen rectangle of the root frame, in dev pixels.
1433 const nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
1434
1435 const bool isNoAutoHide = IsNoAutoHide();
1436 const PopupLevel popupLevel = GetPopupLevel(isNoAutoHide);
1437
1438 Rects result;
1439
1440 // Set the popup's size to the preferred size. Below, this size will be
1441 // adjusted to fit on the screen or within the content area. If the anchor is
1442 // sized to the popup, use the anchor's width instead of the preferred width.
1443 result.mUsedRect = nsRect(nsPoint(), aPrefSize);
1444
1445 const bool anchored = IsAnchored();
1446 if (anchored) {
1447 // In order to deal with transforms, we need the root prescontext:
1448 nsPresContext* rootPc = pc->GetRootPresContext();
1449 if (NS_WARN_IF(!rootPc)NS_warn_if_impl(!rootPc, "!rootPc", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1449)
) {
1450 // If we can't reach a root pres context, don't bother continuing.
1451 return result;
1452 }
1453
1454 result.mAnchorRect = result.mUntransformedAnchorRect = [&] {
1455 // If anchored to a rectangle, use that rectangle. Otherwise, determine
1456 // the rectangle from the anchor.
1457 if (mAnchorType == MenuPopupAnchorType_Rect) {
1458 return mScreenRect;
1459 }
1460 // if the frame is not specified, use the anchor node passed to OpenPopup.
1461 // If that wasn't specified either, use the root frame. Note that
1462 // mAnchorContent might be a different document so its presshell must be
1463 // used.
1464 nsIFrame* anchorFrame = GetAnchorFrame();
1465 if (!anchorFrame) {
1466 return rootScreenRect;
1467 }
1468 return ComputeAnchorRect(rootPc, anchorFrame);
1469 }();
1470
1471 // if we are anchored, there are certain things we don't want to do when
1472 // repositioning the popup to fit on the screen, such as end up positioned
1473 // over the anchor, for instance a popup appearing over the menu label.
1474 // When doing this reposition, we want to move the popup to the side with
1475 // the most room. The combination of anchor and alignment dictate if we
1476 // readjust above/below or to the left/right.
1477 if (mAnchorContent || mAnchorType == MenuPopupAnchorType_Rect) {
1478 // move the popup according to the anchor and alignment. This will also
1479 // tell us which axis the popup is flush against in case we have to move
1480 // it around later. The AdjustPositionForAnchorAlign method accounts for
1481 // the popup's margin.
1482 result.mUsedRect.MoveTo(AdjustPositionForAnchorAlign(
1483 result.mAnchorRect, aPrefSize, hFlip, vFlip));
1484 } else {
1485 // With no anchor, the popup is positioned relative to the root frame.
1486 result.mUsedRect.MoveTo(result.mAnchorRect.TopLeft() +
1487 nsPoint(margin.left, margin.top));
1488 }
1489
1490 // mXPos and mYPos specify an additional offset passed to OpenPopup that
1491 // should be added to the position. We also add the offset to the anchor
1492 // pos so a later flip/resize takes the offset into account.
1493 // FIXME(emilio): Wayland doesn't seem to be accounting for this offset
1494 // anywhere, and it probably should.
1495 {
1496 nsPoint offset(CSSPixel::ToAppUnits(mXPos), CSSPixel::ToAppUnits(mYPos));
1497 if (IsDirectionRTL()) {
1498 offset.x = -offset.x;
1499 }
1500 result.mUsedRect.MoveBy(offset);
1501 result.mAnchorRect.MoveBy(offset);
1502 }
1503 } else {
1504 // Not anchored, use mScreenRect
1505 result.mUsedRect.MoveTo(mScreenRect.TopLeft());
1506 result.mAnchorRect = result.mUntransformedAnchorRect =
1507 nsRect(mScreenRect.TopLeft(), nsSize());
1508
1509 // Right-align RTL context menus, and apply margin and offsets as per the
1510 // platform conventions.
1511 if (mIsContextMenu && IsDirectionRTL()) {
1512 result.mUsedRect.x -= aPrefSize.Width();
1513 result.mUsedRect.MoveBy(-margin.right, margin.top);
1514 } else {
1515 result.mUsedRect.MoveBy(margin.left, margin.top);
1516 }
1517#ifdef XP_MACOSX
1518 // OSX tooltips follow standard flip rule but other popups flip horizontally
1519 // not vertically
1520 if (mPopupType == PopupType::Tooltip) {
1521 vFlip = FlipStyle_Outside;
1522 } else {
1523 hFlip = FlipStyle_Outside;
1524 }
1525#else
1526 // Other OS screen positioned popups can be flipped vertically but never
1527 // horizontally
1528 vFlip = FlipStyle_Outside;
1529#endif // #ifdef XP_MACOSX
1530 }
1531
1532 const int32_t a2d = pc->AppUnitsPerDevPixel();
1533
1534 nsView* view = GetView();
1535 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"
, 1535); MOZ_PretendNoReturn(); } } while (0)
;
1536
1537 nsIWidget* widget = view->GetWidget();
1538
1539 // If a panel has flip="none", don't constrain or flip it.
1540 // Also, always do this for content shells, so that the popup doesn't extend
1541 // outside the containing frame.
1542 if (mInContentShell || mFlip != FlipType_None) {
1543 const Maybe<nsRect> constraintRect =
1544 GetConstraintRect(result.mAnchorRect, rootScreenRect, popupLevel);
1545
1546 if (constraintRect) {
1547 // Ensure that anchorRect is on the constraint rect.
1548 result.mAnchorRect = result.mAnchorRect.Intersect(*constraintRect);
1549 // Shrink the popup down if it is larger than the constraint size
1550 if (result.mUsedRect.width > constraintRect->width) {
1551 result.mUsedRect.width = constraintRect->width;
1552 }
1553 if (result.mUsedRect.height > constraintRect->height) {
1554 result.mUsedRect.height = constraintRect->height;
1555 }
1556 result.mConstrainedByLayout = true;
1557 }
1558
1559 if (IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() && widget) {
1560 // Shrink the popup down if it's larger than popup size received from
1561 // Wayland compositor. We don't know screen size on Wayland so this is the
1562 // only info we have there.
1563 const nsSize waylandSize = LayoutDeviceIntRect::ToAppUnits(
1564 widget->GetMoveToRectPopupSize(), a2d);
1565 if (waylandSize.width > 0 && result.mUsedRect.width > waylandSize.width) {
1566 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)
1567 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)
;
1568 result.mUsedRect.width = waylandSize.width;
1569 }
1570 if (waylandSize.height > 0 &&
1571 result.mUsedRect.height > waylandSize.height) {
1572 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)
1573 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)
;
1574 result.mUsedRect.height = waylandSize.height;
1575 }
1576 if (RefPtr<widget::Screen> s = widget->GetWidgetScreen()) {
1577 const nsSize screenSize =
1578 LayoutDeviceIntSize::ToAppUnits(s->GetAvailRect().Size(), a2d);
1579 if (result.mUsedRect.height > screenSize.height) {
1580 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)
1581 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)
;
1582 result.mUsedRect.height = screenSize.height;
1583 }
1584 if (result.mUsedRect.width > screenSize.width) {
1585 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)
1586 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)
;
1587 result.mUsedRect.width = screenSize.width;
1588 }
1589 }
1590 }
1591
1592 // At this point the anchor (anchorRect) is within the available screen
1593 // area (constraintRect) and the popup is known to be no larger than the
1594 // screen.
1595 if (constraintRect) {
1596 // We might want to "slide" an arrow if the panel is of the correct type -
1597 // but we can only slide on one axis - the other axis must be "flipped or
1598 // resized" as normal.
1599 bool slideHorizontal = false, slideVertical = false;
1600 if (mFlip == FlipType_Slide) {
1601 int8_t position = GetAlignmentPosition();
1602 slideHorizontal = position >= POPUPPOSITION_BEFORESTART0 &&
1603 position <= POPUPPOSITION_AFTEREND3;
1604 slideVertical = position >= POPUPPOSITION_STARTBEFORE4 &&
1605 position <= POPUPPOSITION_ENDAFTER7;
1606 }
1607
1608 // Next, check if there is enough space to show the popup at full size
1609 // when positioned at screenPoint. If not, flip the popups to the opposite
1610 // side of their anchor point, or resize them as necessary.
1611 if (slideHorizontal) {
1612 result.mUsedRect.width = SlideOrResize(
1613 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1614 constraintRect->XMost(), &result.mAlignmentOffset);
1615 } else {
1616 const bool endAligned =
1617 IsDirectionRTL()
1618 ? mPopupAlignment == POPUPALIGNMENT_TOPLEFT1 ||
1619 mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1620 mPopupAlignment == POPUPALIGNMENT_LEFTCENTER16
1621 : mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1 ||
1622 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1623 mPopupAlignment == POPUPALIGNMENT_RIGHTCENTER-16;
1624 result.mUsedRect.width = FlipOrResize(
1625 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1626 constraintRect->XMost(), result.mAnchorRect.x,
1627 result.mAnchorRect.XMost(), margin.left, margin.right, hFlip,
1628 endAligned, &result.mHFlip);
1629 }
1630 if (slideVertical) {
1631 result.mUsedRect.height = SlideOrResize(
1632 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1633 constraintRect->YMost(), &result.mAlignmentOffset);
1634 } else {
1635 bool endAligned = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1636 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1637 mPopupAlignment == POPUPALIGNMENT_BOTTOMCENTER18;
1638 result.mUsedRect.height = FlipOrResize(
1639 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1640 constraintRect->YMost(), result.mAnchorRect.y,
1641 result.mAnchorRect.YMost(), margin.top, margin.bottom, vFlip,
1642 endAligned, &result.mVFlip);
1643 }
1644
1645#ifdef DEBUG1
1646 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"
, 1647); MOZ_PretendNoReturn(); } } while (0)
1647 "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"
, 1647); MOZ_PretendNoReturn(); } } while (0)
;
1648 if (!constraintRect->Contains(result.mUsedRect)) {
1649 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"
, 1652)
1650 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"
, 1652)
1651 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"
, 1652)
1652 .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"
, 1652)
;
1653 }
1654#endif
1655 }
1656 }
1657 // snap the popup's position in screen coordinates to device pixels, see
1658 // bug 622507, bug 961431
1659 result.mUsedRect.x = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.x);
1660 result.mUsedRect.y = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.y);
1661
1662 // determine the x and y position of the view by subtracting the desired
1663 // screen position from the screen position of the root frame.
1664 result.mViewPoint = result.mUsedRect.TopLeft() - rootScreenRect.TopLeft();
1665
1666 // Offset the position by the width and height of the borders and titlebar.
1667 // Even though GetClientOffset should return (0, 0) when there is no titlebar
1668 // or borders, we skip these calculations anyway for non-panels to save time
1669 // since they will never have a titlebar.
1670 if (mPopupType == PopupType::Panel && widget) {
1671 result.mClientOffset = widget->GetClientOffset();
1672 result.mViewPoint +=
1673 LayoutDeviceIntPoint::ToAppUnits(result.mClientOffset, a2d);
1674 }
1675
1676 return result;
1677}
1678
1679void nsMenuPopupFrame::SetPopupPosition(bool aIsMove) {
1680 if (aIsMove && (mPrefSize.width == -1 || mPrefSize.height == -1)) {
1681 return;
1682 }
1683
1684 auto rects = GetRects(mPrefSize);
1685 if (rects.mUsedRect.Size() != mRect.Size()) {
1686 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"
, 1686); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IN_REFLOW)"
")"); do { *((volatile int*)__null) = 1686; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1687 // We need to resize on top of moving, trigger an actual reflow.
1688 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
1689 NS_FRAME_IS_DIRTY);
1690 return;
1691 }
1692 PerformMove(rects);
1693}
1694
1695void nsMenuPopupFrame::PerformMove(const Rects& aRects) {
1696 auto* ps = PresShell();
1697
1698 // We're just moving, sync frame position and offset as needed.
1699 ps->GetViewManager()->MoveViewTo(GetView(), aRects.mViewPoint.x,
1700 aRects.mViewPoint.y);
1701
1702 // Now that we've positioned the view, sync up the frame's origin.
1703 nsBlockFrame::SetPosition(aRects.mViewPoint -
1704 GetParent()->GetOffsetTo(ps->GetRootFrame()));
1705
1706 // If the popup is in the positioned state or if it is shown and the position
1707 // or size changed, dispatch a popuppositioned event if the popup wants it.
1708 if (mPopupState == ePopupPositioning ||
1709 (mPopupState == ePopupShown &&
1710 !aRects.mUsedRect.IsEqualEdges(mUsedScreenRect)) ||
1711 (mPopupState == ePopupShown &&
1712 aRects.mAlignmentOffset != mAlignmentOffset)) {
1713 mUsedScreenRect = aRects.mUsedRect;
1714 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && !mPendingPositionedEvent) {
1715 mPendingPositionedEvent =
1716 nsXULPopupPositionedEvent::DispatchIfNeeded(mContent->AsElement());
1717 }
1718 }
1719
1720 if (!mPositionedByMoveToRect) {
1721 mUntransformedAnchorRect = aRects.mUntransformedAnchorRect;
1722 }
1723
1724 mAlignmentOffset = aRects.mAlignmentOffset;
1725 mLastClientOffset = aRects.mClientOffset;
1726 mHFlip = aRects.mHFlip;
1727 mVFlip = aRects.mVFlip;
1728 mConstrainedByLayout = aRects.mConstrainedByLayout;
1729
1730 // If this is a noautohide popup, set the screen coordinates of the popup.
1731 // This way, the popup stays at the location where it was opened even when the
1732 // window is moved. Popups at the parent level follow the parent window as it
1733 // is moved and remained anchored, so we want to maintain the anchoring
1734 // instead.
1735 //
1736 // FIXME: This suffers from issues like bug 1823552, where constraints imposed
1737 // by the anchor are lost, but this is super-old behavior.
1738 const bool fixPositionToPoint =
1739 IsNoAutoHide() && (GetPopupLevel() != PopupLevel::Parent ||
1740 mAnchorType == MenuPopupAnchorType_Rect);
1741 if (fixPositionToPoint) {
1742 // Account for the margin that will end up being added to the screen
1743 // coordinate the next time SetPopupPosition is called.
1744 const auto& margin = GetMargin();
1745 mAnchorType = MenuPopupAnchorType_Point;
1746 mScreenRect.x = aRects.mUsedRect.x - margin.left;
1747 mScreenRect.y = aRects.mUsedRect.y - margin.top;
1748 }
1749
1750 // For anchored popups that shouldn't follow the anchor, fix the original
1751 // anchor rect.
1752 if (IsAnchored() && !ShouldFollowAnchor() && !mUsedScreenRect.IsEmpty() &&
1753 mAnchorType != MenuPopupAnchorType_Rect) {
1754 mAnchorType = MenuPopupAnchorType_Rect;
1755 mScreenRect = aRects.mUntransformedAnchorRect;
1756 }
1757
1758 // NOTE(emilio): This call below is kind of a workaround, but we need to do
1759 // this here because some position changes don't go through the
1760 // view system -> popup manager, like:
1761 //
1762 // https://searchfox.org/mozilla-central/rev/477950cf9ca9c9bb5ff6f34e0d0f6ca4718ea798/widget/gtk/nsWindow.cpp#3847
1763 //
1764 // So this might be the last chance we have to set the remote browser's
1765 // position.
1766 //
1767 // Ultimately this probably wants to get fixed in the widget size of things,
1768 // but given this is worst-case a redundant DOM traversal, and that popups
1769 // usually don't have all that much content, this is probably an ok
1770 // workaround.
1771 WidgetPositionOrSizeDidChange();
1772}
1773
1774void nsMenuPopupFrame::WidgetPositionOrSizeDidChange() {
1775 // In the case this popup has remote contents having OOP iframes, it's
1776 // possible that OOP iframe's nsSubDocumentFrame has been already reflowed
1777 // thus, we will never have a chance to tell this parent browser's position
1778 // update to the OOP documents without notifying it explicitly.
1779 if (!HasRemoteContent()) {
1780 return;
1781 }
1782 for (nsIContent* content = mContent->GetFirstChild(); content;
1783 content = content->GetNextNode(mContent)) {
1784 if (content->IsXULElement(nsGkAtoms::browser) &&
1785 content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
1786 nsGkAtoms::_true, eIgnoreCase)) {
1787 if (auto* browserParent = dom::BrowserParent::GetFrom(content)) {
1788 browserParent->NotifyPositionUpdatedForContentsInPopup();
1789 }
1790 }
1791 }
1792}
1793
1794Maybe<nsRect> nsMenuPopupFrame::GetConstraintRect(
1795 const nsRect& aAnchorRect, const nsRect& aRootScreenRect,
1796 PopupLevel aPopupLevel) const {
1797 const nsPresContext* pc = PresContext();
1798 const int32_t a2d = PresContext()->AppUnitsPerDevPixel();
1799 Maybe<nsRect> result;
1800
1801 auto AddConstraint = [&result](const nsRect& aConstraint) {
1802 if (result) {
1803 *result = result->Intersect(aConstraint);
1804 } else {
1805 result.emplace(aConstraint);
1806 }
1807 };
1808
1809 // Determine the available screen space. It will be reduced by the OS chrome
1810 // such as menubars. It addition, for content shells, it will be the area of
1811 // the content rather than the screen.
1812 // In Wayland we can't use the screen rect because we can't know absolute
1813 // window position.
1814 if (!IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay()) {
1815 const DesktopToLayoutDeviceScale scale =
1816 pc->DeviceContext()->GetDesktopToDeviceScale();
1817 // For content shells, get the screen where the root frame is located. This
1818 // is because we need to constrain the content to this content area, so we
1819 // should use the same screen. Otherwise, use the screen where the anchor is
1820 // located.
1821 const nsRect& rect = mInContentShell ? aRootScreenRect : aAnchorRect;
1822 auto desktopRect = DesktopIntRect::RoundOut(
1823 LayoutDeviceRect::FromAppUnits(rect, a2d) / scale);
1824 desktopRect.width = std::max(1, desktopRect.width);
1825 desktopRect.height = std::max(1, desktopRect.height);
1826
1827 RefPtr<nsIScreen> screen =
1828 widget::ScreenManager::GetSingleton().ScreenForRect(desktopRect);
1829 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"
, 1829); AnnotateMozCrashReason("MOZ_ASSERT" "(" "screen" ") ("
"We always fall back to the primary screen" ")"); do { *((volatile
int*)__null) = 1829; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
1830 // Non-top-level popups (which will always be panels) should never overlap
1831 // the OS bar.
1832 const bool canOverlapOSBar =
1833 aPopupLevel == PopupLevel::Top &&
1834 LookAndFeel::GetInt(LookAndFeel::IntID::MenusCanOverlapOSBar) &&
1835 !mInContentShell;
1836 // Get the total screen area if the popup is allowed to overlap it.
1837 const auto screenRect =
1838 canOverlapOSBar ? screen->GetRect() : screen->GetAvailRect();
1839 AddConstraint(LayoutDeviceRect::ToAppUnits(screenRect, a2d));
1840 }
1841
1842 if (mInContentShell) {
1843 // For content shells, clip to the client area rather than the screen area
1844 AddConstraint(aRootScreenRect);
1845 } else if (!mOverrideConstraintRect.IsEmpty()) {
1846 AddConstraint(mOverrideConstraintRect);
1847 // This is currently only used for <select> elements where we want to
1848 // constrain vertically to the screen but not horizontally, so do the
1849 // intersection and then reset the horizontal values.
1850 //
1851 // FIXME(emilio): This doesn't make any sense to me...
1852 result->x = mOverrideConstraintRect.x;
1853 result->width = mOverrideConstraintRect.width;
1854 }
1855
1856 // Expand the allowable screen rect by the input margin (which can't be
1857 // interacted with).
1858 if (result) {
1859 const nscoord inputMargin =
1860 StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
1861 result->Inflate(inputMargin);
1862 }
1863 return result;
1864}
1865
1866ConsumeOutsideClicksResult nsMenuPopupFrame::ConsumeOutsideClicks() {
1867 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1868 nsGkAtoms::consumeoutsideclicks,
1869 nsGkAtoms::_true, eCaseMatters)) {
1870 return ConsumeOutsideClicks_True;
1871 }
1872 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1873 nsGkAtoms::consumeoutsideclicks,
1874 nsGkAtoms::_false, eCaseMatters)) {
1875 return ConsumeOutsideClicks_ParentOnly;
1876 }
1877 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1878 nsGkAtoms::consumeoutsideclicks,
1879 nsGkAtoms::never, eCaseMatters)) {
1880 return ConsumeOutsideClicks_Never;
1881 }
1882
1883 nsCOMPtr<nsIContent> parentContent = mContent->GetParent();
1884 if (parentContent) {
1885 dom::NodeInfo* ni = parentContent->NodeInfo();
1886 if (ni->Equals(nsGkAtoms::menulist, kNameSpaceID_XUL8)) {
1887 return ConsumeOutsideClicks_True; // Consume outside clicks for combo
1888 // boxes on all platforms
1889 }
1890#if defined(XP_WIN)
1891 // Don't consume outside clicks for menus in Windows
1892 if (ni->Equals(nsGkAtoms::menu, kNameSpaceID_XUL8) ||
1893 ni->Equals(nsGkAtoms::popupset, kNameSpaceID_XUL8) ||
1894 ((ni->Equals(nsGkAtoms::button, kNameSpaceID_XUL8) ||
1895 ni->Equals(nsGkAtoms::toolbarbutton, kNameSpaceID_XUL8)) &&
1896 parentContent->AsElement()->AttrValueIs(
1897 kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::menu,
1898 eCaseMatters))) {
1899 return ConsumeOutsideClicks_Never;
1900 }
1901#endif
1902 }
1903
1904 return ConsumeOutsideClicks_True;
1905}
1906
1907static ScrollContainerFrame* DoGetScrollContainerFrame(const nsIFrame* aFrame) {
1908 if (const ScrollContainerFrame* sf = do_QueryFrame(aFrame)) {
1909 return const_cast<ScrollContainerFrame*>(sf);
1910 }
1911 for (nsIFrame* childFrame : aFrame->PrincipalChildList()) {
1912 if (auto* sf = DoGetScrollContainerFrame(childFrame)) {
1913 return sf;
1914 }
1915 }
1916 return nullptr;
1917}
1918
1919// XXXroc this is megalame. Fossicking around for a frame of the right
1920// type is a recipe for disaster in the long term.
1921ScrollContainerFrame* nsMenuPopupFrame::GetScrollContainerFrame() const {
1922 return DoGetScrollContainerFrame(this);
1923}
1924
1925void nsMenuPopupFrame::ChangeByPage(bool aIsUp) {
1926 // Only scroll by page within menulists.
1927 if (!IsMenuList()) {
1928 return;
1929 }
1930
1931 ScrollContainerFrame* scrollContainerFrame = GetScrollContainerFrame();
1932
1933 RefPtr popup = &PopupElement();
1934 XULButtonElement* currentMenu = popup->GetActiveMenuChild();
1935 XULButtonElement* newMenu = nullptr;
1936 if (!currentMenu) {
1937 // If there is no current menu item, get the first item. When moving up,
1938 // just use this as the newMenu and leave currentMenu null so that no check
1939 // for a later element is performed. When moving down, set currentMenu so
1940 // that we look for one page down from the first item.
1941 newMenu = popup->GetFirstMenuItem();
1942 if (!aIsUp) {
1943 currentMenu = newMenu;
1944 }
1945 }
1946
1947 if (currentMenu && currentMenu->GetPrimaryFrame()) {
1948 const nscoord scrollHeight =
1949 scrollContainerFrame ? scrollContainerFrame->GetScrollPortRect().height
1950 : mRect.height;
1951 const nsRect currentRect = currentMenu->GetPrimaryFrame()->GetRect();
1952 const XULButtonElement* startMenu = currentMenu;
1953
1954 // Get the position of the current item and add or subtract one popup's
1955 // height to or from it.
1956 const nscoord targetPos = aIsUp ? currentRect.YMost() - scrollHeight
1957 : currentRect.y + scrollHeight;
1958 // Look for the next child which is just past the target position. This
1959 // child will need to be selected.
1960 for (; currentMenu;
1961 currentMenu = aIsUp ? popup->GetPrevMenuItemFrom(*currentMenu)
1962 : popup->GetNextMenuItemFrom(*currentMenu)) {
1963 if (!currentMenu->GetPrimaryFrame()) {
1964 continue;
1965 }
1966 const nsRect curRect = currentMenu->GetPrimaryFrame()->GetRect();
1967 const nscoord curPos = aIsUp ? curRect.y : curRect.YMost();
1968 // If the right position was found, break out. Otherwise, look for another
1969 // item.
1970 if (aIsUp ? (curPos < targetPos) : (curPos > targetPos)) {
1971 if (!newMenu || newMenu == startMenu) {
1972 newMenu = currentMenu;
1973 }
1974 break;
1975 }
1976
1977 // Assign this item to newMenu. This item will be selected in case we
1978 // don't find any more.
1979 newMenu = currentMenu;
1980 }
1981 }
1982
1983 // Select the new menuitem.
1984 if (RefPtr newMenuRef = newMenu) {
1985 popup->SetActiveMenuChild(newMenuRef);
1986 }
1987}
1988
1989dom::XULPopupElement& nsMenuPopupFrame::PopupElement() const {
1990 auto* popup = dom::XULPopupElement::FromNode(GetContent());
1991 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"
, 1991); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "popup"
")"); do { *((volatile int*)__null) = 1991; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1992 return *popup;
1993}
1994
1995XULButtonElement* nsMenuPopupFrame::GetCurrentMenuItem() const {
1996 return PopupElement().GetActiveMenuChild();
1997}
1998
1999nsIFrame* nsMenuPopupFrame::GetCurrentMenuItemFrame() const {
2000 auto* child = GetCurrentMenuItem();
2001 return child ? child->GetPrimaryFrame() : nullptr;
2002}
2003
2004void nsMenuPopupFrame::HandleEnterKeyPress(WidgetEvent& aEvent) {
2005 mIncrementalString.Truncate();
2006 RefPtr popup = &PopupElement();
2007 popup->HandleEnterKeyPress(aEvent);
2008}
2009
2010XULButtonElement* nsMenuPopupFrame::FindMenuWithShortcut(
2011 mozilla::dom::KeyboardEvent& aKeyEvent, bool& aDoAction) {
2012 uint32_t charCode = aKeyEvent.CharCode();
2013 uint32_t keyCode = aKeyEvent.KeyCode();
2014
2015 aDoAction = false;
2016
2017 // Enumerate over our list of frames.
2018 const bool isMenu = !IsMenuList();
2019 TimeStamp keyTime = aKeyEvent.WidgetEventPtr()->mTimeStamp;
2020 if (charCode == 0) {
2021 if (keyCode == dom::KeyboardEvent_Binding::DOM_VK_BACK_SPACE) {
2022 if (!isMenu && !mIncrementalString.IsEmpty()) {
2023 mIncrementalString.SetLength(mIncrementalString.Length() - 1);
2024 return nullptr;
2025 }
2026#ifdef XP_WIN
2027 if (nsCOMPtr<nsISound> sound = do_GetService("@mozilla.org/sound;1")) {
2028 sound->Beep();
2029 }
2030#endif // #ifdef XP_WIN
2031 }
2032 return nullptr;
2033 }
2034 char16_t uniChar = ToLowerCase(static_cast<char16_t>(charCode));
2035 if (isMenu) {
2036 // Menu supports only first-letter navigation
2037 mIncrementalString = uniChar;
2038 } else if (IsWithinIncrementalTime(keyTime)) {
2039 mIncrementalString.Append(uniChar);
2040 } else {
2041 // Interval too long, treat as new typing
2042 mIncrementalString = uniChar;
2043 }
2044
2045 // See bug 188199 & 192346, if all letters in incremental string are same,
2046 // just try to match the first one
2047 nsAutoString incrementalString(mIncrementalString);
2048 uint32_t charIndex = 1, stringLength = incrementalString.Length();
2049 while (charIndex < stringLength &&
2050 incrementalString[charIndex] == incrementalString[charIndex - 1]) {
2051 charIndex++;
2052 }
2053 if (charIndex == stringLength) {
2054 incrementalString.Truncate(1);
2055 stringLength = 1;
Value stored to 'stringLength' is never read
2056 }
2057
2058 sLastKeyTime = keyTime;
2059
2060 auto* item =
2061 PopupElement().FindMenuWithShortcut(incrementalString, aDoAction);
2062 if (item) {
2063 return item;
2064 }
2065
2066 // If we don't match anything, rollback the last typing
2067 mIncrementalString.SetLength(mIncrementalString.Length() - 1);
2068
2069 // didn't find a matching menu item
2070#ifdef XP_WIN
2071 // behavior on Windows - this item is in a menu popup off of the
2072 // menu bar, so beep and do nothing else
2073 if (isMenu) {
2074 if (nsCOMPtr<nsISound> sound = do_GetService("@mozilla.org/sound;1")) {
2075 sound->Beep();
2076 }
2077 }
2078#endif // #ifdef XP_WIN
2079
2080 return nullptr;
2081}
2082
2083nsIWidget* nsMenuPopupFrame::GetWidget() const {
2084 return mView ? mView->GetWidget() : nullptr;
2085}
2086
2087// helpers /////////////////////////////////////////////////////////////
2088
2089nsresult nsMenuPopupFrame::AttributeChanged(int32_t aNameSpaceID,
2090 nsAtom* aAttribute,
2091 int32_t aModType)
2092
2093{
2094 nsresult rv =
2095 nsBlockFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
2096
2097 if (aAttribute == nsGkAtoms::left || aAttribute == nsGkAtoms::top) {
2098 MoveToAttributePosition();
2099 }
2100
2101 if (aAttribute == nsGkAtoms::remote) {
2102 // When the remote attribute changes, we need to create a new widget to
2103 // ensure that it has the correct compositor and transparency settings to
2104 // match the new value.
2105 PrepareWidget(true);
2106 }
2107
2108 if (aAttribute == nsGkAtoms::followanchor) {
2109 if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
2110 pm->UpdateFollowAnchor(this);
2111 }
2112 }
2113
2114 if (aAttribute == nsGkAtoms::label) {
2115 // set the label for the titlebar
2116 nsView* view = GetView();
2117 if (view) {
2118 nsIWidget* widget = view->GetWidget();
2119 if (widget) {
2120 nsAutoString title;
2121 mContent->AsElement()->GetAttr(nsGkAtoms::label, title);
2122 if (!title.IsEmpty()) {
2123 widget->SetTitle(title);
2124 }
2125 }
2126 }
2127 } else if (aAttribute == nsGkAtoms::ignorekeys) {
2128 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2129 if (pm) {
2130 nsAutoString ignorekeys;
2131 mContent->AsElement()->GetAttr(nsGkAtoms::ignorekeys, ignorekeys);
2132 pm->UpdateIgnoreKeys(ignorekeys.EqualsLiteral("true"));
2133 }
2134 }
2135
2136 return rv;
2137}
2138
2139void nsMenuPopupFrame::MoveToAttributePosition() {
2140 // Move the widget around when the user sets the |left| and |top| attributes.
2141 // Note that this is not the best way to move the widget, as it results in
2142 // lots of FE notifications and is likely to be slow as molasses. Use |moveTo|
2143 // on the element if possible.
2144 nsAutoString left, top;
2145 mContent->AsElement()->GetAttr(nsGkAtoms::left, left);
2146 mContent->AsElement()->GetAttr(nsGkAtoms::top, top);
2147 nsresult err1, err2;
2148 mozilla::CSSIntPoint pos(left.ToInteger(&err1), top.ToInteger(&err2));
2149
2150 if (NS_SUCCEEDED(err1)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err1)), 1))) && NS_SUCCEEDED(err2)((bool)(__builtin_expect(!!(!NS_FAILED_impl(err2)), 1)))) MoveTo(pos, false);
2151
2152 PresShell()->FrameNeedsReflow(
2153 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
2154}
2155
2156void nsMenuPopupFrame::Destroy(DestroyContext& aContext) {
2157 // XXX: Currently we don't fire popuphidden for these popups, that seems wrong
2158 // but alas, also pre-existing.
2159 HidePopup(/* aDeselectMenu = */ false, ePopupClosed,
2160 /* aFromFrameDestruction = */ true);
2161
2162 if (RefPtr<nsXULPopupManager> pm = nsXULPopupManager::GetInstance()) {
2163 pm->PopupDestroyed(this);
2164 }
2165
2166 nsBlockFrame::Destroy(aContext);
2167}
2168
2169nsMargin nsMenuPopupFrame::GetMargin() const {
2170 nsMargin margin;
2171 StyleMargin()->GetMargin(margin);
2172 if (mIsTopLevelContextMenu) {
2173 const CSSIntPoint offset(
2174 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetHorizontal),
2175 LookAndFeel::GetInt(LookAndFeel::IntID::ContextMenuOffsetVertical));
2176 auto auOffset = CSSIntPoint::ToAppUnits(offset);
2177 margin.top += auOffset.y;
2178 margin.bottom += auOffset.y;
2179 margin.left += auOffset.x;
2180 margin.right += auOffset.x;
2181 }
2182 if (mPopupType == PopupType::Tooltip && !IsAnchored()) {
2183 const auto auOffset =
2184 CSSPixel::ToAppUnits(LookAndFeel::TooltipOffsetVertical());
2185 margin.top += auOffset;
2186 margin.bottom += auOffset;
2187 }
2188 return margin;
2189}
2190
2191void nsMenuPopupFrame::MoveTo(const CSSPoint& aPos, bool aUpdateAttrs,
2192 bool aByMoveToRect) {
2193 nsIWidget* widget = GetWidget();
2194 nsPoint appUnitsPos = CSSPixel::ToAppUnits(aPos);
2195
2196 // reposition the popup at the specified coordinates. Don't clear the anchor
2197 // and position, because the popup can be reset to its anchor position by
2198 // using (-1, -1) as coordinates.
2199 //
2200 // Subtract off the margin as it will be added to the position when
2201 // SetPopupPosition is called.
2202 {
2203 nsMargin margin = GetMargin();
2204 if (mIsContextMenu && IsDirectionRTL()) {
2205 appUnitsPos.x += margin.right + mRect.Width();
2206 } else {
2207 appUnitsPos.x -= margin.left;
2208 }
2209 appUnitsPos.y -= margin.top;
2210 }
2211
2212 if (mScreenRect.TopLeft() == appUnitsPos &&
2213 (!widget || widget->GetClientOffset() == mLastClientOffset)) {
2214 return;
2215 }
2216
2217 mPositionedByMoveToRect = aByMoveToRect;
2218 mScreenRect.MoveTo(appUnitsPos);
2219 if (mAnchorType == MenuPopupAnchorType_Rect) {
2220 // This ensures that the anchor width is still honored, to prevent it from
2221 // changing spuriously.
2222 mScreenRect.height = 0;
2223 // But we still need to make sure that our top left position ends up in
2224 // appUnitsPos.
2225 mPopupAlignment = POPUPALIGNMENT_TOPLEFT1;
2226 mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT2;
2227 mXPos = mYPos = 0;
2228 } else {
2229 mAnchorType = MenuPopupAnchorType_Point;
2230 }
2231
2232 SetPopupPosition(true);
2233
2234 RefPtr<Element> popup = mContent->AsElement();
2235 if (aUpdateAttrs &&
2236 (popup->HasAttr(nsGkAtoms::left) || popup->HasAttr(nsGkAtoms::top))) {
2237 nsAutoString left, top;
2238 left.AppendInt(RoundedToInt(aPos).x);
2239 top.AppendInt(RoundedToInt(aPos).y);
2240 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::left, left, false);
2241 popup->SetAttr(kNameSpaceID_None, nsGkAtoms::top, top, false);
2242 }
2243}
2244
2245void nsMenuPopupFrame::MoveToAnchor(nsIContent* aAnchorContent,
2246 const nsAString& aPosition, int32_t aXPos,
2247 int32_t aYPos, bool aAttributesOverride) {
2248 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"
, 2249); MOZ_PretendNoReturn(); } } while (0)
2249 "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"
, 2249); MOZ_PretendNoReturn(); } } while (0)
;
2250
2251 nsPopupState oldstate = mPopupState;
2252 InitializePopup(aAnchorContent, mTriggerContent, aPosition, aXPos, aYPos,
2253 MenuPopupAnchorType_Node, aAttributesOverride);
2254 // InitializePopup changed the state so reset it.
2255 mPopupState = oldstate;
2256
2257 // Pass false here so that flipping and adjusting to fit on the screen happen.
2258 SetPopupPosition(false);
2259}
2260
2261int8_t nsMenuPopupFrame::GetAlignmentPosition() const {
2262 // The code below handles most cases of alignment, anchor and position values.
2263 // Those that are not handled just return POPUPPOSITION_UNKNOWN.
2264
2265 if (mPosition == POPUPPOSITION_OVERLAP8 ||
2266 mPosition == POPUPPOSITION_AFTERPOINTER9 ||
2267 mPosition == POPUPPOSITION_SELECTION10) {
2268 return mPosition;
2269 }
2270
2271 int8_t position = mPosition;
2272
2273 if (position == POPUPPOSITION_UNKNOWN-1) {
2274 switch (mPopupAnchor) {
2275 case POPUPALIGNMENT_BOTTOMRIGHT-2:
2276 case POPUPALIGNMENT_BOTTOMLEFT2:
2277 case POPUPALIGNMENT_BOTTOMCENTER18:
2278 position = mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1
2279 ? POPUPPOSITION_AFTEREND3
2280 : POPUPPOSITION_AFTERSTART2;
2281 break;
2282 case POPUPALIGNMENT_TOPRIGHT-1:
2283 case POPUPALIGNMENT_TOPLEFT1:
2284 case POPUPALIGNMENT_TOPCENTER17:
2285 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2286 ? POPUPPOSITION_BEFOREEND1
2287 : POPUPPOSITION_BEFORESTART0;
2288 break;
2289 case POPUPALIGNMENT_LEFTCENTER16:
2290 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2
2291 ? POPUPPOSITION_STARTAFTER6
2292 : POPUPPOSITION_STARTBEFORE4;
2293 break;
2294 case POPUPALIGNMENT_RIGHTCENTER-16:
2295 position = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2
2296 ? POPUPPOSITION_ENDAFTER7
2297 : POPUPPOSITION_ENDBEFORE5;
2298 break;
2299 default:
2300 break;
2301 }
2302 }
2303
2304 if (mHFlip) {
2305 position = POPUPPOSITION_HFLIP(position)(position ^ 1);
2306 }
2307
2308 if (mVFlip) {
2309 position = POPUPPOSITION_VFLIP(position)(position ^ 2);
2310 }
2311
2312 return position;
2313}
2314
2315/**
2316 * KEEP THIS IN SYNC WITH nsIFrame::CreateView
2317 * as much as possible. Until we get rid of views finally...
2318 */
2319void nsMenuPopupFrame::CreatePopupView() {
2320 if (HasView()) {
2321 return;
2322 }
2323
2324 nsViewManager* viewManager = PresContext()->GetPresShell()->GetViewManager();
2325 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"
, 2325); MOZ_PretendNoReturn(); } } while (0)
;
2326
2327 // Create a view
2328 nsView* parentView = viewManager->GetRootView();
2329 auto visibility = ViewVisibility::Hide;
2330
2331 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"
, 2331); MOZ_PretendNoReturn(); } } while (0)
;
2332
2333 // Create a view
2334 nsView* view = viewManager->CreateView(GetRect(), parentView, visibility);
2335 // XXX put view last in document order until we can do better
2336 viewManager->InsertChild(parentView, view, nullptr, true);
2337
2338 // Remember our view
2339 SetView(view);
2340
2341 NS_FRAME_LOG(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
2342 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)
2343 ("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)
;
2344}
2345
2346bool nsMenuPopupFrame::ShouldFollowAnchor() const {
2347 if (mAnchorType != MenuPopupAnchorType_Node || !mAnchorContent) {
2348 return false;
2349 }
2350
2351 // Follow anchor mode is used when followanchor="true" is set or for arrow
2352 // panels.
2353 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2354 nsGkAtoms::followanchor,
2355 nsGkAtoms::_true, eCaseMatters)) {
2356 return true;
2357 }
2358
2359 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2360 nsGkAtoms::followanchor,
2361 nsGkAtoms::_false, eCaseMatters)) {
2362 return false;
2363 }
2364
2365 return mPopupType == PopupType::Panel &&
2366 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
2367 nsGkAtoms::arrow, eCaseMatters);
2368}
2369
2370bool nsMenuPopupFrame::ShouldFollowAnchor(nsRect& aRect) {
2371 if (!ShouldFollowAnchor()) {
2372 return false;
2373 }
2374
2375 if (nsIFrame* anchorFrame = GetAnchorFrame()) {
2376 if (nsPresContext* rootPresContext = PresContext()->GetRootPresContext()) {
2377 aRect = ComputeAnchorRect(rootPresContext, anchorFrame);
2378 }
2379 }
2380
2381 return true;
2382}
2383
2384bool nsMenuPopupFrame::IsDirectionRTL() const {
2385 const nsIFrame* anchor = GetAnchorFrame();
2386 const nsIFrame* f = anchor ? anchor : this;
2387 return f->StyleVisibility()->mDirection == StyleDirection::Rtl;
2388}
2389
2390nsIFrame* nsMenuPopupFrame::GetAnchorFrame() const {
2391 nsIContent* anchor = mAnchorContent;
2392 if (!anchor) {
2393 return nullptr;
2394 }
2395 return MaybeDelegatedAnchorFrame(anchor->GetPrimaryFrame());
2396}
2397
2398void nsMenuPopupFrame::CheckForAnchorChange(nsRect& aRect) {
2399 // Don't update if the popup isn't visible or we shouldn't be following the
2400 // anchor.
2401 if (!IsVisible() || !ShouldFollowAnchor()) {
2402 return;
2403 }
2404
2405 bool shouldHide = false;
2406
2407 nsPresContext* rootPresContext = PresContext()->GetRootPresContext();
2408
2409 // If the frame for the anchor has gone away, hide the popup.
2410 nsIFrame* anchor = GetAnchorFrame();
2411 if (!anchor || !rootPresContext) {
2412 shouldHide = true;
2413 } else if (!anchor->IsVisibleConsideringAncestors(
2414 VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) {
2415 // If the anchor is now inside something that is invisible, hide the popup.
2416 shouldHide = true;
2417 } else {
2418 // If the anchor is now inside a hidden parent popup, hide the popup.
2419 nsIFrame* frame = anchor;
2420 while (frame) {
2421 nsMenuPopupFrame* popup = do_QueryFrame(frame);
2422 if (popup && popup->PopupState() != ePopupShown) {
2423 shouldHide = true;
2424 break;
2425 }
2426
2427 frame = frame->GetParent();
2428 }
2429 }
2430
2431 if (shouldHide) {
2432 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2433 if (pm) {
2434 // As the caller will be iterating over the open popups, hide
2435 // asyncronously.
2436 pm->HidePopup(mContent->AsElement(),
2437 {HidePopupOption::DeselectMenu, HidePopupOption::Async});
2438 }
2439
2440 return;
2441 }
2442
2443 nsRect anchorRect = ComputeAnchorRect(rootPresContext, anchor);
2444
2445 // If the rectangles are different, move the popup.
2446 if (!anchorRect.IsEqualEdges(aRect)) {
2447 aRect = anchorRect;
2448 SetPopupPosition(true);
2449 }
2450}