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 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/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/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/x86_64-linux-gnu/c++/13 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/backward -internal-isystem /usr/lib/llvm-18/lib/clang/18/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../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-05-16-034744-15991-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 "nsIScrollableFrame.h"
28#include "nsIPopupContainer.h"
29#include "nsIDocShell.h"
30#include "nsReadableUtils.h"
31#include "nsUnicharUtils.h"
32#include "nsLayoutUtils.h"
33#include "nsContentUtils.h"
34#include "nsCSSFrameConstructor.h"
35#include "nsPIWindowRoot.h"
36#include "nsIReflowCallback.h"
37#include "nsIDocShellTreeOwner.h"
38#include "nsIBaseWindow.h"
39#include "nsISound.h"
40#include "nsIScreenManager.h"
41#include "nsServiceManagerUtils.h"
42#include "nsStyleConsts.h"
43#include "nsStyleStructInlines.h"
44#include "nsTransitionManager.h"
45#include "nsDisplayList.h"
46#include "nsIDOMXULSelectCntrlEl.h"
47#include "mozilla/widget/ScreenManager.h"
48#include "mozilla/AnimationUtils.h"
49#include "mozilla/BasePrincipal.h"
50#include "mozilla/EventDispatcher.h"
51#include "mozilla/EventStateManager.h"
52#include "mozilla/Preferences.h"
53#include "mozilla/LookAndFeel.h"
54#include "mozilla/MouseEvents.h"
55#include "mozilla/PresShell.h"
56#include "mozilla/Services.h"
57#include "mozilla/dom/BrowserParent.h"
58#include "mozilla/dom/Element.h"
59#include "mozilla/dom/Event.h"
60#include "mozilla/dom/KeyboardEvent.h"
61#include "mozilla/dom/KeyboardEventBinding.h"
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 (nsIScrollableFrame* sf = GetScrollFrame()) {
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 nsIScrollableFrame* sf = GetScrollFrame()) {
1174 // HACK: We ideally would want to use the offset from the bottom
1175 // bottom of our scroll-frame to the bottom of our frame (so as to
1176 // ensure that the bottom of the scrollport is inside the anchor
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 const nsIFrame* f = do_QueryFrame(sf);
1187 maxOffset -= f->GetOffsetTo(this).y;
1188 }
1189 mPositionedOffset =
1190 originalAnchorRect.height + std::min(itemOffset, maxOffset);
1191 }
1192 }
1193
1194 pnt.y -= mPositionedOffset;
1195 }
1196
1197 // Flipping horizontally is allowed as long as the popup is above or below
1198 // the anchor. This will happen if both the anchor and alignment are top or
1199 // both are bottom, but different values. Similarly, flipping vertically is
1200 // allowed if the popup is to the left or right of the anchor. In this case,
1201 // the values of the constants are such that both must be positive or both
1202 // must be negative. A special case, used for overlap, allows flipping
1203 // vertically as well.
1204 // If we are flipping in both directions, we want to set a flip style both
1205 // horizontally and vertically. However, we want to flip on the inside edge
1206 // of the anchor. Consider the example of a typical dropdown menu.
1207 // Vertically, we flip the popup on the outside edges of the anchor menu,
1208 // however horizontally, we want to to use the inside edges so the popup
1209 // still appears underneath the anchor menu instead of floating off the
1210 // side of the menu.
1211 switch (popupAnchor) {
1212 case POPUPALIGNMENT_LEFTCENTER16:
1213 case POPUPALIGNMENT_RIGHTCENTER-16:
1214 aHFlip = FlipStyle_Outside;
1215 aVFlip = FlipStyle_Inside;
1216 break;
1217 case POPUPALIGNMENT_TOPCENTER17:
1218 case POPUPALIGNMENT_BOTTOMCENTER18:
1219 aHFlip = FlipStyle_Inside;
1220 aVFlip = FlipStyle_Outside;
1221 break;
1222 default: {
1223 FlipStyle anchorEdge =
1224 mFlip == FlipType_Both ? FlipStyle_Inside : FlipStyle_None;
1225 aHFlip = (popupAnchor == -popupAlign) ? FlipStyle_Outside : anchorEdge;
1226 if (((popupAnchor > 0) == (popupAlign > 0)) ||
1227 (popupAnchor == POPUPALIGNMENT_TOPLEFT1 &&
1228 popupAlign == POPUPALIGNMENT_TOPLEFT1))
1229 aVFlip = FlipStyle_Outside;
1230 else
1231 aVFlip = anchorEdge;
1232 break;
1233 }
1234 }
1235
1236 return pnt;
1237}
1238
1239nsIFrame* nsMenuPopupFrame::GetSelectedItemForAlignment() const {
1240 // This method adjusts a menulist's popup such that the selected item is under
1241 // the cursor, aligned with the menulist label.
1242 nsCOMPtr<nsIDOMXULSelectControlElement> select;
1243 if (mAnchorContent) {
1244 select = mAnchorContent->AsElement()->AsXULSelectControl();
1245 }
1246
1247 if (!select) {
1248 // If there isn't an anchor, then try just getting the parent of the popup.
1249 select = mContent->GetParent()->AsElement()->AsXULSelectControl();
1250 if (!select) {
1251 return nullptr;
1252 }
1253 }
1254
1255 nsCOMPtr<Element> selectedElement;
1256 select->GetSelectedItem(getter_AddRefs(selectedElement));
1257 return selectedElement ? selectedElement->GetPrimaryFrame() : nullptr;
1258}
1259
1260nscoord nsMenuPopupFrame::SlideOrResize(nscoord& aScreenPoint, nscoord aSize,
1261 nscoord aScreenBegin,
1262 nscoord aScreenEnd,
1263 nscoord* aOffset) const {
1264 // The popup may be positioned such that either the left/top or bottom/right
1265 // is outside the screen - but never both.
1266 nscoord newPos =
1267 std::max(aScreenBegin, std::min(aScreenEnd - aSize, aScreenPoint));
1268 *aOffset = newPos - aScreenPoint;
1269 aScreenPoint = newPos;
1270 return std::min(aSize, aScreenEnd - aScreenPoint);
1271}
1272
1273nscoord nsMenuPopupFrame::FlipOrResize(nscoord& aScreenPoint, nscoord aSize,
1274 nscoord aScreenBegin, nscoord aScreenEnd,
1275 nscoord aAnchorBegin, nscoord aAnchorEnd,
1276 nscoord aMarginBegin, nscoord aMarginEnd,
1277 FlipStyle aFlip, bool aEndAligned,
1278 bool* aFlipSide) const {
1279 // The flip side argument will be set to true if there wasn't room and we
1280 // flipped to the opposite side.
1281 *aFlipSide = false;
1282
1283 // all of the coordinates used here are in app units relative to the screen
1284 nscoord popupSize = aSize;
1285 if (aScreenPoint < aScreenBegin) {
1286 // at its current position, the popup would extend past the left or top
1287 // edge of the screen, so it will have to be moved or resized.
1288 if (aFlip) {
1289 // for inside flips, we flip on the opposite side of the anchor
1290 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1291 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1292
1293 // check whether there is more room to the left and right (or top and
1294 // bottom) of the anchor and put the popup on the side with more room.
1295 if (startpos - aScreenBegin >= aScreenEnd - endpos) {
1296 aScreenPoint = aScreenBegin;
1297 popupSize = startpos - aScreenPoint - aMarginEnd;
1298 *aFlipSide = !aEndAligned;
1299 } else {
1300 // If the newly calculated position is different than the existing
1301 // position, flip such that the popup is to the right or bottom of the
1302 // anchor point instead . However, when flipping use the same margin
1303 // size.
1304 nscoord newScreenPoint = endpos + aMarginEnd;
1305 if (newScreenPoint != aScreenPoint) {
1306 *aFlipSide = aEndAligned;
1307 aScreenPoint = newScreenPoint;
1308 // check if the new position is still off the right or bottom edge of
1309 // the screen. If so, resize the popup.
1310 if (aScreenPoint + aSize > aScreenEnd) {
1311 popupSize = aScreenEnd - aScreenPoint;
1312 }
1313 }
1314 }
1315 } else {
1316 aScreenPoint = aScreenBegin;
1317 }
1318 } else if (aScreenPoint + aSize > aScreenEnd) {
1319 // at its current position, the popup would extend past the right or
1320 // bottom edge of the screen, so it will have to be moved or resized.
1321 if (aFlip) {
1322 // for inside flips, we flip on the opposite side of the anchor
1323 nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
1324 nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
1325
1326 // check whether there is more room to the left and right (or top and
1327 // bottom) of the anchor and put the popup on the side with more room.
1328 if (aScreenEnd - endpos >= startpos - aScreenBegin) {
1329 *aFlipSide = aEndAligned;
1330 if (mIsContextMenu) {
1331 aScreenPoint = aScreenEnd - aSize;
1332 } else {
1333 aScreenPoint = endpos + aMarginBegin;
1334 popupSize = aScreenEnd - aScreenPoint;
1335 }
1336 } else {
1337 // if the newly calculated position is different than the existing
1338 // position, we flip such that the popup is to the left or top of the
1339 // anchor point instead.
1340 nscoord newScreenPoint = startpos - aSize - aMarginBegin;
1341 if (newScreenPoint != aScreenPoint) {
1342 *aFlipSide = !aEndAligned;
1343 aScreenPoint = newScreenPoint;
1344
1345 // check if the new position is still off the left or top edge of the
1346 // screen. If so, resize the popup.
1347 if (aScreenPoint < aScreenBegin) {
1348 aScreenPoint = aScreenBegin;
1349 if (!mIsContextMenu) {
1350 popupSize = startpos - aScreenPoint - aMarginBegin;
1351 }
1352 }
1353 }
1354 }
1355 } else {
1356 aScreenPoint = aScreenEnd - aSize;
1357 }
1358 }
1359
1360 // Make sure that the point is within the screen boundaries and that the
1361 // size isn't off the edge of the screen. This can happen when a large
1362 // positive or negative margin is used.
1363 if (aScreenPoint < aScreenBegin) {
1364 aScreenPoint = aScreenBegin;
1365 }
1366 if (aScreenPoint > aScreenEnd) {
1367 aScreenPoint = aScreenEnd - aSize;
1368 }
1369
1370 // If popupSize ended up being negative, or the original size was actually
1371 // smaller than the calculated popup size, just use the original size instead.
1372 if (popupSize <= 0 || aSize < popupSize) {
1373 popupSize = aSize;
1374 }
1375
1376 return std::min(popupSize, aScreenEnd - aScreenPoint);
1377}
1378
1379nsRect nsMenuPopupFrame::ComputeAnchorRect(nsPresContext* aRootPresContext,
1380 nsIFrame* aAnchorFrame) const {
1381 // Get the root frame for a reference
1382 nsIFrame* rootFrame = aRootPresContext->PresShell()->GetRootFrame();
1383
1384 // The dimensions of the anchor
1385 nsRect anchorRect = aAnchorFrame->GetRectRelativeToSelf();
1386
1387 // Relative to the root
1388 anchorRect = nsLayoutUtils::TransformFrameRectToAncestor(
1389 aAnchorFrame, anchorRect, rootFrame);
1390 // Relative to the screen
1391 anchorRect.MoveBy(rootFrame->GetScreenRectInAppUnits().TopLeft());
1392
1393 // In its own app units
1394 return anchorRect.ScaleToOtherAppUnitsRoundOut(
1395 aRootPresContext->AppUnitsPerDevPixel(),
1396 PresContext()->AppUnitsPerDevPixel());
1397}
1398
1399static nsIFrame* MaybeDelegatedAnchorFrame(nsIFrame* aFrame) {
1400 if (!aFrame) {
1401 return nullptr;
1402 }
1403 if (auto* element = Element::FromNodeOrNull(aFrame->GetContent())) {
1404 if (element->HasAttr(nsGkAtoms::delegatesanchor)) {
1405 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1406 if (!f->IsPlaceholderFrame()) {
1407 return f;
1408 }
1409 }
1410 }
1411 }
1412 return aFrame;
1413}
1414
1415auto nsMenuPopupFrame::GetRects(const nsSize& aPrefSize) const -> Rects {
1416 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"
, 1416)
) {
1417 // Return early if the popup hasn't been laid out yet. On Windows, this can
1418 // happen when using a drag popup before it opens.
1419 return {};
1420 }
1421
1422 nsPresContext* pc = PresContext();
1423 nsIFrame* rootFrame = pc->PresShell()->GetRootFrame();
1424 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"
, 1426); MOZ_PretendNoReturn(); } } while (0)
1425 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"
, 1426); MOZ_PretendNoReturn(); } } while (0)
1426 "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"
, 1426); MOZ_PretendNoReturn(); } } while (0)
;
1427
1428 // Indicators of whether the popup should be flipped or resized.
1429 FlipStyle hFlip = FlipStyle_None, vFlip = FlipStyle_None;
1430
1431 const nsMargin margin = GetMargin();
1432
1433 // the screen rectangle of the root frame, in dev pixels.
1434 const nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
1435
1436 const bool isNoAutoHide = IsNoAutoHide();
1437 const PopupLevel popupLevel = GetPopupLevel(isNoAutoHide);
1438
1439 Rects result;
1440
1441 // Set the popup's size to the preferred size. Below, this size will be
1442 // adjusted to fit on the screen or within the content area. If the anchor is
1443 // sized to the popup, use the anchor's width instead of the preferred width.
1444 result.mUsedRect = nsRect(nsPoint(), aPrefSize);
1445
1446 const bool anchored = IsAnchored();
1447 if (anchored) {
1448 // In order to deal with transforms, we need the root prescontext:
1449 nsPresContext* rootPc = pc->GetRootPresContext();
1450 if (NS_WARN_IF(!rootPc)NS_warn_if_impl(!rootPc, "!rootPc", "/var/lib/jenkins/workspace/firefox-scan-build/layout/xul/nsMenuPopupFrame.cpp"
, 1450)
) {
1451 // If we can't reach a root pres context, don't bother continuing.
1452 return result;
1453 }
1454
1455 result.mAnchorRect = result.mUntransformedAnchorRect = [&] {
1456 // If anchored to a rectangle, use that rectangle. Otherwise, determine
1457 // the rectangle from the anchor.
1458 if (mAnchorType == MenuPopupAnchorType_Rect) {
1459 return mScreenRect;
1460 }
1461 // if the frame is not specified, use the anchor node passed to OpenPopup.
1462 // If that wasn't specified either, use the root frame. Note that
1463 // mAnchorContent might be a different document so its presshell must be
1464 // used.
1465 nsIFrame* anchorFrame = GetAnchorFrame();
1466 if (!anchorFrame) {
1467 return rootScreenRect;
1468 }
1469 return ComputeAnchorRect(rootPc, anchorFrame);
1470 }();
1471
1472 // if we are anchored, there are certain things we don't want to do when
1473 // repositioning the popup to fit on the screen, such as end up positioned
1474 // over the anchor, for instance a popup appearing over the menu label.
1475 // When doing this reposition, we want to move the popup to the side with
1476 // the most room. The combination of anchor and alignment dictate if we
1477 // readjust above/below or to the left/right.
1478 if (mAnchorContent || mAnchorType == MenuPopupAnchorType_Rect) {
1479 // move the popup according to the anchor and alignment. This will also
1480 // tell us which axis the popup is flush against in case we have to move
1481 // it around later. The AdjustPositionForAnchorAlign method accounts for
1482 // the popup's margin.
1483 result.mUsedRect.MoveTo(AdjustPositionForAnchorAlign(
1484 result.mAnchorRect, aPrefSize, hFlip, vFlip));
1485 } else {
1486 // With no anchor, the popup is positioned relative to the root frame.
1487 result.mUsedRect.MoveTo(result.mAnchorRect.TopLeft() +
1488 nsPoint(margin.left, margin.top));
1489 }
1490
1491 // mXPos and mYPos specify an additional offset passed to OpenPopup that
1492 // should be added to the position. We also add the offset to the anchor
1493 // pos so a later flip/resize takes the offset into account.
1494 // FIXME(emilio): Wayland doesn't seem to be accounting for this offset
1495 // anywhere, and it probably should.
1496 {
1497 nsPoint offset(CSSPixel::ToAppUnits(mXPos), CSSPixel::ToAppUnits(mYPos));
1498 if (IsDirectionRTL()) {
1499 offset.x = -offset.x;
1500 }
1501 result.mUsedRect.MoveBy(offset);
1502 result.mAnchorRect.MoveBy(offset);
1503 }
1504 } else {
1505 // Not anchored, use mScreenRect
1506 result.mUsedRect.MoveTo(mScreenRect.TopLeft());
1507 result.mAnchorRect = result.mUntransformedAnchorRect =
1508 nsRect(mScreenRect.TopLeft(), nsSize());
1509
1510 // Right-align RTL context menus, and apply margin and offsets as per the
1511 // platform conventions.
1512 if (mIsContextMenu && IsDirectionRTL()) {
1513 result.mUsedRect.x -= aPrefSize.Width();
1514 result.mUsedRect.MoveBy(-margin.right, margin.top);
1515 } else {
1516 result.mUsedRect.MoveBy(margin.left, margin.top);
1517 }
1518#ifdef XP_MACOSX
1519 // OSX tooltips follow standard flip rule but other popups flip horizontally
1520 // not vertically
1521 if (mPopupType == PopupType::Tooltip) {
1522 vFlip = FlipStyle_Outside;
1523 } else {
1524 hFlip = FlipStyle_Outside;
1525 }
1526#else
1527 // Other OS screen positioned popups can be flipped vertically but never
1528 // horizontally
1529 vFlip = FlipStyle_Outside;
1530#endif // #ifdef XP_MACOSX
1531 }
1532
1533 const int32_t a2d = pc->AppUnitsPerDevPixel();
1534
1535 nsView* view = GetView();
1536 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"
, 1536); MOZ_PretendNoReturn(); } } while (0)
;
1537
1538 nsIWidget* widget = view->GetWidget();
1539
1540 // If a panel has flip="none", don't constrain or flip it.
1541 // Also, always do this for content shells, so that the popup doesn't extend
1542 // outside the containing frame.
1543 if (mInContentShell || mFlip != FlipType_None) {
1544 const Maybe<nsRect> constraintRect =
1545 GetConstraintRect(result.mAnchorRect, rootScreenRect, popupLevel);
1546
1547 if (constraintRect) {
1548 // Ensure that anchorRect is on the constraint rect.
1549 result.mAnchorRect = result.mAnchorRect.Intersect(*constraintRect);
1550 // Shrink the popup down if it is larger than the constraint size
1551 if (result.mUsedRect.width > constraintRect->width) {
1552 result.mUsedRect.width = constraintRect->width;
1553 }
1554 if (result.mUsedRect.height > constraintRect->height) {
1555 result.mUsedRect.height = constraintRect->height;
1556 }
1557 result.mConstrainedByLayout = true;
1558 }
1559
1560 if (IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay() && widget) {
1561 // Shrink the popup down if it's larger than popup size received from
1562 // Wayland compositor. We don't know screen size on Wayland so this is the
1563 // only info we have there.
1564 const nsSize waylandSize = LayoutDeviceIntRect::ToAppUnits(
1565 widget->GetMoveToRectPopupSize(), a2d);
1566 if (waylandSize.width > 0 && result.mUsedRect.width > waylandSize.width) {
1567 LOG_WAYLAND("Wayland constraint width [%p]: %d to %d", widget,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)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)
;
1569 result.mUsedRect.width = waylandSize.width;
1570 }
1571 if (waylandSize.height > 0 &&
1572 result.mUsedRect.height > waylandSize.height) {
1573 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)
1574 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)
;
1575 result.mUsedRect.height = waylandSize.height;
1576 }
1577 if (RefPtr<widget::Screen> s = widget->GetWidgetScreen()) {
1578 const nsSize screenSize =
1579 LayoutDeviceIntSize::ToAppUnits(s->GetAvailRect().Size(), a2d);
1580 if (result.mUsedRect.height > screenSize.height) {
1581 LOG_WAYLAND("Wayland constraint height to screen [%p]: %d to %d",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 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)
;
1583 result.mUsedRect.height = screenSize.height;
1584 }
1585 if (result.mUsedRect.width > screenSize.width) {
1586 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)
1587 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)
;
1588 result.mUsedRect.width = screenSize.width;
1589 }
1590 }
1591 }
1592
1593 // At this point the anchor (anchorRect) is within the available screen
1594 // area (constraintRect) and the popup is known to be no larger than the
1595 // screen.
1596 if (constraintRect) {
1597 // We might want to "slide" an arrow if the panel is of the correct type -
1598 // but we can only slide on one axis - the other axis must be "flipped or
1599 // resized" as normal.
1600 bool slideHorizontal = false, slideVertical = false;
1601 if (mFlip == FlipType_Slide) {
1602 int8_t position = GetAlignmentPosition();
1603 slideHorizontal = position >= POPUPPOSITION_BEFORESTART0 &&
1604 position <= POPUPPOSITION_AFTEREND3;
1605 slideVertical = position >= POPUPPOSITION_STARTBEFORE4 &&
1606 position <= POPUPPOSITION_ENDAFTER7;
1607 }
1608
1609 // Next, check if there is enough space to show the popup at full size
1610 // when positioned at screenPoint. If not, flip the popups to the opposite
1611 // side of their anchor point, or resize them as necessary.
1612 if (slideHorizontal) {
1613 result.mUsedRect.width = SlideOrResize(
1614 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1615 constraintRect->XMost(), &result.mAlignmentOffset);
1616 } else {
1617 const bool endAligned =
1618 IsDirectionRTL()
1619 ? mPopupAlignment == POPUPALIGNMENT_TOPLEFT1 ||
1620 mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1621 mPopupAlignment == POPUPALIGNMENT_LEFTCENTER16
1622 : mPopupAlignment == POPUPALIGNMENT_TOPRIGHT-1 ||
1623 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1624 mPopupAlignment == POPUPALIGNMENT_RIGHTCENTER-16;
1625 result.mUsedRect.width = FlipOrResize(
1626 result.mUsedRect.x, result.mUsedRect.width, constraintRect->x,
1627 constraintRect->XMost(), result.mAnchorRect.x,
1628 result.mAnchorRect.XMost(), margin.left, margin.right, hFlip,
1629 endAligned, &result.mHFlip);
1630 }
1631 if (slideVertical) {
1632 result.mUsedRect.height = SlideOrResize(
1633 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1634 constraintRect->YMost(), &result.mAlignmentOffset);
1635 } else {
1636 bool endAligned = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT2 ||
1637 mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT-2 ||
1638 mPopupAlignment == POPUPALIGNMENT_BOTTOMCENTER18;
1639 result.mUsedRect.height = FlipOrResize(
1640 result.mUsedRect.y, result.mUsedRect.height, constraintRect->y,
1641 constraintRect->YMost(), result.mAnchorRect.y,
1642 result.mAnchorRect.YMost(), margin.top, margin.bottom, vFlip,
1643 endAligned, &result.mVFlip);
1644 }
1645
1646#ifdef DEBUG1
1647 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"
, 1648); MOZ_PretendNoReturn(); } } while (0)
1648 "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"
, 1648); MOZ_PretendNoReturn(); } } while (0)
;
1649 if (!constraintRect->Contains(result.mUsedRect)) {
1650 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"
, 1653)
1651 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"
, 1653)
1652 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"
, 1653)
1653 .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"
, 1653)
;
1654 }
1655#endif
1656 }
1657 }
1658 // snap the popup's position in screen coordinates to device pixels, see
1659 // bug 622507, bug 961431
1660 result.mUsedRect.x = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.x);
1661 result.mUsedRect.y = pc->RoundAppUnitsToNearestDevPixels(result.mUsedRect.y);
1662
1663 // determine the x and y position of the view by subtracting the desired
1664 // screen position from the screen position of the root frame.
1665 result.mViewPoint = result.mUsedRect.TopLeft() - rootScreenRect.TopLeft();
1666
1667 // Offset the position by the width and height of the borders and titlebar.
1668 // Even though GetClientOffset should return (0, 0) when there is no titlebar
1669 // or borders, we skip these calculations anyway for non-panels to save time
1670 // since they will never have a titlebar.
1671 if (mPopupType == PopupType::Panel && widget) {
1672 result.mClientOffset = widget->GetClientOffset();
1673 result.mViewPoint +=
1674 LayoutDeviceIntPoint::ToAppUnits(result.mClientOffset, a2d);
1675 }
1676
1677 return result;
1678}
1679
1680void nsMenuPopupFrame::SetPopupPosition(bool aIsMove) {
1681 if (aIsMove && (mPrefSize.width == -1 || mPrefSize.height == -1)) {
1682 return;
1683 }
1684
1685 auto rects = GetRects(mPrefSize);
1686 if (rects.mUsedRect.Size() != mRect.Size()) {
1687 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"
, 1687); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IN_REFLOW)"
")"); do { *((volatile int*)__null) = 1687; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1688 // We need to resize on top of moving, trigger an actual reflow.
1689 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
1690 NS_FRAME_IS_DIRTY);
1691 return;
1692 }
1693 PerformMove(rects);
1694}
1695
1696void nsMenuPopupFrame::PerformMove(const Rects& aRects) {
1697 auto* ps = PresShell();
1698
1699 // We're just moving, sync frame position and offset as needed.
1700 ps->GetViewManager()->MoveViewTo(GetView(), aRects.mViewPoint.x,
1701 aRects.mViewPoint.y);
1702
1703 // Now that we've positioned the view, sync up the frame's origin.
1704 nsBlockFrame::SetPosition(aRects.mViewPoint -
1705 GetParent()->GetOffsetTo(ps->GetRootFrame()));
1706
1707 // If the popup is in the positioned state or if it is shown and the position
1708 // or size changed, dispatch a popuppositioned event if the popup wants it.
1709 if (mPopupState == ePopupPositioning ||
1710 (mPopupState == ePopupShown &&
1711 !aRects.mUsedRect.IsEqualEdges(mUsedScreenRect)) ||
1712 (mPopupState == ePopupShown &&
1713 aRects.mAlignmentOffset != mAlignmentOffset)) {
1714 mUsedScreenRect = aRects.mUsedRect;
1715 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && !mPendingPositionedEvent) {
1716 mPendingPositionedEvent =
1717 nsXULPopupPositionedEvent::DispatchIfNeeded(mContent->AsElement());
1718 }
1719 }
1720
1721 if (!mPositionedByMoveToRect) {
1722 mUntransformedAnchorRect = aRects.mUntransformedAnchorRect;
1723 }
1724
1725 mAlignmentOffset = aRects.mAlignmentOffset;
1726 mLastClientOffset = aRects.mClientOffset;
1727 mHFlip = aRects.mHFlip;
1728 mVFlip = aRects.mVFlip;
1729 mConstrainedByLayout = aRects.mConstrainedByLayout;
1730
1731 // If this is a noautohide popup, set the screen coordinates of the popup.
1732 // This way, the popup stays at the location where it was opened even when the
1733 // window is moved. Popups at the parent level follow the parent window as it
1734 // is moved and remained anchored, so we want to maintain the anchoring
1735 // instead.
1736 //
1737 // FIXME: This suffers from issues like bug 1823552, where constraints imposed
1738 // by the anchor are lost, but this is super-old behavior.
1739 const bool fixPositionToPoint =
1740 IsNoAutoHide() && (GetPopupLevel() != PopupLevel::Parent ||
1741 mAnchorType == MenuPopupAnchorType_Rect);
1742 if (fixPositionToPoint) {
1743 // Account for the margin that will end up being added to the screen
1744 // coordinate the next time SetPopupPosition is called.
1745 const auto& margin = GetMargin();
1746 mAnchorType = MenuPopupAnchorType_Point;
1747 mScreenRect.x = aRects.mUsedRect.x - margin.left;
1748 mScreenRect.y = aRects.mUsedRect.y - margin.top;
1749 }
1750
1751 // For anchored popups that shouldn't follow the anchor, fix the original
1752 // anchor rect.
1753 if (IsAnchored() && !ShouldFollowAnchor() && !mUsedScreenRect.IsEmpty() &&
1754 mAnchorType != MenuPopupAnchorType_Rect) {
1755 mAnchorType = MenuPopupAnchorType_Rect;
1756 mScreenRect = aRects.mUntransformedAnchorRect;
1757 }
1758
1759 // NOTE(emilio): This call below is kind of a workaround, but we need to do
1760 // this here because some position changes don't go through the
1761 // view system -> popup manager, like:
1762 //
1763 // https://searchfox.org/mozilla-central/rev/477950cf9ca9c9bb5ff6f34e0d0f6ca4718ea798/widget/gtk/nsWindow.cpp#3847
1764 //
1765 // So this might be the last chance we have to set the remote browser's
1766 // position.
1767 //
1768 // Ultimately this probably wants to get fixed in the widget size of things,
1769 // but given this is worst-case a redundant DOM traversal, and that popups
1770 // usually don't have all that much content, this is probably an ok
1771 // workaround.
1772 WidgetPositionOrSizeDidChange();
1773}
1774
1775void nsMenuPopupFrame::WidgetPositionOrSizeDidChange() {
1776 // In the case this popup has remote contents having OOP iframes, it's
1777 // possible that OOP iframe's nsSubDocumentFrame has been already reflowed
1778 // thus, we will never have a chance to tell this parent browser's position
1779 // update to the OOP documents without notifying it explicitly.
1780 if (!HasRemoteContent()) {
1781 return;
1782 }
1783 for (nsIContent* content = mContent->GetFirstChild(); content;
1784 content = content->GetNextNode(mContent)) {
1785 if (content->IsXULElement(nsGkAtoms::browser) &&
1786 content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
1787 nsGkAtoms::_true, eIgnoreCase)) {
1788 if (auto* browserParent = dom::BrowserParent::GetFrom(content)) {
1789 browserParent->NotifyPositionUpdatedForContentsInPopup();
1790 }
1791 }
1792 }
1793}
1794
1795Maybe<nsRect> nsMenuPopupFrame::GetConstraintRect(
1796 const nsRect& aAnchorRect, const nsRect& aRootScreenRect,
1797 PopupLevel aPopupLevel) const {
1798 const nsPresContext* pc = PresContext();
1799 const int32_t a2d = PresContext()->AppUnitsPerDevPixel();
1800 Maybe<nsRect> result;
1801
1802 auto AddConstraint = [&result](const nsRect& aConstraint) {
1803 if (result) {
1804 *result = result->Intersect(aConstraint);
1805 } else {
1806 result.emplace(aConstraint);
1807 }
1808 };
1809
1810 // Determine the available screen space. It will be reduced by the OS chrome
1811 // such as menubars. It addition, for content shells, it will be the area of
1812 // the content rather than the screen.
1813 // In Wayland we can't use the screen rect because we can't know absolute
1814 // window position.
1815 if (!IS_WAYLAND_DISPLAY()mozilla::widget::GdkIsWaylandDisplay()) {
1816 const DesktopToLayoutDeviceScale scale =
1817 pc->DeviceContext()->GetDesktopToDeviceScale();
1818 // For content shells, get the screen where the root frame is located. This
1819 // is because we need to constrain the content to this content area, so we
1820 // should use the same screen. Otherwise, use the screen where the anchor is
1821 // located.
1822 const nsRect& rect = mInContentShell ? aRootScreenRect : aAnchorRect;
1823 auto desktopRect = DesktopIntRect::RoundOut(
1824 LayoutDeviceRect::FromAppUnits(rect, a2d) / scale);
1825 desktopRect.width = std::max(1, desktopRect.width);
1826 desktopRect.height = std::max(1, desktopRect.height);
1827
1828 RefPtr<nsIScreen> screen =
1829 widget::ScreenManager::GetSingleton().ScreenForRect(desktopRect);
1830 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"
, 1830); AnnotateMozCrashReason("MOZ_ASSERT" "(" "screen" ") ("
"We always fall back to the primary screen" ")"); do { *((volatile
int*)__null) = 1830; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
1831 // Non-top-level popups (which will always be panels) should never overlap
1832 // the OS bar.
1833 const bool canOverlapOSBar =
1834 aPopupLevel == PopupLevel::Top &&
1835 LookAndFeel::GetInt(LookAndFeel::IntID::MenusCanOverlapOSBar) &&
1836 !mInContentShell;
1837 // Get the total screen area if the popup is allowed to overlap it.
1838 const auto screenRect =
1839 canOverlapOSBar ? screen->GetRect() : screen->GetAvailRect();
1840 AddConstraint(LayoutDeviceRect::ToAppUnits(screenRect, a2d));
1841 }
1842
1843 if (mInContentShell) {
1844 // For content shells, clip to the client area rather than the screen area
1845 AddConstraint(aRootScreenRect);
1846 } else if (!mOverrideConstraintRect.IsEmpty()) {
1847 AddConstraint(mOverrideConstraintRect);
1848 // This is currently only used for <select> elements where we want to
1849 // constrain vertically to the screen but not horizontally, so do the
1850 // intersection and then reset the horizontal values.
1851 //
1852 // FIXME(emilio): This doesn't make any sense to me...
1853 result->x = mOverrideConstraintRect.x;
1854 result->width = mOverrideConstraintRect.width;
1855 }
1856
1857 // Expand the allowable screen rect by the input margin (which can't be
1858 // interacted with).
1859 if (result) {
1860 const nscoord inputMargin =
1861 StyleUIReset()->mMozWindowInputRegionMargin.ToAppUnits();
1862 result->Inflate(inputMargin);
1863 }
1864 return result;
1865}
1866
1867ConsumeOutsideClicksResult nsMenuPopupFrame::ConsumeOutsideClicks() {
1868 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1869 nsGkAtoms::consumeoutsideclicks,
1870 nsGkAtoms::_true, eCaseMatters)) {
1871 return ConsumeOutsideClicks_True;
1872 }
1873 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1874 nsGkAtoms::consumeoutsideclicks,
1875 nsGkAtoms::_false, eCaseMatters)) {
1876 return ConsumeOutsideClicks_ParentOnly;
1877 }
1878 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
1879 nsGkAtoms::consumeoutsideclicks,
1880 nsGkAtoms::never, eCaseMatters)) {
1881 return ConsumeOutsideClicks_Never;
1882 }
1883
1884 nsCOMPtr<nsIContent> parentContent = mContent->GetParent();
1885 if (parentContent) {
1886 dom::NodeInfo* ni = parentContent->NodeInfo();
1887 if (ni->Equals(nsGkAtoms::menulist, kNameSpaceID_XUL8)) {
1888 return ConsumeOutsideClicks_True; // Consume outside clicks for combo
1889 // boxes on all platforms
1890 }
1891#if defined(XP_WIN)
1892 // Don't consume outside clicks for menus in Windows
1893 if (ni->Equals(nsGkAtoms::menu, kNameSpaceID_XUL8) ||
1894 ni->Equals(nsGkAtoms::popupset, kNameSpaceID_XUL8) ||
1895 ((ni->Equals(nsGkAtoms::button, kNameSpaceID_XUL8) ||
1896 ni->Equals(nsGkAtoms::toolbarbutton, kNameSpaceID_XUL8)) &&
1897 parentContent->AsElement()->AttrValueIs(
1898 kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::menu,
1899 eCaseMatters))) {
1900 return ConsumeOutsideClicks_Never;
1901 }
1902#endif
1903 }
1904
1905 return ConsumeOutsideClicks_True;
1906}
1907
1908static nsIScrollableFrame* DoGetScrollFrame(const nsIFrame* aFrame) {
1909 if (const nsIScrollableFrame* sf = do_QueryFrame(aFrame)) {
1910 return const_cast<nsIScrollableFrame*>(sf);
1911 }
1912 for (nsIFrame* childFrame : aFrame->PrincipalChildList()) {
1913 if (auto* sf = DoGetScrollFrame(childFrame)) {
1914 return sf;
1915 }
1916 }
1917 return nullptr;
1918}
1919
1920// XXXroc this is megalame. Fossicking around for a frame of the right
1921// type is a recipe for disaster in the long term.
1922nsIScrollableFrame* nsMenuPopupFrame::GetScrollFrame() const {
1923 return DoGetScrollFrame(this);
1924}
1925
1926void nsMenuPopupFrame::ChangeByPage(bool aIsUp) {
1927 // Only scroll by page within menulists.
1928 if (!IsMenuList()) {
1929 return;
1930 }
1931
1932 nsIScrollableFrame* scrollframe = GetScrollFrame();
1933
1934 RefPtr popup = &PopupElement();
1935 XULButtonElement* currentMenu = popup->GetActiveMenuChild();
1936 XULButtonElement* newMenu = nullptr;
1937 if (!currentMenu) {
1938 // If there is no current menu item, get the first item. When moving up,
1939 // just use this as the newMenu and leave currentMenu null so that no check
1940 // for a later element is performed. When moving down, set currentMenu so
1941 // that we look for one page down from the first item.
1942 newMenu = popup->GetFirstMenuItem();
1943 if (!aIsUp) {
1944 currentMenu = newMenu;
1945 }
1946 }
1947
1948 if (currentMenu && currentMenu->GetPrimaryFrame()) {
1949 const nscoord scrollHeight =
1950 scrollframe ? scrollframe->GetScrollPortRect().height : mRect.height;
1951 const nsRect currentRect = currentMenu->GetPrimaryFrame()->GetRect();
1952 const XULButtonElement* startMenu = currentMenu;
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 auto zIndex = ZIndex();
2336 viewManager->SetViewZIndex(view, zIndex.isNothing(), zIndex.valueOr(0));
2337 // XXX put view last in document order until we can do better
2338 viewManager->InsertChild(parentView, view, nullptr, true);
2339
2340 // Remember our view
2341 SetView(view);
2342
2343 NS_FRAME_LOG(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p"
, this, view); } } while (0)
2344 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)
2345 ("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)
;
2346}
2347
2348bool nsMenuPopupFrame::ShouldFollowAnchor() const {
2349 if (mAnchorType != MenuPopupAnchorType_Node || !mAnchorContent) {
2350 return false;
2351 }
2352
2353 // Follow anchor mode is used when followanchor="true" is set or for arrow
2354 // panels.
2355 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2356 nsGkAtoms::followanchor,
2357 nsGkAtoms::_true, eCaseMatters)) {
2358 return true;
2359 }
2360
2361 if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
2362 nsGkAtoms::followanchor,
2363 nsGkAtoms::_false, eCaseMatters)) {
2364 return false;
2365 }
2366
2367 return mPopupType == PopupType::Panel &&
2368 mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
2369 nsGkAtoms::arrow, eCaseMatters);
2370}
2371
2372bool nsMenuPopupFrame::ShouldFollowAnchor(nsRect& aRect) {
2373 if (!ShouldFollowAnchor()) {
2374 return false;
2375 }
2376
2377 if (nsIFrame* anchorFrame = GetAnchorFrame()) {
2378 if (nsPresContext* rootPresContext = PresContext()->GetRootPresContext()) {
2379 aRect = ComputeAnchorRect(rootPresContext, anchorFrame);
2380 }
2381 }
2382
2383 return true;
2384}
2385
2386bool nsMenuPopupFrame::IsDirectionRTL() const {
2387 const nsIFrame* anchor = GetAnchorFrame();
2388 const nsIFrame* f = anchor ? anchor : this;
2389 return f->StyleVisibility()->mDirection == StyleDirection::Rtl;
2390}
2391
2392nsIFrame* nsMenuPopupFrame::GetAnchorFrame() const {
2393 nsIContent* anchor = mAnchorContent;
2394 if (!anchor) {
2395 return nullptr;
2396 }
2397 return MaybeDelegatedAnchorFrame(anchor->GetPrimaryFrame());
2398}
2399
2400void nsMenuPopupFrame::CheckForAnchorChange(nsRect& aRect) {
2401 // Don't update if the popup isn't visible or we shouldn't be following the
2402 // anchor.
2403 if (!IsVisible() || !ShouldFollowAnchor()) {
2404 return;
2405 }
2406
2407 bool shouldHide = false;
2408
2409 nsPresContext* rootPresContext = PresContext()->GetRootPresContext();
2410
2411 // If the frame for the anchor has gone away, hide the popup.
2412 nsIFrame* anchor = GetAnchorFrame();
2413 if (!anchor || !rootPresContext) {
2414 shouldHide = true;
2415 } else if (!anchor->IsVisibleConsideringAncestors(
2416 VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) {
2417 // If the anchor is now inside something that is invisible, hide the popup.
2418 shouldHide = true;
2419 } else {
2420 // If the anchor is now inside a hidden parent popup, hide the popup.
2421 nsIFrame* frame = anchor;
2422 while (frame) {
2423 nsMenuPopupFrame* popup = do_QueryFrame(frame);
2424 if (popup && popup->PopupState() != ePopupShown) {
2425 shouldHide = true;
2426 break;
2427 }
2428
2429 frame = frame->GetParent();
2430 }
2431 }
2432
2433 if (shouldHide) {
2434 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2435 if (pm) {
2436 // As the caller will be iterating over the open popups, hide
2437 // asyncronously.
2438 pm->HidePopup(mContent->AsElement(),
2439 {HidePopupOption::DeselectMenu, HidePopupOption::Async});
2440 }
2441
2442 return;
2443 }
2444
2445 nsRect anchorRect = ComputeAnchorRect(rootPresContext, anchor);
2446
2447 // If the rectangles are different, move the popup.
2448 if (!anchorRect.IsEqualEdges(aRect)) {
2449 aRect = anchorRect;
2450 SetPopupPosition(true);
2451 }
2452}