Bug Summary

File:root/firefox-clang/obj-x86_64-pc-linux-gnu/layout/generic/./../../../layout/generic/nsIFrame.cpp
Warning:line 3856, column 7
Value stored to 'createdContainer' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_cpp_layout_generic2.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=/root/firefox-clang/obj-x86_64-pc-linux-gnu/layout/generic -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/layout/generic -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /root/firefox-clang/layout/generic -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/layout/generic -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /root/firefox-clang/ipc/chromium/src -I /root/firefox-clang/third_party/abseil-cpp -I /root/firefox-clang/layout/base -I /root/firefox-clang/layout/forms -I /root/firefox-clang/layout/painting -I /root/firefox-clang/layout/style -I /root/firefox-clang/layout/tables -I /root/firefox-clang/layout/xul -I /root/firefox-clang/docshell/base -I /root/firefox-clang/dom/base -I /root/firefox-clang/dom/html -I /root/firefox-clang/dom/xul -I /root/firefox-clang/gfx/cairo/cairo/src -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -I /usr/include/gtk-3.0/unix-print -I /usr/include/gtk-3.0 -I /usr/include/pango-1.0 -I /usr/include/cloudproviders -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/fribidi -I /usr/include/harfbuzz -I /usr/include/atk-1.0 -I /usr/include/cairo -I /usr/include/pixman-1 -I /usr/include/gdk-pixbuf-2.0 -I /usr/include/glycin-2 -I /usr/include/freetype2 -I /usr/include/libpng16 -I /usr/include/gio-unix-2.0 -I /usr/include/glib-2.0 -I /usr/lib/x86_64-linux-gnu/glib-2.0/include -I /usr/include/libmount -I /usr/include/blkid -I /usr/include/sysprof-6 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -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-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 -Wno-character-conversion -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-11-12-001017-1011516-1 -x c++ Unified_cpp_layout_generic2.cpp
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5/* base class of all rendering objects */
6
7#include "nsIFrame.h"
8
9#include <stdarg.h>
10
11#include <algorithm>
12#include <type_traits>
13
14#include "AnchorPositioningUtils.h"
15#include "LayoutLogging.h"
16#include "PseudoStyleType.h"
17#include "RubyUtils.h"
18#include "TextOverflow.h"
19#include "gfx2DGlue.h"
20#include "gfxUtils.h"
21#include "mozilla/AbsoluteContainingBlock.h"
22#include "mozilla/Attributes.h"
23#include "mozilla/CaretAssociationHint.h"
24#include "mozilla/ComputedStyle.h"
25#include "mozilla/DebugOnly.h"
26#include "mozilla/DisplayPortUtils.h"
27#include "mozilla/EventForwards.h"
28#include "mozilla/FocusModel.h"
29#include "mozilla/IntegerRange.h"
30#include "mozilla/Logging.h"
31#include "mozilla/Maybe.h"
32#include "mozilla/PresShell.h"
33#include "mozilla/PresShellInlines.h"
34#include "mozilla/ReflowInput.h"
35#include "mozilla/RestyleManager.h"
36#include "mozilla/ResultExtensions.h"
37#include "mozilla/SVGClipPathFrame.h"
38#include "mozilla/SVGIntegrationUtils.h"
39#include "mozilla/SVGMaskFrame.h"
40#include "mozilla/SVGObserverUtils.h"
41#include "mozilla/SVGTextFrame.h"
42#include "mozilla/SVGUtils.h"
43#include "mozilla/ScrollContainerFrame.h"
44#include "mozilla/SelectionMovementUtils.h"
45#include "mozilla/ServoStyleConsts.h"
46#include "mozilla/Sprintf.h"
47#include "mozilla/StaticAnalysisFunctions.h"
48#include "mozilla/StaticPrefs_dom.h"
49#include "mozilla/StaticPrefs_layout.h"
50#include "mozilla/StaticPrefs_print.h"
51#include "mozilla/StaticPrefs_ui.h"
52#include "mozilla/TextControlElement.h"
53#include "mozilla/ToString.h"
54#include "mozilla/Try.h"
55#include "mozilla/ViewportFrame.h"
56#include "mozilla/ViewportUtils.h"
57#include "mozilla/WritingModes.h"
58#include "mozilla/dom/AncestorIterator.h"
59#include "mozilla/dom/CSSAnimation.h"
60#include "mozilla/dom/CSSTransition.h"
61#include "mozilla/dom/ContentVisibilityAutoStateChangeEvent.h"
62#include "mozilla/dom/DocumentInlines.h"
63#include "mozilla/dom/ElementInlines.h"
64#include "mozilla/dom/HTMLDetailsElement.h"
65#include "mozilla/dom/Range.h"
66#include "mozilla/dom/Selection.h"
67#include "mozilla/dom/Text.h"
68#include "mozilla/gfx/2D.h"
69#include "mozilla/gfx/PathHelpers.h"
70#include "mozilla/intl/BidiEmbeddingLevel.h"
71#include "nsAnimationManager.h"
72#include "nsAtom.h"
73#include "nsBidiPresUtils.h"
74#include "nsCOMPtr.h"
75#include "nsCSSFrameConstructor.h"
76#include "nsCSSProps.h"
77#include "nsCSSRendering.h"
78#include "nsCanvasFrame.h"
79#include "nsContentUtils.h"
80#include "nsFieldSetFrame.h"
81#include "nsFlexContainerFrame.h"
82#include "nsFocusManager.h"
83#include "nsFrameList.h"
84#include "nsFrameSelection.h"
85#include "nsFrameState.h"
86#include "nsFrameTraversal.h"
87#include "nsGkAtoms.h"
88#include "nsGridContainerFrame.h"
89#include "nsIBaseWindow.h"
90#include "nsIContent.h"
91#include "nsIContentInlines.h"
92#include "nsIPercentBSizeObserver.h"
93#include "nsImageFrame.h"
94#include "nsInlineFrame.h"
95#include "nsLayoutUtils.h"
96#include "nsMenuPopupFrame.h"
97#include "nsNameSpaceManager.h"
98#include "nsPlaceholderFrame.h"
99#include "nsPresContext.h"
100#include "nsPresContextInlines.h"
101#include "nsReadableUtils.h"
102#include "nsString.h"
103#include "nsStyleConsts.h"
104#include "nsStyleStructInlines.h"
105#include "nsStyleTransformMatrix.h"
106#include "nsTableWrapperFrame.h"
107#include "nsTextControlFrame.h"
108#include "nsXULElement.h"
109
110// For triple-click pref
111#include "RetainedDisplayListBuilder.h"
112#include "ScrollSnap.h"
113#include "StickyScrollContainer.h"
114#include "gfxContext.h"
115#include "imgIRequest.h"
116#include "nsBlockFrame.h"
117#include "nsChangeHint.h"
118#include "nsContainerFrame.h"
119#include "nsDisplayList.h"
120#include "nsError.h"
121#include "nsFontInflationData.h"
122#include "nsIFrameInlines.h"
123#include "nsRegion.h"
124#include "nsStyleChangeList.h"
125#include "nsSubDocumentFrame.h"
126#include "nsViewportInfo.h"
127#include "nsWindowSizes.h"
128
129#ifdef ACCESSIBILITY1
130# include "mozilla/a11y/PdfStructTreeBuilder.h"
131# include "nsAccessibilityService.h"
132#endif
133
134#include "ActiveLayerTracker.h"
135#include "mozilla/AsyncEventDispatcher.h"
136#include "mozilla/CSSClipPathInstance.h"
137#include "mozilla/EffectCompositor.h"
138#include "mozilla/EffectSet.h"
139#include "mozilla/EventListenerManager.h"
140#include "mozilla/EventStateManager.h"
141#include "mozilla/LookAndFeel.h"
142#include "mozilla/MouseEvents.h"
143#include "mozilla/Preferences.h"
144#include "mozilla/ServoStyleSet.h"
145#include "mozilla/ServoStyleSetInlines.h"
146#include "mozilla/css/ImageLoader.h"
147#include "mozilla/dom/HTMLBodyElement.h"
148#include "mozilla/dom/SVGPathData.h"
149#include "mozilla/dom/TouchEvent.h"
150#include "mozilla/gfx/Tools.h"
151#include "mozilla/layers/WebRenderUserData.h"
152#include "mozilla/layout/ScrollAnchorContainer.h"
153#include "nsITheme.h"
154#include "nsPrintfCString.h"
155
156using namespace mozilla;
157using namespace mozilla::css;
158using namespace mozilla::dom;
159using namespace mozilla::gfx;
160using namespace mozilla::layers;
161using namespace mozilla::layout;
162using nsStyleTransformMatrix::TransformReferenceBox;
163
164nsIFrame* nsILineIterator::LineInfo::GetLastFrameOnLine() const {
165 if (!mNumFramesOnLine) {
166 return nullptr; // empty line, not illegal
167 }
168 MOZ_ASSERT(mFirstFrameOnLine)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mFirstFrameOnLine)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mFirstFrameOnLine))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("mFirstFrameOnLine"
, "./../../../layout/generic/nsIFrame.cpp", 168); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "mFirstFrameOnLine" ")"); do { MOZ_CrashSequence
(__null, 168); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
169 nsIFrame* maybeLastFrame = mFirstFrameOnLine;
170 for ([[maybe_unused]] int32_t i : IntegerRange(mNumFramesOnLine - 1)) {
171 maybeLastFrame = maybeLastFrame->GetNextSibling();
172 if (NS_WARN_IF(!maybeLastFrame)NS_warn_if_impl(!maybeLastFrame, "!maybeLastFrame", "./../../../layout/generic/nsIFrame.cpp"
, 172)
) {
173 return nullptr;
174 }
175 }
176 return maybeLastFrame;
177}
178
179#ifdef HAVE_64BIT_BUILD1
180static_assert(sizeof(nsIFrame) == 120, "nsIFrame should remain small");
181#else
182static_assert(sizeof(void*) == 4, "Odd build config?");
183// FIXME(emilio): Investigate why win32 and android-arm32 have bigger sizes (80)
184// than Linux32 (76).
185static_assert(sizeof(nsIFrame) <= 80, "nsIFrame should remain small");
186#endif
187
188const mozilla::LayoutFrameType nsIFrame::sLayoutFrameTypes[kFrameClassCount] = {
189#define FRAME_ID(class_, type_, ...) mozilla::LayoutFrameType::type_,
190#define ABSTRACT_FRAME_ID(...)
191#include "mozilla/FrameIdList.h"
192#undef FRAME_ID
193#undef ABSTRACT_FRAME_ID
194};
195
196const nsIFrame::ClassFlags nsIFrame::sLayoutFrameClassFlags[kFrameClassCount] =
197 {
198#define FRAME_ID(class_, type_, flags_, ...) flags_,
199#define ABSTRACT_FRAME_ID(...)
200#include "mozilla/FrameIdList.h"
201#undef FRAME_ID
202#undef ABSTRACT_FRAME_ID
203};
204
205std::string format_as(nsDirection aDirection) {
206 return aDirection == eDirNext ? "eDirNext" : "eDirPrevious";
207}
208
209std::ostream& operator<<(std::ostream& aStream, nsDirection aDirection) {
210 return aStream << format_as(aDirection);
211}
212
213struct nsContentAndOffset {
214 nsIContent* mContent = nullptr;
215 int32_t mOffset = 0;
216 // Whether the boundary is a newline inside a text node rather than a <br> or
217 // a block frame.
218 bool mIsTerminalNewlineInText = false;
219};
220
221#include "nsILineIterator.h"
222#include "prenv.h"
223
224FrameDestroyContext::~FrameDestroyContext() {
225 for (auto& content : mozilla::Reversed(mAnonymousContent)) {
226 mPresShell->NativeAnonymousContentWillBeRemoved(content);
227 content->UnbindFromTree();
228 }
229}
230
231// Formerly the nsIFrameDebug interface
232
233std::ostream& operator<<(std::ostream& aStream, const nsReflowStatus& aStatus) {
234 char complete = 'Y';
235 if (aStatus.IsIncomplete()) {
236 complete = 'N';
237 } else if (aStatus.IsOverflowIncomplete()) {
238 complete = 'O';
239 }
240
241 char brk = 'N';
242 if (aStatus.IsInlineBreakBefore()) {
243 brk = 'B';
244 } else if (aStatus.IsInlineBreakAfter()) {
245 brk = 'A';
246 }
247
248 aStream << "["
249 << "Complete=" << complete << ","
250 << "NIF=" << (aStatus.NextInFlowNeedsReflow() ? 'Y' : 'N') << ","
251 << "Break=" << brk << ","
252 << "FirstLetter=" << (aStatus.FirstLetterComplete() ? 'Y' : 'N')
253 << "]";
254 return aStream;
255}
256
257#ifdef DEBUG1
258
259/**
260 * Note: the log module is created during library initialization which
261 * means that you cannot perform logging before then.
262 */
263mozilla::LazyLogModule nsIFrame::sFrameLogModule("frame");
264
265#endif
266
267NS_DECLARE_FRAME_PROPERTY_DELETABLE(AbsoluteContainingBlockProperty,static const mozilla::FramePropertyDescriptor<AbsoluteContainingBlock
>* AbsoluteContainingBlockProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<AbsoluteContainingBlock
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
268 AbsoluteContainingBlock)static const mozilla::FramePropertyDescriptor<AbsoluteContainingBlock
>* AbsoluteContainingBlockProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<AbsoluteContainingBlock
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
269
270bool nsIFrame::HasAbsolutelyPositionedChildren() const {
271 const auto* absCB = GetAbsoluteContainingBlock();
272 return absCB && absCB->HasAbsoluteFrames();
273}
274
275AbsoluteContainingBlock* nsIFrame::GetAbsoluteContainingBlock() const {
276 if (!IsAbsoluteContainer()) {
277 return nullptr;
278 }
279 AbsoluteContainingBlock* absCB =
280 GetProperty(AbsoluteContainingBlockProperty());
281 NS_ASSERTION(absCB,do { if (!(absCB)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "The frame is marked as an abspos container but doesn't have "
"the property", "absCB", "./../../../layout/generic/nsIFrame.cpp"
, 283); MOZ_PretendNoReturn(); } } while (0)
282 "The frame is marked as an abspos container but doesn't have "do { if (!(absCB)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "The frame is marked as an abspos container but doesn't have "
"the property", "absCB", "./../../../layout/generic/nsIFrame.cpp"
, 283); MOZ_PretendNoReturn(); } } while (0)
283 "the property")do { if (!(absCB)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "The frame is marked as an abspos container but doesn't have "
"the property", "absCB", "./../../../layout/generic/nsIFrame.cpp"
, 283); MOZ_PretendNoReturn(); } } while (0)
;
284 return absCB;
285}
286
287void nsIFrame::MarkAsAbsoluteContainingBlock() {
288 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
, "./../../../layout/generic/nsIFrame.cpp", 288); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
")"); do { MOZ_CrashSequence(__null, 288); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
289 NS_ASSERTION(!GetProperty(AbsoluteContainingBlockProperty()),do { if (!(!GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Already has an abs-pos containing block property?"
, "!GetProperty(AbsoluteContainingBlockProperty())", "./../../../layout/generic/nsIFrame.cpp"
, 290); MOZ_PretendNoReturn(); } } while (0)
290 "Already has an abs-pos containing block property?")do { if (!(!GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Already has an abs-pos containing block property?"
, "!GetProperty(AbsoluteContainingBlockProperty())", "./../../../layout/generic/nsIFrame.cpp"
, 290); MOZ_PretendNoReturn(); } } while (0)
;
291 NS_ASSERTION(!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN),do { if (!(!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Already has NS_FRAME_HAS_ABSPOS_CHILDREN state bit?"
, "!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN)", "./../../../layout/generic/nsIFrame.cpp"
, 292); MOZ_PretendNoReturn(); } } while (0)
292 "Already has NS_FRAME_HAS_ABSPOS_CHILDREN state bit?")do { if (!(!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Already has NS_FRAME_HAS_ABSPOS_CHILDREN state bit?"
, "!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN)", "./../../../layout/generic/nsIFrame.cpp"
, 292); MOZ_PretendNoReturn(); } } while (0)
;
293 AddStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
294 SetProperty(AbsoluteContainingBlockProperty(), new AbsoluteContainingBlock());
295}
296
297void nsIFrame::MarkAsNotAbsoluteContainingBlock() {
298 NS_ASSERTION(!HasAbsolutelyPositionedChildren(), "Think of the children!")do { if (!(!HasAbsolutelyPositionedChildren())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Think of the children!", "!HasAbsolutelyPositionedChildren()"
, "./../../../layout/generic/nsIFrame.cpp", 298); MOZ_PretendNoReturn
(); } } while (0)
;
299 NS_ASSERTION(GetProperty(AbsoluteContainingBlockProperty()),do { if (!(GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have an abs-pos containing block property"
, "GetProperty(AbsoluteContainingBlockProperty())", "./../../../layout/generic/nsIFrame.cpp"
, 300); MOZ_PretendNoReturn(); } } while (0)
300 "Should have an abs-pos containing block property")do { if (!(GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have an abs-pos containing block property"
, "GetProperty(AbsoluteContainingBlockProperty())", "./../../../layout/generic/nsIFrame.cpp"
, 300); MOZ_PretendNoReturn(); } } while (0)
;
301 NS_ASSERTION(HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN),do { if (!(HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Should have NS_FRAME_HAS_ABSPOS_CHILDREN state bit"
, "HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN)", "./../../../layout/generic/nsIFrame.cpp"
, 302); MOZ_PretendNoReturn(); } } while (0)
302 "Should have NS_FRAME_HAS_ABSPOS_CHILDREN state bit")do { if (!(HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Should have NS_FRAME_HAS_ABSPOS_CHILDREN state bit"
, "HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN)", "./../../../layout/generic/nsIFrame.cpp"
, 302); MOZ_PretendNoReturn(); } } while (0)
;
303 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
, "./../../../layout/generic/nsIFrame.cpp", 303); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
")"); do { MOZ_CrashSequence(__null, 303); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
304 RemoveStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
305 RemoveProperty(AbsoluteContainingBlockProperty());
306}
307
308bool nsIFrame::CheckAndClearPaintedState() {
309 bool result = HasAnyStateBits(NS_FRAME_PAINTED_THEBES);
310 RemoveStateBits(NS_FRAME_PAINTED_THEBES);
311
312 for (const auto& childList : ChildLists()) {
313 for (nsIFrame* child : childList.mList) {
314 if (child->CheckAndClearPaintedState()) {
315 result = true;
316 }
317 }
318 }
319 return result;
320}
321
322nsIFrame* nsIFrame::FindLineContainer() const {
323 MOZ_ASSERT(IsLineParticipant())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsLineParticipant())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsLineParticipant()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("IsLineParticipant()"
, "./../../../layout/generic/nsIFrame.cpp", 323); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "IsLineParticipant()" ")"); do { MOZ_CrashSequence
(__null, 323); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
324 nsIFrame* parent = GetParent();
325 while (parent &&
326 (parent->IsLineParticipant() || parent->CanContinueTextRun())) {
327 parent = parent->GetParent();
328 }
329 return parent;
330}
331
332bool nsIFrame::CheckAndClearDisplayListState() {
333 bool result = BuiltDisplayList();
334 SetBuiltDisplayList(false);
335
336 for (const auto& childList : ChildLists()) {
337 for (nsIFrame* child : childList.mList) {
338 if (child->CheckAndClearDisplayListState()) {
339 result = true;
340 }
341 }
342 }
343 return result;
344}
345
346bool nsIFrame::IsVisibleConsideringAncestors(uint32_t aFlags) const {
347 if (!StyleVisibility()->IsVisible() ||
348 HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
349 return false;
350 }
351
352 if (PresShell()->IsUnderHiddenEmbedderElement()) {
353 return false;
354 }
355
356 const nsIFrame* frame = this;
357 while (frame) {
358 // Checking mMozSubtreeHiddenOnlyVisually is relatively slow because it
359 // involves loading more memory. It's only allowed in chrome sheets so let's
360 // only support it in the parent process so we can mostly optimize this out
361 // in content processes.
362 if (XRE_IsParentProcess()) {
363 if (const nsMenuPopupFrame* popup = do_QueryFrame(frame);
364 popup && !popup->IsOpen()) {
365 return false;
366 }
367 if (frame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
368 return false;
369 }
370 }
371
372 // This method is used to determine if a frame is focusable, because it's
373 // called by nsIFrame::IsFocusable. `content-visibility: auto` should not
374 // force this frame to be unfocusable, so we only take into account
375 // `content-visibility: hidden` here.
376 if (this != frame &&
377 frame->HidesContent(IncludeContentVisibility::Hidden)) {
378 return false;
379 }
380
381 if (nsIFrame* parent = frame->GetParent()) {
382 frame = parent;
383 } else {
384 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame);
385 if (!parent) {
386 break;
387 }
388
389 if ((aFlags & nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY) == 0 &&
390 parent->PresContext()->IsChrome() &&
391 !frame->PresContext()->IsChrome()) {
392 break;
393 }
394
395 frame = parent;
396 }
397 }
398
399 return true;
400}
401
402void nsIFrame::FindCloserFrameForSelection(
403 const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
404 if (nsLayoutUtils::PointIsCloserToRect(aPoint, mRect,
405 aCurrentBestFrame->mXDistance,
406 aCurrentBestFrame->mYDistance)) {
407 aCurrentBestFrame->mFrame = this;
408 }
409}
410
411void nsIFrame::ElementStateChanged(mozilla::dom::ElementState aStates) {}
412
413void WeakFrame::Clear(mozilla::PresShell* aPresShell) {
414 if (aPresShell) {
415 aPresShell->RemoveWeakFrame(this);
416 }
417 mFrame = nullptr;
418}
419
420AutoWeakFrame::AutoWeakFrame(const WeakFrame& aOther)
421 : mPrev(nullptr), mFrame(nullptr) {
422 Init(aOther.GetFrame());
423}
424
425void AutoWeakFrame::Clear(mozilla::PresShell* aPresShell) {
426 if (aPresShell) {
427 aPresShell->RemoveAutoWeakFrame(this);
428 }
429 mFrame = nullptr;
430 mPrev = nullptr;
431}
432
433AutoWeakFrame::~AutoWeakFrame() {
434 Clear(mFrame ? mFrame->PresShell() : nullptr);
435}
436
437void AutoWeakFrame::Init(nsIFrame* aFrame) {
438 Clear(mFrame ? mFrame->PresShell() : nullptr);
439 mFrame = aFrame;
440 if (mFrame) {
441 mozilla::PresShell* presShell = mFrame->PresShell();
442 NS_WARNING_ASSERTION(presShell, "Null PresShell in AutoWeakFrame!")do { if (!(presShell)) { NS_DebugBreak(NS_DEBUG_WARNING, "Null PresShell in AutoWeakFrame!"
, "presShell", "./../../../layout/generic/nsIFrame.cpp", 442)
; } } while (false)
;
443 if (presShell) {
444 presShell->AddAutoWeakFrame(this);
445 } else {
446 mFrame = nullptr;
447 }
448 }
449}
450
451void WeakFrame::Init(nsIFrame* aFrame) {
452 Clear(mFrame ? mFrame->PresShell() : nullptr);
453 mFrame = aFrame;
454 if (mFrame) {
455 mozilla::PresShell* presShell = mFrame->PresShell();
456 MOZ_ASSERT(presShell, "Null PresShell in WeakFrame!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(presShell)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(presShell))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("presShell" " (" "Null PresShell in WeakFrame!"
")", "./../../../layout/generic/nsIFrame.cpp", 456); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "presShell" ") (" "Null PresShell in WeakFrame!"
")"); do { MOZ_CrashSequence(__null, 456); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
457 if (presShell) {
458 presShell->AddWeakFrame(this);
459 } else {
460 mFrame = nullptr;
461 }
462 }
463}
464
465WeakFrame& WeakFrame::operator=(WeakFrame&& aOther) {
466 if (this != &aOther) {
467 Init(aOther.mFrame);
468 aOther.Clear(aOther.mFrame ? aOther.mFrame->PresShell() : nullptr);
469 }
470 return *this;
471}
472
473nsIFrame* NS_NewEmptyFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
474 return new nsIFrame(aStyle, aPresShell->GetPresContext());
475}
476
477nsIFrame::~nsIFrame() {
478 MOZ_COUNT_DTOR(nsIFrame)do { static_assert(std::is_class_v<nsIFrame>, "Token '"
"nsIFrame" "' is not a class type."); static_assert(!std::is_base_of_v
<nsISupports, nsIFrame>, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogDtor((void*)this, "nsIFrame", sizeof
(*this)); } while (0)
;
479
480 MOZ_ASSERT(GetVisibility() != Visibility::ApproximatelyVisible,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetVisibility() != Visibility::ApproximatelyVisible)
>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetVisibility() != Visibility::ApproximatelyVisible)
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("GetVisibility() != Visibility::ApproximatelyVisible"
" (" "Visible nsIFrame is being destroyed" ")", "./../../../layout/generic/nsIFrame.cpp"
, 481); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetVisibility() != Visibility::ApproximatelyVisible"
") (" "Visible nsIFrame is being destroyed" ")"); do { MOZ_CrashSequence
(__null, 481); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
481 "Visible nsIFrame is being destroyed")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetVisibility() != Visibility::ApproximatelyVisible)
>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetVisibility() != Visibility::ApproximatelyVisible)
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("GetVisibility() != Visibility::ApproximatelyVisible"
" (" "Visible nsIFrame is being destroyed" ")", "./../../../layout/generic/nsIFrame.cpp"
, 481); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetVisibility() != Visibility::ApproximatelyVisible"
") (" "Visible nsIFrame is being destroyed" ")"); do { MOZ_CrashSequence
(__null, 481); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
482}
483
484NS_IMPL_FRAMEARENA_HELPERS(nsIFrame)void* nsIFrame ::operator new(size_t sz) { return mozilla::FrameArena
::Allocate(nsQueryFrame::nsIFrame_id, sz); }
485
486// Dummy operator delete. Will never be called, but must be defined
487// to satisfy some C++ ABIs.
488void nsIFrame::operator delete(void*, size_t) {
489 MOZ_CRASH("nsIFrame::operator delete should never be called")do { do { } while (false); MOZ_ReportCrash("" "nsIFrame::operator delete should never be called"
, "./../../../layout/generic/nsIFrame.cpp", 489); AnnotateMozCrashReason
("MOZ_CRASH(" "nsIFrame::operator delete should never be called"
")"); do { MOZ_CrashSequence(__null, 489); __attribute__((nomerge
)) ::abort(); } while (false); } while (false)
;
490}
491
492NS_QUERYFRAME_HEAD(nsIFrame)void* nsIFrame ::QueryFrame(FrameIID id) const { switch (id) {
493 NS_QUERYFRAME_ENTRY(nsIFrame)case nsIFrame ::kFrameIID: { static_assert( std::is_same_v<
nsIFrame, nsIFrame ::Has_NS_DECL_QUERYFRAME_TARGET>, "nsIFrame"
" must declare itself as a queryframe target"); return const_cast
<nsIFrame*>(static_cast<const nsIFrame*>(this)); }
494NS_QUERYFRAME_TAIL_INHERITANCE_ROOTdefault: break; } do { static_assert( mozilla::detail::AssertionConditionType
<decltype(id != GetFrameId())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(id != GetFrameId()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("id != GetFrameId()"
" (" "A frame failed to QueryFrame to its *own type*. " "It may be missing NS_DECL_QUERYFRAME, or a "
"NS_QUERYFRAME_ENTRY() line with its own type name" ")", "./../../../layout/generic/nsIFrame.cpp"
, 494); AnnotateMozCrashReason("MOZ_ASSERT" "(" "id != GetFrameId()"
") (" "A frame failed to QueryFrame to its *own type*. " "It may be missing NS_DECL_QUERYFRAME, or a "
"NS_QUERYFRAME_ENTRY() line with its own type name" ")"); do
{ MOZ_CrashSequence(__null, 494); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false); return nullptr; }
495
496/////////////////////////////////////////////////////////////////////////////
497// nsIFrame
498
499static bool IsFontSizeInflationContainer(nsIFrame* aFrame,
500 const nsStyleDisplay* aStyleDisplay) {
501 /*
502 * Font size inflation is built around the idea that we're inflating
503 * the fonts for a pan-and-zoom UI so that when the user scales up a
504 * block or other container to fill the width of the device, the fonts
505 * will be readable. To do this, we need to pick what counts as a
506 * container.
507 *
508 * From a code perspective, the only hard requirement is that frames
509 * that are line participants (nsIFrame::IsLineParticipant) are never
510 * containers, since line layout assumes that the inflation is consistent
511 * within a line.
512 *
513 * This is not an imposition, since we obviously want a bunch of text
514 * (possibly with inline elements) flowing within a block to count the
515 * block (or higher) as its container.
516 *
517 * We also want form controls, including the text in the anonymous
518 * content inside of them, to match each other and the text next to
519 * them, so they and their anonymous content should also not be a
520 * container.
521 *
522 * However, because we can't reliably compute sizes across XUL during
523 * reflow, any XUL frame with a XUL parent is always a container.
524 *
525 * There are contexts where it would be nice if some blocks didn't
526 * count as a container, so that, for example, an indented quotation
527 * didn't end up with a smaller font size. However, it's hard to
528 * distinguish these situations where we really do want the indented
529 * thing to count as a container, so we don't try, and blocks are
530 * always containers.
531 */
532
533 // The root frame should always be an inflation container.
534 if (!aFrame->GetParent()) {
535 return true;
536 }
537
538 nsIContent* content = aFrame->GetContent();
539 if (content && content->IsInNativeAnonymousSubtree()) {
540 // Native anonymous content shouldn't be a font inflation root,
541 // except for the custom content container.
542 return content ==
543 aFrame->PresContext()->Document()->GetCustomContentContainer();
544 }
545
546 LayoutFrameType frameType = aFrame->Type();
547 bool isInline =
548 aFrame->GetDisplay().IsInlineFlow() || RubyUtils::IsRubyBox(frameType) ||
549 (aStyleDisplay->IsFloatingStyle() &&
550 frameType == LayoutFrameType::Letter) ||
551 // Given multiple frames for the same node, only the
552 // outer one should be considered a container.
553 // (Important, e.g., for scrolled frames.)
554 (aFrame->GetParent()->GetContent() == content) ||
555 (content &&
556 // Form controls shouldn't become inflation containers.
557 (content->IsAnyOfHTMLElements(nsGkAtoms::option, nsGkAtoms::optgroup,
558 nsGkAtoms::select, nsGkAtoms::input,
559 nsGkAtoms::button, nsGkAtoms::textarea)));
560 NS_ASSERTION(!aFrame->IsLineParticipant() || isInline ||do { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
561 // br frames and mathml frames report being linedo { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
562 // participants even when their position or display isdo { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
563 // setdo { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
564 aFrame->IsBrFrame() || aFrame->IsMathMLFrame(),do { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
565 "line participants must not be containers")do { if (!(!aFrame->IsLineParticipant() || isInline || aFrame
->IsBrFrame() || aFrame->IsMathMLFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "line participants must not be containers"
, "!aFrame->IsLineParticipant() || isInline || aFrame->IsBrFrame() || aFrame->IsMathMLFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 565); MOZ_PretendNoReturn
(); } } while (0)
;
566 return !isInline;
567}
568
569static void MaybeScheduleReflowSVGNonDisplayText(nsIFrame* aFrame) {
570 if (!aFrame->IsInSVGTextSubtree()) {
571 return;
572 }
573
574 // We need to ensure that any non-display SVGTextFrames get reflowed when a
575 // child text frame gets new style. Thus we need to schedule a reflow in
576 // |DidSetComputedStyle|. We also need to call it from |DestroyFrom|,
577 // because otherwise we won't get notified when style changes to
578 // "display:none".
579 SVGTextFrame* svgTextFrame = static_cast<SVGTextFrame*>(
580 nsLayoutUtils::GetClosestFrameOfType(aFrame, LayoutFrameType::SVGText));
581 nsIFrame* anonBlock = svgTextFrame->PrincipalChildList().FirstChild();
582
583 // Note that we must check NS_FRAME_FIRST_REFLOW on our SVGTextFrame's
584 // anonymous block frame rather than our aFrame, since NS_FRAME_FIRST_REFLOW
585 // may be set on us if we're a new frame that has been inserted after the
586 // document's first reflow. (In which case this DidSetComputedStyle call may
587 // be happening under frame construction under a Reflow() call.)
588 if (!anonBlock || anonBlock->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
589 return;
590 }
591
592 if (!svgTextFrame->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) ||
593 svgTextFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)) {
594 return;
595 }
596 if (SVGUtils::AnyOuterSVGIsCallingReflowSVG(svgTextFrame)) {
597 return;
598 }
599
600 svgTextFrame->ScheduleReflowSVGNonDisplayText(
601 IntrinsicDirty::FrameAncestorsAndDescendants);
602}
603
604bool nsIFrame::IsReplaced() const {
605 if (HasAnyClassFlag(ClassFlags::Replaced)) {
606 return true;
607 }
608 if (!Style()->IsAnonBox() && mContent->IsHTMLElement(nsGkAtoms::button)) {
609 // Button always behaves as a replaced element.
610 return true;
611 }
612 return false;
613}
614
615bool nsIFrame::IsAtomicInline() const {
616 // See: https://drafts.csswg.org/css-display-4/#atomic-inline
617 return IsInlineOutside() &&
618 (IsReplaced() || !StyleDisplay()->IsInlineInsideStyle());
619}
620
621bool nsIFrame::ShouldPropagateRepaintsToRoot() const {
622 if (!IsPrimaryFrame()) {
623 // special case for table frames because style images are associated to the
624 // table frame, but the table wrapper frame is the primary frame
625 if (IsTableFrame()) {
626 MOZ_ASSERT(GetParent() && GetParent()->IsTableWrapperFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetParent() && GetParent()->IsTableWrapperFrame
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetParent() && GetParent()->IsTableWrapperFrame
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("GetParent() && GetParent()->IsTableWrapperFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 626); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "GetParent() && GetParent()->IsTableWrapperFrame()"
")"); do { MOZ_CrashSequence(__null, 626); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
627 return GetParent()->ShouldPropagateRepaintsToRoot();
628 }
629
630 return false;
631 }
632 nsIContent* content = GetContent();
633 Document* document = content->OwnerDoc();
634 return content == document->GetRootElement() ||
635 content == document->GetBodyElement();
636}
637
638bool nsIFrame::IsRenderedLegend() const {
639 if (auto* parent = GetParent(); parent && parent->IsFieldSetFrame()) {
640 return static_cast<nsFieldSetFrame*>(parent)->GetLegend() == this;
641 }
642 return false;
643}
644
645void nsIFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
646 nsIFrame* aPrevInFlow) {
647 MOZ_ASSERT(nsQueryFrame::FrameIID(mClass) == GetFrameId())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nsQueryFrame::FrameIID(mClass) == GetFrameId())>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(nsQueryFrame::FrameIID(mClass) == GetFrameId()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("nsQueryFrame::FrameIID(mClass) == GetFrameId()"
, "./../../../layout/generic/nsIFrame.cpp", 647); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "nsQueryFrame::FrameIID(mClass) == GetFrameId()"
")"); do { MOZ_CrashSequence(__null, 647); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
648 MOZ_ASSERT(!mContent, "Double-initing a frame?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mContent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!mContent" " (" "Double-initing a frame?"
")", "./../../../layout/generic/nsIFrame.cpp", 648); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!mContent" ") (" "Double-initing a frame?"
")"); do { MOZ_CrashSequence(__null, 648); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
649
650 mContent = aContent;
651 mParent = aParent;
652 MOZ_RELEASE_ASSERT(!mParent || PresContext() == mParent->PresContext())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mParent || PresContext() == mParent->PresContext
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mParent || PresContext() == mParent->PresContext
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mParent || PresContext() == mParent->PresContext()", "./../../../layout/generic/nsIFrame.cpp"
, 652); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "!mParent || PresContext() == mParent->PresContext()"
")"); do { MOZ_CrashSequence(__null, 652); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
653
654 if (aPrevInFlow) {
655 mWritingMode = aPrevInFlow->GetWritingMode();
656
657 // Copy some state bits from prev-in-flow (the bits that should apply
658 // throughout a continuation chain). The bits are sorted according to their
659 // order in nsFrameStateBits.h.
660
661 // clang-format off
662 AddStateBits(aPrevInFlow->GetStateBits() &
663 (NS_FRAME_GENERATED_CONTENT |
664 NS_FRAME_OUT_OF_FLOW |
665 NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN |
666 NS_FRAME_PART_OF_IBSPLIT |
667 NS_FRAME_MAY_BE_TRANSFORMED |
668 NS_FRAME_HAS_MULTI_COLUMN_ANCESTOR));
669 // clang-format on
670
671 // Copy other bits in nsIFrame from prev-in-flow.
672 mHasColumnSpanSiblings = aPrevInFlow->HasColumnSpanSiblings();
673
674 // If our prev-in-flow is an absolute containing block, we must be one, too.
675 if (aPrevInFlow->IsAbsoluteContainer()) {
676 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
" (" "We should've carried this bit from our prev-in-flow!" ")"
, "./../../../layout/generic/nsIFrame.cpp", 677); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
") (" "We should've carried this bit from our prev-in-flow!"
")"); do { MOZ_CrashSequence(__null, 677); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
677 "We should've carried this bit from our prev-in-flow!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
" (" "We should've carried this bit from our prev-in-flow!" ")"
, "./../../../layout/generic/nsIFrame.cpp", 677); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
") (" "We should've carried this bit from our prev-in-flow!"
")"); do { MOZ_CrashSequence(__null, 677); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
678 MarkAsAbsoluteContainingBlock();
679 }
680 } else {
681 PresContext()->ConstructedFrame();
682 }
683
684 if (GetParent()) {
685 if (MOZ_UNLIKELY(mContent == PresContext()->Document()->GetRootElement() &&(__builtin_expect(!!(mContent == PresContext()->Document()
->GetRootElement() && mContent == GetParent()->
GetContent()), 0))
686 mContent == GetParent()->GetContent())(__builtin_expect(!!(mContent == PresContext()->Document()
->GetRootElement() && mContent == GetParent()->
GetContent()), 0))
) {
687 // Our content is the root element and we have the same content as our
688 // parent. That is, we are the internal anonymous frame of the root
689 // element. Copy the used mWritingMode from our parent because
690 // mDocElementContainingBlock gets its mWritingMode from <body>.
691 mWritingMode = GetParent()->GetWritingMode();
692 }
693
694 // Copy some state bits from our parent (the bits that should apply
695 // recursively throughout a subtree). The bits are sorted according to their
696 // order in nsFrameStateBits.h.
697
698 // clang-format off
699 AddStateBits(GetParent()->GetStateBits() &
700 (NS_FRAME_GENERATED_CONTENT |
701 NS_FRAME_IS_SVG_TEXT |
702 NS_FRAME_IN_POPUP |
703 NS_FRAME_IS_NONDISPLAY));
704 // clang-format on
705
706 if (HasAnyStateBits(NS_FRAME_IN_POPUP) && TrackingVisibility()) {
707 // Assume all frames in popups are visible.
708 IncApproximateVisibleCount();
709 }
710 }
711 if (aPrevInFlow) {
712 mMayHaveOpacityAnimation = aPrevInFlow->MayHaveOpacityAnimation();
713 mMayHaveTransformAnimation = aPrevInFlow->MayHaveTransformAnimation();
714 } else if (mContent) {
715 // It's fine to fetch the EffectSet for the style frame here because in the
716 // following code we take care of the case where animations may target
717 // a different frame.
718 EffectSet* effectSet = EffectSet::GetForStyleFrame(this);
719 if (effectSet) {
720 mMayHaveOpacityAnimation = effectSet->MayHaveOpacityAnimation();
721
722 if (effectSet->MayHaveTransformAnimation()) {
723 // If we are the inner table frame for display:table content, then
724 // transform animations should go on our parent frame (the table wrapper
725 // frame).
726 //
727 // We do this when initializing the child frame (table inner frame),
728 // because when initializng the table wrapper frame, we don't yet have
729 // access to its children so we can't tell if we have transform
730 // animations or not.
731 if (SupportsCSSTransforms()) {
732 mMayHaveTransformAnimation = true;
733 AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
734 } else if (aParent && nsLayoutUtils::GetStyleFrame(aParent) == this) {
735 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent->SupportsCSSTransforms())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->SupportsCSSTransforms
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->SupportsCSSTransforms()" " (" "Style frames that don't support transforms should have parents"
" that do" ")", "./../../../layout/generic/nsIFrame.cpp", 738
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { MOZ_CrashSequence(__null, 738); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
736 aParent->SupportsCSSTransforms(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent->SupportsCSSTransforms())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->SupportsCSSTransforms
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->SupportsCSSTransforms()" " (" "Style frames that don't support transforms should have parents"
" that do" ")", "./../../../layout/generic/nsIFrame.cpp", 738
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { MOZ_CrashSequence(__null, 738); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
737 "Style frames that don't support transforms should have parents"do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent->SupportsCSSTransforms())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->SupportsCSSTransforms
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->SupportsCSSTransforms()" " (" "Style frames that don't support transforms should have parents"
" that do" ")", "./../../../layout/generic/nsIFrame.cpp", 738
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { MOZ_CrashSequence(__null, 738); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
738 " that do")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent->SupportsCSSTransforms())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->SupportsCSSTransforms
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->SupportsCSSTransforms()" " (" "Style frames that don't support transforms should have parents"
" that do" ")", "./../../../layout/generic/nsIFrame.cpp", 738
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { MOZ_CrashSequence(__null, 738); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
739 aParent->mMayHaveTransformAnimation = true;
740 aParent->AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
741 }
742 }
743 }
744 }
745
746 const nsStyleDisplay* disp = StyleDisplay();
747 if (disp->HasTransform(this)) {
748 // If 'transform' dynamically changes, RestyleManager takes care of
749 // updating this bit.
750 AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
751 }
752
753 if (nsLayoutUtils::FontSizeInflationEnabled(PresContext()) ||
754 !GetParent()
755#ifdef DEBUG1
756 // We have assertions that check inflation invariants even when
757 // font size inflation is not enabled.
758 || true
759#endif
760 ) {
761 if (IsFontSizeInflationContainer(this, disp)) {
762 AddStateBits(NS_FRAME_FONT_INFLATION_CONTAINER);
763 if (!GetParent() ||
764 // I'd use NS_FRAME_OUT_OF_FLOW, but it's not set yet.
765 disp->IsFloating(this) || disp->IsAbsolutelyPositioned(this) ||
766 GetParent()->IsFlexContainerFrame() ||
767 GetParent()->IsGridContainerFrame()) {
768 AddStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT);
769 }
770 }
771 NS_ASSERTION(do { if (!(GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "root frame should always be a container"
, "GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)"
, "./../../../layout/generic/nsIFrame.cpp", 773); MOZ_PretendNoReturn
(); } } while (0)
772 GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER),do { if (!(GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "root frame should always be a container"
, "GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)"
, "./../../../layout/generic/nsIFrame.cpp", 773); MOZ_PretendNoReturn
(); } } while (0)
773 "root frame should always be a container")do { if (!(GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "root frame should always be a container"
, "GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)"
, "./../../../layout/generic/nsIFrame.cpp", 773); MOZ_PretendNoReturn
(); } } while (0)
;
774 }
775
776 if (TrackingVisibility() && PresShell()->AssumeAllFramesVisible()) {
777 IncApproximateVisibleCount();
778 }
779
780 DidSetComputedStyle(nullptr);
781
782 // For a newly created frame, we need to update this frame's visibility state.
783 // Usually we update the state when the frame is restyled and has a
784 // VisibilityChange change hint but we don't generate any change hints for
785 // newly created frames.
786 // Note: We don't need to do this for placeholders since placeholders have
787 // different styles so that the styles don't have visibility:hidden even if
788 // the parent has visibility:hidden style. We also don't need to update the
789 // state when creating continuations because its visibility is the same as its
790 // prev-in-flow, and the animation code cares only primary frames.
791 if (!IsPlaceholderFrame() && !aPrevInFlow) {
792 UpdateVisibleDescendantsState();
793 }
794
795 if (!aPrevInFlow && HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
796 // We aren't going to get a reflow, so nothing else will call
797 // InvalidateRenderingObservers, we have to do it here.
798 SVGObserverUtils::InvalidateRenderingObservers(this);
799 }
800}
801
802void nsIFrame::InitPrimaryFrame() {
803 MOZ_ASSERT(IsPrimaryFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsPrimaryFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsPrimaryFrame()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("IsPrimaryFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 803); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "IsPrimaryFrame()" ")"); do { MOZ_CrashSequence
(__null, 803); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
804 HandlePrimaryFrameStyleChange(nullptr);
805}
806
807// If `aFrame` is a generated content container (::before/::after/::marker/...)
808// whose content changed only in the text of its string items, rewrite the
809// existing generated text nodes in place instead of reconstructing the frame.
810// See nsStyleContent::CanUpdateGeneratedContentText and its usage.
811static void UpdateGeneratedContentTextIfNeeded(
812 nsIFrame* aFrame, const ComputedStyle* aOldComputedStyle) {
813 if (!aFrame->IsGeneratedContentFrame()) {
814 return;
815 }
816 // Update once per element, not per continuation.
817 if (aFrame->GetPrevContinuation()) {
818 return;
819 }
820 nsIContent* content = aFrame->GetContent();
821 if (!content || !content->IsRootOfNativeAnonymousSubtree()) {
822 return;
823 }
824
825 const auto* oldStyle = aOldComputedStyle->StyleContent();
826 const auto* newStyle = aFrame->StyleContent();
827 if (oldStyle->mContent == newStyle->mContent ||
828 !nsStyleContent::CanUpdateGeneratedContentText(*oldStyle, *newStyle)) {
829 return;
830 }
831
832 auto oldItems = oldStyle->NonAltContentItems();
833 auto newItems = newStyle->NonAltContentItems();
834 MOZ_ASSERT(oldItems.Length() == newItems.Length(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(oldItems.Length() == newItems.Length())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(oldItems.Length() == newItems.Length()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("oldItems.Length() == newItems.Length()"
" (" "CanUpdateGeneratedContentText should guarantee equal lengths"
")", "./../../../layout/generic/nsIFrame.cpp", 835); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "oldItems.Length() == newItems.Length()" ") ("
"CanUpdateGeneratedContentText should guarantee equal lengths"
")"); do { MOZ_CrashSequence(__null, 835); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
835 "CanUpdateGeneratedContentText should guarantee equal lengths")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(oldItems.Length() == newItems.Length())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(oldItems.Length() == newItems.Length()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("oldItems.Length() == newItems.Length()"
" (" "CanUpdateGeneratedContentText should guarantee equal lengths"
")", "./../../../layout/generic/nsIFrame.cpp", 835); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "oldItems.Length() == newItems.Length()" ") ("
"CanUpdateGeneratedContentText should guarantee equal lengths"
")"); do { MOZ_CrashSequence(__null, 835); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
836 nsIContent* child = content->GetFirstChild();
837 for (size_t i = 0; i < newItems.Length(); i++) {
838 const auto& item = newItems[i];
839 const bool isString = item.IsString();
840 if (isString && item.AsString().AsString().IsEmpty()) {
841 // Empty strings have no associated content node.
842 continue;
843 }
844 MOZ_ASSERT(child,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(child))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("child" " (" "Mismatch between content items and generated content nodes?"
")", "./../../../layout/generic/nsIFrame.cpp", 845); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "child" ") (" "Mismatch between content items and generated content nodes?"
")"); do { MOZ_CrashSequence(__null, 845); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
845 "Mismatch between content items and generated content nodes?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(child))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("child" " (" "Mismatch between content items and generated content nodes?"
")", "./../../../layout/generic/nsIFrame.cpp", 845); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "child" ") (" "Mismatch between content items and generated content nodes?"
")"); do { MOZ_CrashSequence(__null, 845); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
846 if (isString && item != oldItems[i]) {
847 MOZ_ASSERT(child->IsText(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child->IsText())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(child->IsText()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("child->IsText()"
" (" "A non-empty string item should map to a text node" ")"
, "./../../../layout/generic/nsIFrame.cpp", 848); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "child->IsText()" ") (" "A non-empty string item should map to a text node"
")"); do { MOZ_CrashSequence(__null, 848); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
848 "A non-empty string item should map to a text node")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child->IsText())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(child->IsText()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("child->IsText()"
" (" "A non-empty string item should map to a text node" ")"
, "./../../../layout/generic/nsIFrame.cpp", 848); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "child->IsText()" ") (" "A non-empty string item should map to a text node"
")"); do { MOZ_CrashSequence(__null, 848); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
849 child->AsText()->SetText(
850 NS_ConvertUTF8toUTF16(item.AsString().AsString()),
851 /* aNotify = */ true);
852 }
853 child = child->GetNextSibling();
854 }
855 MOZ_ASSERT(!child, "More generated content than content items.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!child)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(!child))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!child" " (" "More generated content than content items."
")", "./../../../layout/generic/nsIFrame.cpp", 855); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!child" ") (" "More generated content than content items."
")"); do { MOZ_CrashSequence(__null, 855); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
856}
857
858void nsIFrame::HandlePrimaryFrameStyleChange(ComputedStyle* aOldStyle) {
859 const nsStyleDisplay* disp = StyleDisplay();
860 const nsStyleDisplay* oldDisp =
861 aOldStyle ? aOldStyle->StyleDisplay() : nullptr;
862
863 const bool wasQueryContainer = oldDisp && oldDisp->IsQueryContainer();
864 const bool isQueryContainer = disp->IsQueryContainer();
865 if (wasQueryContainer != isQueryContainer) {
866 auto* pc = PresContext();
867 if (isQueryContainer) {
868 pc->RegisterContainerQueryFrame(this);
869 } else {
870 pc->UnregisterContainerQueryFrame(this);
871 }
872 }
873
874 const bool wasReferringToAnchor = aOldStyle &&
875 oldDisp->IsAbsolutelyPositionedStyle() &&
876 aOldStyle->HasAnchorPosReference();
877 const bool isReferringToAnchor = HasAnchorPosReference();
878 if (wasReferringToAnchor && !isReferringToAnchor) {
879 PresShell()->RemoveAnchorPosPositioned(this);
880 RemoveProperty(NormalPositionProperty());
881 } else if (!wasReferringToAnchor && isReferringToAnchor) {
882 PresShell()->AddAnchorPosPositioned(this);
883 }
884
885 bool handleAnchorPosAnchorNameChange =
886 oldDisp ? oldDisp->mAnchorName != disp->mAnchorName
887 : disp->HasAnchorName();
888 if (handleAnchorPosAnchorNameChange &&
889 !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
890 if (oldDisp && oldDisp->HasAnchorName()) {
891 PresShell()->RemoveAnchorPosAnchor(oldDisp->mAnchorName.AsSpan(), this);
892 }
893 PresShell()->AddAnchorPosAnchor(disp->mAnchorName.AsSpan(), this);
894 }
895
896 // According to the Anchor Positioning spec,
897 // https://drafts.csswg.org/css-anchor-position-1/#last-successful-position-option:
898 //
899 // If el has a last successful position option remove its last successful
900 // position option if any of the following are true:
901 // 1. Its computed position value has changed, its containing block has
902 // changed, or it no longer generates a box.
903 // 2. Its computed value for any longhand of position-try has changed.
904 // 3. Its computed value for any @position-try property has changed.
905 // 4. Any of the @position-try rules referenced by it have been added,
906 // removed, or mutated.
907 //
908 // Case 1 will cause a reframe, so does not need to be handled here.
909 // Cases 2 and 3 are handled here.
910 // TODO: case 4, see bug 1987960.
911 if (aOldStyle && HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
912 HasProperty(LastSuccessfulPositionFallback())) {
913 const auto* pos = StylePosition();
914 const auto* oldPos = aOldStyle->StylePosition();
915 if (pos->mPositionTryFallbacks != oldPos->mPositionTryFallbacks ||
916 pos->mPositionTryOrder != oldPos->mPositionTryOrder ||
917 pos->mOffset != oldPos->mOffset ||
918 pos->mAlignSelf != oldPos->mAlignSelf ||
919 pos->mJustifySelf != oldPos->mJustifySelf ||
920 pos->mPositionAnchor != oldPos->mPositionAnchor ||
921 pos->mPositionArea != oldPos->mPositionArea ||
922 pos->mMinWidth != oldPos->mMinWidth ||
923 pos->mMinHeight != oldPos->mMinHeight ||
924 pos->mMaxWidth != oldPos->mMaxWidth ||
925 pos->mMaxHeight != oldPos->mMaxHeight ||
926 pos->mWidth != oldPos->mWidth || pos->mHeight != oldPos->mHeight ||
927 StyleMargin()->mMargin != aOldStyle->StyleMargin()->mMargin) {
928 RemoveProperty(LastSuccessfulPositionFallback());
929 }
930 }
931
932 const auto cv = disp->ContentVisibility(*this);
933 const auto oldCv = oldDisp ? oldDisp->ContentVisibility(*this)
934 : StyleContentVisibility::Visible;
935 if (!oldDisp || cv != oldCv) {
936 // 'content-visibility' has changed (or this is a new frame being
937 // initialized). Inform PresShell so it can update its bookkeeping
938 // about frames with particular content-visibility values:
939 // * Inform it of the new value (for the values that it cares about):
940 if (cv == StyleContentVisibility::Hidden) {
941 PresShell()->IncrementContentVisibilityHiddenCount();
942 } else if (cv == StyleContentVisibility::Auto) {
943 PresShell()->RegisterContentVisibilityAutoFrame(this);
944 }
945
946 // * Inform it of the old value (for the values that it cares about):
947 if (oldCv == StyleContentVisibility::Hidden) {
948 PresShell()->DecrementContentVisibilityHiddenCount();
949 } else if (oldCv == StyleContentVisibility::Auto) {
950 if (auto* element = Element::FromNodeOrNull(GetContent())) {
951 element->ClearContentRelevancy();
952 }
953 PresShell()->UnregisterContentVisibilityAutoFrame(this);
954 }
955 PresContext()->SetNeedsToUpdateHiddenByContentVisibilityForAnimations();
956 }
957
958 HandleLastRememberedSize();
959
960 bool handleStickyChange =
961 oldDisp ? (disp->mPosition != oldDisp->mPosition &&
962 (disp->mPosition == StylePositionProperty::Sticky ||
963 oldDisp->mPosition == StylePositionProperty::Sticky))
964 : disp->mPosition == StylePositionProperty::Sticky;
965 if (handleStickyChange &&
966 !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY | NS_FRAME_SVG_LAYOUT)) {
967 if (auto* ssc = StickyScrollContainer::GetOrCreateForFrame(this)) {
968 if (IsStickyPositioned()) {
969 ssc->AddFrame(this);
970 } else {
971 ssc->RemoveFrame(this);
972 }
973 }
974 }
975}
976
977void nsIFrame::Destroy(DestroyContext& aContext) {
978 NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),do { if (!(!nsContentUtils::IsSafeToRunScript())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "destroy called on frame while scripts not blocked"
, "!nsContentUtils::IsSafeToRunScript()", "./../../../layout/generic/nsIFrame.cpp"
, 979); MOZ_PretendNoReturn(); } } while (0)
979 "destroy called on frame while scripts not blocked")do { if (!(!nsContentUtils::IsSafeToRunScript())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "destroy called on frame while scripts not blocked"
, "!nsContentUtils::IsSafeToRunScript()", "./../../../layout/generic/nsIFrame.cpp"
, 979); MOZ_PretendNoReturn(); } } while (0)
;
980 NS_ASSERTION(!GetNextSibling() && !GetPrevSibling(),do { if (!(!GetNextSibling() && !GetPrevSibling())) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Frames should be removed before destruction."
, "!GetNextSibling() && !GetPrevSibling()", "./../../../layout/generic/nsIFrame.cpp"
, 981); MOZ_PretendNoReturn(); } } while (0)
981 "Frames should be removed before destruction.")do { if (!(!GetNextSibling() && !GetPrevSibling())) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Frames should be removed before destruction."
, "!GetNextSibling() && !GetPrevSibling()", "./../../../layout/generic/nsIFrame.cpp"
, 981); MOZ_PretendNoReturn(); } } while (0)
;
982 MOZ_ASSERT(!HasAbsolutelyPositionedChildren())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAbsolutelyPositionedChildren())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasAbsolutelyPositionedChildren
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAbsolutelyPositionedChildren()", "./../../../layout/generic/nsIFrame.cpp"
, 982); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAbsolutelyPositionedChildren()"
")"); do { MOZ_CrashSequence(__null, 982); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
983 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
" (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")", "./../../../layout/generic/nsIFrame.cpp", 984); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
") (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")"); do { MOZ_CrashSequence(__null, 984); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
984 "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
" (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")", "./../../../layout/generic/nsIFrame.cpp", 984); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
") (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")"); do { MOZ_CrashSequence(__null, 984); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
985
986 MaybeScheduleReflowSVGNonDisplayText(this);
987
988 SVGObserverUtils::InvalidateDirectRenderingObservers(
989 this, SVGObserverUtils::InvalidationFlag::FrameBeingDestroyed);
990
991 if (IsStickyPositioned()) {
992 if (auto* ssc = StickyScrollContainer::GetForFrame(this)) {
993 ssc->RemoveFrame(this);
994 }
995 }
996
997 if (HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
998 if (nsPlaceholderFrame* placeholder = GetPlaceholderFrame()) {
999 placeholder->SetOutOfFlowFrame(nullptr);
1000 }
1001 }
1002
1003 nsPresContext* pc = PresContext();
1004 mozilla::PresShell* ps = pc->GetPresShell();
1005 const auto* disp = StyleDisplay();
1006 if (IsPrimaryFrame()) {
1007 if (disp->IsQueryContainer()) {
1008 pc->UnregisterContainerQueryFrame(this);
1009 }
1010 auto contentVisibility = disp->ContentVisibility(*this);
1011 if (contentVisibility == StyleContentVisibility::Hidden) {
1012 ps->DecrementContentVisibilityHiddenCount();
1013 } else if (contentVisibility == StyleContentVisibility::Auto) {
1014 ps->UnregisterContentVisibilityAutoFrame(this);
1015 }
1016 // This needs to happen before we clear our Properties() table.
1017 ActiveLayerTracker::TransferActivityToContent(this, mContent);
1018 }
1019
1020 ScrollAnchorContainer* anchor = nullptr;
1021 if (IsScrollAnchor(&anchor)) {
1022 anchor->InvalidateAnchor();
1023 }
1024
1025 if (HasCSSAnimations() || HasCSSTransitions() ||
1026 // It's fine to look up the style frame here since if we're destroying the
1027 // frames for display:table content we should be destroying both wrapper
1028 // and inner frame.
1029 EffectSet::GetForStyleFrame(this)) {
1030 // If no new frame for this element is created by the end of the
1031 // restyling process, stop animations and transitions for this frame
1032 RestyleManager::AnimationsWithDestroyedFrame* adf =
1033 pc->RestyleManager()->GetAnimationsWithDestroyedFrame();
1034 // AnimationsWithDestroyedFrame only lives during the restyling process.
1035 if (adf) {
1036 adf->Put(mContent, mComputedStyle);
1037 }
1038 }
1039
1040 if (HasAnchorPosName()) {
1041 PresShell()->RemoveAnchorPosAnchor(disp->mAnchorName.AsSpan(), this);
1042 }
1043
1044 if (HasAnchorPosReference()) {
1045 ps->RemoveAnchorPosPositioned(this);
1046 }
1047
1048 // Disable visibility tracking. Note that we have to do this before we clear
1049 // frame properties and lose track of whether we were previously visible.
1050 // XXX(seth): It'd be ideal to assert that we're already marked nonvisible
1051 // here, but it's unfortunately tricky to guarantee in the face of things like
1052 // frame reconstruction induced by style changes.
1053 DisableVisibilityTracking();
1054
1055 // Ensure that we're not in the approximately visible list anymore.
1056 ps->RemoveFrameFromApproximatelyVisibleList(this);
1057
1058 ps->NotifyDestroyingFrame(this);
1059
1060 if (HasAnyStateBits(NS_FRAME_EXTERNAL_REFERENCE)) {
1061 ps->ClearFrameRefs(this);
1062 }
1063
1064 // Make sure that our deleted frame can't be returned from GetPrimaryFrame()
1065 if (IsPrimaryFrame()) {
1066 mContent->SetPrimaryFrame(nullptr);
1067
1068 // Pass the root of a generated content subtree (e.g. ::after/::before) to
1069 // aPostDestroyData to unbind it after frame destruction is done.
1070 if (HasAnyStateBits(NS_FRAME_GENERATED_CONTENT) &&
1071 mContent->IsRootOfNativeAnonymousSubtree()) {
1072 aContext.AddAnonymousContent(mContent.forget());
1073 }
1074 }
1075
1076 // Remove all properties attached to the frame, to ensure any property
1077 // destructors that need the frame pointer are handled properly.
1078 RemoveAllProperties();
1079
1080 // Must retrieve the object ID before calling destructors, so the
1081 // vtable is still valid.
1082 //
1083 // Note to future tweakers: having the method that returns the
1084 // object size call the destructor will not avoid an indirect call;
1085 // the compiler cannot devirtualize the call to the destructor even
1086 // if it's from a method defined in the same class.
1087
1088 nsQueryFrame::FrameIID id = GetFrameId();
1089 this->~nsIFrame();
1090
1091#ifdef DEBUG1
1092 {
1093 nsIFrame* rootFrame = ps->GetRootFrame();
1094 MOZ_ASSERT(rootFrame)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(rootFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(rootFrame))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("rootFrame", "./../../../layout/generic/nsIFrame.cpp"
, 1094); AnnotateMozCrashReason("MOZ_ASSERT" "(" "rootFrame" ")"
); do { MOZ_CrashSequence(__null, 1094); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1095 if (this != rootFrame) {
1096 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(rootFrame);
1097 auto* data = builder ? builder->Data() : nullptr;
1098
1099 const bool inData =
1100 data && (data->IsModified(this) || data->HasProps(this));
1101
1102 if (inData) {
1103 DL_LOG(LogLevel::Warning, "Frame %p found in retained data", this)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "Frame %p found in retained data", this)
; } } while (0)
;
1104 }
1105
1106 MOZ_ASSERT(!inData, "Deleted frame in retained data!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!inData)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!inData))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!inData" " (" "Deleted frame in retained data!"
")", "./../../../layout/generic/nsIFrame.cpp", 1106); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!inData" ") (" "Deleted frame in retained data!"
")"); do { MOZ_CrashSequence(__null, 1106); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1107 }
1108 }
1109#endif
1110
1111 // Now that we're totally cleaned out, we need to add ourselves to
1112 // the frame arena.
1113 FrameArena::Free(id, this);
1114}
1115
1116std::pair<int32_t, int32_t> nsIFrame::GetOffsets() const {
1117 return std::make_pair(0, 0);
1118}
1119
1120static void CompareLayers(
1121 const nsStyleImageLayers* aFirstLayers,
1122 const nsStyleImageLayers* aSecondLayers,
1123 const std::function<void(imgRequestProxy* aReq)>& aCallback) {
1124 NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, (*aFirstLayers))for (uint32_t i = ((*aFirstLayers)).mImageCount; (i)-- != 0;) {
1125 const auto& image = aFirstLayers->mLayers[i].mImage;
1126 if (!image.IsImageRequestType() || !image.IsResolved()) {
1127 continue;
1128 }
1129
1130 // aCallback is called when the style image in aFirstLayers is thought to
1131 // be different with the corresponded one in aSecondLayers
1132 if (!aSecondLayers || i >= aSecondLayers->mImageCount ||
1133 (!aSecondLayers->mLayers[i].mImage.IsResolved() ||
1134 image.GetImageRequest() !=
1135 aSecondLayers->mLayers[i].mImage.GetImageRequest())) {
1136 if (imgRequestProxy* req = image.GetImageRequest()) {
1137 aCallback(req);
1138 }
1139 }
1140 }
1141}
1142
1143static void AddAndRemoveImageAssociations(
1144 ImageLoader& aImageLoader, nsIFrame* aFrame,
1145 const nsStyleImageLayers* aOldLayers,
1146 const nsStyleImageLayers* aNewLayers) {
1147 // If the old context had a background-image image, or mask-image image,
1148 // and new context does not have the same image, clear the image load
1149 // notifier (which keeps the image loading, if it still is) for the frame.
1150 // We want to do this conservatively because some frames paint their
1151 // backgrounds from some other frame's style data, and we don't want
1152 // to clear those notifiers unless we have to. (They'll be reset
1153 // when we paint, although we could miss a notification in that
1154 // interval.)
1155 if (aOldLayers && aFrame->HasImageRequest()) {
1156 CompareLayers(aOldLayers, aNewLayers, [&](imgRequestProxy* aReq) {
1157 aImageLoader.DisassociateRequestFromFrame(aReq, aFrame);
1158 });
1159 }
1160
1161 CompareLayers(aNewLayers, aOldLayers, [&](imgRequestProxy* aReq) {
1162 aImageLoader.AssociateRequestToFrame(aReq, aFrame);
1163 });
1164}
1165
1166void nsIFrame::AddDisplayItem(nsDisplayItem* aItem) {
1167 MOZ_DIAGNOSTIC_ASSERT(!mDisplayItems.Contains(aItem))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mDisplayItems.Contains(aItem))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mDisplayItems.Contains(aItem
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mDisplayItems.Contains(aItem)", "./../../../layout/generic/nsIFrame.cpp"
, 1167); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "!mDisplayItems.Contains(aItem)"
")"); do { MOZ_CrashSequence(__null, 1167); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1168 mDisplayItems.AppendElement(aItem);
1169#ifdef ACCESSIBILITY1
1170 if (nsAccessibilityService* accService = GetAccService()) {
1171 accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
1172 }
1173#endif
1174}
1175
1176bool nsIFrame::RemoveDisplayItem(nsDisplayItem* aItem) {
1177 return mDisplayItems.RemoveElement(aItem);
1178}
1179
1180bool nsIFrame::HasDisplayItems() { return !mDisplayItems.IsEmpty(); }
1181
1182bool nsIFrame::HasDisplayItem(nsDisplayItem* aItem) {
1183 return mDisplayItems.Contains(aItem);
1184}
1185
1186bool nsIFrame::HasDisplayItem(uint32_t aKey) {
1187 for (nsDisplayItem* i : mDisplayItems) {
1188 if (i->GetPerFrameKey() == aKey) {
1189 return true;
1190 }
1191 }
1192 return false;
1193}
1194
1195template <typename Condition>
1196static void DiscardDisplayItems(nsIFrame* aFrame, Condition aCondition) {
1197 for (nsDisplayItem* i : aFrame->DisplayItems()) {
1198 // Only discard items that are invalidated by this frame, as we're only
1199 // guaranteed to rebuild those items. Table background items are created by
1200 // the relevant table part, but have the cell frame as the primary frame,
1201 // and we don't want to remove them if this is the cell.
1202 if (aCondition(i) && i->FrameForInvalidation() == aFrame) {
1203 i->SetCantBeReused();
1204 }
1205 }
1206}
1207
1208static void DiscardOldItems(nsIFrame* aFrame) {
1209 DiscardDisplayItems(aFrame,
1210 [](nsDisplayItem* aItem) { return aItem->IsOldItem(); });
1211}
1212
1213void nsIFrame::RemoveDisplayItemDataForDeletion() {
1214 // Destroying a WebRenderUserDataTable can cause destruction of other objects
1215 // which can remove frame properties in their destructor. If we delete a frame
1216 // property it runs the destructor of the stored object in the middle of
1217 // updating the frame property table, so if the destruction of that object
1218 // causes another update to the frame property table it would leave the frame
1219 // property table in an inconsistent state. So we remove it from the table and
1220 // then destroy it. (bug 1530657)
1221 WebRenderUserDataTable* userDataTable =
1222 TakeProperty(WebRenderUserDataProperty::Key());
1223 if (userDataTable) {
1224 for (const auto& data : userDataTable->Values()) {
1225 data->RemoveFromTable();
1226 }
1227 delete userDataTable;
1228 }
1229
1230 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
1231 if (!builder) {
1232 MOZ_ASSERT(DisplayItems().IsEmpty())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(DisplayItems().IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(DisplayItems().IsEmpty()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("DisplayItems().IsEmpty()"
, "./../../../layout/generic/nsIFrame.cpp", 1232); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "DisplayItems().IsEmpty()" ")"); do { MOZ_CrashSequence
(__null, 1232); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1233 MOZ_ASSERT(!IsFrameModified())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsFrameModified())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsFrameModified()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("!IsFrameModified()"
, "./../../../layout/generic/nsIFrame.cpp", 1233); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsFrameModified()" ")"); do { MOZ_CrashSequence
(__null, 1233); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1234 return;
1235 }
1236
1237 for (nsDisplayItem* i : DisplayItems()) {
1238 if (i->GetDependentFrame() == this && !i->HasDeletedFrame()) {
1239 i->Frame()->MarkNeedsDisplayItemRebuild();
1240 }
1241 i->RemoveFrame(this);
1242 }
1243
1244 DisplayItems().Clear();
1245
1246 nsAutoString name;
1247#ifdef DEBUG_FRAME_DUMP1
1248 if (DL_LOG_TEST(LogLevel::Debug)(__builtin_expect(!!(mozilla::detail::log_test(GetLoggerByProcess
(), LogLevel::Debug)), 0))
) {
1249 GetFrameName(name);
1250 }
1251#endif
1252 DL_LOGV("Removing display item data for frame %p (%s)", this,do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "Removing display item data for frame %p (%s)"
, this, NS_ConvertUTF16toUTF8(name).get()); } } while (0)
1253 NS_ConvertUTF16toUTF8(name).get())do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "Removing display item data for frame %p (%s)"
, this, NS_ConvertUTF16toUTF8(name).get()); } } while (0)
;
1254
1255 builder->Data()->Remove(this);
1256}
1257
1258void nsIFrame::MarkNeedsDisplayItemRebuild() {
1259 if (!nsLayoutUtils::AreRetainedDisplayListsEnabled() || IsFrameModified() ||
1260 HasAnyStateBits(NS_FRAME_IN_POPUP)) {
1261 // Skip frames that are already marked modified.
1262 return;
1263 }
1264
1265 if (Type() == LayoutFrameType::Placeholder) {
1266 nsIFrame* oof = static_cast<nsPlaceholderFrame*>(this)->GetOutOfFlowFrame();
1267 if (oof) {
1268 oof->MarkNeedsDisplayItemRebuild();
1269 }
1270 // Do not mark placeholder frames modified.
1271 return;
1272 }
1273
1274#ifdef ACCESSIBILITY1
1275 if (nsAccessibilityService* accService = GetAccService()) {
1276 accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
1277 }
1278#endif
1279
1280 nsIFrame* rootFrame = PresShell()->GetRootFrame();
1281
1282 if (rootFrame->IsFrameModified()) {
1283 // The whole frame tree is modified.
1284 return;
1285 }
1286
1287 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
1288 if (!builder) {
1289 MOZ_ASSERT(DisplayItems().IsEmpty())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(DisplayItems().IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(DisplayItems().IsEmpty()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("DisplayItems().IsEmpty()"
, "./../../../layout/generic/nsIFrame.cpp", 1289); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "DisplayItems().IsEmpty()" ")"); do { MOZ_CrashSequence
(__null, 1289); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1290 return;
1291 }
1292
1293 RetainedDisplayListData* data = builder->Data();
1294 MOZ_ASSERT(data)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(data)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(data))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("data", "./../../../layout/generic/nsIFrame.cpp"
, 1294); AnnotateMozCrashReason("MOZ_ASSERT" "(" "data" ")");
do { MOZ_CrashSequence(__null, 1294); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1295
1296 if (data->AtModifiedFrameLimit()) {
1297 // This marks the whole frame tree modified.
1298 // See |RetainedDisplayListBuilder::ShouldBuildPartial()|.
1299 data->AddModifiedFrame(rootFrame);
1300 return;
1301 }
1302
1303 nsAutoString name;
1304#ifdef DEBUG_FRAME_DUMP1
1305 if (DL_LOG_TEST(LogLevel::Debug)(__builtin_expect(!!(mozilla::detail::log_test(GetLoggerByProcess
(), LogLevel::Debug)), 0))
) {
1306 GetFrameName(name);
1307 }
1308#endif
1309
1310 DL_LOGV("RDL - Rebuilding display items for frame %p (%s)", this,do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "RDL - Rebuilding display items for frame %p (%s)"
, this, NS_ConvertUTF16toUTF8(name).get()); } } while (0)
1311 NS_ConvertUTF16toUTF8(name).get())do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "RDL - Rebuilding display items for frame %p (%s)"
, this, NS_ConvertUTF16toUTF8(name).get()); } } while (0)
;
1312
1313 data->AddModifiedFrame(this);
1314
1315 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding
) == 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding
) == 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
, "./../../../layout/generic/nsIFrame.cpp", 1316); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
")"); do { MOZ_CrashSequence(__null, 1316); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1316 PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding
) == 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding
) == 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
, "./../../../layout/generic/nsIFrame.cpp", 1316); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
")"); do { MOZ_CrashSequence(__null, 1316); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1317
1318 // Hopefully this is cheap, but we could use a frame state bit to note
1319 // the presence of dependencies to speed it up.
1320 for (nsDisplayItem* i : DisplayItems()) {
1321 if (i->HasDeletedFrame() || i->Frame() == this) {
1322 // Ignore the items with deleted frames, and the items with |this| as
1323 // the primary frame.
1324 continue;
1325 }
1326
1327 if (i->GetDependentFrame() == this) {
1328 // For items with |this| as a dependent frame, mark the primary frame
1329 // for rebuild.
1330 i->Frame()->MarkNeedsDisplayItemRebuild();
1331 }
1332 }
1333}
1334
1335// Subclass hook for style post processing
1336/* virtual */
1337void nsIFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
1338 if (aOldComputedStyle) {
1339#ifdef ACCESSIBILITY1
1340 // Don't notify for reconstructed frames here, since the frame is still
1341 // being constructed at this point and so LocalAccessible::GetFrame() will
1342 // return null. Style changes for reconstructed frames are handled in
1343 // DocAccessible::PruneOrInsertSubtree.
1344 if (nsAccessibilityService* accService = GetAccService()) {
1345 accService->NotifyOfComputedStyleChange(PresShell(), mContent);
1346 }
1347#endif
1348 UpdateGeneratedContentTextIfNeeded(this, aOldComputedStyle);
1349 }
1350
1351 MaybeScheduleReflowSVGNonDisplayText(this);
1352
1353 Document* doc = PresContext()->Document();
1354 ImageLoader& loader = doc->EnsureStyleImageLoader();
1355 // Continuing text frame doesn't initialize its continuation pointer before
1356 // reaching here for the first time, so we have to exclude text frames. This
1357 // doesn't affect correctness because text can't match selectors.
1358 //
1359 // FIXME(emilio): We should consider fixing that.
1360 //
1361 // TODO(emilio): Can we avoid doing some / all of the image stuff when
1362 // isNonTextFirstContinuation is false? We should consider doing this just for
1363 // primary frames and pseudos, but the first-line reparenting code makes it
1364 // all bad, should get around to bug 1465474 eventually :(
1365 const bool isNonText = !IsTextFrame();
1366 if (isNonText) {
1367 mComputedStyle->StartImageLoads(*doc, aOldComputedStyle);
1368 }
1369
1370 const bool isRootElementStyle = Style()->IsRootElementStyle();
1371 if (isRootElementStyle) {
1372 PresShell()->SetNeedsWindowPropertiesSync();
1373 }
1374
1375 const nsStyleImageLayers* oldLayers =
1376 aOldComputedStyle ? &aOldComputedStyle->StyleBackground()->mImage
1377 : nullptr;
1378 const nsStyleImageLayers* newLayers = &StyleBackground()->mImage;
1379 AddAndRemoveImageAssociations(loader, this, oldLayers, newLayers);
1380
1381 oldLayers =
1382 aOldComputedStyle ? &aOldComputedStyle->StyleSVGReset()->mMask : nullptr;
1383 newLayers = &StyleSVGReset()->mMask;
1384 AddAndRemoveImageAssociations(loader, this, oldLayers, newLayers);
1385
1386 const nsStyleDisplay* disp = StyleDisplay();
1387 if (aOldComputedStyle) {
1388 // Detect style changes that should trigger a scroll anchor adjustment
1389 // suppression.
1390 // https://drafts.csswg.org/css-scroll-anchoring/#suppression-triggers
1391 bool needScrollAnchorSuppression = false;
1392
1393 const nsStyleMargin* oldMargin = aOldComputedStyle->StyleMargin();
1394 if (!oldMargin->MarginEquals(*StyleMargin())) {
1395 needScrollAnchorSuppression = true;
1396 }
1397
1398 const nsStylePadding* oldPadding = aOldComputedStyle->StylePadding();
1399 if (oldPadding->mPadding != StylePadding()->mPadding) {
1400 SetHasPaddingChange(true);
1401 needScrollAnchorSuppression = true;
1402 }
1403
1404 const nsStyleDisplay* oldDisp = aOldComputedStyle->StyleDisplay();
1405 if (oldDisp->mOverflowAnchor != disp->mOverflowAnchor) {
1406 if (auto* container = ScrollAnchorContainer::FindFor(this)) {
1407 container->InvalidateAnchor();
1408 }
1409 if (ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(this)) {
1410 scrollContainerFrame->Anchor()->InvalidateAnchor();
1411 }
1412 }
1413
1414 if (mInScrollAnchorChain) {
1415 const nsStylePosition* pos = StylePosition();
1416 const nsStylePosition* oldPos = aOldComputedStyle->StylePosition();
1417 if (!needScrollAnchorSuppression &&
1418 (oldPos->mOffset != pos->mOffset || oldPos->mWidth != pos->mWidth ||
1419 oldPos->mMinWidth != pos->mMinWidth ||
1420 oldPos->mMaxWidth != pos->mMaxWidth ||
1421 oldPos->mHeight != pos->mHeight ||
1422 oldPos->mMinHeight != pos->mMinHeight ||
1423 oldPos->mMaxHeight != pos->mMaxHeight ||
1424 oldDisp->mPosition != disp->mPosition ||
1425 oldDisp->mTransform != disp->mTransform)) {
1426 needScrollAnchorSuppression = true;
1427 }
1428
1429 if (needScrollAnchorSuppression &&
1430 StaticPrefs::layout_css_scroll_anchoring_suppressions_enabled()) {
1431 ScrollAnchorContainer::FindFor(this)->SuppressAdjustments();
1432 }
1433 }
1434
1435 if (disp->mPosition != oldDisp->mPosition) {
1436 if (!disp->IsRelativelyOrStickyPositionedStyle() &&
1437 oldDisp->IsRelativelyOrStickyPositionedStyle()) {
1438 RemoveProperty(NormalPositionProperty());
1439 }
1440 }
1441 if (disp->mScrollSnapAlign != oldDisp->mScrollSnapAlign) {
1442 ScrollSnapUtils::PostPendingResnapFor(this);
1443 }
1444 if (isRootElementStyle &&
1445 disp->mScrollSnapType != oldDisp->mScrollSnapType) {
1446 if (ScrollContainerFrame* sf =
1447 PresShell()->GetRootScrollContainerFrame()) {
1448 sf->PostPendingResnap();
1449 }
1450 }
1451 if (StyleUIReset()->mMozSubtreeHiddenOnlyVisually &&
1452 !aOldComputedStyle->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
1453 PresShell::ClearMouseCapture(this);
1454 }
1455 }
1456
1457 imgIRequest* oldBorderImage =
1458 aOldComputedStyle
1459 ? aOldComputedStyle->StyleBorder()->GetBorderImageRequest()
1460 : nullptr;
1461 imgIRequest* newBorderImage = StyleBorder()->GetBorderImageRequest();
1462 // FIXME (Bug 759996): The following is no longer true.
1463 // For border-images, we can't be as conservative (we need to set the
1464 // new loaders if there has been any change) since the CalcDifference
1465 // call depended on the result of GetComputedBorder() and that result
1466 // depends on whether the image has loaded, start the image load now
1467 // so that we'll get notified when it completes loading and can do a
1468 // restyle. Otherwise, the image might finish loading from the
1469 // network before we start listening to its notifications, and then
1470 // we'll never know that it's finished loading. Likewise, we want to
1471 // do this for freshly-created frames to prevent a similar race if the
1472 // image loads between reflow (which can depend on whether the image
1473 // is loaded) and paint. We also don't really care about any callers who try
1474 // to paint borders with a different style, because they won't have the
1475 // correct size for the border either.
1476 if (oldBorderImage != newBorderImage) {
1477 // stop and restart the image loading/notification
1478 if (oldBorderImage && HasImageRequest()) {
1479 loader.DisassociateRequestFromFrame(oldBorderImage, this);
1480 }
1481 if (newBorderImage) {
1482 loader.AssociateRequestToFrame(newBorderImage, this);
1483 }
1484 }
1485
1486 auto GetShapeImageRequest = [](const ComputedStyle* aStyle) -> imgIRequest* {
1487 if (!aStyle) {
1488 return nullptr;
1489 }
1490 auto& shape = aStyle->StyleDisplay()->mShapeOutside;
1491 if (!shape.IsImage()) {
1492 return nullptr;
1493 }
1494 return shape.AsImage().GetImageRequest();
1495 };
1496
1497 imgIRequest* oldShapeImage = GetShapeImageRequest(aOldComputedStyle);
1498 imgIRequest* newShapeImage = GetShapeImageRequest(Style());
1499 if (oldShapeImage != newShapeImage) {
1500 if (oldShapeImage && HasImageRequest()) {
1501 loader.DisassociateRequestFromFrame(oldShapeImage, this);
1502 }
1503 if (newShapeImage) {
1504 loader.AssociateRequestToFrame(
1505 newShapeImage, this,
1506 ImageLoader::Flags::
1507 RequiresReflowOnFirstFrameCompleteAndLoadEventBlocking);
1508 }
1509 }
1510
1511 // SVGObserverUtils::GetEffectProperties() asserts that we only invoke it with
1512 // the first continuation so we need to check that in advance.
1513 const bool isNonTextFirstContinuation = isNonText && !GetPrevContinuation();
1514 if (isNonTextFirstContinuation) {
1515 // Kick off loading of external SVG resources referenced from properties if
1516 // any. This currently includes filter, clip-path, and mask.
1517 SVGObserverUtils::InitiateResourceDocLoads(this);
1518 }
1519
1520 // If the page contains markup that overrides text direction, and
1521 // does not contain any characters that would activate the Unicode
1522 // bidi algorithm, we need to call |SetBidiEnabled| on the pres
1523 // context before reflow starts. See bug 115921.
1524 if (StyleVisibility()->mDirection == StyleDirection::Rtl) {
1525 PresContext()->SetBidiEnabled();
1526 }
1527
1528 // The following part is for caching offset-path:path(). We cache the
1529 // flatten gfx path, so we don't have to rebuild and re-flattern it at
1530 // each cycle if we have animations on offset-* with a fixed offset-path.
1531 const StyleOffsetPath* oldPath =
1532 aOldComputedStyle ? &aOldComputedStyle->StyleDisplay()->mOffsetPath
1533 : nullptr;
1534 const StyleOffsetPath& newPath = StyleDisplay()->mOffsetPath;
1535 if (!oldPath || *oldPath != newPath) {
1536 // FIXME: Bug 1837042. Cache all basic shapes.
1537 if (newPath.IsPath()) {
1538 RefPtr<gfx::PathBuilder> builder = MotionPathUtils::GetPathBuilder();
1539 RefPtr<gfx::Path> path =
1540 MotionPathUtils::BuildSVGPath(newPath.AsSVGPathData(), builder);
1541 if (path) {
1542 // The newPath could be path('') (i.e. empty path), so its gfx path
1543 // could be nullptr, and so we only set property for a non-empty path.
1544 SetProperty(nsIFrame::OffsetPathCache(), path.forget().take());
1545 } else {
1546 // May have an old cached path, so we have to delete it.
1547 RemoveProperty(nsIFrame::OffsetPathCache());
1548 }
1549 } else if (oldPath) {
1550 RemoveProperty(nsIFrame::OffsetPathCache());
1551 }
1552 }
1553
1554 if (IsPrimaryFrame()) {
1555 MOZ_ASSERT(aOldComputedStyle)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aOldComputedStyle)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aOldComputedStyle))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aOldComputedStyle"
, "./../../../layout/generic/nsIFrame.cpp", 1555); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aOldComputedStyle" ")"); do { MOZ_CrashSequence
(__null, 1555); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1556 HandlePrimaryFrameStyleChange(aOldComputedStyle);
1557 }
1558
1559 RemoveStateBits(NS_FRAME_SIMPLE_DISPLAYLIST);
1560
1561 mMayHaveRoundedCorners = true;
1562}
1563
1564void nsIFrame::HandleLastRememberedSize() {
1565 MOZ_ASSERT(IsPrimaryFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsPrimaryFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsPrimaryFrame()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("IsPrimaryFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 1565); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "IsPrimaryFrame()" ")"); do { MOZ_CrashSequence
(__null, 1565); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1566 auto* element = Element::FromNodeOrNull(mContent);
1567 if (!element) {
1568 return;
1569 }
1570 const WritingMode wm = GetWritingMode();
1571 const nsStylePosition* stylePos = StylePosition();
1572 bool canRememberBSize = stylePos->ContainIntrinsicBSize(wm).HasAuto();
1573 bool canRememberISize = stylePos->ContainIntrinsicISize(wm).HasAuto();
1574 if (!canRememberBSize) {
1575 element->RemoveLastRememberedBSize();
1576 }
1577 if (!canRememberISize) {
1578 element->RemoveLastRememberedISize();
1579 }
1580 if ((canRememberBSize || canRememberISize) && !HidesContent()) {
1581 bool isNonReplacedInline = IsLineParticipant() && !IsReplaced();
1582 if (!isNonReplacedInline) {
1583 PresContext()->Document()->ObserveForLastRememberedSize(*element);
1584 return;
1585 }
1586 }
1587 PresContext()->Document()->UnobserveForLastRememberedSize(*element);
1588}
1589
1590#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED1
1591void nsIFrame::AssertNewStyleIsSane(ComputedStyle& aNewStyle) {
1592 MOZ_DIAGNOSTIC_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1593 aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1594 // ::first-line continuations are weird, this should probably be fixed viado { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1595 // bug 1465474.do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1596 (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1597 aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1598 // ::first-letter continuations are broken, in particular floating ones,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1599 // see bug 1490281. The construction code tries to fix this up after thedo { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1600 // fact, then restyling undoes it...do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1601 (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1602 aNewStyle.GetPseudoType() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1603 PseudoStyleType::MozFirstLetterContinuation) ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1604 (mComputedStyle->GetPseudoType() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1605 PseudoStyleType::MozFirstLetterContinuation &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1606 aNewStyle.GetPseudoType() == PseudoStyleType::MozText))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType
() || (mComputedStyle->GetPseudoType() == PseudoStyleType::
FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType
::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType
::MozText && aNewStyle.GetPseudoType() == PseudoStyleType
::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle
.GetPseudoType() == PseudoStyleType::MozText))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewStyle.GetPseudoType() ==
mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType
() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType
() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::MozText && aNewStyle.GetPseudoType
() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation
&& aNewStyle.GetPseudoType() == PseudoStyleType::MozText
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
, "./../../../layout/generic/nsIFrame.cpp", 1606); AnnotateMozCrashReason
("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::FirstLine && aNewStyle.GetPseudoType() == PseudoStyleType::MozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozText && aNewStyle.GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::MozFirstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::MozText)"
")"); do { MOZ_CrashSequence(__null, 1606); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1607}
1608#endif
1609
1610/* virtual */
1611nsMargin nsIFrame::GetUsedMargin() const {
1612 nsMargin margin;
1613 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1614 IsInSVGTextSubtree()) {
1615 return margin;
1616 }
1617
1618 if (nsMargin* m = GetProperty(UsedMarginProperty())) {
1619 margin = *m;
1620 } else if (!StyleMargin()->GetMargin(margin)) {
1621 // If we get here, our caller probably shouldn't be calling us...
1622 NS_ERROR(do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized margin, because this margin "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1624); MOZ_PretendNoReturn(); } while (0)
1623 "Returning bogus 0-sized margin, because this margin "do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized margin, because this margin "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1624); MOZ_PretendNoReturn(); } while (0)
1624 "depends on layout & isn't cached!")do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized margin, because this margin "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1624); MOZ_PretendNoReturn(); } while (0)
;
1625 }
1626 return margin;
1627}
1628
1629/* virtual */
1630nsMargin nsIFrame::GetUsedBorder() const {
1631 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1632 IsInSVGTextSubtree()) {
1633 return {};
1634 }
1635
1636 const nsStyleDisplay* disp = StyleDisplay();
1637 if (IsThemed(disp)) {
1638 // Theme methods don't use const-ness.
1639 auto* mutable_this = const_cast<nsIFrame*>(this);
1640 nsPresContext* pc = PresContext();
1641 LayoutDeviceIntMargin widgetBorder = pc->Theme()->GetWidgetBorder(
1642 pc->DeviceContext(), mutable_this, disp->EffectiveAppearance());
1643 return LayoutDevicePixel::ToAppUnits(widgetBorder,
1644 pc->AppUnitsPerDevPixel());
1645 }
1646
1647 return StyleBorder()->GetComputedBorder();
1648}
1649
1650/* virtual */
1651nsMargin nsIFrame::GetUsedPadding() const {
1652 nsMargin padding;
1653 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1654 IsInSVGTextSubtree()) {
1655 return padding;
1656 }
1657
1658 const nsStyleDisplay* disp = StyleDisplay();
1659 if (IsThemed(disp)) {
1660 // Theme methods don't use const-ness.
1661 nsIFrame* mutable_this = const_cast<nsIFrame*>(this);
1662 nsPresContext* pc = PresContext();
1663 LayoutDeviceIntMargin widgetPadding;
1664 if (pc->Theme()->GetWidgetPadding(pc->DeviceContext(), mutable_this,
1665 disp->EffectiveAppearance(),
1666 &widgetPadding)) {
1667 return LayoutDevicePixel::ToAppUnits(widgetPadding,
1668 pc->AppUnitsPerDevPixel());
1669 }
1670 }
1671
1672 if (nsMargin* p = GetProperty(UsedPaddingProperty())) {
1673 padding = *p;
1674 } else if (!StylePadding()->GetPadding(padding)) {
1675 // If we get here, our caller probably shouldn't be calling us...
1676 NS_ERROR(do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized padding, because this padding "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1678); MOZ_PretendNoReturn(); } while (0)
1677 "Returning bogus 0-sized padding, because this padding "do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized padding, because this padding "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1678); MOZ_PretendNoReturn(); } while (0)
1678 "depends on layout & isn't cached!")do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized padding, because this padding "
"depends on layout & isn't cached!", "Error", "./../../../layout/generic/nsIFrame.cpp"
, 1678); MOZ_PretendNoReturn(); } while (0)
;
1679 }
1680 return padding;
1681}
1682
1683nsIFrame::Sides nsIFrame::GetSkipSides() const {
1684 if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
1685 StyleBoxDecorationBreak::Clone)(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
&&
1686 !HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
1687 return Sides();
1688 }
1689
1690 // Convert the logical skip sides to physical sides using the frame's
1691 // writing mode
1692 WritingMode writingMode = GetWritingMode();
1693 LogicalSides logicalSkip = GetLogicalSkipSides();
1694 Sides skip;
1695
1696 if (logicalSkip.BStart()) {
1697 if (writingMode.IsVertical()) {
1698 skip |= writingMode.IsVerticalLR() ? SideBits::eLeft : SideBits::eRight;
1699 } else {
1700 skip |= SideBits::eTop;
1701 }
1702 }
1703
1704 if (logicalSkip.BEnd()) {
1705 if (writingMode.IsVertical()) {
1706 skip |= writingMode.IsVerticalLR() ? SideBits::eRight : SideBits::eLeft;
1707 } else {
1708 skip |= SideBits::eBottom;
1709 }
1710 }
1711
1712 if (logicalSkip.IStart()) {
1713 if (writingMode.IsVertical()) {
1714 skip |=
1715 writingMode.IsInlineReversed() ? SideBits::eBottom : SideBits::eTop;
1716 } else {
1717 skip |= writingMode.IsBidiLTR() ? SideBits::eLeft : SideBits::eRight;
1718 }
1719 }
1720
1721 if (logicalSkip.IEnd()) {
1722 if (writingMode.IsVertical()) {
1723 skip |=
1724 writingMode.IsInlineReversed() ? SideBits::eTop : SideBits::eBottom;
1725 } else {
1726 skip |= writingMode.IsBidiLTR() ? SideBits::eRight : SideBits::eLeft;
1727 }
1728 }
1729 return skip;
1730}
1731
1732nsRect nsIFrame::GetPaddingRectRelativeToSelf() const {
1733 nsMargin border = GetUsedBorder().ApplySkipSides(GetSkipSides());
1734 nsRect r(0, 0, mRect.width, mRect.height);
1735 r.Deflate(border);
1736 return r;
1737}
1738
1739nsRect nsIFrame::GetPaddingRect() const {
1740 return GetPaddingRectRelativeToSelf() + GetPosition();
1741}
1742
1743WritingMode nsIFrame::WritingModeForLine(WritingMode aSelfWM,
1744 nsIFrame* aSubFrame) const {
1745 MOZ_ASSERT(aSelfWM == GetWritingMode())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aSelfWM == GetWritingMode())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aSelfWM == GetWritingMode())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("aSelfWM == GetWritingMode()"
, "./../../../layout/generic/nsIFrame.cpp", 1745); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aSelfWM == GetWritingMode()" ")"); do { MOZ_CrashSequence
(__null, 1745); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1746 WritingMode writingMode = aSelfWM;
1747
1748 if (StyleTextReset()->mUnicodeBidi == StyleUnicodeBidi::Plaintext) {
1749 mozilla::intl::BidiEmbeddingLevel frameLevel =
1750 nsBidiPresUtils::GetFrameBaseLevel(aSubFrame);
1751 writingMode.SetDirectionFromBidiLevel(frameLevel);
1752 }
1753
1754 return writingMode;
1755}
1756
1757nsRect nsIFrame::GetMarginRect() const {
1758 return GetMarginRectRelativeToSelf() + GetPosition();
1759}
1760
1761nsRect nsIFrame::GetMarginRectRelativeToSelf() const {
1762 nsMargin m = GetUsedMargin().ApplySkipSides(GetSkipSides());
1763 nsRect r(0, 0, mRect.width, mRect.height);
1764 r.Inflate(m);
1765 return r;
1766}
1767
1768bool nsIFrame::IsTransformed() const {
1769 if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
1770 MOZ_ASSERT(!IsCSSTransformed())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsCSSTransformed())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsCSSTransformed()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("!IsCSSTransformed()"
, "./../../../layout/generic/nsIFrame.cpp", 1770); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsCSSTransformed()" ")"); do { MOZ_CrashSequence
(__null, 1770); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1771 MOZ_ASSERT(!GetParentSVGTransforms())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetParentSVGTransforms())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetParentSVGTransforms())))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("!GetParentSVGTransforms()"
, "./../../../layout/generic/nsIFrame.cpp", 1771); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!GetParentSVGTransforms()" ")"); do { MOZ_CrashSequence
(__null, 1771); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1772 return false;
1773 }
1774 return IsCSSTransformed() || GetParentSVGTransforms();
1775}
1776
1777bool nsIFrame::IsCSSTransformed() const {
1778 return HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED) &&
1779 (StyleDisplay()->HasTransform(this) || HasAnimationOfTransform());
1780}
1781
1782bool nsIFrame::HasAnimationOfTransform() const {
1783 if (!MayHaveTransformAnimation()) {
1784 MOZ_ASSERT(!IsPrimaryFrame() || !SupportsCSSTransforms() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils
::HasAnimationOfTransformAndMotionPath(this))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsPrimaryFrame() || !SupportsCSSTransforms
() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this)"
, "./../../../layout/generic/nsIFrame.cpp", 1785); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this)"
")"); do { MOZ_CrashSequence(__null, 1785); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1785 !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils
::HasAnimationOfTransformAndMotionPath(this))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsPrimaryFrame() || !SupportsCSSTransforms
() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this)"
, "./../../../layout/generic/nsIFrame.cpp", 1785); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsPrimaryFrame() || !SupportsCSSTransforms() || !nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this)"
")"); do { MOZ_CrashSequence(__null, 1785); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1786 return false;
1787 }
1788 return IsPrimaryFrame() && SupportsCSSTransforms() &&
1789 nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this);
1790}
1791
1792bool nsIFrame::ChildrenHavePerspective(
1793 const nsStyleDisplay* aStyleDisplay) const {
1794 MOZ_ASSERT(aStyleDisplay == StyleDisplay())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStyleDisplay == StyleDisplay())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStyleDisplay == StyleDisplay
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aStyleDisplay == StyleDisplay()", "./../../../layout/generic/nsIFrame.cpp"
, 1794); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStyleDisplay == StyleDisplay()"
")"); do { MOZ_CrashSequence(__null, 1794); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1795 return aStyleDisplay->HasPerspective(this);
1796}
1797
1798bool nsIFrame::HasAnimationOfOpacity(EffectSet* aEffectSet) const {
1799 return ((nsLayoutUtils::IsPrimaryStyleFrame(this) ||
1800 nsLayoutUtils::FirstContinuationOrIBSplitSibling(this)
1801 ->IsPrimaryFrame()) &&
1802 nsLayoutUtils::HasAnimationOfPropertySet(
1803 this, nsCSSPropertyIDSet::OpacityProperties(), aEffectSet));
1804}
1805
1806bool nsIFrame::HasOpacityInternal(float aThreshold,
1807 const nsStyleDisplay* aStyleDisplay,
1808 const nsStyleEffects* aStyleEffects,
1809 EffectSet* aEffectSet) const {
1810 MOZ_ASSERT(0.0 <= aThreshold && aThreshold <= 1.0, "Invalid argument")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(0.0 <= aThreshold && aThreshold <= 1.0
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(0.0 <= aThreshold && aThreshold <= 1.0
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"0.0 <= aThreshold && aThreshold <= 1.0" " (" "Invalid argument"
")", "./../../../layout/generic/nsIFrame.cpp", 1810); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "0.0 <= aThreshold && aThreshold <= 1.0"
") (" "Invalid argument" ")"); do { MOZ_CrashSequence(__null
, 1810); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
1811 if (aStyleEffects->mOpacity < aThreshold ||
1812 aStyleDisplay->mWillChange.bits & StyleWillChangeBits::OPACITY) {
1813 return true;
1814 }
1815
1816 if (!mMayHaveOpacityAnimation) {
1817 return false;
1818 }
1819
1820 return HasAnimationOfOpacity(aEffectSet);
1821}
1822
1823bool nsIFrame::DoGetParentSVGTransforms(gfx::Matrix*) const { return false; }
1824
1825bool nsIFrame::Extend3DContext(const nsStyleDisplay* aStyleDisplay,
1826 const nsStyleEffects* aStyleEffects,
1827 mozilla::EffectSet* aEffectSetForOpacity) const {
1828 if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
1829 return false;
1830 }
1831 const nsStyleDisplay* disp = StyleDisplayWithOptionalParam(aStyleDisplay);
1832 if (disp->mTransformStyle != StyleTransformStyle::Preserve3d ||
1833 !SupportsCSSTransforms()) {
1834 return false;
1835 }
1836
1837 // If we're all scroll frame, then all descendants will be clipped, so we
1838 // can't preserve 3d.
1839 if (IsScrollContainerFrame()) {
1840 return false;
1841 }
1842
1843 const nsStyleEffects* effects = StyleEffectsWithOptionalParam(aStyleEffects);
1844 if (HasOpacity(disp, effects, aEffectSetForOpacity)) {
1845 return false;
1846 }
1847
1848 return ShouldApplyOverflowClipping(disp).isEmpty() &&
1849 !GetClipPropClipRect(disp, effects, GetSize()) &&
1850 !SVGIntegrationUtils::UsingEffectsForFrame(this) &&
1851 !effects->HasMixBlendMode() &&
1852 !ForcesStackingContextForViewTransition() &&
1853 disp->mIsolation != StyleIsolation::Isolate;
1854}
1855
1856bool nsIFrame::Combines3DTransformWithAncestors() const {
1857 // Check these first as they are faster then both calls below and are we are
1858 // likely to hit the early return (backface hidden is uncommon and
1859 // GetReferenceFrame is a hot caller of this which only calls this if
1860 // IsCSSTransformed is false).
1861 if (!IsCSSTransformed() && !BackfaceIsHidden()) {
1862 return false;
1863 }
1864 nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
1865 return parent && parent->Extend3DContext();
1866}
1867
1868bool nsIFrame::In3DContextAndBackfaceIsHidden() const {
1869 // While both tests fail most of the time, test BackfaceIsHidden()
1870 // first since it's likely to fail faster.
1871 return BackfaceIsHidden() && Combines3DTransformWithAncestors();
1872}
1873
1874bool nsIFrame::HasPerspective() const {
1875 if (!IsCSSTransformed()) {
1876 return false;
1877 }
1878 nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
1879 if (!parent) {
1880 return false;
1881 }
1882 return parent->ChildrenHavePerspective();
1883}
1884
1885nsRect nsIFrame::GetContentRectRelativeToSelf() const {
1886 nsMargin bp = GetUsedBorderAndPadding().ApplySkipSides(GetSkipSides());
1887 nsRect r(0, 0, mRect.width, mRect.height);
1888 r.Deflate(bp);
1889 return r;
1890}
1891
1892nsRect nsIFrame::GetContentRect() const {
1893 return GetContentRectRelativeToSelf() + GetPosition();
1894}
1895
1896bool nsIFrame::ComputeBorderRadii(const BorderRadius& aBorderRadius,
1897 const CornerShapeRect& aCornerShape,
1898 const nsSize& aFrameSize,
1899 const nsSize& aBorderArea, Sides aSkipSides,
1900 nsRectCornerRadii& aRadii) {
1901 // Percentages are relative to whichever side they're on.
1902 for (const auto i : mozilla::AllPhysicalHalfCorners()) {
1903 const LengthPercentage& c = aBorderRadius.Get(i);
1904 nscoord axis = HalfCornerIsX(i) ? aFrameSize.width : aFrameSize.height;
1905 aRadii[i] = std::max(0, c.Resolve(axis));
1906 }
1907
1908 aRadii.mShapeK[mozilla::eCornerTopLeft] = aCornerShape.top_left.k;
1909 aRadii.mShapeK[mozilla::eCornerTopRight] = aCornerShape.top_right.k;
1910 aRadii.mShapeK[mozilla::eCornerBottomLeft] = aCornerShape.bottom_left.k;
1911 aRadii.mShapeK[mozilla::eCornerBottomRight] = aCornerShape.bottom_right.k;
1912
1913 bool isTopLeftSquare =
1914 std::isinf(aCornerShape.top_left.k) && (aCornerShape.top_left.k > 0.0f);
1915 bool isTopRightSquare =
1916 std::isinf(aCornerShape.top_right.k) && (aCornerShape.top_right.k > 0.0f);
1917 bool isBottomLeftSquare = std::isinf(aCornerShape.bottom_left.k) &&
1918 (aCornerShape.bottom_left.k > 0.0f);
1919 bool isBottomRightSquare = std::isinf(aCornerShape.bottom_right.k) &&
1920 (aCornerShape.bottom_right.k > 0.0f);
1921
1922 if (aSkipSides.Intersects(SideBits::eTop | SideBits::eLeft) ||
1923 isTopLeftSquare) {
1924 aRadii.TopLeft() = {};
1925 }
1926 if (aSkipSides.Intersects(SideBits::eTop | SideBits::eRight) ||
1927 isTopRightSquare) {
1928 aRadii.TopRight() = {};
1929 }
1930 if (aSkipSides.Intersects(SideBits::eBottom | SideBits::eLeft) ||
1931 isBottomLeftSquare) {
1932 aRadii.BottomLeft() = {};
1933 }
1934 if (aSkipSides.Intersects(SideBits::eBottom | SideBits::eRight) ||
1935 isBottomRightSquare) {
1936 aRadii.BottomRight() = {};
1937 }
1938
1939 // css3-background specifies this algorithm for reducing
1940 // corner radii when they are too big.
1941 bool haveRadius = false;
1942 double ratio = 1.0f;
1943 for (const auto side : mozilla::AllPhysicalSides()) {
1944 auto hc1 = SideToHalfCorner(side, false, true);
1945 auto hc2 = SideToHalfCorner(side, true, true);
1946 nscoord length =
1947 SideIsVertical(side) ? aBorderArea.height : aBorderArea.width;
1948 nscoord sum = aRadii[hc1] + aRadii[hc2];
1949 if (sum) {
1950 haveRadius = true;
1951 // avoid floating point division in the normal case
1952 if (length < sum) {
1953 ratio = std::min(ratio, double(length) / sum);
1954 }
1955 }
1956 }
1957 if (ratio < 1.0) {
1958 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1959 aRadii[corner] *= ratio;
1960 }
1961 }
1962
1963 return haveRadius;
1964}
1965
1966static inline bool RadiiAreDefinitelyZero(const BorderRadius& aBorderRadius) {
1967 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1968 if (!aBorderRadius.Get(corner).IsDefinitelyZero()) {
1969 return false;
1970 }
1971 }
1972 return true;
1973}
1974
1975/* virtual */
1976bool nsIFrame::GetBorderRadii(const nsSize& aFrameSize,
1977 const nsSize& aBorderArea, Sides aSkipSides,
1978 nsRectCornerRadii& aRadii) const {
1979 if (!mMayHaveRoundedCorners) {
1980 return false;
1981 }
1982
1983 if (IsThemed()) {
1984 // When we're themed, the native theme code draws the border and
1985 // background, and therefore it doesn't make sense to tell other
1986 // code that's interested in border-radius that we have any radii.
1987 //
1988 // In an ideal world, we might have a way for the them to tell us an
1989 // border radius, but since we don't, we're better off assuming
1990 // zero.
1991 return false;
1992 }
1993
1994 const auto& radii = StyleBorder()->mBorderRadius;
1995 const auto& cornerShape = StyleBorder()->mCornerShape;
1996 const bool hasRadii = ComputeBorderRadii(radii, cornerShape, aFrameSize,
1997 aBorderArea, aSkipSides, aRadii);
1998 if (!hasRadii) {
1999 // TODO(emilio): Maybe we can just remove this bit and do the
2000 // IsDefinitelyZero check unconditionally. That should still avoid most of
2001 // the work, though maybe not the cache miss of going through the style and
2002 // the border struct.
2003 const_cast<nsIFrame*>(this)->mMayHaveRoundedCorners =
2004 !RadiiAreDefinitelyZero(radii);
2005 }
2006 return hasRadii;
2007}
2008
2009bool nsIFrame::GetBorderRadii(nsRectCornerRadii& aRadii) const {
2010 nsSize sz = GetSize();
2011 return GetBorderRadii(sz, sz, GetSkipSides(), aRadii);
2012}
2013
2014bool nsIFrame::GetMarginBoxBorderRadii(nsRectCornerRadii& aRadii) const {
2015 if (!GetBorderRadii(aRadii)) {
2016 return false;
2017 }
2018 aRadii.AdjustOutwards(GetUsedMargin());
2019 return true;
2020}
2021
2022bool nsIFrame::GetPaddingBoxBorderRadii(nsRectCornerRadii& aRadii) const {
2023 if (!GetBorderRadii(aRadii)) {
2024 return false;
2025 }
2026 aRadii.AdjustInwards(GetUsedBorder());
2027 return true;
2028}
2029
2030bool nsIFrame::GetContentBoxBorderRadii(nsRectCornerRadii& aRadii) const {
2031 if (!GetBorderRadii(aRadii)) {
2032 return false;
2033 }
2034 aRadii.AdjustInwards(GetUsedBorderAndPadding());
2035 return true;
2036}
2037
2038bool nsIFrame::GetShapeBoxBorderRadii(nsRectCornerRadii& aRadii) const {
2039 using Tag = StyleShapeOutside::Tag;
2040 auto& shapeOutside = StyleDisplay()->mShapeOutside;
2041 auto box = StyleShapeBox::MarginBox;
2042 switch (shapeOutside.tag) {
2043 case Tag::Image:
2044 case Tag::None:
2045 return false;
2046 case Tag::Box:
2047 box = shapeOutside.AsBox();
2048 break;
2049 case Tag::Shape:
2050 box = shapeOutside.AsShape()._1;
2051 break;
2052 }
2053
2054 switch (box) {
2055 case StyleShapeBox::ContentBox:
2056 return GetContentBoxBorderRadii(aRadii);
2057 case StyleShapeBox::PaddingBox:
2058 return GetPaddingBoxBorderRadii(aRadii);
2059 case StyleShapeBox::BorderBox:
2060 return GetBorderRadii(aRadii);
2061 case StyleShapeBox::MarginBox:
2062 return GetMarginBoxBorderRadii(aRadii);
2063 default:
2064 MOZ_ASSERT_UNREACHABLE("Unexpected box value")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Unexpected box value" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2064); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unexpected box value" ")"); do {
MOZ_CrashSequence(__null, 2064); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
2065 return false;
2066 }
2067}
2068
2069nscoord nsIFrame::OneEmInAppUnits() const {
2070 return StyleFont()
2071 ->mFont.size.ScaledBy(nsLayoutUtils::FontSizeInflationFor(this))
2072 .ToAppUnits();
2073}
2074
2075RubyMetrics nsIFrame::RubyMetrics(float aRubyMetricsFactor) const {
2076 RefPtr<nsFontMetrics> fm =
2077 nsLayoutUtils::GetInflatedFontMetricsForFrame(this);
2078 return mozilla::RubyMetrics{
2079 nscoord(NS_round(fm->TrimmedAscent() * aRubyMetricsFactor)),
2080 nscoord(NS_round(fm->TrimmedDescent() * aRubyMetricsFactor))};
2081}
2082
2083nscoord nsIFrame::SynthesizeFallbackBaseline(
2084 WritingMode aWM, BaselineSharingGroup aBaselineGroup) const {
2085 NS_ASSERTION(!IsSubtreeDirty(), "frame must not be dirty")do { if (!(!IsSubtreeDirty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "frame must not be dirty", "!IsSubtreeDirty()", "./../../../layout/generic/nsIFrame.cpp"
, 2085); MOZ_PretendNoReturn(); } } while (0)
;
2086 return Baseline::SynthesizeBOffsetFromMarginBox(this, aWM, aBaselineGroup);
2087}
2088
2089nscoord nsIFrame::GetLogicalBaseline(WritingMode aWM) const {
2090 return GetLogicalBaseline(aWM, GetDefaultBaselineSharingGroup(),
2091 BaselineExportContext::LineLayout);
2092}
2093
2094nscoord nsIFrame::GetLogicalBaseline(
2095 WritingMode aWM, BaselineSharingGroup aBaselineGroup,
2096 BaselineExportContext aExportContext) const {
2097 const auto result =
2098 GetNaturalBaselineBOffset(aWM, aBaselineGroup, aExportContext)
2099 .valueOrFrom([this, aWM, aBaselineGroup]() {
2100 return SynthesizeFallbackBaseline(aWM, aBaselineGroup);
2101 });
2102 if (aBaselineGroup == BaselineSharingGroup::Last) {
2103 return BSize(aWM) - result;
2104 }
2105 return result;
2106}
2107
2108nscoord nsIFrame::GetCaretBaseline() const {
2109 const WritingMode wm = GetWritingMode();
2110 const BaselineSharingGroup group = GetDefaultBaselineSharingGroup();
2111 const nscoord result =
2112 GetNaturalBaselineBOffset(wm, group, BaselineExportContext::LineLayout)
2113 .valueOrFrom([this, wm, group]() {
2114 // The synthesized caret baseline is placed at the frame's edge
2115 // at the default baseline for the writing mode.
2116 return Baseline::SynthesizeBOffsetFromMarginBox(
2117 this, wm, group,
2118 Baseline::DefaultAlignmentBaselineForWritingMode(wm));
2119 });
2120 if (group == BaselineSharingGroup::Last) {
2121 return BSize(wm) - result;
2122 }
2123 return result;
2124}
2125
2126const nsFrameList& nsIFrame::GetChildList(ChildListID aListID) const {
2127 if (IsAbsoluteContainer()) {
2128 if (aListID == FrameChildListID::Absolute) {
2129 return GetAbsoluteContainingBlock()->GetChildList();
2130 }
2131 if (aListID == FrameChildListID::PushedAbsolute) {
2132 return GetAbsoluteContainingBlock()->GetPushedChildList();
2133 }
2134 }
2135 return nsFrameList::EmptyList();
2136}
2137
2138void nsIFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
2139 if (const auto* absCB = GetAbsoluteContainingBlock()) {
2140 const nsFrameList& absoluteList = absCB->GetChildList();
2141 absoluteList.AppendIfNonempty(aLists, FrameChildListID::Absolute);
2142 const nsFrameList& pushedAbsoluteList = absCB->GetPushedChildList();
2143 pushedAbsoluteList.AppendIfNonempty(aLists,
2144 FrameChildListID::PushedAbsolute);
2145 }
2146}
2147
2148AutoTArray<nsIFrame::ChildList, 4> nsIFrame::CrossDocChildLists() {
2149 AutoTArray<ChildList, 4> childLists;
2150 nsSubDocumentFrame* subdocumentFrame = do_QueryFrame(this);
2151 if (subdocumentFrame) {
2152 // Descend into the subdocument
2153 nsIFrame* root = subdocumentFrame->GetSubdocumentRootFrame();
2154 if (root) {
2155 childLists.EmplaceBack(
2156 nsFrameList(root, nsLayoutUtils::GetLastSibling(root)),
2157 FrameChildListID::Principal);
2158 }
2159 }
2160
2161 GetChildLists(&childLists);
2162 return childLists;
2163}
2164
2165nsIFrame::CaretBlockAxisMetrics nsIFrame::GetCaretBlockAxisMetrics(
2166 mozilla::WritingMode aWM, const nsFontMetrics& aFM) const {
2167 // Note(dshin): Ultimately, this does something highly similar (But still
2168 // different) to `nsLayoutUtils::GetFirstLinePosition`.
2169 const auto baseline = GetCaretBaseline();
2170 nscoord ascent = 0, descent = 0;
2171 ascent = aFM.MaxAscent();
2172 descent = aFM.MaxDescent();
2173 const nscoord height = ascent + descent;
2174 if (aWM.IsVertical() && aWM.IsLineInverted()) {
2175 return CaretBlockAxisMetrics{.mOffset = baseline - descent,
2176 .mExtent = height};
2177 }
2178 return CaretBlockAxisMetrics{.mOffset = baseline - ascent, .mExtent = height};
2179}
2180
2181nscoord nsIFrame::GetFontMetricsDerivedCaretBaseline() const {
2182 float inflation = nsLayoutUtils::FontSizeInflationFor(this);
2183 RefPtr<nsFontMetrics> fm =
2184 nsLayoutUtils::GetFontMetricsForFrame(this, inflation);
2185 const WritingMode wm = GetWritingMode();
2186 const nscoord lineHeight = ReflowInput::CalcLineHeight(
2187 *Style(), PresContext(), GetContent(), inflation);
2188 return nsLayoutUtils::GetCenteredFontBaseline(fm, lineHeight,
2189 wm.IsLineInverted()) +
2190 GetLogicalUsedBorderAndPadding(wm).BStart(wm);
2191}
2192
2193const nsAtom* nsIFrame::ComputePageValue(const nsAtom* aAutoValue) const {
2194 const nsAtom* value = aAutoValue ? aAutoValue : nsGkAtoms::_empty;
2195 const nsIFrame* frame = this;
2196 // Find what CSS page name value this frame's subtree has, if any.
2197 // Starting with this frame, check if a page name other than auto is present,
2198 // and record it if so. Then, if the current frame is a container frame, find
2199 // the first non-placeholder child and repeat.
2200 // This will find the most deeply nested first in-flow child of this frame's
2201 // subtree, and return its page name (with auto resolved if applicable, and
2202 // subtrees with no page-names returning the empty atom rather than null).
2203 do {
2204 if (const nsAtom* maybePageName = frame->GetStylePageName()) {
2205 value = maybePageName;
2206 }
2207 // Get the next frame to read from.
2208 const nsIFrame* firstNonPlaceholderFrame = nullptr;
2209 // If this is a container frame, inspect its in-flow children.
2210 if (const nsContainerFrame* containerFrame = do_QueryFrame(frame)) {
2211 for (const nsIFrame* childFrame : containerFrame->PrincipalChildList()) {
2212 if (!childFrame->IsPlaceholderFrame()) {
2213 firstNonPlaceholderFrame = childFrame;
2214 break;
2215 }
2216 }
2217 }
2218 frame = firstNonPlaceholderFrame;
2219 } while (frame);
2220 return value;
2221}
2222
2223Visibility nsIFrame::GetVisibility() const {
2224 if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2225 return Visibility::Untracked;
2226 }
2227
2228 bool isSet = false;
2229 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2230
2231 MOZ_ASSERT(isSet,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2233); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2233); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2232 "Should have a VisibilityStateProperty value "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2233); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2233); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2233 "if NS_FRAME_VISIBILITY_IS_TRACKED is set")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2233); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2233); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2234
2235 return visibleCount > 0 ? Visibility::ApproximatelyVisible
2236 : Visibility::ApproximatelyNonVisible;
2237}
2238
2239void nsIFrame::UpdateVisibilitySynchronously() {
2240 mozilla::PresShell* presShell = PresShell();
2241 if (!presShell) {
2242 return;
2243 }
2244
2245 if (presShell->AssumeAllFramesVisible()) {
2246 presShell->EnsureFrameInApproximatelyVisibleList(this);
2247 return;
2248 }
2249
2250 bool visible = StyleVisibility()->IsVisible();
2251 nsIFrame* f = GetParent();
2252 nsRect rect = GetRectRelativeToSelf();
2253 nsIFrame* rectFrame = this;
2254 while (f && visible) {
2255 if (ScrollContainerFrame* sf = do_QueryFrame(f)) {
2256 nsRect transformedRect =
2257 nsLayoutUtils::TransformFrameRectToAncestor(rectFrame, rect, f);
2258 if (!sf->IsRectNearlyVisible(transformedRect)) {
2259 visible = false;
2260 break;
2261 }
2262
2263 // In this code we're trying to synchronously update *approximate*
2264 // visibility. (In the future we may update precise visibility here as
2265 // well, which is why the method name does not contain 'approximate'.) The
2266 // IsRectNearlyVisible() check above tells us that the rect we're checking
2267 // is approximately visible within the scrollframe, but we still need to
2268 // ensure that, even if it was scrolled into view, it'd be visible when we
2269 // consider the rest of the document. To do that, we move transformedRect
2270 // to be contained in the scrollport as best we can (it might not fit) to
2271 // pretend that it was scrolled into view.
2272 rect = transformedRect.MoveInsideAndClamp(sf->GetScrollPortRect());
2273 rectFrame = f;
2274 }
2275 nsIFrame* parent = f->GetParent();
2276 if (!parent) {
2277 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(f);
2278 if (parent && parent->PresContext()->IsChrome()) {
2279 break;
2280 }
2281 }
2282 f = parent;
2283 }
2284
2285 if (visible) {
2286 presShell->EnsureFrameInApproximatelyVisibleList(this);
2287 } else {
2288 presShell->RemoveFrameFromApproximatelyVisibleList(this);
2289 }
2290}
2291
2292void nsIFrame::EnableVisibilityTracking() {
2293 if (HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2294 return; // Nothing to do.
2295 }
2296
2297 MOZ_ASSERT(!HasProperty(VisibilityStateProperty()),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasProperty(VisibilityStateProperty()))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasProperty(VisibilityStateProperty())))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!HasProperty(VisibilityStateProperty())"
" (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")", "./../../../layout/generic/nsIFrame.cpp", 2299); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())" ") ("
"Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { MOZ_CrashSequence(__null, 2299); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2298 "Shouldn't have a VisibilityStateProperty value "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasProperty(VisibilityStateProperty()))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasProperty(VisibilityStateProperty())))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!HasProperty(VisibilityStateProperty())"
" (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")", "./../../../layout/generic/nsIFrame.cpp", 2299); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())" ") ("
"Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { MOZ_CrashSequence(__null, 2299); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2299 "if NS_FRAME_VISIBILITY_IS_TRACKED is not set")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasProperty(VisibilityStateProperty()))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasProperty(VisibilityStateProperty())))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!HasProperty(VisibilityStateProperty())"
" (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")", "./../../../layout/generic/nsIFrame.cpp", 2299); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())" ") ("
"Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { MOZ_CrashSequence(__null, 2299); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2300
2301 // Add the state bit so we know to track visibility for this frame, and
2302 // initialize the frame property.
2303 AddStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
2304 SetProperty(VisibilityStateProperty(), 0);
2305
2306 mozilla::PresShell* presShell = PresShell();
2307 if (!presShell) {
2308 return;
2309 }
2310
2311 // Schedule a visibility update. This method will virtually always be called
2312 // when layout has changed anyway, so it's very unlikely that any additional
2313 // visibility updates will be triggered by this, but this way we guarantee
2314 // that if this frame is currently visible we'll eventually find out.
2315 presShell->ScheduleApproximateFrameVisibilityUpdateSoon();
2316}
2317
2318void nsIFrame::DisableVisibilityTracking() {
2319 if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2320 return; // Nothing to do.
2321 }
2322
2323 bool isSet = false;
2324 uint32_t visibleCount = TakeProperty(VisibilityStateProperty(), &isSet);
2325
2326 MOZ_ASSERT(isSet,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2328); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2327 "Should have a VisibilityStateProperty value "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2328); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2328 "if NS_FRAME_VISIBILITY_IS_TRACKED is set")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2328); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2329
2330 RemoveStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
2331
2332 if (visibleCount == 0) {
2333 return; // We were nonvisible.
2334 }
2335
2336 // We were visible, so send an OnVisibilityChange() notification.
2337 OnVisibilityChange(Visibility::ApproximatelyNonVisible);
2338}
2339
2340void nsIFrame::DecApproximateVisibleCount(
2341 const Maybe<OnNonvisible>& aNonvisibleAction
2342 /* = Nothing() */) {
2343 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
, "./../../../layout/generic/nsIFrame.cpp", 2343); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
")"); do { MOZ_CrashSequence(__null, 2343); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2344
2345 bool isSet = false;
2346 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2347
2348 MOZ_ASSERT(isSet,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2350); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2349 "Should have a VisibilityStateProperty value "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2350); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2350 "if NS_FRAME_VISIBILITY_IS_TRACKED is set")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2350); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2351 MOZ_ASSERT(visibleCount > 0,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(visibleCount > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(visibleCount > 0))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("visibleCount > 0"
" (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")", "./../../../layout/generic/nsIFrame.cpp", 2353); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "visibleCount > 0" ") (" "Frame is already nonvisible and we're "
"decrementing its visible count?" ")"); do { MOZ_CrashSequence
(__null, 2353); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
2352 "Frame is already nonvisible and we're "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(visibleCount > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(visibleCount > 0))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("visibleCount > 0"
" (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")", "./../../../layout/generic/nsIFrame.cpp", 2353); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "visibleCount > 0" ") (" "Frame is already nonvisible and we're "
"decrementing its visible count?" ")"); do { MOZ_CrashSequence
(__null, 2353); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
2353 "decrementing its visible count?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(visibleCount > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(visibleCount > 0))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("visibleCount > 0"
" (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")", "./../../../layout/generic/nsIFrame.cpp", 2353); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "visibleCount > 0" ") (" "Frame is already nonvisible and we're "
"decrementing its visible count?" ")"); do { MOZ_CrashSequence
(__null, 2353); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
2354
2355 visibleCount--;
2356 SetProperty(VisibilityStateProperty(), visibleCount);
2357 if (visibleCount > 0) {
2358 return;
2359 }
2360
2361 // We just became nonvisible, so send an OnVisibilityChange() notification.
2362 OnVisibilityChange(Visibility::ApproximatelyNonVisible, aNonvisibleAction);
2363}
2364
2365void nsIFrame::IncApproximateVisibleCount() {
2366 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
, "./../../../layout/generic/nsIFrame.cpp", 2366); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
")"); do { MOZ_CrashSequence(__null, 2366); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2367
2368 bool isSet = false;
2369 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2370
2371 MOZ_ASSERT(isSet,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2373); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2373); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2372 "Should have a VisibilityStateProperty value "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2373); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2373); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2373 "if NS_FRAME_VISIBILITY_IS_TRACKED is set")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isSet)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(isSet))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("isSet" " (" "Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2373); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { MOZ_CrashSequence(__null, 2373); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2374
2375 visibleCount++;
2376 SetProperty(VisibilityStateProperty(), visibleCount);
2377 if (visibleCount > 1) {
2378 return;
2379 }
2380
2381 // We just became visible, so send an OnVisibilityChange() notification.
2382 OnVisibilityChange(Visibility::ApproximatelyVisible);
2383}
2384
2385void nsIFrame::OnVisibilityChange(Visibility aNewVisibility,
2386 const Maybe<OnNonvisible>& aNonvisibleAction
2387 /* = Nothing() */) {
2388 // XXX(seth): In bug 1218990 we'll implement visibility tracking for CSS
2389 // images here.
2390}
2391
2392static nsIFrame* GetActiveSelectionFrame(nsPresContext* aPresContext,
2393 nsIFrame* aFrame) {
2394 nsIContent* capturingContent = PresShell::GetCapturingContent();
2395 if (capturingContent) {
2396 nsIFrame* activeFrame =
2397 aPresContext->GetPrimaryOrAreaImageFrameFor(capturingContent);
2398 return activeFrame ? activeFrame : aFrame;
2399 }
2400
2401 return aFrame;
2402}
2403
2404bool nsIFrame::ShouldHandleSelectionMovementEvents(ForSelectionStart aType) {
2405 if (GetDisplaySelection() == nsISelectionController::SELECTION_OFF) {
2406 return false;
2407 }
2408 if (UsedUserSelect(this, aType) == StyleUserSelect::None) {
2409 // Check whether style allows selection.
2410 return false;
2411 }
2412 if (IsScrollbarFrame() || IsHTMLCanvasFrame()) {
2413 // Scrollbars and canvas don't move selection with the mouse.
2414 return false;
2415 }
2416 return true;
2417}
2418
2419static Element* FindElementAncestorForMozSelection(nsIContent* aContent) {
2420 NS_ENSURE_TRUE(aContent, nullptr)do { if ((__builtin_expect(!!(!(aContent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aContent" ") failed", nullptr
, "./../../../layout/generic/nsIFrame.cpp", 2420); return nullptr
; } } while (false)
;
2421 while (aContent && aContent->IsInNativeAnonymousSubtree()) {
2422 aContent = aContent->GetClosestNativeAnonymousSubtreeRootParentOrHost();
2423 }
2424 NS_ASSERTION(aContent, "aContent isn't in non-anonymous tree?")do { if (!(aContent)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aContent isn't in non-anonymous tree?"
, "aContent", "./../../../layout/generic/nsIFrame.cpp", 2424)
; MOZ_PretendNoReturn(); } } while (0)
;
2425 return aContent ? aContent->GetAsElementOrParentElement() : nullptr;
2426}
2427
2428already_AddRefed<ComputedStyle> nsIFrame::ComputeSelectionStyle(
2429 int16_t aSelectionStatus) const {
2430 // Just bail out if not a selection-status that ::selection applies to.
2431 if (aSelectionStatus != nsISelectionController::SELECTION_ON &&
2432 aSelectionStatus != nsISelectionController::SELECTION_DISABLED) {
2433 return nullptr;
2434 }
2435 Element* element = FindElementAncestorForMozSelection(GetContent());
2436 if (!element) {
2437 return nullptr;
2438 }
2439 nsIFrame* primaryFrame = element->GetPrimaryFrame();
2440 ComputedStyle* parentStyle = primaryFrame ? primaryFrame->Style() : Style();
2441 RefPtr<ComputedStyle> pseudoStyle =
2442 PresContext()->StyleSet()->ProbePseudoElementStyle(
2443 *element, PseudoStyleType::Selection, nullptr, parentStyle);
2444 if (!pseudoStyle) {
2445 return nullptr;
2446 }
2447 // When in high-contrast mode, the style system ends up ignoring the color
2448 // declarations, which means that the ::selection style becomes the inherited
2449 // color, and default background. That's no good.
2450 // When force-color-adjust is set to none allow using the color styles,
2451 // as they will not be replaced.
2452 if (PresContext()->ForcingColors() &&
2453 pseudoStyle->StyleText()->mForcedColorAdjust !=
2454 StyleForcedColorAdjust::None) {
2455 return nullptr;
2456 }
2457 return do_AddRef(pseudoStyle);
2458}
2459
2460already_AddRefed<ComputedStyle> nsIFrame::ComputeHighlightSelectionStyle(
2461 nsAtom* aHighlightName) {
2462 Element* element = FindElementAncestorForMozSelection(GetContent());
2463 if (!element) {
2464 return nullptr;
2465 }
2466 nsIFrame* primaryFrame = element->GetPrimaryFrame();
2467 ComputedStyle* parentStyle = primaryFrame ? primaryFrame->Style() : Style();
2468 return PresContext()->StyleSet()->ProbePseudoElementStyle(
2469 *element, PseudoStyleType::Highlight, aHighlightName, parentStyle);
2470}
2471
2472already_AddRefed<ComputedStyle> nsIFrame::ComputeTargetTextStyle() const {
2473 const Element* element = FindElementAncestorForMozSelection(GetContent());
2474 if (!element) {
2475 return nullptr;
2476 }
2477 nsIFrame* primaryFrame = element->GetPrimaryFrame();
2478 ComputedStyle* parentStyle = primaryFrame ? primaryFrame->Style() : Style();
2479 RefPtr pseudoStyle = PresContext()->StyleSet()->ProbePseudoElementStyle(
2480 *element, PseudoStyleType::TargetText, nullptr, parentStyle);
2481 if (!pseudoStyle) {
2482 return nullptr;
2483 }
2484 if (PresContext()->ForcingColors() &&
2485 pseudoStyle->StyleText()->mForcedColorAdjust !=
2486 StyleForcedColorAdjust::None) {
2487 return nullptr;
2488 }
2489 return pseudoStyle.forget();
2490}
2491
2492nsTextControlFrame* nsIFrame::GetContainingTextControlFrame() const {
2493 for (const nsIFrame* cur = this; cur; cur = cur->GetParent()) {
2494 if (const nsTextControlFrame* tc = do_QueryFrame(cur)) {
2495 return const_cast<nsTextControlFrame*>(tc);
2496 }
2497 if (cur->Style()->IsAnonBox()) {
2498 // Anon boxes could belong to the <input> / <textarea> itself.
2499 continue;
2500 }
2501 auto* content = cur->GetContent();
2502 if (!content || !content->IsInNativeAnonymousSubtree()) {
2503 // All content inside text controls is anonymous.
2504 break;
2505 }
2506 }
2507 return nullptr;
2508}
2509
2510bool nsIFrame::CanBeDynamicReflowRoot() const {
2511 const auto& display = *StyleDisplay();
2512 if (IsLineParticipant() || display.mDisplay.IsRuby() ||
2513 display.IsInnerTableStyle() ||
2514 display.DisplayInside() == StyleDisplayInside::Table) {
2515 // We have a display type where 'width' and 'height' don't actually set the
2516 // width or height (i.e., the size depends on content).
2517 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
" (" "should not have dynamic reflow root bit" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2518); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
") (" "should not have dynamic reflow root bit" ")"); do { MOZ_CrashSequence
(__null, 2518); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
2518 "should not have dynamic reflow root bit")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
" (" "should not have dynamic reflow root bit" ")", "./../../../layout/generic/nsIFrame.cpp"
, 2518); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
") (" "should not have dynamic reflow root bit" ")"); do { MOZ_CrashSequence
(__null, 2518); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
2519 return false;
2520 }
2521
2522 // In general, frames that have contain:layout+size can be reflow roots.
2523 // (One exception: table-wrapper frames don't work well as reflow roots,
2524 // because their inner-table ReflowInput init path tries to reuse & deref
2525 // the wrapper's containing block's reflow input, which may be null if we
2526 // initiate reflow from the table-wrapper itself.)
2527 //
2528 // Changes to `contain` force frame reconstructions, so we used to use
2529 // NS_FRAME_REFLOW_ROOT, this bit could be set for the whole lifetime of
2530 // this frame. But after the support of `content-visibility: auto` which
2531 // is with contain layout + size when it's not relevant to user, and only
2532 // with contain layout when it is relevant. The frame does not reconstruct
2533 // when the relevancy changes. So we use NS_FRAME_DYNAMIC_REFLOW_ROOT instead.
2534 //
2535 // We place it above the pref check on purpose, to make sure it works for
2536 // containment even with the pref disabled.
2537 if (display.IsContainLayout() && GetContainSizeAxes().IsBoth()) {
2538 return true;
2539 }
2540
2541 if (!StaticPrefs::layout_dynamic_reflow_roots_enabled()) {
2542 return false;
2543 }
2544
2545 // We can't serve as a dynamic reflow root if our used 'width' and 'height'
2546 // might be influenced by content.
2547 //
2548 // FIXME: For display:block, we should probably optimize inline-size: auto.
2549 // FIXME: Other flex and grid cases?
2550 const auto& pos = *StylePosition();
2551 const auto anchorResolutionParams = AnchorPosResolutionParams::From(this);
2552 const auto width = pos.GetWidth(anchorResolutionParams);
2553 const auto height = pos.GetHeight(anchorResolutionParams);
2554 if (!width->IsLengthPercentage() || width->HasPercent() ||
2555 !height->IsLengthPercentage() || height->HasPercent() ||
2556 IsIntrinsicKeyword(*pos.GetMinWidth(anchorResolutionParams)) ||
2557 IsIntrinsicKeyword(*pos.GetMaxWidth(anchorResolutionParams)) ||
2558 IsIntrinsicKeyword(*pos.GetMinHeight(anchorResolutionParams)) ||
2559 IsIntrinsicKeyword(*pos.GetMaxHeight(anchorResolutionParams)) ||
2560 ((pos.GetMinWidth(anchorResolutionParams)->IsAuto() ||
2561 pos.GetMinHeight(anchorResolutionParams)->IsAuto()) &&
2562 IsFlexOrGridItem())) {
2563 return false;
2564 }
2565
2566 // If our flex-basis is 'auto', it'll defer to 'width' (or 'height') which
2567 // we've already checked. Otherwise, it preempts them, so we need to
2568 // perform the same "could-this-value-be-influenced-by-content" checks that
2569 // we performed for 'width' and 'height' above.
2570 if (IsFlexItem()) {
2571 const auto& flexBasis = pos.mFlexBasis;
2572 if (!flexBasis.IsAuto()) {
2573 if (!flexBasis.IsSize() || !flexBasis.AsSize().IsLengthPercentage() ||
2574 flexBasis.AsSize().HasPercent()) {
2575 return false;
2576 }
2577 }
2578 }
2579
2580 if (!IsFixedPosContainingBlock()) {
2581 // We can't treat this frame as a reflow root, since dynamic changes
2582 // to absolutely-positioned frames inside of it require that we
2583 // reflow the placeholder before we reflow the absolutely positioned
2584 // frame.
2585 // FIXME: Alternatively, we could sort the reflow roots in
2586 // PresShell::ProcessReflowCommands by depth in the tree, from
2587 // deepest to least deep. However, for performance (FIXME) we
2588 // should really be sorting them in the opposite order!
2589 return false;
2590 }
2591
2592 // If we participate in a container's block reflow context, or margins
2593 // can collapse through us, we can't be a dynamic reflow root.
2594 // (NS_BLOCK_BFC is block specific bit, check first as an optimization, it's
2595 // okay because we also check that it is a block frame.)
2596 if (!HasAnyStateBits(NS_BLOCK_BFC) && IsBlockFrameOrSubclass()) {
2597 return false;
2598 }
2599
2600 // Subgrids are never reflow roots, but 'contain:layout/paint' prevents
2601 // creating a subgrid in the first place.
2602 if (pos.mGridTemplateColumns.IsSubgrid() ||
2603 pos.mGridTemplateRows.IsSubgrid()) {
2604 // NOTE: we could check that 'display' of our parent's primary frame is
2605 // '[inline-]grid' here but that's probably not worth it in practice.
2606 if (!display.IsContainLayout() && !display.IsContainPaint()) {
2607 return false;
2608 }
2609 }
2610
2611 // If we are split, we can't be a dynamic reflow root. Our reflow status may
2612 // change after reflow, and our parent is responsible to create or delete our
2613 // next-in-flow.
2614 if (GetPrevContinuation() || GetNextContinuation()) {
2615 return false;
2616 }
2617
2618 return true;
2619}
2620
2621/********************************************************
2622 * Refreshes each content's frame
2623 *********************************************************/
2624
2625void nsIFrame::DisplayOutlineUnconditional(nsDisplayListBuilder* aBuilder,
2626 const nsDisplayListSet& aLists) {
2627 // Per https://drafts.csswg.org/css-tables-3/#global-style-overrides:
2628 // "All css properties of table-column and table-column-group boxes are
2629 // ignored, except when explicitly specified by this specification."
2630 // CSS outlines fall into this category, so we skip them on these boxes.
2631 MOZ_ASSERT(!IsTableColGroupFrame() && !IsTableColFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsTableColGroupFrame() && !IsTableColFrame(
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!IsTableColGroupFrame() && !IsTableColFrame(
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!IsTableColGroupFrame() && !IsTableColFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 2631); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsTableColGroupFrame() && !IsTableColFrame()"
")"); do { MOZ_CrashSequence(__null, 2631); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2632 const auto& outline = *StyleOutline();
2633
2634 if (!outline.ShouldPaintOutline()) {
2635 return;
2636 }
2637
2638 // Outlines are painted by the table wrapper frame.
2639 if (IsTableFrame()) {
2640 return;
2641 }
2642
2643 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT) &&
2644 ScrollableOverflowRect().IsEmpty()) {
2645 // Skip parts of IB-splits with an empty overflow rect, see bug 434301.
2646 // We may still want to fix some of the overflow area calculations over in
2647 // that bug.
2648 return;
2649 }
2650
2651 // We don't display outline-style: auto on themed frames that have their own
2652 // focus indicators.
2653 if (outline.mOutlineStyle.IsAuto()) {
2654 auto* disp = StyleDisplay();
2655 if (IsThemed(disp) && PresContext()->Theme()->ThemeDrawsFocusForWidget(
2656 this, disp->EffectiveAppearance())) {
2657 return;
2658 }
2659 }
2660
2661 aLists.Outlines()->AppendNewToTop<nsDisplayOutline>(aBuilder, this);
2662}
2663
2664void nsIFrame::DisplayOutline(nsDisplayListBuilder* aBuilder,
2665 const nsDisplayListSet& aLists) {
2666 if (!IsVisibleForPainting()) {
2667 return;
2668 }
2669
2670 DisplayOutlineUnconditional(aBuilder, aLists);
2671}
2672
2673void nsIFrame::DisplayInsetBoxShadowUnconditional(
2674 nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
2675 // XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
2676 // just because we're visible? Or should it depend on the cell visibility
2677 // when we're not the whole table?
2678 const auto* effects = StyleEffects();
2679 if (effects->HasBoxShadowWithInset(true)) {
2680 aList->AppendNewToTop<nsDisplayBoxShadowInner>(aBuilder, this);
2681 }
2682}
2683
2684void nsIFrame::DisplayInsetBoxShadow(nsDisplayListBuilder* aBuilder,
2685 nsDisplayList* aList) {
2686 if (!IsVisibleForPainting()) {
2687 return;
2688 }
2689
2690 DisplayInsetBoxShadowUnconditional(aBuilder, aList);
2691}
2692
2693void nsIFrame::DisplayOutsetBoxShadowUnconditional(
2694 nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
2695 // XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
2696 // just because we're visible? Or should it depend on the cell visibility
2697 // when we're not the whole table?
2698 const auto* effects = StyleEffects();
2699 if (effects->HasBoxShadowWithInset(false)) {
2700 aList->AppendNewToTop<nsDisplayBoxShadowOuter>(aBuilder, this);
2701 }
2702}
2703
2704void nsIFrame::DisplayOutsetBoxShadow(nsDisplayListBuilder* aBuilder,
2705 nsDisplayList* aList) {
2706 if (!IsVisibleForPainting()) {
2707 return;
2708 }
2709
2710 DisplayOutsetBoxShadowUnconditional(aBuilder, aList);
2711}
2712
2713void nsIFrame::DisplayCaret(nsDisplayListBuilder* aBuilder,
2714 nsDisplayList* aList) {
2715 if (!IsVisibleForPainting()) {
2716 return;
2717 }
2718
2719 aList->AppendNewToTop<nsDisplayCaret>(aBuilder, this);
2720}
2721
2722nscolor nsIFrame::GetCaretColorAt(int32_t aOffset) {
2723 return nsLayoutUtils::GetTextColor(this, &nsStyleUI::mCaretColor);
2724}
2725
2726auto nsIFrame::ComputeShouldPaintBackground() const -> ShouldPaintBackground {
2727 nsPresContext* pc = PresContext();
2728 ShouldPaintBackground settings{pc->GetBackgroundColorDraw(),
2729 pc->GetBackgroundImageDraw()};
2730 if (settings.mColor && settings.mImage) {
2731 return settings;
2732 }
2733
2734 if (StyleVisibility()->mPrintColorAdjust == StylePrintColorAdjust::Exact) {
2735 return {true, true};
2736 }
2737
2738 return settings;
2739}
2740
2741bool nsIFrame::DisplayBackgroundUnconditional(nsDisplayListBuilder* aBuilder,
2742 const nsDisplayListSet& aLists) {
2743 if (aBuilder->IsForEventDelivery() && !aBuilder->HitTestIsForVisibility()) {
2744 // For hit-testing, we generally just need a light-weight data structure
2745 // like nsDisplayEventReceiver. But if the hit-testing is for visibility,
2746 // then we need to know the opaque region in order to determine whether to
2747 // stop or not.
2748 aLists.BorderBackground()->AppendNewToTop<nsDisplayEventReceiver>(aBuilder,
2749 this);
2750 return false;
2751 }
2752
2753 const AppendedBackgroundType result =
2754 nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
2755 aBuilder, this,
2756 GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this),
2757 aLists.BorderBackground());
2758
2759 if (result == AppendedBackgroundType::None) {
2760 aBuilder->BuildCompositorHitTestInfoIfNeeded(this,
2761 aLists.BorderBackground());
2762 }
2763
2764 return result == AppendedBackgroundType::ThemedBackground;
2765}
2766
2767void nsIFrame::DisplayBorderBackgroundOutline(nsDisplayListBuilder* aBuilder,
2768 const nsDisplayListSet& aLists) {
2769 // The visibility check belongs here since child elements have the
2770 // opportunity to override the visibility property and display even if
2771 // their parent is hidden.
2772 if (!IsVisibleForPainting()) {
2773 return;
2774 }
2775
2776 DisplayOutsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
2777
2778 bool bgIsThemed = DisplayBackgroundUnconditional(aBuilder, aLists);
2779 DisplayInsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
2780
2781 // If there's a themed background, we should not create a border item.
2782 // It won't be rendered.
2783 // Don't paint borders for tables here, since they paint them in a different
2784 // order.
2785 if (!bgIsThemed && StyleBorder()->HasBorder() && !IsTableFrame()) {
2786 aLists.BorderBackground()->AppendNewToTop<nsDisplayBorder>(aBuilder, this);
2787 }
2788
2789 DisplayOutlineUnconditional(aBuilder, aLists);
2790}
2791
2792inline static bool IsSVGContentWithCSSClip(const nsIFrame* aFrame) {
2793 // The CSS spec says that the 'clip' property only applies to absolutely
2794 // positioned elements, whereas the SVG spec says that it applies to SVG
2795 // elements regardless of the value of the 'position' property. Here we obey
2796 // the CSS spec for outer-<svg> (since that's what we generally do), but
2797 // obey the SVG spec for other SVG elements to which 'clip' applies.
2798 return aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) &&
2799 aFrame->GetContent()->IsAnyOfSVGElements(nsGkAtoms::svg,
2800 nsGkAtoms::foreignObject);
2801}
2802
2803Maybe<nsRect> nsIFrame::GetClipPropClipRect(const nsStyleDisplay* aDisp,
2804 const nsStyleEffects* aEffects,
2805 const nsSize& aSize) const {
2806 if (aEffects->mClip.IsAuto() ||
2807 !(aDisp->IsAbsolutelyPositioned(this) || IsSVGContentWithCSSClip(this))) {
2808 return Nothing();
2809 }
2810
2811 auto& clipRect = aEffects->mClip.AsRect();
2812 nsRect rect = clipRect.ToLayoutRect();
2813 if (MOZ_LIKELY(StyleBorder()->mBoxDecorationBreak ==(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Slice), 1))
2814 StyleBoxDecorationBreak::Slice)(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Slice), 1))
) {
2815 // The clip applies to the joined boxes so it's relative the first
2816 // continuation.
2817 nscoord y = 0;
2818 for (nsIFrame* f = GetPrevContinuation(); f; f = f->GetPrevContinuation()) {
2819 y += f->GetRect().height;
2820 }
2821 rect.MoveBy(nsPoint(0, -y));
2822 }
2823
2824 if (clipRect.right.IsAuto()) {
2825 rect.width = aSize.width - rect.x;
2826 }
2827 if (clipRect.bottom.IsAuto()) {
2828 rect.height = aSize.height - rect.y;
2829 }
2830 return Some(rect);
2831}
2832
2833// https://drafts.csswg.org/css-view-transitions-1/#named-and-transitioning
2834//
2835// Note https://github.com/w3c/csswg-drafts/issues/11772, however, for the root
2836// style check.
2837bool nsIFrame::ForcesStackingContextForViewTransition() const {
2838 auto* style = Style();
2839 return !style->IsRootElementStyle() &&
2840 (style->StyleUIReset()->HasViewTransitionName() ||
2841 HasAnyStateBits(NS_FRAME_CAPTURED_IN_VIEW_TRANSITION) ||
2842 style->StyleDisplay()->mWillChange.bits &
2843 mozilla::StyleWillChangeBits::VIEW_TRANSITION_NAME);
2844}
2845
2846/**
2847 * If the CSS 'overflow' property applies to this frame, and is not
2848 * handled by constructing a dedicated nsHTML/XULScrollFrame, set up clipping
2849 * for that overflow in aBuilder->ClipState() to clip all containing-block
2850 * descendants.
2851 */
2852static void ApplyOverflowClipping(
2853 nsDisplayListBuilder* aBuilder, const nsIFrame* aFrame,
2854 PhysicalAxes aClipAxes,
2855 DisplayListClipState::AutoClipMultiple& aClipState) {
2856 nsRect clipRect;
2857 nsRectCornerRadii radii;
2858 nsMargin inset;
2859 bool haveRadii = aFrame->ComputeOverflowClipRectRelativeToSelf(
2860 aClipAxes, clipRect, radii, inset);
2861 aClipState.ClipContainingBlockDescendantsExtra(
2862 clipRect + aBuilder->ToReferenceFrame(aFrame),
2863 haveRadii ? &radii : nullptr, haveRadii ? &inset : nullptr);
2864}
2865
2866static Sides ToSkipSides(PhysicalAxes aClipAxes) {
2867 SideBits result{};
2868 if (!aClipAxes.contains(PhysicalAxis::Vertical)) {
2869 result |= SideBits::eTop;
2870 result |= SideBits::eBottom;
2871 }
2872 if (!aClipAxes.contains(PhysicalAxis::Horizontal)) {
2873 result |= SideBits::eLeft;
2874 result |= SideBits::eRight;
2875 }
2876 return Sides(result);
2877}
2878
2879bool nsIFrame::ComputeOverflowClipRectRelativeToSelf(
2880 const PhysicalAxes aClipAxes, nsRect& aOutRect,
2881 nsRectCornerRadii& aOutRadii, nsMargin& aOutInset) const {
2882 // Only 'clip' is handled here (and 'hidden' for table frames, and any
2883 // non-'visible' value for blocks in a paginated context).
2884 // We allow 'clip' to apply to any kind of frame. This is required by
2885 // comboboxes which make their display text (an inline frame) have clipping.
2886 MOZ_ASSERT(!aClipAxes.isEmpty())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aClipAxes.isEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aClipAxes.isEmpty()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!aClipAxes.isEmpty()"
, "./../../../layout/generic/nsIFrame.cpp", 2886); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!aClipAxes.isEmpty()" ")"); do { MOZ_CrashSequence
(__null, 2886); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
2887 MOZ_ASSERT(ShouldApplyOverflowClipping(StyleDisplay()) == aClipAxes)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ShouldApplyOverflowClipping(StyleDisplay()) == aClipAxes
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(ShouldApplyOverflowClipping(StyleDisplay()) == aClipAxes
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"ShouldApplyOverflowClipping(StyleDisplay()) == aClipAxes", "./../../../layout/generic/nsIFrame.cpp"
, 2887); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ShouldApplyOverflowClipping(StyleDisplay()) == aClipAxes"
")"); do { MOZ_CrashSequence(__null, 2887); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2888 auto boxMargin = OverflowClipMargin(aClipAxes, /* aAllowNegative = */ true);
2889 boxMargin.ApplySkipSides(GetSkipSides() | ToSkipSides(aClipAxes));
2890 aOutInset = -boxMargin;
2891
2892 aOutRect = nsRect(nsPoint(), GetSize());
2893 aOutRect.Inflate(boxMargin);
2894 if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Horizontal))(__builtin_expect(!!(!aClipAxes.contains(PhysicalAxis::Horizontal
)), 0))
) {
2895 // NOTE(mats) We shouldn't be clipping at all in this dimension really,
2896 // but clipping in just one axis isn't supported by our GFX APIs so we
2897 // clip to our visual overflow rect instead.
2898 nsRect o = InkOverflowRectRelativeToSelf();
2899 aOutRect.x = o.x;
2900 aOutRect.width = o.width;
2901 }
2902 if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Vertical))(__builtin_expect(!!(!aClipAxes.contains(PhysicalAxis::Vertical
)), 0))
) {
2903 // See the note above.
2904 nsRect o = InkOverflowRectRelativeToSelf();
2905 aOutRect.y = o.y;
2906 aOutRect.height = o.height;
2907 }
2908 if (!GetBorderRadii(aOutRadii)) {
2909 return false;
2910 }
2911 aOutRadii.AdjustOutwards(boxMargin);
2912 return true;
2913}
2914
2915nsMargin nsIFrame::OverflowClipMargin(PhysicalAxes aClipAxes,
2916 bool aAllowNegative) const {
2917 nsMargin result;
2918 if (aClipAxes.isEmpty()) {
2919 return result;
2920 }
2921 const auto& margin = StyleMargin()->mOverflowClipMargin;
2922 if (!aAllowNegative && margin.offset.IsZero()) {
2923 return result;
2924 }
2925 switch (margin.visual_box) {
2926 case StyleOverflowClipMarginBox::BorderBox:
2927 break;
2928 case StyleOverflowClipMarginBox::PaddingBox:
2929 result = -GetUsedBorder();
2930 break;
2931 case StyleOverflowClipMarginBox::ContentBox:
2932 result = -GetUsedBorderAndPadding();
2933 break;
2934 }
2935 if (!margin.offset.IsZero()) {
2936 nscoord marginAu = margin.offset.ToAppUnits();
2937 result += nsMargin(marginAu, marginAu, marginAu, marginAu);
2938 }
2939 if (!aAllowNegative) {
2940 result.EnsureAtLeast(nsMargin());
2941 }
2942 return result;
2943}
2944
2945/**
2946 * Returns whether a display item that gets created with the builder's current
2947 * state will have a scrolled clip, i.e. a clip that is scrolled by a scroll
2948 * frame which does not move the item itself.
2949 */
2950static bool BuilderHasScrolledClip(nsDisplayListBuilder* aBuilder) {
2951 const DisplayItemClipChain* currentClip =
2952 aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
2953 if (!currentClip) {
2954 return false;
2955 }
2956
2957 const ActiveScrolledRoot* currentClipASR = currentClip->mASR;
2958 const ActiveScrolledRoot* currentASR = aBuilder->CurrentActiveScrolledRoot();
2959 return ActiveScrolledRoot::PickDescendant(currentClipASR, currentASR) !=
2960 currentASR;
2961}
2962
2963class AutoTrackStackingContextBits {
2964 nsDisplayListBuilder& mBuilder;
2965 StackingContextBits mBitsToSet;
2966
2967 public:
2968 explicit AutoTrackStackingContextBits(nsDisplayListBuilder& aBuilder)
2969 : mBuilder(aBuilder), mBitsToSet(aBuilder.GetStackingContextBits()) {}
2970
2971 ~AutoTrackStackingContextBits() {
2972 mBuilder.SetStackingContextBits(mBitsToSet);
2973 }
2974
2975 void AddToParent(StackingContextBits aBits) { mBitsToSet |= aBits; }
2976};
2977
2978static bool IsFrameOrAncestorApzAware(nsIFrame* aFrame) {
2979 nsIContent* node = aFrame->GetContent();
2980 if (!node) {
2981 return false;
2982 }
2983
2984 do {
2985 if (node->IsNodeApzAware()) {
2986 return true;
2987 }
2988 nsIContent* shadowRoot = node->GetShadowRoot();
2989 if (shadowRoot && shadowRoot->IsNodeApzAware()) {
2990 return true;
2991 }
2992
2993 // Even if the node owning aFrame doesn't have apz-aware event listeners
2994 // itself, its shadow root or display: contents ancestors (which have no
2995 // frames) might, so we need to account for them too.
2996 } while ((node = node->GetFlattenedTreeParent()) && node->IsElement() &&
2997 node->AsElement()->IsDisplayContents());
2998
2999 return false;
3000}
3001
3002static void CheckForApzAwareEventHandlers(nsDisplayListBuilder* aBuilder,
3003 nsIFrame* aFrame) {
3004 if (aBuilder->GetAncestorHasApzAwareEventHandler()) {
3005 return;
3006 }
3007
3008 if (IsFrameOrAncestorApzAware(aFrame)) {
3009 aBuilder->SetAncestorHasApzAwareEventHandler(true);
3010 }
3011}
3012
3013static void UpdateCurrentHitTestInfo(nsDisplayListBuilder* aBuilder,
3014 nsIFrame* aFrame) {
3015 if (!aBuilder->BuildCompositorHitTestInfo()) {
3016 // Compositor hit test info is not used.
3017 return;
3018 }
3019
3020 CheckForApzAwareEventHandlers(aBuilder, aFrame);
3021
3022 const CompositorHitTestInfo info =
3023 aFrame->GetCompositorHitTestInfoWithoutPointerEvents(aBuilder);
3024 aBuilder->SetInheritedCompositorHitTestInfo(info);
3025}
3026
3027/**
3028 * True if aDescendant participates the context aAncestor participating.
3029 */
3030static bool FrameParticipatesIn3DContext(nsIFrame* aAncestor,
3031 nsIFrame* aDescendant) {
3032 MOZ_ASSERT(aAncestor != aDescendant)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aAncestor != aDescendant)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aAncestor != aDescendant))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("aAncestor != aDescendant"
, "./../../../layout/generic/nsIFrame.cpp", 3032); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aAncestor != aDescendant" ")"); do { MOZ_CrashSequence
(__null, 3032); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3033 MOZ_ASSERT(aAncestor->GetContent() != aDescendant->GetContent())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aAncestor->GetContent() != aDescendant->GetContent
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aAncestor->GetContent() != aDescendant->GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aAncestor->GetContent() != aDescendant->GetContent()"
, "./../../../layout/generic/nsIFrame.cpp", 3033); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aAncestor->GetContent() != aDescendant->GetContent()"
")"); do { MOZ_CrashSequence(__null, 3033); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3034 MOZ_ASSERT(aAncestor->Extend3DContext())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aAncestor->Extend3DContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aAncestor->Extend3DContext
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aAncestor->Extend3DContext()", "./../../../layout/generic/nsIFrame.cpp"
, 3034); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAncestor->Extend3DContext()"
")"); do { MOZ_CrashSequence(__null, 3034); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3035
3036 nsIFrame* ancestor = aAncestor->FirstContinuation();
3037 MOZ_ASSERT(ancestor->IsPrimaryFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ancestor->IsPrimaryFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(ancestor->IsPrimaryFrame(
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("ancestor->IsPrimaryFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 3037); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ancestor->IsPrimaryFrame()"
")"); do { MOZ_CrashSequence(__null, 3037); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3038
3039 nsIFrame* frame;
3040 for (frame = aDescendant->GetClosestFlattenedTreeAncestorPrimaryFrame();
3041 frame && ancestor != frame;
3042 frame = frame->GetClosestFlattenedTreeAncestorPrimaryFrame()) {
3043 if (!frame->Extend3DContext()) {
3044 return false;
3045 }
3046 }
3047
3048 MOZ_ASSERT(frame == ancestor)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame == ancestor)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(frame == ancestor))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("frame == ancestor"
, "./../../../layout/generic/nsIFrame.cpp", 3048); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "frame == ancestor" ")"); do { MOZ_CrashSequence
(__null, 3048); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3049 return true;
3050}
3051
3052static bool ItemParticipatesIn3DContext(nsIFrame* aAncestor,
3053 nsDisplayItem* aItem) {
3054 auto type = aItem->GetType();
3055 const bool isContainer = type == DisplayItemType::TYPE_WRAP_LIST ||
3056 type == DisplayItemType::TYPE_CONTAINER;
3057
3058 if (isContainer && aItem->GetChildren()->Length() == 1) {
3059 // If the wraplist has only one child item, use the type of that item.
3060 type = aItem->GetChildren()->GetBottom()->GetType();
3061 }
3062
3063 if (type != DisplayItemType::TYPE_TRANSFORM &&
3064 type != DisplayItemType::TYPE_PERSPECTIVE) {
3065 return false;
3066 }
3067 nsIFrame* transformFrame = aItem->Frame();
3068 if (aAncestor->GetContent() == transformFrame->GetContent()) {
3069 return true;
3070 }
3071 return FrameParticipatesIn3DContext(aAncestor, transformFrame);
3072}
3073
3074static void WrapSeparatorTransform(nsDisplayListBuilder* aBuilder,
3075 nsIFrame* aFrame,
3076 nsDisplayList* aNonParticipants,
3077 nsDisplayList* aParticipants, int aIndex,
3078 nsDisplayItem** aSeparator) {
3079 if (aNonParticipants->IsEmpty()) {
3080 return;
3081 }
3082
3083 nsDisplayTransform* item = MakeDisplayItemWithIndex<nsDisplayTransform>(
3084 aBuilder, aFrame, aIndex, aNonParticipants, aBuilder->GetVisibleRect());
3085
3086 if (*aSeparator == nullptr && item) {
3087 *aSeparator = item;
3088 }
3089
3090 aParticipants->AppendToTop(item);
3091}
3092
3093static bool HitTestsCapturedElementsAtLivePosition(nsPresContext* aPc) {
3094 switch (StaticPrefs::dom_viewTransitions_hit_testing()) {
3095 case 0:
3096 return false;
3097 case 1:
3098 return true;
3099 default:
3100 return aPc->IsChrome();
3101 }
3102}
3103
3104// Try to compute a clip rect to bound the contents of the mask item
3105// that will be built for |aMaskedFrame|. If we're not able to compute
3106// one, return an empty Maybe.
3107// The returned clip rect, if there is one, is relative to |aMaskedFrame|.
3108// Bug 1958124: If this is inlined in
3109// nsIFrame::BuildDisplayListForStackingContext on Win32, its variables enlarge
3110// that function's stack frame, which is on a deeply recursive path that is
3111// already up against the stack limit. Only masked frames reach this code, so
3112// never inlining it on Win32 costs us nothing.
3113#if defined(XP_WIN) && !defined(_WIN64)
3114MOZ_NEVER_INLINE__attribute__((noinline))
3115#endif
3116static Maybe<nsRect> ComputeClipForMaskItem(
3117 nsDisplayListBuilder* aBuilder, nsIFrame* aMaskedFrame,
3118 const SVGUtils::MaskUsage& aMaskUsage) {
3119 const nsStyleSVGReset* svgReset = aMaskedFrame->StyleSVGReset();
3120
3121 nsPoint offsetToUserSpace =
3122 nsLayoutUtils::ComputeOffsetToUserSpace(aBuilder, aMaskedFrame);
3123 int32_t devPixelRatio = aMaskedFrame->PresContext()->AppUnitsPerDevPixel();
3124 gfxPoint devPixelOffsetToUserSpace =
3125 nsLayoutUtils::PointToGfxPoint(offsetToUserSpace, devPixelRatio);
3126 CSSToLayoutDeviceScale cssToDevScale =
3127 aMaskedFrame->PresContext()->CSSToDevPixelScale();
3128
3129 nsPoint toReferenceFrame;
3130 aBuilder->FindReferenceFrameFor(aMaskedFrame, &toReferenceFrame);
3131
3132 Maybe<gfxRect> combinedClip;
3133 if (aMaskUsage.ShouldApplyBasicShapeOrPath()) {
3134 Maybe<Rect> result =
3135 CSSClipPathInstance::GetBoundingRectForBasicShapeOrPathClip(
3136 aMaskedFrame, svgReset->mClipPath);
3137 if (result) {
3138 combinedClip = Some(ThebesRect(*result));
3139 }
3140 } else if (aMaskUsage.ShouldApplyClipPath()) {
3141 nsIFrame* firstFrame =
3142 nsLayoutUtils::FirstContinuationOrIBSplitSibling(aMaskedFrame);
3143 SVGClipPathFrame* clipPathFrame = nullptr;
3144 SVGObserverUtils::GetAndObserveClipPath(firstFrame, &clipPathFrame);
3145 MOZ_ASSERT(clipPathFrame, "ShouldApplyClipPath needs a clip path")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(clipPathFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(clipPathFrame))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("clipPathFrame" " ("
"ShouldApplyClipPath needs a clip path" ")", "./../../../layout/generic/nsIFrame.cpp"
, 3145); AnnotateMozCrashReason("MOZ_ASSERT" "(" "clipPathFrame"
") (" "ShouldApplyClipPath needs a clip path" ")"); do { MOZ_CrashSequence
(__null, 3145); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3146 gfxRect result = clipPathFrame
3147 ->GetBBoxForClipPathFrame(
3148 clipPathFrame->GetClipPathTransform(aMaskedFrame))
3149 .ToThebesRect();
3150 combinedClip = Some(
3151 ThebesRect((CSSRect::FromUnknownRect(ToRect(result)) * cssToDevScale)
3152 .ToUnknownRect()));
3153 // The clip path is in the user space of the first continuation, which is
3154 // where SVGIntegrationUtils paints it too.
3155 if (firstFrame != aMaskedFrame) {
3156 devPixelOffsetToUserSpace = nsLayoutUtils::PointToGfxPoint(
3157 nsLayoutUtils::ComputeOffsetToUserSpace(aBuilder, firstFrame),
3158 devPixelRatio);
3159 }
3160 } else {
3161 // The code for this case is adapted from ComputeMaskGeometry().
3162
3163 nsRect borderArea(toReferenceFrame, aMaskedFrame->GetSize());
3164 borderArea -= offsetToUserSpace;
3165
3166 // Use an infinite dirty rect to pass into nsCSSRendering::
3167 // GetImageLayerClip() because we don't have an actual dirty rect to
3168 // pass in. This is fine because the only time GetImageLayerClip() will
3169 // not intersect the incoming dirty rect with something is in the "NoClip"
3170 // case, and we handle that specially.
3171 nsRect dirtyRect(nscoord_MIN / 2, nscoord_MIN / 2, nscoord_MAX,
3172 nscoord_MAX);
3173
3174 nsIFrame* firstFrame =
3175 nsLayoutUtils::FirstContinuationOrIBSplitSibling(aMaskedFrame);
3176 nsTArray<SVGMaskFrame*> maskFrames;
3177 // XXX check return value?
3178 SVGObserverUtils::GetAndObserveMasks(firstFrame, &maskFrames);
3179
3180 for (uint32_t i = 0; i < maskFrames.Length(); ++i) {
3181 gfxRect clipArea;
3182 if (maskFrames[i]) {
3183 clipArea = maskFrames[i]->GetMaskArea(aMaskedFrame);
3184 clipArea = ThebesRect(
3185 (CSSRect::FromUnknownRect(ToRect(clipArea)) * cssToDevScale)
3186 .ToUnknownRect());
3187 } else {
3188 const auto& layer = svgReset->mMask.mLayers[i];
3189 if (layer.mClip == StyleBackgroundClip::NoClip) {
3190 return Nothing();
3191 }
3192
3193 nsCSSRendering::ImageLayerClipState clipState;
3194 nsCSSRendering::GetImageLayerClip(
3195 layer, aMaskedFrame, *aMaskedFrame->StyleBorder(), borderArea,
3196 dirtyRect, false /* aWillPaintBorder */, devPixelRatio, &clipState);
3197 clipArea = clipState.mDirtyRectInDevPx;
3198 }
3199 combinedClip = UnionMaybeRects(combinedClip, Some(clipArea));
3200 }
3201 }
3202 if (combinedClip) {
3203 // Convert to user space.
3204 *combinedClip += devPixelOffsetToUserSpace;
3205
3206 // Round the clip out. In FrameLayerBuilder we round clips to nearest
3207 // pixels, and if we have a really thin clip here, that can cause the
3208 // clip to become empty if we didn't round out here.
3209 // The rounding happens in coordinates that are relative to the reference
3210 // frame, which matches what FrameLayerBuilder does.
3211 combinedClip->RoundOut();
3212
3213 // Convert to app units.
3214 nsRect result =
3215 nsLayoutUtils::RoundGfxRectToAppRect(*combinedClip, devPixelRatio);
3216
3217 // The resulting clip is relative to the reference frame, but the caller
3218 // expects it to be relative to the masked frame, so adjust it.
3219 result -= toReferenceFrame;
3220 return Some(result);
3221 }
3222 return Nothing();
3223}
3224
3225struct AutoCheckBuilder {
3226 explicit AutoCheckBuilder(nsDisplayListBuilder* aBuilder)
3227 : mBuilder(aBuilder) {
3228 aBuilder->Check();
3229 }
3230
3231 ~AutoCheckBuilder() { mBuilder->Check(); }
3232
3233 nsDisplayListBuilder* mBuilder;
3234};
3235
3236/**
3237 * Tries to reuse a top-level stacking context item from the previous paint.
3238 * Returns true if an item was reused, otherwise false.
3239 */
3240bool TryToReuseStackingContextItem(nsDisplayListBuilder* aBuilder,
3241 nsDisplayList* aList, nsIFrame* aFrame) {
3242 if (!aBuilder->IsForPainting() || !aBuilder->IsPartialUpdate() ||
3243 aBuilder->InInvalidSubtree()) {
3244 return false;
3245 }
3246
3247 if (aFrame->IsFrameModified() || aFrame->HasModifiedDescendants()) {
3248 return false;
3249 }
3250
3251 auto& items = aFrame->DisplayItems();
3252 auto* res = std::find_if(
3253 items.begin(), items.end(),
3254 [](nsDisplayItem* aItem) { return aItem->IsPreProcessed(); });
3255
3256 if (res == items.end()) {
3257 return false;
3258 }
3259
3260 nsDisplayItem* container = *res;
3261 MOZ_ASSERT(container->Frame() == aFrame)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(container->Frame() == aFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(container->Frame() == aFrame
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"container->Frame() == aFrame", "./../../../layout/generic/nsIFrame.cpp"
, 3261); AnnotateMozCrashReason("MOZ_ASSERT" "(" "container->Frame() == aFrame"
")"); do { MOZ_CrashSequence(__null, 3261); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3262 DL_LOGD("RDL - Found SC item %p (%s) (frame: %p)", container,do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "RDL - Found SC item %p (%s) (frame: %p)",
container, container->Name(), container->Frame()); } }
while (0)
3263 container->Name(), container->Frame())do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "RDL - Found SC item %p (%s) (frame: %p)",
container, container->Name(), container->Frame()); } }
while (0)
;
3264
3265 aList->AppendToTop(container);
3266 aBuilder->ReuseDisplayItem(container);
3267 return true;
3268}
3269
3270void nsIFrame::BuildDisplayListForStackingContext(
3271 nsDisplayListBuilder* aBuilder, nsDisplayList* aList,
3272 bool* aCreatedContainerItem) {
3273#ifdef DEBUG1
3274 DL_LOGV("BuildDisplayListForStackingContext (%p) <", this)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "BuildDisplayListForStackingContext (%p) <"
, this); } } while (0)
;
3275 ScopeExit e(
3276 [this]() { DL_LOGV("> BuildDisplayListForStackingContext (%p)", this)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "> BuildDisplayListForStackingContext (%p)"
, this); } } while (0)
; });
3277#endif
3278
3279 AutoCheckBuilder check(aBuilder);
3280
3281 if (aBuilder->IsReusingStackingContextItems() &&
3282 TryToReuseStackingContextItem(aBuilder, aList, this)) {
3283 if (aCreatedContainerItem) {
3284 *aCreatedContainerItem = true;
3285 }
3286 return;
3287 }
3288
3289 if (HasAnyStateBits(NS_FRAME_TOO_DEEP_IN_FRAME_TREE |
3290 NS_FRAME_IS_NONDISPLAY)) {
3291 return;
3292 }
3293
3294 const auto& style = *Style();
3295 const nsStyleDisplay* disp = style.StyleDisplay();
3296 const nsStyleEffects* effects = style.StyleEffects();
3297 EffectSet* effectSetForOpacity =
3298 EffectSet::GetForFrame(this, nsCSSPropertyIDSet::OpacityProperties());
3299 // We can stop right away if this is a zero-opacity stacking context and
3300 // we're painting, and we're not animating opacity.
3301 bool needHitTestInfo = aBuilder->BuildCompositorHitTestInfo() &&
3302 Style()->PointerEvents() != StylePointerEvents::None;
3303 bool opacityItemForEventsOnly = false;
3304 if (effects->IsTransparent() && aBuilder->IsForPainting() &&
3305 !(disp->mWillChange.bits & StyleWillChangeBits::OPACITY) &&
3306 !nsLayoutUtils::HasAnimationOfPropertySet(
3307 this, nsCSSPropertyIDSet::OpacityProperties(), effectSetForOpacity)) {
3308 if (needHitTestInfo) {
3309 opacityItemForEventsOnly = true;
3310 } else {
3311 return;
3312 }
3313 }
3314
3315 // Root gets handled in
3316 // ScrollContainerFrame::MaybeCreateTopLayerAndWrapRootItems.
3317 const bool capturedByViewTransition =
3318 HasAnyStateBits(NS_FRAME_CAPTURED_IN_VIEW_TRANSITION) &&
3319 !style.IsRootElementStyle();
3320
3321 // Do not need to build the display list of the captured frames for event
3322 // delivery (i.e. to determine if this frame is under the mouse position).
3323 //
3324 // Per spec, hit-testing is skipped because the element’s DOM location does
3325 // not correspond to where its contents are rendered, so we could just skip
3326 // the building of the display list for these frames, and then these APIs,
3327 // e.g. elementFromPoint(), will skip these frames as well.
3328 // https://drafts.csswg.org/css-view-transitions-1/#view-transition-stacking-layer
3329 //
3330 // dom.viewTransitions.hit-testing can make us hit-test them at their live
3331 // position instead, which chrome documents do by default so the browser UI
3332 // stays interactive while it animates. See
3333 // https://github.com/w3c/csswg-drafts/issues/10930
3334 if (capturedByViewTransition && aBuilder->IsForEventDelivery() &&
3335 !HitTestsCapturedElementsAtLivePosition(PresContext())) {
3336 return;
3337 }
3338
3339 // For preserves3d, use the dirty rect already installed on the
3340 // builder, since aDirtyRect maybe distorted for transforms along
3341 // the chain.
3342 nsRect visibleRect = aBuilder->GetVisibleRect();
3343 nsRect dirtyRect = aBuilder->GetDirtyRect();
3344
3345 // We build an opacity item if it's not going to be drawn by SVG content.
3346 // We could in principle skip creating an nsDisplayOpacity item if
3347 // nsDisplayOpacity::NeedsActiveLayer returns false and usingSVGEffects is
3348 // true (the nsDisplayFilter/nsDisplayMasksAndClipPaths could handle the
3349 // opacity). Since SVG has perf issues where we sometimes spend a lot of
3350 // time creating display list items that might be helpful. We'd need to
3351 // restore our mechanism to do that (changed in bug 1482403), and we'd
3352 // need to invalidate the frame if the value that would be return from
3353 // NeedsActiveLayer was to change, which we don't currently do.
3354 const bool useOpacity =
3355 HasVisualOpacity(disp, effects, effectSetForOpacity) &&
3356 !SVGUtils::CanOptimizeOpacity(this);
3357
3358 const bool isTransformed = IsTransformed();
3359 const bool hasPerspective = isTransformed && HasPerspective();
3360 const bool extend3DContext =
3361 Extend3DContext(disp, effects, effectSetForOpacity);
3362 const bool combines3DTransformWithAncestors =
3363 (extend3DContext || isTransformed) && Combines3DTransformWithAncestors();
3364
3365 UniquePtr<nsDisplayListBuilder::AutoPreserves3DContext>
3366 autoPreserves3DContext;
3367 if (extend3DContext && !combines3DTransformWithAncestors) {
3368 // Start a new preserves3d context to keep informations on
3369 // nsDisplayListBuilder.
3370 autoPreserves3DContext =
3371 std::make_unique<nsDisplayListBuilder::AutoPreserves3DContext>(
3372 aBuilder);
3373 // Save dirty rect on the builder to avoid being distorted for
3374 // multiple transforms along the chain.
3375 aBuilder->SavePreserves3DRect();
3376
3377 // We rebuild everything within preserve-3d and don't try
3378 // to retain, so override the dirty rect now.
3379 if (aBuilder->IsRetainingDisplayList()) {
3380 dirtyRect = visibleRect;
3381 aBuilder->SetDisablePartialUpdates(true);
3382 }
3383 }
3384
3385 AutoTrackStackingContextBits stackingContextTracker(*aBuilder);
3386 aBuilder->ClearStackingContextBits();
3387
3388 nsRect visibleRectOutsideTransform = visibleRect;
3389 nsDisplayTransform::PrerenderInfo prerenderInfo;
3390 bool inTransform = aBuilder->IsInTransform();
3391 if (isTransformed) {
3392 prerenderInfo = nsDisplayTransform::ShouldPrerenderTransformedContent(
3393 aBuilder, this, &visibleRect);
3394
3395 switch (prerenderInfo.mDecision) {
3396 case nsDisplayTransform::PrerenderDecision::Full:
3397 case nsDisplayTransform::PrerenderDecision::Partial:
3398 dirtyRect = visibleRect;
3399 break;
3400 case nsDisplayTransform::PrerenderDecision::No: {
3401 // If we didn't prerender an animated frame in a preserve-3d context,
3402 // then we want disable async animations for the rest of the preserve-3d
3403 // (especially ancestors).
3404 if ((extend3DContext || combines3DTransformWithAncestors) &&
3405 prerenderInfo.mHasAnimations) {
3406 aBuilder->SavePreserves3DAllowAsyncAnimation(false);
3407 }
3408
3409 const nsRect overflow = InkOverflowRectRelativeToSelf();
3410 if (overflow.IsEmpty() && !extend3DContext) {
3411 return;
3412 }
3413
3414 // If we're in preserve-3d then grab the dirty rect that was given to
3415 // the root and transform using the combined transform.
3416 if (combines3DTransformWithAncestors) {
3417 visibleRect = dirtyRect = aBuilder->GetPreserves3DRect();
3418 }
3419
3420 const float appPerDev = PresContext()->AppUnitsPerDevPixel();
3421 uint32_t flags = nsDisplayTransform::kTransformRectFlags &
3422 ~nsDisplayTransform::OFFSET_BY_ORIGIN;
3423 if (!hasPerspective) {
3424 flags &= ~nsDisplayTransform::INCLUDE_PERSPECTIVE;
3425 }
3426 if (!combines3DTransformWithAncestors) {
3427 flags &= ~nsDisplayTransform::INCLUDE_PRESERVE3D_ANCESTORS;
3428 }
3429 auto transform = nsDisplayTransform::GetResultingTransformMatrix(
3430 this, nsPoint(), appPerDev, flags);
3431 nsRect untransformedDirtyRect;
3432 if (nsDisplayTransform::UntransformRect(dirtyRect, overflow, transform,
3433 appPerDev,
3434 &untransformedDirtyRect)) {
3435 dirtyRect = untransformedDirtyRect;
3436 nsDisplayTransform::UntransformRect(visibleRect, overflow, transform,
3437 appPerDev, &visibleRect);
3438 } else {
3439 // This should only happen if the transform is singular, in which case
3440 // nothing is visible anyway
3441 dirtyRect.SetEmpty();
3442 visibleRect.SetEmpty();
3443 }
3444 }
3445 }
3446 inTransform = true;
3447 } else if (IsFixedPosContainingBlock()) {
3448 // Restict the building area to the overflow rect for these frames, since
3449 // RetainedDisplayListBuilder uses it to know if the size of the stacking
3450 // context changed.
3451 visibleRect.IntersectRect(visibleRect, InkOverflowRect());
3452 dirtyRect.IntersectRect(dirtyRect, InkOverflowRect());
3453 }
3454
3455 bool hasOverrideDirtyRect = false;
3456 // If we're doing a partial build, we're not invalid and we're capable
3457 // of having an override building rect (stacking context and fixed pos
3458 // containing block), then we should assume we have one.
3459 // Either we have an explicit one, or nothing in our subtree changed and
3460 // we have an implicit empty rect.
3461 //
3462 // These conditions should match |CanStoreDisplayListBuildingRect()| in
3463 // RetainedDisplayListBuilder.cpp
3464 if (!aBuilder->IsReusingStackingContextItems() &&
3465 aBuilder->IsPartialUpdate() && !aBuilder->InInvalidSubtree() &&
3466 !IsFrameModified() && IsFixedPosContainingBlock() &&
3467 !GetPrevContinuation() && !GetNextContinuation()) {
3468 dirtyRect = nsRect();
3469 if (HasOverrideDirtyRegion()) {
3470 nsDisplayListBuilder::DisplayListBuildingData* data =
3471 GetProperty(nsDisplayListBuilder::DisplayListBuildingRect());
3472 if (data) {
3473 dirtyRect = data->mDirtyRect.Intersect(visibleRect);
3474 hasOverrideDirtyRect = true;
3475 }
3476 }
3477 }
3478
3479 const bool usingFilter = effects->HasFilters() && !style.IsRootElementStyle();
3480 const SVGUtils::MaskUsage maskUsage =
3481 SVGUtils::DetermineMaskUsage(this, false);
3482 const bool usingMask = maskUsage.UsingMaskOrClipPath();
3483 const bool usingSVGEffects = usingFilter || usingMask;
3484
3485 const nsRect visibleRectOutsideSVGEffects = visibleRect;
3486 nsDisplayList hoistedScrollInfoItemsStorage;
3487 if (usingSVGEffects) {
3488 dirtyRect =
3489 SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, dirtyRect);
3490 visibleRect =
3491 SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, visibleRect);
3492 aBuilder->EnterSVGEffectsContents(this, &hoistedScrollInfoItemsStorage);
3493 }
3494
3495 const bool useStickyPosition =
3496 disp->mPosition == StylePositionProperty::Sticky;
3497 bool shouldFlattenStickyItem = true;
3498
3499 const bool useFixedPosition =
3500 disp->mPosition == StylePositionProperty::Fixed &&
3501 aBuilder->IsPaintingToWindow() && !IsMenuPopupFrame() &&
3502 (DisplayPortUtils::IsFixedPosFrameInDisplayPort(this) ||
3503 BuilderHasScrolledClip(aBuilder));
3504
3505 if (capturedByViewTransition) {
3506 // Captured view transition elements must have their frames built regardless
3507 // of onscreen visibility so they can be snapshotted, since the snapshot can
3508 // itself be in view. We set visibleRect and dirtyRect to ensure the frame
3509 // and its descendants are painted.
3510 visibleRect = InkOverflowRectRelativeToSelf();
3511 dirtyRect = InkOverflowRectRelativeToSelf();
3512 }
3513
3514 nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
3515 aBuilder, this, visibleRect, dirtyRect, isTransformed);
3516
3517 UpdateCurrentHitTestInfo(aBuilder, this);
3518
3519 // Depending on the effects that are applied to this frame, we can create
3520 // multiple container display items and wrap them around our contents.
3521 // This enum lists all the potential container display items, in the order
3522 // outside to inside.
3523 enum class ContainerItemType : uint8_t {
3524 None = 0,
3525 FixedPosition,
3526 OwnLayerForTransformWithRoundedClip,
3527 Perspective,
3528 Transform,
3529 Filter,
3530 ViewTransitionCapture,
3531 };
3532
3533 // NOTE(emilio): The order of these RAII objects is quite subtle.
3534 nsDisplayListBuilder::AutoEnterViewTransitionCapture
3535 inViewTransitionCaptureSetter(aBuilder, capturedByViewTransition);
3536 RefPtr<const ActiveScrolledRoot> stickyASR = nullptr;
3537 nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(aBuilder);
3538 if (aBuilder->IsInViewTransitionCapture()) {
3539 // View transition contents shouldn't scroll along our ASR. They get
3540 // "pulled out" of the rendering (or when they don't, you can't scroll
3541 // anyways).
3542 asrSetter.SetCurrentActiveScrolledRoot(nullptr);
3543 }
3544 DisplayListClipState::AutoSaveRestore stickyItemClipState(aBuilder);
3545 if (useStickyPosition) {
3546 StickyScrollContainer* stickyScrollContainer =
3547 StickyScrollContainer::GetOrCreateForFrame(this);
3548 if (stickyScrollContainer && aBuilder->IsPaintingToWindow()) {
3549 if (!aBuilder->IsInViewTransitionCapture() &&
3550 stickyScrollContainer->ScrollContainer()
3551 ->IsMaybeAsynchronouslyScrolled()) {
3552 shouldFlattenStickyItem = false;
3553 }
3554 // The flattening decision stored on the StickyScrollContainer is shared
3555 // by every sticky frame that it scrolls, so only store decisions which
3556 // apply to all of them. Being inside a view transition capture flattens
3557 // just the captured frame (which gets no display item at all), so
3558 // storing that decision would incorrectly flatten the container's other
3559 // sticky frames as well.
3560 if (!aBuilder->IsInViewTransitionCapture()) {
3561 stickyScrollContainer->SetShouldFlatten(shouldFlattenStickyItem);
3562 }
3563 }
3564
3565 if (shouldFlattenStickyItem) {
3566 stickyASR = aBuilder->CurrentActiveScrolledRoot();
3567 } else {
3568 stickyASR = aBuilder->GetOrCreateActiveScrolledRoot(
3569 aBuilder->CurrentActiveScrolledRoot(), this,
3570 ActiveScrolledRoot::ASRKind::Sticky);
3571 asrSetter.SetCurrentActiveScrolledRoot(stickyASR);
3572 stickyItemClipState.MaybeRemoveDisplayportClip();
3573 }
3574 }
3575
3576 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
3577
3578 auto cssClip = GetClipPropClipRect(disp, effects, GetSize());
3579 auto ApplyClipProp = [&](DisplayListClipState::AutoSaveRestore& aClipState) {
3580 if (!cssClip) {
3581 return;
3582 }
3583 nsPoint offset = aBuilder->GetCurrentFrameOffsetToReferenceFrame();
3584 aBuilder->IntersectDirtyRect(*cssClip);
3585 aBuilder->IntersectVisibleRect(*cssClip);
3586 aClipState.ClipContentDescendants(*cssClip + offset);
3587 };
3588
3589 // The CSS clip property is effectively inside the transform, but outside the
3590 // filters. So if we're not transformed we can apply it just here for
3591 // simplicity, instead of on each of the places that handle clipCapturedBy.
3592 DisplayListClipState::AutoSaveRestore untransformedCssClip(aBuilder);
3593 if (!isTransformed) {
3594 ApplyClipProp(untransformedCssClip);
3595 }
3596
3597 // If there is a current clip, then depending on the container items we
3598 // create, different things can happen to it. Some container items simply
3599 // propagate the clip to their children and aren't clipped themselves.
3600 // But other container items, especially those that establish a different
3601 // geometry for their contents (e.g. transforms), capture the clip on
3602 // themselves and unset the clip for their contents. If we create more than
3603 // one of those container items, the clip will be captured on the outermost
3604 // one and the inner container items will be unclipped.
3605 ContainerItemType clipCapturedBy = ContainerItemType::None;
3606 if (capturedByViewTransition) {
3607 clipCapturedBy = isTransformed ? ContainerItemType::Transform
3608 : ContainerItemType::ViewTransitionCapture;
3609 } else if (useFixedPosition) {
3610 clipCapturedBy = ContainerItemType::FixedPosition;
3611 } else if (isTransformed) {
3612 const DisplayItemClipChain* currentClip =
3613 aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
3614 if ((hasPerspective || extend3DContext) &&
3615 (currentClip && currentClip->HasRoundedCorners())) {
3616 // If we're creating an nsDisplayTransform item that is going to combine
3617 // its transform with its children (preserve-3d or perspective), then we
3618 // can't have an intermediate surface. Mask layers force an intermediate
3619 // surface, so if we're going to need both then create a separate
3620 // wrapping layer for the mask.
3621 clipCapturedBy = ContainerItemType::OwnLayerForTransformWithRoundedClip;
3622 } else if (hasPerspective) {
3623 clipCapturedBy = ContainerItemType::Perspective;
3624 } else {
3625 clipCapturedBy = ContainerItemType::Transform;
3626 }
3627 } else if (usingFilter) {
3628 clipCapturedBy = ContainerItemType::Filter;
3629 }
3630
3631 DisplayListClipState::AutoSaveRestore clipState(aBuilder);
3632 if (clipCapturedBy != ContainerItemType::None) {
3633 clipState.Clear();
3634 }
3635
3636 DisplayListClipState::AutoSaveRestore transformedCssClip(aBuilder);
3637 if (isTransformed) {
3638 // FIXME(emilio, bug 1525159): In the case we have a both a transform _and_
3639 // filters, this clips the input to the filters as well, which is not
3640 // correct (clipping by the `clip` property is supposed to happen after
3641 // applying the filter effects, per [1].
3642 //
3643 // This is not a regression though, since we used to do that anyway before
3644 // bug 1514384, and even without the transform we get it wrong.
3645 //
3646 // [1]: https://drafts.fxtf.org/css-masking/#placement
3647 ApplyClipProp(transformedCssClip);
3648 }
3649
3650 uint32_t numActiveScrollframesEncounteredBefore =
3651 aBuilder->GetNumActiveScrollframesEncountered();
3652
3653 nsDisplayListCollection set(aBuilder);
3654 Maybe<nsRect> clipForMask;
3655
3656 {
3657 DisplayListClipState::AutoSaveRestore nestedClipState(aBuilder);
3658 nsDisplayListBuilder::AutoInTransformSetter inTransformSetter(aBuilder,
3659 inTransform);
3660 nsDisplayListBuilder::AutoEnterFilter filterASRSetter(aBuilder,
3661 usingFilter);
3662 nsDisplayListBuilder::AutoInEventsOnly inEventsSetter(
3663 aBuilder, opacityItemForEventsOnly);
3664
3665 DisplayListClipState::AutoSaveRestore stickyItemNestedClipState(aBuilder);
3666 if (useStickyPosition && !shouldFlattenStickyItem) {
3667 stickyItemNestedClipState.MaybeRemoveDisplayportClip();
3668 }
3669
3670 // If we have a mask, compute a clip to bound the masked content.
3671 // This is necessary in case the content moves with an ancestor
3672 // ASR of the mask.
3673 // Don't do this if we also have a filter, because then the clip
3674 // would be applied before the filter, violating
3675 // https://www.w3.org/TR/filter-effects-1/#placement.
3676 // Filters are a containing block for fixed and absolute descendants,
3677 // so the masked content cannot move with an ancestor ASR.
3678 if (usingMask && !usingFilter) {
3679 clipForMask = ComputeClipForMaskItem(aBuilder, this, maskUsage);
3680 if (clipForMask) {
3681 aBuilder->IntersectDirtyRect(*clipForMask);
3682 aBuilder->IntersectVisibleRect(*clipForMask);
3683 nestedClipState.ClipContentDescendants(
3684 *clipForMask + aBuilder->GetCurrentFrameOffsetToReferenceFrame());
3685 }
3686 }
3687
3688 // extend3DContext also guarantees that applyAbsPosClipping and
3689 // usingSVGEffects are false We only modify the preserve-3d rect if we are
3690 // the top of a preserve-3d heirarchy
3691 if (extend3DContext) {
3692 // Mark these first so MarkAbsoluteFramesForDisplayList knows if we are
3693 // going to be forced to descend into frames.
3694 aBuilder->MarkPreserve3DFramesForDisplayList(this);
3695 }
3696
3697 aBuilder->AdjustWindowDraggingRegion(this);
3698
3699 MarkAbsoluteFramesForDisplayList(aBuilder);
3700 aBuilder->Check();
3701 BuildDisplayList(aBuilder, set);
3702 // mBuiltDisplayList is observed only by painting-related tests (reftests
3703 // and paint-regression mochitests via nsIDOMWindowUtils), so record the
3704 // build only for painting display lists, not hit-testing, frame
3705 // visibility, or glyph-mask builds.
3706 if (aBuilder->IsForPainting()) {
3707 SetBuiltDisplayList(true);
3708 }
3709 aBuilder->Check();
3710 aBuilder->DisplayCaret(this, set.Outlines());
3711
3712 // Blend modes are a real pain for retained display lists. We build a blend
3713 // container item if the built list contains any blend mode items within
3714 // the current stacking context. This can change without an invalidation
3715 // to the stacking context frame, or the blend mode frame (e.g. by moving
3716 // an intermediate frame).
3717 // When we gain/remove a blend container item, we need to mark this frame
3718 // as invalid and have the full display list for merging to track
3719 // the change correctly.
3720 // It seems really hard to track this in advance, as the bookkeeping
3721 // required to note which stacking contexts have blend descendants
3722 // is complex and likely to be buggy.
3723 // Instead we're doing the sad thing, detecting it afterwards, and just
3724 // repeating display list building if it changed.
3725 // We have to repeat building for the entire display list (or at least
3726 // the outer stacking context), since we need to mark this frame as invalid
3727 // to remove any existing content that isn't wrapped in the blend container,
3728 // and then we need to build content infront/behind the blend container
3729 // to get correct positioning during merging.
3730 if (aBuilder->ContainsBlendMode() && aBuilder->IsRetainingDisplayList()) {
3731 if (aBuilder->IsPartialUpdate()) {
3732 aBuilder->SetPartialBuildFailed(true);
3733 } else {
3734 aBuilder->SetDisablePartialUpdates(true);
3735 }
3736 }
3737 }
3738
3739 if (aBuilder->IsBackgroundOnly()) {
3740 set.BlockBorderBackgrounds()->DeleteAll(aBuilder);
3741 set.Floats()->DeleteAll(aBuilder);
3742 set.Content()->DeleteAll(aBuilder);
3743 set.PositionedDescendants()->DeleteAll(aBuilder);
3744 set.Outlines()->DeleteAll(aBuilder);
3745 }
3746
3747 if (hasOverrideDirtyRect &&
3748 StaticPrefs::layout_display_list_show_rebuild_area()) {
3749 nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
3750 aBuilder, this,
3751 dirtyRect + aBuilder->GetCurrentFrameOffsetToReferenceFrame(),
3752 NS_RGBA(255, 0, 0, 64)((nscolor)(((64) << 24) | ((0) << 16) | ((0) <<
8) | (255)))
);
3753 if (color) {
3754 color->SetOverrideZIndex(INT32_MAX(2147483647));
3755 set.PositionedDescendants()->AppendToTop(color);
3756 }
3757 }
3758
3759 nsIContent* content = GetContent();
3760 if (!content) {
3761 content = PresContext()->Document()->GetRootElement();
3762 }
3763
3764 nsDisplayList resultList;
3765 set.SerializeWithCorrectZOrder(&resultList, content);
3766
3767 // Get the ASR to use for the container items that we create here.
3768 const ActiveScrolledRoot* containerItemASR = contASRTracker.GetContainerASR();
3769
3770 bool createdContainer = false;
3771 const StackingContextBits localIsolationReasons = [&] {
3772 auto reasons = StackingContextBits::None;
3773 if (!GetParent()) {
3774 // We don't need to isolate the root frame.
3775 return reasons;
3776 }
3777 // Elements with a view-transition name also form a backdrop-root. Same for
3778 // masks / clip-path.
3779 // See https://www.w3.org/TR/css-view-transitions-1/#named-and-transitioning
3780 // and https://github.com/w3c/csswg-drafts/issues/11772
3781 const bool hasViewTransitionName =
3782 style.StyleUIReset()->HasViewTransitionName() &&
3783 !style.IsRootElementStyle();
3784 if ((disp->mWillChange.bits & StyleWillChangeBits::BACKDROP_ROOT) ||
3785 hasViewTransitionName || usingMask) {
3786 reasons |= StackingContextBits::ContainsBackdropFilter;
3787 }
3788 return reasons;
3789 }();
3790
3791 StackingContextBits currentIsolationReasons =
3792 localIsolationReasons & aBuilder->GetStackingContextBits();
3793 bool isolated = false;
3794 auto MarkAsIsolated = [&] {
3795 isolated = true;
3796 currentIsolationReasons = StackingContextBits::None;
3797 };
3798 auto ShouldForceIsolation = [&] {
3799 if (localIsolationReasons == StackingContextBits::None) {
3800 return false;
3801 }
3802 bool force = currentIsolationReasons != StackingContextBits::None;
3803 MarkAsIsolated();
3804 return force;
3805 };
3806
3807 // If adding both a nsDisplayBlendContainer and a nsDisplayBlendMode to the
3808 // same list, the nsDisplayBlendContainer should be added first. This only
3809 // happens when the element creating this stacking context has mix-blend-mode
3810 // and also contains a child which has mix-blend-mode.
3811 // The nsDisplayBlendContainer must be added to the list first, so it does not
3812 // isolate the containing element blending as well.
3813 if (aBuilder->ContainsBlendMode()) {
3814 resultList.AppendToTop(nsDisplayBlendContainer::CreateForMixBlendMode(
3815 aBuilder, this, &resultList, containerItemASR,
3816 nsDisplayItem::ContainerASRType::AncestorOfContained));
3817 createdContainer = true;
3818 MarkAsIsolated();
3819 }
3820
3821 // NOTE: When changing this condition make sure to tweak ScrollContainerFrame
3822 // as well.
3823 const bool usingBackdropFilter = effects->HasBackdropFilters() &&
3824 IsVisibleForPainting() &&
3825 !style.IsRootElementStyle();
3826 if (usingBackdropFilter) {
3827 stackingContextTracker.AddToParent(
3828 StackingContextBits::ContainsBackdropFilter);
3829 nsRect backdropRect =
3830 GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
3831 resultList.AppendNewToTop<nsDisplayBackdropFilters>(
3832 aBuilder, this, &resultList, backdropRect, this);
3833 createdContainer = true;
3834 MarkAsIsolated();
3835 }
3836
3837 // If there are any SVG effects, wrap the list up in an SVG effects item
3838 // (which also handles CSS group opacity). Note that we create an SVG effects
3839 // item even if resultList is empty, since a filter can produce graphical
3840 // output even if the element being filtered wouldn't otherwise do so.
3841 if (usingSVGEffects) {
3842 MOZ_ASSERT(usingFilter || usingMask,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(usingFilter || usingMask)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(usingFilter || usingMask))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("usingFilter || usingMask"
" (" "Beside filter & mask/clip-path, what else effect do we have?"
")", "./../../../layout/generic/nsIFrame.cpp", 3843); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "usingFilter || usingMask" ") (" "Beside filter & mask/clip-path, what else effect do we have?"
")"); do { MOZ_CrashSequence(__null, 3843); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
3843 "Beside filter & mask/clip-path, what else effect do we have?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(usingFilter || usingMask)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(usingFilter || usingMask))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("usingFilter || usingMask"
" (" "Beside filter & mask/clip-path, what else effect do we have?"
")", "./../../../layout/generic/nsIFrame.cpp", 3843); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "usingFilter || usingMask" ") (" "Beside filter & mask/clip-path, what else effect do we have?"
")"); do { MOZ_CrashSequence(__null, 3843); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3844
3845 if (clipCapturedBy == ContainerItemType::Filter) {
3846 clipState.Restore();
3847 }
3848 // Revert to the post-filter dirty rect.
3849 aBuilder->SetVisibleRect(visibleRectOutsideSVGEffects);
3850
3851 // Skip all filter effects while generating glyph mask.
3852 if (usingFilter && !aBuilder->IsForGenerateGlyphMask()) {
3853 /* List now emptied, so add the new list to the top. */
3854 resultList.AppendNewToTop<nsDisplayFilters>(aBuilder, this, &resultList,
3855 this, usingBackdropFilter);
3856 createdContainer = true;
Value stored to 'createdContainer' is never read
3857 }
3858
3859 if (usingMask) {
3860 // The mask should move with aBuilder->CurrentActiveScrolledRoot(), so
3861 // that's the ASR we prefer to use for the mask item. However, we can
3862 // only do this if the mask if clipped with respect to that ASR, because
3863 // an item always needs to have finite bounds with respect to its ASR.
3864 // If we weren't able to compute a clip for the mask, we fall back to
3865 // using containerItemASR, which is the lowest common ancestor clip of
3866 // the mask's contents. That's not entirely correct, but it satisfies
3867 // the base requirement of the ASR system (that items have finite bounds
3868 // wrt. their ASR).
3869 const ActiveScrolledRoot* maskASR =
3870 clipForMask.isSome() ? aBuilder->CurrentActiveScrolledRoot()
3871 : containerItemASR;
3872 /* List now emptied, so add the new list to the top. */
3873 resultList.AppendNewToTop<nsDisplayMasksAndClipPaths>(
3874 aBuilder, this, &resultList, maskASR,
3875 clipForMask.isSome()
3876 ? nsDisplayItem::ContainerASRType::Constant
3877 : nsDisplayItem::ContainerASRType::AncestorOfContained,
3878 usingBackdropFilter, ShouldForceIsolation());
3879 createdContainer = true;
3880 }
3881
3882 // TODO(miko): We could probably create a wraplist here and avoid creating
3883 // it later in |BuildDisplayListForChild()|.
3884 createdContainer = false;
3885
3886 // Also add the hoisted scroll info items. We need those for APZ scrolling
3887 // because nsDisplayMasksAndClipPaths items can't build active layers.
3888 aBuilder->ExitSVGEffectsContents();
3889 resultList.AppendToTop(&hoistedScrollInfoItemsStorage);
3890 }
3891
3892 // If the list is non-empty and there is CSS group opacity without SVG
3893 // effects, wrap it up in an opacity item.
3894 if (useOpacity) {
3895 const bool needsActiveOpacityLayer =
3896 nsDisplayOpacity::NeedsActiveLayer(this);
3897 resultList.AppendNewToTop<nsDisplayOpacity>(
3898 aBuilder, this, &resultList, containerItemASR,
3899 nsDisplayItem::ContainerASRType::AncestorOfContained,
3900 opacityItemForEventsOnly, needsActiveOpacityLayer, usingBackdropFilter,
3901 ShouldForceIsolation());
3902 createdContainer = true;
3903 }
3904
3905 // We build nsDisplayViewTransitionCapture here, and then use
3906 // nsDisplayTransform to wrap it, to make sure we create the correct transform
3907 // for the captured element and its descendants. This is necessary to make
3908 // sure our captured element doesn't become blurry when using scale()
3909 // transform.
3910 //
3911 // So the display list looks like this:
3912 // nsDisplayTransform // For the captured element if it is transformed
3913 // VTCapture // For the captured element
3914 // ...
3915 // Other display items // For the descendants of the captured element
3916 // ...
3917 // ...
3918 //
3919 // We intentionally use nsDisplayTransform to wrap the VTCapture (so it's
3920 // different from opacity display item) because nsDisplayTransform may push a
3921 // reference frame which creates a new coordinate system in WR. So it's just
3922 // like a separator between the VTCapture the outside, if it is transformed.
3923 if (capturedByViewTransition) {
3924 resultList.AppendNewToTop<nsDisplayViewTransitionCapture>(
3925 aBuilder, this, &resultList, nullptr,
3926 nsDisplayViewTransitionCapture::Kind::Element);
3927 createdContainer = true;
3928 MarkAsIsolated();
3929 // We don't want the capture to be clipped, so we do this _after_ building
3930 // the wrapping item.
3931 if (clipCapturedBy == ContainerItemType::ViewTransitionCapture) {
3932 clipState.Restore();
3933 }
3934 }
3935
3936 // If we're going to apply a transformation and don't have preserve-3d set,
3937 // wrap everything in an nsDisplayTransform. If there's nothing in the list,
3938 // don't add anything.
3939 //
3940 // For the preserve-3d case we want to individually wrap every child in the
3941 // list with a separate nsDisplayTransform instead. When the child is already
3942 // an nsDisplayTransform, we can skip this step, as the computed transform
3943 // will already include our own.
3944 //
3945 // We also traverse into sublists created by nsDisplayWrapList, so that we
3946 // find all the correct children.
3947 //
3948 // We still need to create nsDisplayTransform to wrap the VT capture element
3949 // to make sure WR renders it properly if it is transformed as well.
3950 if (isTransformed) {
3951 if (extend3DContext) {
3952 // Install dummy nsDisplayTransform as a leaf containing
3953 // descendants not participating this 3D rendering context.
3954 nsDisplayList nonparticipants;
3955 nsDisplayList participants;
3956 int index = 1;
3957
3958 nsDisplayItem* separator = nullptr;
3959
3960 // TODO: This can be simplified: |participants| is just |resultList|.
3961 for (nsDisplayItem* item : resultList.TakeItems()) {
3962 if (ItemParticipatesIn3DContext(this, item) &&
3963 !item->GetClip().HasClip()) {
3964 // The frame of this item participates the same 3D context.
3965 WrapSeparatorTransform(aBuilder, this, &nonparticipants,
3966 &participants, index++, &separator);
3967
3968 participants.AppendToTop(item);
3969 } else {
3970 // The frame of the item doesn't participate the current
3971 // context, or has no transform.
3972 //
3973 // For items participating but not transformed, they are add
3974 // to nonparticipants to get a separator layer for handling
3975 // clips, if there is, on an intermediate surface.
3976 // \see ContainerLayer::DefaultComputeEffectiveTransforms().
3977 nonparticipants.AppendToTop(item);
3978 }
3979 }
3980 WrapSeparatorTransform(aBuilder, this, &nonparticipants, &participants,
3981 index++, &separator);
3982
3983 if (separator) {
3984 createdContainer = true;
3985 MarkAsIsolated();
3986 }
3987
3988 resultList.AppendToTop(&participants);
3989 }
3990
3991 transformedCssClip.Restore();
3992 if (clipCapturedBy == ContainerItemType::Transform) {
3993 // Restore clip state now so nsDisplayTransform is clipped properly.
3994 clipState.Restore();
3995 }
3996 // Revert to the dirtyrect coming in from the parent, without our transform
3997 // taken into account.
3998 aBuilder->SetVisibleRect(visibleRectOutsideTransform);
3999
4000 if (this != aBuilder->RootReferenceFrame()) {
4001 // Revert to the outer reference frame and offset because all display
4002 // items we create from now on are outside the transform.
4003 nsPoint toOuterReferenceFrame;
4004 const nsIFrame* outerReferenceFrame =
4005 aBuilder->FindReferenceFrameFor(GetParent(), &toOuterReferenceFrame);
4006 toOuterReferenceFrame += GetPosition();
4007
4008 buildingDisplayList.SetReferenceFrameAndCurrentOffset(
4009 outerReferenceFrame, toOuterReferenceFrame);
4010 }
4011
4012 // We would like to block async animations for ancestors of ones not
4013 // prerendered in the preserve-3d tree. Now that we've finished processing
4014 // all descendants, update allowAsyncAnimation to take their prerender
4015 // state into account
4016 // FIXME: We don't block async animations for previous siblings because
4017 // their prerender decisions have been made. We may have to figure out a
4018 // better way to rollback their prerender decisions.
4019 // Alternatively we could not block animations for later siblings, and only
4020 // block them for ancestors of a blocked one.
4021 if ((extend3DContext || combines3DTransformWithAncestors) &&
4022 prerenderInfo.CanUseAsyncAnimations() &&
4023 !aBuilder->GetPreserves3DAllowAsyncAnimation()) {
4024 // aBuilder->GetPreserves3DAllowAsyncAnimation() means the inner or
4025 // previous silbing frames are allowed/disallowed for async animations.
4026 prerenderInfo.mDecision = nsDisplayTransform::PrerenderDecision::No;
4027 }
4028
4029 // A transform does not form a Backdrop Root, so if a descendant has a
4030 // backdrop-filter this stacking context must not be used to resolve it,
4031 // even though WebRender may give it a surface (e.g. to apply a clip it
4032 // inherits). Unless we are forcing isolation, in which case we are the
4033 // backdrop root that the descendant should resolve from.
4034 const bool forceIsolation = ShouldForceIsolation();
4035 const bool wrapsBackdropFilter =
4036 usingBackdropFilter ||
4037 (!forceIsolation && aBuilder->ContainsBackdropFilter());
4038
4039 nsDisplayTransform* transformItem = MakeDisplayItem<nsDisplayTransform>(
4040 aBuilder, this, &resultList, visibleRect, prerenderInfo.mDecision,
4041 wrapsBackdropFilter, forceIsolation);
4042 if (transformItem) {
4043 resultList.AppendToTop(transformItem);
4044 createdContainer = true;
4045
4046 if (numActiveScrollframesEncounteredBefore !=
4047 aBuilder->GetNumActiveScrollframesEncountered()) {
4048 transformItem->SetContainsASRs(true);
4049 }
4050
4051 if (hasPerspective) {
4052 transformItem->MarkWithAssociatedPerspective();
4053
4054 if (clipCapturedBy == ContainerItemType::Perspective) {
4055 clipState.Restore();
4056 }
4057 resultList.AppendNewToTop<nsDisplayPerspective>(aBuilder, this,
4058 &resultList);
4059 createdContainer = true;
4060 }
4061 }
4062 if (clipCapturedBy ==
4063 ContainerItemType::OwnLayerForTransformWithRoundedClip) {
4064 clipState.Restore();
4065 resultList.AppendNewToTopWithIndex<nsDisplayOwnLayer>(
4066 aBuilder, this,
4067 /* aIndex = */ nsDisplayOwnLayer::OwnLayerForTransformWithRoundedClip,
4068 &resultList, aBuilder->CurrentActiveScrolledRoot(),
4069 nsDisplayItem::ContainerASRType::Constant,
4070 nsDisplayOwnLayerFlags::None, ScrollbarData{},
4071 /* aForceActive = */ false, false);
4072 createdContainer = true;
4073 }
4074 }
4075
4076 // If we have sticky positioning, wrap it in a sticky position item.
4077 if (useFixedPosition && !capturedByViewTransition) {
4078 if (clipCapturedBy == ContainerItemType::FixedPosition) {
4079 clipState.Restore();
4080 }
4081 // The ASR for the fixed item should be the ASR of our containing block,
4082 // which has been set as the builder's current ASR, unless this frame is
4083 // invisible and we hadn't saved display item data for it. In that case,
4084 // we need to take the containerItemASR since we might have fixed children.
4085 // For WebRender, we want to the know what |containerItemASR| is for the
4086 // case where the fixed-pos item is not a "real" fixed-pos item (e.g. it's
4087 // nested inside a scrolling transform), so we stash that on the display
4088 // item as well.
4089 const ActiveScrolledRoot* fixedASR = ActiveScrolledRoot::PickAncestor(
4090 containerItemASR, aBuilder->CurrentActiveScrolledRoot());
4091 const ActiveScrolledRoot* scrollTargetASR =
4092 containerItemASR ? containerItemASR->GetNearestScrollASR() : nullptr;
4093 resultList.AppendNewToTop<nsDisplayFixedPosition>(
4094 aBuilder, this, &resultList, fixedASR,
4095 nsDisplayItem::ContainerASRType::AncestorOfContained, scrollTargetASR,
4096 ShouldForceIsolation());
4097 createdContainer = true;
4098 } else if (useStickyPosition && !capturedByViewTransition) {
4099 // For position:sticky, the clip needs to be applied both to the sticky
4100 // container item and to the contents. The container item needs the clip
4101 // because a scrolled clip needs to move independently from the sticky
4102 // contents, and the contents need the clip so that they have finite
4103 // clipped bounds with respect to the container item's ASR. The latter is
4104 // a little tricky in the case where the sticky item has both fixed and
4105 // non-fixed descendants, because that means that the sticky container
4106 // item's ASR is the ASR of the fixed descendant.
4107 // For WebRender display list building, though, we still want to know the
4108 // the ASR that the sticky container item would normally have, so we stash
4109 // that on the display item as the "container ASR" (i.e. the normal ASR of
4110 // the container item, excluding the special behaviour induced by fixed
4111 // descendants).
4112 const ActiveScrolledRoot* stickyItemASR = ActiveScrolledRoot::PickAncestor(
4113 containerItemASR, aBuilder->CurrentActiveScrolledRoot());
4114
4115 auto* stickyItem = MakeDisplayItem<nsDisplayStickyPosition>(
4116 aBuilder, this, &resultList, stickyItemASR,
4117 nsDisplayItem::ContainerASRType::AncestorOfContained,
4118 aBuilder->CurrentActiveScrolledRoot());
4119
4120 stickyItem->SetShouldFlatten(shouldFlattenStickyItem);
4121
4122 resultList.AppendToTop(stickyItem);
4123 createdContainer = true;
4124
4125 // If the sticky element is inside a filter, annotate the scroll frame that
4126 // scrolls the filter as having out-of-flow content inside a filter (this
4127 // inhibits paint skipping).
4128 if (aBuilder->GetFilterASR() && aBuilder->GetFilterASR() == stickyItemASR) {
4129 aBuilder->GetFilterASR()
4130 ->GetNearestScrollASR()
4131 ->ScrollFrame()
4132 ->SetHasOutOfFlowContentInsideFilter();
4133 }
4134 }
4135
4136 // If there's blending, wrap up the list in a blend-mode item. Note that
4137 // opacity can be applied before blending as the blend color is not affected
4138 // by foreground opacity (only background alpha).
4139 if (effects->mMixBlendMode != StyleBlend::Normal) {
4140 stackingContextTracker.AddToParent(
4141 StackingContextBits::ContainsMixBlendMode);
4142 resultList.AppendNewToTop<nsDisplayBlendMode>(
4143 aBuilder, this, &resultList, effects->mMixBlendMode, containerItemASR,
4144 nsDisplayItem::ContainerASRType::AncestorOfContained, false);
4145 createdContainer = true;
4146 MarkAsIsolated();
4147 }
4148
4149 if (!isolated && localIsolationReasons != StackingContextBits::None) {
4150 resultList.AppendToTop(nsDisplayBlendContainer::CreateForIsolation(
4151 aBuilder, this, &resultList, containerItemASR,
4152 nsDisplayItem::ContainerASRType::AncestorOfContained,
4153 ShouldForceIsolation()));
4154 createdContainer = true;
4155 }
4156
4157 if (aBuilder->IsReusingStackingContextItems()) {
4158 if (resultList.IsEmpty()) {
4159 return;
4160 }
4161
4162 nsDisplayItem* container = resultList.GetBottom();
4163 if (resultList.Length() > 1 || container->Frame() != this) {
4164 container = MakeDisplayItem<nsDisplayContainer>(
4165 aBuilder, this, containerItemASR,
4166 nsDisplayItem::ContainerASRType::AncestorOfContained, &resultList);
4167 } else {
4168 MOZ_ASSERT(resultList.Length() == 1)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(resultList.Length() == 1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(resultList.Length() == 1))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("resultList.Length() == 1"
, "./../../../layout/generic/nsIFrame.cpp", 4168); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "resultList.Length() == 1" ")"); do { MOZ_CrashSequence
(__null, 4168); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
4169 resultList.RemoveBottom();
4170 }
4171
4172 // Mark the outermost display item as reusable. These display items and
4173 // their chidren can be reused during the next paint if no ancestor or
4174 // descendant frames have been modified.
4175 if (!container->IsReusedItem()) {
4176 container->SetReusable();
4177 }
4178 aList->AppendToTop(container);
4179 createdContainer = true;
4180 } else {
4181 aList->AppendToTop(&resultList);
4182 }
4183
4184 if (aCreatedContainerItem) {
4185 *aCreatedContainerItem = createdContainer;
4186 }
4187}
4188
4189static nsDisplayItem* WrapInWrapList(nsDisplayListBuilder* aBuilder,
4190 nsIFrame* aFrame, nsDisplayList* aList,
4191 const ActiveScrolledRoot* aContainerASR,
4192 bool aBuiltContainerItem = false) {
4193 nsDisplayItem* item = aList->GetBottom();
4194 if (!item) {
4195 return nullptr;
4196 }
4197
4198 // We need a wrap list if there are multiple items, or if the single
4199 // item has a different frame. This can change in a partial build depending
4200 // on which items we build, so we need to ensure that we don't transition
4201 // to/from a wrap list without invalidating correctly.
4202 bool needsWrapList =
4203 aList->Length() > 1 || item->Frame() != aFrame || item->GetChildren();
4204
4205 // If we have an explicit container item (that can't change without an
4206 // invalidation) or we're doing a full build and don't need a wrap list, then
4207 // we can skip adding one.
4208 if (aBuiltContainerItem || (!aBuilder->IsPartialUpdate() && !needsWrapList)) {
4209 MOZ_ASSERT(aList->Length() == 1)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aList->Length() == 1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aList->Length() == 1))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("aList->Length() == 1"
, "./../../../layout/generic/nsIFrame.cpp", 4209); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aList->Length() == 1" ")"); do { MOZ_CrashSequence
(__null, 4209); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
4210 aList->RemoveBottom();
4211 return item;
4212 }
4213
4214 // If we're doing a partial build and we didn't need a wrap list
4215 // previously then we can try to work from there.
4216 if (aBuilder->IsPartialUpdate() &&
4217 !aFrame->HasDisplayItem(uint32_t(DisplayItemType::TYPE_CONTAINER))) {
4218 // If we now need a wrap list, we must previously have had no display items
4219 // or a single one belonging to this frame. Mark the item itself as
4220 // discarded so that RetainedDisplayListBuilder uses the ones we just built.
4221 // We don't want to mark the frame as modified as that would invalidate
4222 // positioned descendants that might be outside of this list, and might not
4223 // have been rebuilt this time.
4224 if (needsWrapList) {
4225 DiscardOldItems(aFrame);
4226 } else {
4227 MOZ_ASSERT(aList->Length() == 1)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aList->Length() == 1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aList->Length() == 1))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("aList->Length() == 1"
, "./../../../layout/generic/nsIFrame.cpp", 4227); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aList->Length() == 1" ")"); do { MOZ_CrashSequence
(__null, 4227); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
4228 aList->RemoveBottom();
4229 return item;
4230 }
4231 }
4232
4233 // The last case we could try to handle is when we previously had a wrap list,
4234 // but no longer need it. Unfortunately we can't differentiate this case from
4235 // a partial build where other children exist but we just didn't build them
4236 // this time.
4237 // TODO:RetainedDisplayListBuilder's merge phase has the full list and
4238 // could strip them out.
4239
4240 return MakeDisplayItem<nsDisplayContainer>(
4241 aBuilder, aFrame, aContainerASR,
4242 nsDisplayItem::ContainerASRType::AncestorOfContained, aList);
4243}
4244
4245/**
4246 * Check if a frame should be visited for building display list.
4247 */
4248static bool DescendIntoChild(nsDisplayListBuilder* aBuilder,
4249 const nsIFrame* aChild, const nsRect& aVisible,
4250 const nsRect& aDirty) {
4251 if (aChild->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
4252 return true;
4253 }
4254
4255 // If the child is a scrollframe that we want to ignore, then we need
4256 // to descend into it because its scrolled child may intersect the dirty
4257 // area even if the scrollframe itself doesn't.
4258 if (aChild == aBuilder->GetIgnoreScrollFrame()) {
4259 return true;
4260 }
4261
4262 // There are cases where the "ignore scroll frame" on the builder is not set
4263 // correctly, and so we additionally want to catch cases where the child is
4264 // a root scrollframe and we are ignoring scrolling on the viewport.
4265 if (aChild == aBuilder->GetPresShellIgnoreScrollFrame()) {
4266 return true;
4267 }
4268
4269 nsRect overflow = aChild->InkOverflowRect();
4270
4271 // On mobile, there may be a dynamic toolbar. The root content document's
4272 // root scroll frame's ink overflow rect does not include the toolbar
4273 // height, but if the toolbar is hidden, we still want to be able to target
4274 // content underneath the toolbar, so expand the overflow rect here to
4275 // allow display list building to descend into the scroll frame.
4276 if (aBuilder->IsForEventDelivery() &&
4277 aChild == aChild->PresShell()->GetRootScrollContainerFrame() &&
4278 aChild->PresContext()->IsRootContentDocumentCrossProcess() &&
4279 aChild->PresContext()->HasDynamicToolbar()) {
4280 overflow.SizeTo(nsLayoutUtils::ExpandHeightForDynamicToolbar(
4281 aChild->PresContext(), overflow.Size()));
4282 }
4283
4284 if (aDirty.Intersects(overflow)) {
4285 return true;
4286 }
4287
4288 if (aChild->ForceDescendIntoIfVisible() && aVisible.Intersects(overflow)) {
4289 return true;
4290 }
4291
4292 if (aChild->IsTablePart()) {
4293 // Relative positioning and transforms can cause table parts to move, but we
4294 // will still paint the backgrounds for their ancestor parts under them at
4295 // their 'normal' position. That means that we must consider the overflow
4296 // rects at both positions.
4297
4298 // We convert the overflow rect into the nsTableFrame's coordinate
4299 // space, applying the normal position offset at each step. Then we
4300 // compare that against the builder's cached dirty rect in table
4301 // coordinate space.
4302 const nsIFrame* f = aChild;
4303 nsRect normalPositionOverflowRelativeToTable = overflow;
4304
4305 while (f->IsTablePart()) {
4306 normalPositionOverflowRelativeToTable += f->GetNormalPosition();
4307 f = f->GetParent();
4308 }
4309
4310 nsDisplayTableBackgroundSet* tableBGs = aBuilder->GetTableBackgroundSet();
4311 if (tableBGs && tableBGs->GetDirtyRect().Intersects(
4312 normalPositionOverflowRelativeToTable)) {
4313 return true;
4314 }
4315 }
4316
4317 return false;
4318}
4319
4320void nsIFrame::BuildDisplayListForSimpleChild(nsDisplayListBuilder* aBuilder,
4321 nsIFrame* aChild,
4322 const nsDisplayListSet& aLists) {
4323 // This is the shortcut for frames been handled along the common
4324 // path, the most common one of THE COMMON CASE mentioned later.
4325 MOZ_ASSERT(aChild->Type() != LayoutFrameType::Placeholder)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->Type() != LayoutFrameType::Placeholder)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aChild->Type() != LayoutFrameType::Placeholder)))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("aChild->Type() != LayoutFrameType::Placeholder"
, "./../../../layout/generic/nsIFrame.cpp", 4325); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aChild->Type() != LayoutFrameType::Placeholder"
")"); do { MOZ_CrashSequence(__null, 4325); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4326 MOZ_ASSERT(!aBuilder->GetSelectedFramesOnly() &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aBuilder->GetSelectedFramesOnly() && !aBuilder
->GetIncludeAllOutOfFlows())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aBuilder->GetSelectedFramesOnly
() && !aBuilder->GetIncludeAllOutOfFlows()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
" (" "It should be held for painting to window" ")", "./../../../layout/generic/nsIFrame.cpp"
, 4328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { MOZ_CrashSequence
(__null, 4328); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
4327 !aBuilder->GetIncludeAllOutOfFlows(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aBuilder->GetSelectedFramesOnly() && !aBuilder
->GetIncludeAllOutOfFlows())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aBuilder->GetSelectedFramesOnly
() && !aBuilder->GetIncludeAllOutOfFlows()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
" (" "It should be held for painting to window" ")", "./../../../layout/generic/nsIFrame.cpp"
, 4328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { MOZ_CrashSequence
(__null, 4328); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
4328 "It should be held for painting to window")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aBuilder->GetSelectedFramesOnly() && !aBuilder
->GetIncludeAllOutOfFlows())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aBuilder->GetSelectedFramesOnly
() && !aBuilder->GetIncludeAllOutOfFlows()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
" (" "It should be held for painting to window" ")", "./../../../layout/generic/nsIFrame.cpp"
, 4328); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { MOZ_CrashSequence
(__null, 4328); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
4329 MOZ_ASSERT(aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST)", "./../../../layout/generic/nsIFrame.cpp"
, 4329); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST)"
")"); do { MOZ_CrashSequence(__null, 4329); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4330
4331 const nsPoint offset = aChild->GetOffsetTo(this);
4332 const nsRect visible = aBuilder->GetVisibleRect() - offset;
4333 const nsRect dirty = aBuilder->GetDirtyRect() - offset;
4334
4335 if (!DescendIntoChild(aBuilder, aChild, visible, dirty)) {
4336 DL_LOGV("Skipped frame %p", aChild)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "Skipped frame %p", aChild); } } while (
0)
;
4337 return;
4338 }
4339
4340 // Child cannot be transformed since it is not a stacking context.
4341 nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
4342 aBuilder, aChild, visible, dirty, false);
4343
4344 UpdateCurrentHitTestInfo(aBuilder, aChild);
4345
4346 aChild->MarkAbsoluteFramesForDisplayList(aBuilder);
4347 aBuilder->AdjustWindowDraggingRegion(aChild);
4348 aBuilder->Check();
4349 aChild->BuildDisplayList(aBuilder, aLists);
4350 if (aBuilder->IsForPainting()) {
4351 aChild->SetBuiltDisplayList(true);
4352 }
4353 aBuilder->Check();
4354 aBuilder->DisplayCaret(aChild, aLists.Outlines());
4355}
4356
4357static bool ShouldSkipFrame(nsDisplayListBuilder* aBuilder,
4358 const nsIFrame* aFrame) {
4359 // If painting is restricted to just the background of the top level frame,
4360 // then we have nothing to do here.
4361 if (aBuilder->IsBackgroundOnly()) {
4362 return true;
4363 }
4364 if (aBuilder->IsForGenerateGlyphMask()) {
4365 if ((aFrame->IsLeaf() && !aFrame->IsTextFrame()) ||
4366 aFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
4367 // Only in-flow text frames are painted for background-clip: text mask
4368 // generation.
4369 return true;
4370 }
4371 }
4372 if (aBuilder->GetSelectedFramesOnly() && aFrame->IsLeaf() &&
4373 !aFrame->IsSelected()) {
4374 return true;
4375 }
4376 static const nsFrameState skipFlags = NS_FRAME_TOO_DEEP_IN_FRAME_TREE |
4377 NS_FRAME_IS_NONDISPLAY |
4378 NS_FRAME_POSITION_VISIBILITY_HIDDEN;
4379 if (aFrame->HasAnyStateBits(skipFlags)) {
4380 return true;
4381 }
4382 // Checking mMozSubtreeHiddenOnlyVisually is relatively slow because it
4383 // involves loading more memory. It's only allowed in chrome sheets so let's
4384 // only support it in the parent process so we can mostly optimize this out in
4385 // content processes.
4386 return XRE_IsParentProcess() &&
4387 aFrame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually;
4388}
4389
4390#ifdef ACCESSIBILITY1
4391// Bug 2025119: If this is inlined in nsIFrame::BuildDisplayListForChild on
4392// Win32, we end up with crashes when there is deep recursion due to the
4393// increased stack size caused by the additional variables here. Work around
4394// this by having this code in its own function and ensuring it is never inlined
4395// on Win32.
4396# if defined(XP_WIN) && !defined(_WIN64)
4397MOZ_NEVER_INLINE__attribute__((noinline))
4398# endif
4399static void MaybeAddAccId(nsIFrame* aChildOrOutOfFlow,
4400 nsDisplayListBuilder* aBuilder,
4401 const nsDisplayListSet& aLists) {
4402 auto [innerWindowId, accId] =
4403 a11y::PdfStructTreeBuilder::GetAccId(aChildOrOutOfFlow);
4404 if (!innerWindowId) {
4405 return;
4406 }
4407 // When generating tagged PDF, associate this content with the correct
4408 // node in the structure tree.
4409 auto* item = MakeDisplayItem<nsDisplayAccessibleId>(
4410 aBuilder, aChildOrOutOfFlow, innerWindowId, accId);
4411 aLists.Content()->AppendToTop(item);
4412}
4413#endif
4414
4415void nsIFrame::BuildDisplayListForChild(nsDisplayListBuilder* aBuilder,
4416 nsIFrame* aChild,
4417 const nsDisplayListSet& aLists,
4418 DisplayChildFlags aFlags) {
4419 AutoCheckBuilder check(aBuilder);
4420 MOZ_ASSERT(!HidesContent(), "Caller should check")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HidesContent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HidesContent()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!HidesContent()"
" (" "Caller should check" ")", "./../../../layout/generic/nsIFrame.cpp"
, 4420); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HidesContent()"
") (" "Caller should check" ")"); do { MOZ_CrashSequence(__null
, 4420); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
4421#ifdef DEBUG1
4422 DL_LOGV("BuildDisplayListForChild (%p) <", aChild)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "BuildDisplayListForChild (%p) <", aChild
); } } while (0)
;
4423 ScopeExit e(
4424 [aChild]() { DL_LOGV("> BuildDisplayListForChild (%p)", aChild)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "> BuildDisplayListForChild (%p)", aChild
); } } while (0)
; });
4425#endif
4426
4427 nsIFrame* child = aChild;
4428 auto* placeholder = child->IsPlaceholderFrame()
4429 ? static_cast<nsPlaceholderFrame*>(child)
4430 : nullptr;
4431 nsIFrame* childOrOutOfFlow =
4432 placeholder ? placeholder->GetOutOfFlowFrame() : child;
4433 if (!childOrOutOfFlow || ShouldSkipFrame(aBuilder, childOrOutOfFlow)) {
4434 return;
4435 }
4436
4437 if (aBuilder->IsInLineClampAbsPosTraversal()) {
4438 const bool isOnForcedDescendPath = childOrOutOfFlow->HasAnyStateBits(
4439 NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
4440
4441 if (!isOnForcedDescendPath) {
4442 return;
4443 }
4444 }
4445
4446 // If we're generating a display list for printing, include Link items for
4447 // frames that correspond to HTML link elements so that we can have active
4448 // links in saved PDF output. Note that the state of "within a link" is
4449 // set on the display-list builder, such that all descendants of the link
4450 // element will generate display-list links, except for descendants entirely
4451 // covered by the link element's frame, since those would add nothing useful
4452 // to the final PDF.
4453 Maybe<nsDisplayListBuilder::Linkifier> linkifier;
4454 if (aBuilder->IsForPrinting()) {
4455#ifdef ACCESSIBILITY1
4456 MaybeAddAccId(childOrOutOfFlow, aBuilder, aLists);
4457#endif
4458 if (StaticPrefs::print_save_as_pdf_links_enabled()) {
4459 linkifier.emplace(aBuilder, childOrOutOfFlow, aLists.Content());
4460 linkifier->MaybeAppendLink(aBuilder, childOrOutOfFlow);
4461 }
4462 }
4463
4464 nsIFrame* parent = childOrOutOfFlow->GetParent();
4465 const auto* parentDisplay = parent->StyleDisplay();
4466 const auto overflowClipAxes =
4467 parent->ShouldApplyOverflowClipping(parentDisplay);
4468
4469 const bool isPaintingToWindow = aBuilder->IsPaintingToWindow();
4470 const bool doingShortcut =
4471 isPaintingToWindow &&
4472 child->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST) &&
4473 // Animations may change the stacking context state.
4474 // ShouldApplyOverflowClipping is affected by the parent style, which does
4475 // not invalidate the NS_FRAME_SIMPLE_DISPLAYLIST bit.
4476 !(!overflowClipAxes.isEmpty() || child->MayHaveTransformAnimation() ||
4477 child->MayHaveOpacityAnimation());
4478
4479 if (StaticPrefs::layout_css_scroll_anchoring_highlight()) {
4480 if (child->FirstContinuation()->IsScrollAnchor()) {
4481 nsRect bounds = child->GetContentRectRelativeToSelf() +
4482 aBuilder->ToReferenceFrame(child);
4483 nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
4484 aBuilder, child, bounds, NS_RGBA(255, 0, 255, 64)((nscolor)(((64) << 24) | ((255) << 16) | ((0) <<
8) | (255)))
);
4485 if (color) {
4486 color->SetOverrideZIndex(INT32_MAX(2147483647));
4487 aLists.PositionedDescendants()->AppendToTop(color);
4488 }
4489 }
4490 }
4491
4492 if (doingShortcut) {
4493 BuildDisplayListForSimpleChild(aBuilder, child, aLists);
4494 return;
4495 }
4496
4497 // dirty rect in child-relative coordinates
4498 NS_ASSERTION(aBuilder->GetCurrentFrame() == this, "Wrong coord space!")do { if (!(aBuilder->GetCurrentFrame() == this)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Wrong coord space!", "aBuilder->GetCurrentFrame() == this"
, "./../../../layout/generic/nsIFrame.cpp", 4498); MOZ_PretendNoReturn
(); } } while (0)
;
4499 const nsPoint offset = child->GetOffsetTo(this);
4500 nsRect visible = aBuilder->GetVisibleRect() - offset;
4501 nsRect dirty = aBuilder->GetDirtyRect() - offset;
4502
4503 nsDisplayListBuilder::OutOfFlowDisplayData* savedOutOfFlowData = nullptr;
4504 if (placeholder) {
4505 if (placeholder->HasAnyStateBits(PLACEHOLDER_FOR_TOPLAYER)) {
4506 // If the out-of-flow frame is in the top layer, the viewport frame
4507 // will paint it. Skip it here. Note that, only out-of-flow frames
4508 // with this property should be skipped, because non-HTML elements
4509 // may stop their children from being out-of-flow. Those frames
4510 // should still be handled in the normal in-flow path.
4511 return;
4512 }
4513
4514 child = childOrOutOfFlow;
4515
4516 // If 'child' is a pushed out-of-flow then it's owned by a block that's not
4517 // an ancestor of the placeholder, and it will be painted by that block and
4518 // should not be painted through the placeholder. Also recheck
4519 // NS_FRAME_TOO_DEEP_IN_FRAME_TREE and NS_FRAME_IS_NONDISPLAY.
4520 static const nsFrameState skipFlags =
4521 (NS_FRAME_IS_PUSHED_OUT_OF_FLOW | NS_FRAME_TOO_DEEP_IN_FRAME_TREE |
4522 NS_FRAME_IS_NONDISPLAY);
4523 if (child->HasAnyStateBits(skipFlags) || nsLayoutUtils::IsPopup(child)) {
4524 return;
4525 }
4526
4527 // For a transformed absolute containing block, if the abspos's placeholder
4528 // is in a different continuation's subtree, the abspos was already built
4529 // directly by DisplayAbsoluteFramesNotBuiltByPlaceholder() on its
4530 // containing block. Exclude inline frames because IB-split (bug 489100)
4531 // can cause the placeholder to live in a later IB-split sibling.
4532 if (parent->IsTransformed() && !parent->IsInlineFrame() &&
4533 child->IsAbsolutelyPositioned() &&
4534 !nsLayoutUtils::IsProperAncestorFrame(parent, placeholder)) {
4535 return;
4536 }
4537
4538 MOZ_ASSERT(child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)"
, "./../../../layout/generic/nsIFrame.cpp", 4538); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)"
")"); do { MOZ_CrashSequence(__null, 4538); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4539 savedOutOfFlowData = nsDisplayListBuilder::GetOutOfFlowData(child);
4540
4541 if (aBuilder->GetIncludeAllOutOfFlows()) {
4542 visible = child->InkOverflowRect();
4543 dirty = child->InkOverflowRect();
4544 } else if (savedOutOfFlowData) {
4545 visible =
4546 savedOutOfFlowData->GetVisibleRectForFrame(aBuilder, child, &dirty);
4547 } else {
4548 // The out-of-flow frame did not intersect the dirty area. We may still
4549 // need to traverse into it, since it may contain placeholders we need
4550 // to enter to reach other out-of-flow frames that are visible.
4551 visible.SetEmpty();
4552 dirty.SetEmpty();
4553 }
4554 }
4555
4556 NS_ASSERTION(!child->IsPlaceholderFrame(),do { if (!(!child->IsPlaceholderFrame())) { NS_DebugBreak(
NS_DEBUG_ASSERTION, "Should have dealt with placeholders already"
, "!child->IsPlaceholderFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 4557); MOZ_PretendNoReturn(); } } while (0)
4557 "Should have dealt with placeholders already")do { if (!(!child->IsPlaceholderFrame())) { NS_DebugBreak(
NS_DEBUG_ASSERTION, "Should have dealt with placeholders already"
, "!child->IsPlaceholderFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 4557); MOZ_PretendNoReturn(); } } while (0)
;
4558
4559 if (!DescendIntoChild(aBuilder, child, visible, dirty)) {
4560 DL_LOGV("Skipped frame %p", child)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Verbose)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Verbose, "Skipped frame %p", child); } } while (0
)
;
4561 return;
4562 }
4563
4564 const bool isSVG = child->HasAnyStateBits(NS_FRAME_SVG_LAYOUT);
4565
4566 // This flag is raised if the control flow strays off the common path.
4567 // The common path is the most common one of THE COMMON CASE mentioned later.
4568 bool awayFromCommonPath = !isPaintingToWindow;
4569
4570 // true if this is a real or pseudo stacking context
4571 bool pseudoStackingContext =
4572 aFlags.contains(DisplayChildFlag::ForcePseudoStackingContext);
4573
4574 if (!pseudoStackingContext && !isSVG &&
4575 aFlags.contains(DisplayChildFlag::Inline) &&
4576 !child->IsLineParticipant()) {
4577 // child is a non-inline frame in an inline context, i.e.,
4578 // it acts like inline-block or inline-table. Therefore it is a
4579 // pseudo-stacking-context.
4580 pseudoStackingContext = true;
4581 }
4582
4583 // Since we're now sure that we're adding this frame to the display list
4584 // (which means we're painting it, modulo occlusion), mark it as visible
4585 // within the displayport.
4586 if (isPaintingToWindow && child->TrackingVisibility() &&
4587 child->IsVisibleForPainting()) {
4588 child->PresShell()->EnsureFrameInApproximatelyVisibleList(child);
4589 awayFromCommonPath = true;
4590 }
4591
4592 // Child is composited if it's transformed, partially transparent, or has
4593 // SVG effects or a blend mode..
4594 const nsStyleDisplay* disp = child->StyleDisplay();
4595 const nsStyleEffects* effects = child->StyleEffects();
4596
4597 const bool isPositioned = disp->IsPositionedStyle();
4598 const bool isStackingContext =
4599 aFlags.contains(DisplayChildFlag::ForceStackingContext) ||
4600 child->IsStackingContext(disp, effects);
4601
4602 if (pseudoStackingContext || isStackingContext || isPositioned ||
4603 placeholder || (!isSVG && disp->IsFloating(child)) ||
4604 (isSVG && effects->mClip.IsRect() && IsSVGContentWithCSSClip(child))) {
4605 pseudoStackingContext = true;
4606 awayFromCommonPath = true;
4607 }
4608
4609 NS_ASSERTION(!isStackingContext || pseudoStackingContext,do { if (!(!isStackingContext || pseudoStackingContext)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Stacking contexts must also be pseudo-stacking-contexts"
, "!isStackingContext || pseudoStackingContext", "./../../../layout/generic/nsIFrame.cpp"
, 4610); MOZ_PretendNoReturn(); } } while (0)
4610 "Stacking contexts must also be pseudo-stacking-contexts")do { if (!(!isStackingContext || pseudoStackingContext)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Stacking contexts must also be pseudo-stacking-contexts"
, "!isStackingContext || pseudoStackingContext", "./../../../layout/generic/nsIFrame.cpp"
, 4610); MOZ_PretendNoReturn(); } } while (0)
;
4611
4612 Maybe<nsDisplayListBuilder::AutoInLineClampAbsPosTraversal>
4613 buildAbsPosNormally;
4614 if (aBuilder->IsInLineClampAbsPosTraversal() &&
4615 child->IsAbsolutelyPositioned() && savedOutOfFlowData) {
4616 buildAbsPosNormally.emplace(aBuilder, false);
4617 }
4618
4619 nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
4620 aBuilder, child, visible, dirty);
4621
4622 UpdateCurrentHitTestInfo(aBuilder, child);
4623
4624 DisplayListClipState::AutoClipMultiple clipState(aBuilder);
4625 nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(aBuilder);
4626
4627 if (savedOutOfFlowData) {
4628 aBuilder->SetBuildingInvisibleItems(false);
4629#ifdef DEBUG1
4630 savedOutOfFlowData->CheckASR(aBuilder, child);
4631#endif
4632 const ActiveScrolledRoot* asr =
4633 savedOutOfFlowData->mContainingBlockActiveScrolledRoot;
4634 if (child->IsAbsolutelyPositioned(disp)) {
4635 asr = DisplayPortUtils::GetASRForAbsPosFrame(child, asr, aBuilder);
4636 }
4637
4638 if (aBuilder->IsInViewTransitionCapture()) {
4639 if (!savedOutOfFlowData->mContainingBlockInViewTransitionCapture) {
4640 clipState.Clear();
4641 } else {
4642 clipState.SetClipChainForContainingBlockDescendants(
4643 savedOutOfFlowData->mContainingBlockClipChain);
4644 }
4645 asrSetter.SetCurrentActiveScrolledRoot(nullptr);
4646 } else {
4647 clipState.SetClipChainForContainingBlockDescendants(
4648 savedOutOfFlowData->mContainingBlockClipChain);
4649 asrSetter.SetCurrentActiveScrolledRoot(asr);
4650 asrSetter.SetCurrentScrollParentId(savedOutOfFlowData->mScrollParentId);
4651 }
4652 MOZ_ASSERT(awayFromCommonPath,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(awayFromCommonPath)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(awayFromCommonPath))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("awayFromCommonPath"
" (" "It is impossible when savedOutOfFlowData is true" ")",
"./../../../layout/generic/nsIFrame.cpp", 4653); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "awayFromCommonPath" ") (" "It is impossible when savedOutOfFlowData is true"
")"); do { MOZ_CrashSequence(__null, 4653); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
4653 "It is impossible when savedOutOfFlowData is true")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(awayFromCommonPath)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(awayFromCommonPath))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("awayFromCommonPath"
" (" "It is impossible when savedOutOfFlowData is true" ")",
"./../../../layout/generic/nsIFrame.cpp", 4653); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "awayFromCommonPath" ") (" "It is impossible when savedOutOfFlowData is true"
")"); do { MOZ_CrashSequence(__null, 4653); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4654 } else if (HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) &&
4655 placeholder) {
4656 NS_ASSERTION(visible.IsEmpty(), "should have empty visible rect")do { if (!(visible.IsEmpty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "should have empty visible rect", "visible.IsEmpty()", "./../../../layout/generic/nsIFrame.cpp"
, 4656); MOZ_PretendNoReturn(); } } while (0)
;
4657 // Every item we build from now until we descent into an out of flow that
4658 // does have saved out of flow data should be invisible. This state gets
4659 // restored when AutoBuildingDisplayList gets out of scope.
4660 aBuilder->SetBuildingInvisibleItems(true);
4661
4662 // If we have nested out-of-flow frames and the outer one isn't visible
4663 // then we won't have stored clip data for it. We can just clear the clip
4664 // instead since we know we won't render anything, and the inner out-of-flow
4665 // frame will setup the correct clip for itself.
4666 clipState.SetClipChainForContainingBlockDescendants(nullptr);
4667 }
4668
4669 // Setup clipping for the parent's overflow:clip,
4670 // or overflow:hidden on elements that don't support scrolling (and therefore
4671 // don't create nsHTML/XULScrollFrame). This clipping needs to not clip
4672 // anything directly rendered by the parent, only the rendering of its
4673 // children.
4674 // Don't use overflowClip to restrict the dirty rect, since some of the
4675 // descendants may not be clipped by it. Even if we end up with unnecessary
4676 // display items, they'll be pruned during ComputeVisibility.
4677 //
4678 // FIXME(emilio): Why can't we handle this more similarly to `clip` (on the
4679 // parent, rather than on the children)? Would ClipContentDescendants do what
4680 // we want?
4681 if (!overflowClipAxes.isEmpty()) {
4682 ApplyOverflowClipping(aBuilder, parent, overflowClipAxes, clipState);
4683 awayFromCommonPath = true;
4684 }
4685
4686 nsDisplayList list;
4687 nsDisplayList extraPositionedDescendants;
4688 const ActiveScrolledRoot* wrapListASR;
4689 bool builtContainerItem = false;
4690 if (isStackingContext) {
4691 // True stacking context.
4692 // For stacking contexts, BuildDisplayListForStackingContext handles
4693 // clipping and MarkAbsoluteFramesForDisplayList.
4694 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
4695 child->BuildDisplayListForStackingContext(aBuilder, &list,
4696 &builtContainerItem);
4697 wrapListASR = contASRTracker.GetContainerASR();
4698 if (!aBuilder->IsReusingStackingContextItems() &&
4699 aBuilder->GetCaretFrame() == child) {
4700 builtContainerItem = false;
4701 }
4702 } else {
4703 Maybe<nsRect> clipPropClip =
4704 child->GetClipPropClipRect(disp, effects, child->GetSize());
4705 if (clipPropClip) {
4706 aBuilder->IntersectVisibleRect(*clipPropClip);
4707 aBuilder->IntersectDirtyRect(*clipPropClip);
4708 clipState.ClipContentDescendants(*clipPropClip +
4709 aBuilder->ToReferenceFrame(child));
4710 awayFromCommonPath = true;
4711 }
4712
4713 child->MarkAbsoluteFramesForDisplayList(aBuilder);
4714 if (aBuilder->IsForPainting()) {
4715 child->SetBuiltDisplayList(true);
4716 }
4717
4718 // Some SVG frames might change opacity without invalidating the frame, so
4719 // exclude them from the fast-path.
4720 if (!awayFromCommonPath && !child->IsSVGFrame()) {
4721 // The shortcut is available for the child for next time.
4722 child->AddStateBits(NS_FRAME_SIMPLE_DISPLAYLIST);
4723 }
4724
4725 if (!pseudoStackingContext) {
4726 // THIS IS THE COMMON CASE.
4727 // Not a pseudo or real stacking context. Do the simple thing and
4728 // return early.
4729 aBuilder->AdjustWindowDraggingRegion(child);
4730 aBuilder->Check();
4731 child->BuildDisplayList(aBuilder, aLists);
4732 aBuilder->Check();
4733 aBuilder->DisplayCaret(child, aLists.Outlines());
4734 return;
4735 }
4736
4737 // A pseudo-stacking context (e.g., a positioned element with z-index auto).
4738 // We allow positioned descendants of the child to escape to our parent
4739 // stacking context's positioned descendant list, because they might be
4740 // z-index:non-auto
4741 nsDisplayListCollection pseudoStack(aBuilder);
4742
4743 aBuilder->AdjustWindowDraggingRegion(child);
4744 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
4745 aBuilder->Check();
4746 child->BuildDisplayList(aBuilder, pseudoStack);
4747 aBuilder->Check();
4748 if (aBuilder->DisplayCaret(child, pseudoStack.Outlines())) {
4749 builtContainerItem = false;
4750 }
4751 wrapListASR = contASRTracker.GetContainerASR();
4752
4753 list.AppendToTop(pseudoStack.BorderBackground());
4754 list.AppendToTop(pseudoStack.BlockBorderBackgrounds());
4755 list.AppendToTop(pseudoStack.Floats());
4756 list.AppendToTop(pseudoStack.Content());
4757 list.AppendToTop(pseudoStack.Outlines());
4758 extraPositionedDescendants.AppendToTop(pseudoStack.PositionedDescendants());
4759 }
4760
4761 buildingForChild.RestoreBuildingInvisibleItemsValue();
4762
4763 if (!list.IsEmpty()) {
4764 if (isPositioned || isStackingContext) {
4765 // Genuine stacking contexts, and positioned pseudo-stacking-contexts,
4766 // go in this level.
4767 nsDisplayItem* item = WrapInWrapList(aBuilder, child, &list, wrapListASR,
4768 builtContainerItem);
4769 if (isSVG) {
4770 aLists.Content()->AppendToTop(item);
4771 } else {
4772 aLists.PositionedDescendants()->AppendToTop(item);
4773 }
4774 } else if (!isSVG && disp->IsFloating(child)) {
4775 aLists.Floats()->AppendToTop(
4776 WrapInWrapList(aBuilder, child, &list, wrapListASR));
4777 } else {
4778 aLists.Content()->AppendToTop(&list);
4779 }
4780 }
4781 // We delay placing the positioned descendants of positioned frames to here,
4782 // because in the absence of z-index this is the correct order for them.
4783 // This doesn't affect correctness because the positioned descendants list
4784 // is sorted by z-order and content in BuildDisplayListForStackingContext,
4785 // but it means that sort routine needs to do less work.
4786 aLists.PositionedDescendants()->AppendToTop(&extraPositionedDescendants);
4787}
4788
4789void nsIFrame::MarkAbsoluteFramesForDisplayList(
4790 nsDisplayListBuilder* aBuilder) {
4791 if (const auto* absCB = GetAbsoluteContainingBlock()) {
4792 aBuilder->MarkFramesForDisplayList(this, absCB->GetChildList());
4793 }
4794}
4795
4796const nsIFrame* nsIFrame::GetGeneratedRootFrame() const {
4797 if (!IsGeneratedContentFrame()) {
4798 return nullptr;
4799 }
4800 const nsIFrame* generatedRoot = this;
4801 while (true) {
4802 auto* parent = nsLayoutUtils::GetParentOrPlaceholderFor(generatedRoot);
4803 if (!parent || !parent->IsGeneratedContentFrame()) {
4804 break;
4805 }
4806 generatedRoot = parent;
4807 }
4808 return generatedRoot;
4809}
4810
4811nsIContent* nsIFrame::GetExplicitEventTargetContent(
4812 const WidgetEvent* aEvent /* = nullptr */) const {
4813 // Return the content as-is if this is not a generated content.
4814 if (!IsGeneratedContentFrame()) {
4815 return GetContent();
4816 }
4817 // If the content is a generated content, it won't handle any events from the
4818 // DOM point of view. Therefore, let's return the parent of the generated
4819 // content.
4820 const nsIFrame* generatedRoot = GetGeneratedRootFrame();
4821 MOZ_ASSERT(generatedRoot)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(generatedRoot)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(generatedRoot))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("generatedRoot",
"./../../../layout/generic/nsIFrame.cpp", 4821); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "generatedRoot" ")"); do { MOZ_CrashSequence
(__null, 4821); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
4822 // Return the non-generated ancestor.
4823 return generatedRoot->GetContent()->GetParent();
4824}
4825
4826nsIContent* nsIFrame::GetEventTargetContent(
4827 const mozilla::WidgetEvent* aEvent /* = nullptr */) const {
4828 return nsContentUtils::GetEventTargetContent(
4829 GetExplicitEventTargetContent(aEvent), aEvent);
4830}
4831
4832void nsIFrame::FireDOMEvent(const nsAString& aDOMEventName,
4833 nsIContent* aContent) {
4834 nsIContent* target = aContent ? aContent : GetContent();
4835
4836 if (target) {
4837 auto asyncDispatcher = MakeRefPtr<AsyncEventDispatcher>(
4838 target, aDOMEventName, CanBubble::eYes, ChromeOnlyDispatch::eNo);
4839 DebugOnly<nsresult> rv = asyncDispatcher->PostDOMEvent();
4840 NS_ASSERTION(NS_SUCCEEDED(rv), "AsyncEventDispatcher failed to dispatch")do { if (!(((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1
))))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "AsyncEventDispatcher failed to dispatch"
, "NS_SUCCEEDED(rv)", "./../../../layout/generic/nsIFrame.cpp"
, 4840); MOZ_PretendNoReturn(); } } while (0)
;
4841 }
4842}
4843
4844nsresult nsIFrame::HandleEvent(nsPresContext* aPresContext,
4845 WidgetGUIEvent* aEvent,
4846 nsEventStatus* aEventStatus) {
4847 if (aEvent->mMessage == eMouseMove) {
4848 // XXX If the second argument of HandleDrag() is WidgetMouseEvent,
4849 // the implementation becomes simpler.
4850 return HandleDrag(aPresContext, aEvent, aEventStatus);
4851 }
4852
4853 if (aEvent->mMessage == eContextMenu) {
4854 // A web page cannot cancel the context menu when the user has turned off
4855 // dom.event.contextmenu.enabled, and the menu opens anyway.
4856 const bool isMenuCanceled =
4857 *aEventStatus == nsEventStatus_eConsumeNoDefault &&
4858 (Preferences::GetBool("dom.event.contextmenu.enabled", true) ||
4859 (mContent && mContent->NodePrincipal()->IsSystemPrincipal()));
4860 // An untrusted event must not move the selection, since that is the
4861 // user's.
4862 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
4863 if (!isMenuCanceled && mouseEvent && mouseEvent->IsReal() &&
4864 aEvent->IsTrusted()) {
4865 HandleContextMenuEventToSelectWordOrLink(*mouseEvent);
4866 // Be aware, this frame might have already been destroyed here.
4867 }
4868 return NS_OK;
4869 }
4870
4871 if ((aEvent->mClass == eMouseEventClass &&
4872 aEvent->AsMouseEvent()->mButton == MouseButton::ePrimary) ||
4873 aEvent->mClass == eTouchEventClass) {
4874 if (aEvent->mMessage == eMouseDown || aEvent->mMessage == eTouchStart) {
4875 HandlePress(aPresContext, aEvent, aEventStatus);
4876 } else if (aEvent->mMessage == eMouseUp || aEvent->mMessage == eTouchEnd) {
4877 HandleRelease(aPresContext, aEvent, aEventStatus);
4878 }
4879 return NS_OK;
4880 }
4881
4882 // When secondary button is down, we need to move selection to make users
4883 // possible to paste something at click point quickly.
4884 // When middle button is down, we need to just move selection and focus at
4885 // the clicked point. Note that even if middle click paste is not enabled,
4886 // Chrome moves selection at middle mouse button down. So, we should follow
4887 // the behavior for the compatibility.
4888 if (aEvent->mMessage == eMouseDown) {
4889 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
4890 if (mouseEvent && (mouseEvent->mButton == MouseButton::eSecondary ||
4891 mouseEvent->mButton == MouseButton::eMiddle)) {
4892 if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
4893 return NS_OK;
4894 }
4895 return MoveCaretToEventPoint(aPresContext, mouseEvent, aEventStatus);
4896 }
4897 }
4898
4899 return NS_OK;
4900}
4901
4902nsresult nsIFrame::GetDataForTableSelection(
4903 const nsFrameSelection* aFrameSelection, mozilla::PresShell* aPresShell,
4904 WidgetMouseEvent* aMouseEvent, nsIContent** aParentContent,
4905 int32_t* aContentOffset, TableSelectionMode* aTarget) {
4906 if (!aFrameSelection || !aPresShell || !aMouseEvent || !aParentContent ||
4907 !aContentOffset || !aTarget) {
4908 return NS_ERROR_NULL_POINTER;
4909 }
4910
4911 *aParentContent = nullptr;
4912 *aContentOffset = 0;
4913 *aTarget = TableSelectionMode::None;
4914
4915 int16_t displaySelection = aPresShell->GetSelectionFlags();
4916
4917 bool selectingTableCells = aFrameSelection->IsInTableSelectionMode();
4918
4919 // DISPLAY_ALL means we're in an editor.
4920 // If already in cell selection mode,
4921 // continue selecting with mouse drag or end on mouse up,
4922 // or when using shift key to extend block of cells
4923 // (Mouse down does normal selection unless Ctrl/Cmd is pressed)
4924 bool doTableSelection =
4925 displaySelection == nsISelectionDisplay::DISPLAY_ALL &&
4926 selectingTableCells &&
4927 (aMouseEvent->mMessage == eMouseMove ||
4928 (aMouseEvent->mMessage == eMouseUp &&
4929 aMouseEvent->mButton == MouseButton::ePrimary) ||
4930 aMouseEvent->IsShift());
4931
4932 if (!doTableSelection) {
4933 // In Browser, special 'table selection' key must be pressed for table
4934 // selection or when just Shift is pressed and we're already in table/cell
4935 // selection mode
4936#ifdef XP_MACOSX
4937 doTableSelection = aMouseEvent->IsMeta() ||
4938 (aMouseEvent->IsShift() && selectingTableCells);
4939#else
4940 doTableSelection = aMouseEvent->IsControl() ||
4941 (aMouseEvent->IsShift() && selectingTableCells);
4942#endif
4943 }
4944 if (!doTableSelection) {
4945 return NS_OK;
4946 }
4947
4948 // Get the cell frame or table frame (or parent) of the current content node
4949 nsIFrame* frame = this;
4950 bool foundCell = false;
4951 bool foundTable = false;
4952
4953 const Element* const independentSelectionLimiter =
4954 aFrameSelection->GetIndependentSelectionRootElement();
4955
4956 if (independentSelectionLimiter &&
4957 !independentSelectionLimiter->Contains(GetContent())) {
4958 // If our content is not under the limiting node, stop the search right now.
4959 return NS_OK;
4960 }
4961
4962 for (; frame; frame = frame->GetParent()) {
4963 // Check for a table cell by querying to a known CellFrame interface
4964 if (static_cast<nsITableCellLayout*>(do_QueryFrame(frame))) {
4965 foundCell = true;
4966 // TODO: If we want to use proximity to top or left border
4967 // for row and column selection, this is the place to do it
4968 break;
4969 }
4970 if (frame->IsTableWrapperFrame()) {
4971 // If not a cell, check for table. This will happen when the starting
4972 // frame is the table or child of a table, such as a row (we were
4973 // in-between cells or in table border).
4974 // TODO: How can we select row when along left table edge
4975 // or select column when along top edge?
4976 foundTable = true;
4977 break;
4978 }
4979 }
4980
4981 if (!foundCell && !foundTable) {
4982 // We aren't in a cell or table.
4983 return NS_OK;
4984 }
4985
4986 nsIContent* tableOrCellContent = frame->GetContent();
4987 if (!tableOrCellContent) {
4988 return NS_OK;
4989 }
4990
4991 if (independentSelectionLimiter &&
4992 !independentSelectionLimiter->Contains(tableOrCellContent)) {
4993 return NS_OK;
4994 }
4995
4996 nsCOMPtr<nsIContent> parentContent = tableOrCellContent->GetParent();
4997 if (!parentContent) {
4998 return NS_ERROR_FAILURE;
4999 }
5000
5001 const int32_t offset =
5002 parentContent->ComputeIndexOf_Deprecated(tableOrCellContent);
5003 // Not likely?
5004 if (offset < 0) {
5005 return NS_ERROR_FAILURE;
5006 }
5007
5008 // Everything is OK -- set the return values
5009 parentContent.forget(aParentContent);
5010
5011 *aContentOffset = offset;
5012
5013#if 0
5014 if (selectRow)
5015 *aTarget = TableSelectionMode::Row;
5016 else if (selectColumn)
5017 *aTarget = TableSelectionMode::Column;
5018 else
5019#endif
5020 if (foundCell) {
5021 *aTarget = TableSelectionMode::Cell;
5022 } else if (foundTable) {
5023 *aTarget = TableSelectionMode::Table;
5024 }
5025
5026 return NS_OK;
5027}
5028
5029static bool IsEditingHost(const nsIFrame* aFrame) {
5030 if (aFrame->Style()->GetPseudoType() ==
5031 PseudoStyleType::MozTextControlEditingRoot) {
5032 return true;
5033 }
5034 nsIContent* content = aFrame->GetContent();
5035 return content && content->IsEditingHost();
5036}
5037
5038mozilla::StyleUserSelect nsIFrame::UsedUserSelect(
5039 const nsIFrame* aFrame, nsIFrame::ForSelectionStart aType) {
5040 return UsedUserSelectRecurse(aFrame, aType).valueOr(StyleUserSelect::Text);
5041}
5042
5043Maybe<mozilla::StyleUserSelect> nsIFrame::UsedUserSelectRecurse(
5044 const nsIFrame* aFrame, nsIFrame::ForSelectionStart aType) {
5045 if (aFrame->IsGeneratedContentFrame()) {
5046 return Some(StyleUserSelect::None);
5047 }
5048
5049 // nsTableColFrame is inserted after nsTableRowGroupFrame and its content is
5050 // the corresponding <col> if one exists, or <colgroup> or <table> otherwise.
5051 // That means the frame tree order is different from the DOM tree order of
5052 // HTML table so that the caret navigation may return start of the <table>
5053 // after end of the last cell. Fortunately, it's invisible from user's
5054 // selection point of view. So, we should be able to treat it as unselectable.
5055 if (aFrame->IsTableColFrame()) {
5056 return Some(StyleUserSelect::None);
5057 }
5058
5059 // Per https://drafts.csswg.org/css-ui-4/#content-selection:
5060 //
5061 // The used value is the same as the computed value, except:
5062 //
5063 // 1 - on editable elements where the used value is always 'contain'
5064 // regardless of the computed value
5065 // 2 - when the computed value is auto, in which case the used value is one
5066 // of the other values...
5067 //
5068 // See https://github.com/w3c/csswg-drafts/issues/3344 to see why we do this
5069 // at used-value time instead of at computed-value time.
5070
5071 // Although the draft does not define that editable elements under an editing
5072 // host should ignore `user-select`, Chrome ignores `user-select:none` and
5073 // `user-select:all` and we've already considered as ignoring the
5074 // `user-select` according to this test:
5075 // https://searchfox.org/firefox-main/rev/6abddcb0a5076c3b888686ede6f4cf7d082460d3/dom/base/test/test_bug1101364.html#73-85
5076 // https://searchfox.org/firefox-main/rev/4fd0fa7e5814c0b51f1dd075821988377bc56cc1/testing/web-platform/tests/css/css-ui/user-select-none-in-editable.html#23-24,32-36
5077 // Therefore, we check aFrame->ContentIsEditable() instead of
5078 // IsEditingHost(aFrame).
5079 if (aFrame->IsTextInputFrame() || aFrame->ContentIsEditable()) {
5080 // We don't implement 'contain' itself, but we make 'text' behave as
5081 // 'contain' for contenteditable and <input> / <textarea> elements anyway so
5082 // this is ok.
5083 return Some(StyleUserSelect::Text);
5084 }
5085
5086 auto style = aFrame->Style()->UserSelect();
5087 if (style != StyleUserSelect::Auto) {
5088 return Some(style);
5089 }
5090
5091 const auto IsButton = [](const nsIFrame* aFrame) {
5092 const auto* content = aFrame->GetContent();
5093 if (!content) {
5094 return false;
5095 }
5096 return content->IsAnyOfHTMLElements(nsGkAtoms::button);
5097 };
5098
5099 auto* parent = nsLayoutUtils::GetParentOrPlaceholderFor(aFrame);
5100 const auto parentResult =
5101 parent ? UsedUserSelectRecurse(parent, aType) : Nothing{};
5102 if (parentResult.valueOr(StyleUserSelect::Auto) != StyleUserSelect::None &&
5103 aType == nsIFrame::ForSelectionStart::Yes && IsButton(aFrame)) {
5104 // If the parent did not force our hands, we want non-`contenteditable`
5105 // buttons to be clickable without accidentally selecting the text within
5106 // it, but still allow selection that originates outside of it.
5107 return Some(StyleUserSelect::None);
5108 }
5109 return parentResult;
5110}
5111
5112bool nsIFrame::IsSelectable(StyleUserSelect* aSelectStyle) const {
5113 auto style = UsedUserSelect(this, ForSelectionStart::No);
5114 if (aSelectStyle) {
5115 *aSelectStyle = style;
5116 }
5117 return style != StyleUserSelect::None;
5118}
5119
5120bool nsIFrame::ShouldPaintNormalSelection() const {
5121 if (IsSelectable()) {
5122 // NOTE: Ideally, we should return false if display selection is "OFF".
5123 // However, here is a hot path at painting. Therefore, it should be checked
5124 // before and we shouldn't need to check it.
5125 return true;
5126 }
5127 // If we're not selectable by user, we should paint selection only while the
5128 // normal selection is styled as "attention" by "Find in Page" or something.
5129 return GetDisplaySelection() == nsISelectionController::SELECTION_ATTENTION;
5130}
5131
5132bool nsIFrame::ShouldHaveLineIfEmpty() const {
5133 switch (Style()->GetPseudoType()) {
5134 case PseudoStyleType::NotPseudo:
5135 break;
5136 case PseudoStyleType::MozScrolledContent:
5137 return GetParent()->ShouldHaveLineIfEmpty();
5138 default:
5139 return false;
5140 }
5141 return IsInputButtonControlFrame() || IsEditingHost(this);
5142}
5143
5144/**
5145 * Handles the Mouse Press Event for the frame
5146 */
5147NS_IMETHODIMPnsresult
5148nsIFrame::HandlePress(nsPresContext* aPresContext, WidgetGUIEvent* aEvent,
5149 nsEventStatus* aEventStatus) {
5150 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "./../../../layout/generic/nsIFrame.cpp", 5150); return
NS_ERROR_INVALID_POINTER; } } while (false)
;
5151 if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
5152 return NS_OK;
5153 }
5154
5155 NS_ENSURE_ARG_POINTER(aEvent)do { if ((__builtin_expect(!!(!(aEvent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEvent" ") failed", nullptr
, "./../../../layout/generic/nsIFrame.cpp", 5155); return NS_ERROR_INVALID_POINTER
; } } while (false)
;
5156 if (aEvent->mClass == eTouchEventClass) {
5157 return NS_OK;
5158 }
5159
5160 return MoveCaretToEventPoint(aPresContext, aEvent->AsMouseEvent(),
5161 aEventStatus);
5162}
5163
5164nsresult nsIFrame::MoveCaretToEventPoint(nsPresContext* aPresContext,
5165 WidgetMouseEvent* aMouseEvent,
5166 nsEventStatus* aEventStatus) {
5167 MOZ_ASSERT(aPresContext)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPresContext)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aPresContext))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aPresContext", "./../../../layout/generic/nsIFrame.cpp"
, 5167); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPresContext"
")"); do { MOZ_CrashSequence(__null, 5167); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5168 MOZ_ASSERT(aMouseEvent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aMouseEvent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aMouseEvent))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("aMouseEvent", "./../../../layout/generic/nsIFrame.cpp"
, 5168); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aMouseEvent"
")"); do { MOZ_CrashSequence(__null, 5168); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5169 MOZ_ASSERT(aMouseEvent->mMessage == eMouseDown)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aMouseEvent->mMessage == eMouseDown)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aMouseEvent->mMessage == eMouseDown))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aMouseEvent->mMessage == eMouseDown"
, "./../../../layout/generic/nsIFrame.cpp", 5169); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aMouseEvent->mMessage == eMouseDown" ")"
); do { MOZ_CrashSequence(__null, 5169); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5170 MOZ_ASSERT(aEventStatus)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aEventStatus)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aEventStatus))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aEventStatus", "./../../../layout/generic/nsIFrame.cpp"
, 5170); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEventStatus"
")"); do { MOZ_CrashSequence(__null, 5170); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5171 MOZ_ASSERT(nsEventStatus_eConsumeNoDefault != *aEventStatus)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nsEventStatus_eConsumeNoDefault != *aEventStatus)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(nsEventStatus_eConsumeNoDefault != *aEventStatus))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("nsEventStatus_eConsumeNoDefault != *aEventStatus"
, "./../../../layout/generic/nsIFrame.cpp", 5171); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "nsEventStatus_eConsumeNoDefault != *aEventStatus"
")"); do { MOZ_CrashSequence(__null, 5171); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5172
5173 mozilla::PresShell* presShell = aPresContext->GetPresShell();
5174 if (!presShell) {
5175 return NS_ERROR_FAILURE;
5176 }
5177
5178 // We often get out of sync state issues with mousedown events that
5179 // get interrupted by alerts/dialogs.
5180 // Check with the ESM to see if we should process this one
5181 EventStateManager* const esm = aPresContext->EventStateManager();
5182 if (!esm->EventStatusOK(aMouseEvent)) {
5183 return NS_OK;
5184 }
5185
5186 if (nsIContent* dragGestureContent = esm->GetTrackingDragGestureContent()) {
5187 // When the current tracked dragging gesture is different than this frame,
5188 // it means this frame was being dragged, however it got moved/destroyed. So
5189 // we should consider the drag is still happening, so return early here.
5190 // Additionally, when dragGestureContent is a `Text` and the text frame is
5191 // reframed by a preceding event listener, we're the parent element frame.
5192 // In that case, we need to treat this as a normal mouse button down.
5193 // Therefore, we should compare the inclusive flattened tree ancestor
5194 // element of dragGestureContent and our content.
5195 const bool isDragGestureContent =
5196 mContent == dragGestureContent ||
5197 mContent ==
5198 dragGestureContent->GetInclusiveFlattenedTreeAncestorElement();
5199 if (!isDragGestureContent) {
5200 return NS_OK;
5201 }
5202 }
5203
5204 const nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5205 aMouseEvent, RelativeTo{this});
5206
5207 // When not using `alt`, and clicking on a draggable, but non-editable
5208 // element, don't do anything, and let d&d handle the event.
5209 //
5210 // See bug 48876, bug 388659 and bug 55921 for context here.
5211 //
5212 // FIXME(emilio): The .Contains(pt) check looks a bit fishy. When would it be
5213 // false given we're the event target? If it is needed, why not checking the
5214 // actual draggable node rect instead?
5215 if (!aMouseEvent->IsAlt() && GetRectRelativeToSelf().Contains(pt)) {
5216 for (nsIContent* content = mContent; content;
5217 content = content->GetFlattenedTreeParent()) {
5218 if (nsContentUtils::ContentIsDraggable(content) &&
5219 !content->IsEditable()) {
5220 return NS_OK;
5221 }
5222 }
5223 }
5224
5225 // If we are in Navigator and the click is in a draggable node, we don't want
5226 // to start selection because we don't want to interfere with a potential
5227 // drag of said node and steal all its glory.
5228 const bool isEditor =
5229 presShell->GetSelectionFlags() == nsISelectionDisplay::DISPLAY_ALL;
5230
5231 // Don't do something if it's middle button down event.
5232 const bool isPrimaryButtonDown =
5233 aMouseEvent->mButton == MouseButton::ePrimary;
5234
5235 // Check whether this frame should handle selection events. If not, don't
5236 // tell selection the mouse event even occurred.
5237 if (!ShouldHandleSelectionMovementEvents(ForSelectionStart::Yes)) {
5238 return NS_OK;
5239 }
5240
5241 if (isPrimaryButtonDown) {
5242 // If the mouse is dragged outside the nearest enclosing scrollable area
5243 // while making a selection, the area will be scrolled. To do this, capture
5244 // the mouse on the nearest scroll container frame. If there isn't a scroll
5245 // container frame, or something else is already capturing the mouse,
5246 // there's no reason to capture.
5247 if (!PresShell::GetCapturingContent()) {
5248 ScrollContainerFrame* scrollContainerFrame =
5249 nsLayoutUtils::GetNearestScrollContainerFrame(
5250 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
5251 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
5252 if (scrollContainerFrame) {
5253 nsIFrame* capturingFrame = scrollContainerFrame;
5254 PresShell::SetCapturingContent(capturingFrame->GetContent(),
5255 CaptureFlags::IgnoreAllowedState);
5256 }
5257 }
5258 }
5259
5260 // XXX This is screwy; it really should use the selection frame, not the
5261 // event frame
5262 const nsFrameSelection* frameselection = GetConstFrameSelection();
5263 if (!frameselection || frameselection->GetDisplaySelection() ==
5264 nsISelectionController::SELECTION_OFF) {
5265 return NS_OK; // nothing to do we cannot affect selection from here
5266 }
5267
5268#ifdef XP_MACOSX
5269 // If Control key is pressed on macOS, it should be treated as right click.
5270 // So, don't change selection.
5271 if (aMouseEvent->IsControl()) {
5272 return NS_OK;
5273 }
5274 const bool control = aMouseEvent->IsMeta();
5275#else
5276 const bool control = aMouseEvent->IsControl();
5277#endif
5278
5279 RefPtr<nsFrameSelection> fc = const_cast<nsFrameSelection*>(frameselection);
5280 if (isPrimaryButtonDown && aMouseEvent->mClickCount > 1) {
5281 // These methods aren't const but can't actually delete anything,
5282 // so no need for AutoWeakFrame.
5283 fc->SetDragState(true);
5284 return HandleMultiplePress(aPresContext, aMouseEvent, aEventStatus,
5285 control);
5286 }
5287
5288 ContentOffsets offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
5289
5290 if (!offsets.content) {
5291 return NS_ERROR_FAILURE;
5292 }
5293
5294 const bool isSecondaryButton =
5295 aMouseEvent->mButton == MouseButton::eSecondary;
5296 if (isSecondaryButton) {
5297 if (!MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
5298 *frameselection, *aMouseEvent, *offsets.content,
5299 // When we collapse selection in nsFrameSelection::TakeFocus,
5300 // we always collapse selection to the start offset. Therefore,
5301 // we can ignore the end offset here. E.g., when an <img> is
5302 // clicked, set the primary offset to after it, but the the
5303 // secondary offset may be before it, see OffsetsForSingleFrame for
5304 // the detail.
5305 offsets.StartOffset())) {
5306 return NS_OK;
5307 }
5308 }
5309
5310 if (aMouseEvent->mMessage == eMouseDown &&
5311 aMouseEvent->mButton == MouseButton::eMiddle &&
5312 !offsets.content->IsEditable()) {
5313 // However, some users don't like the Chrome compatible behavior of
5314 // middle mouse click. They want to keep selection after starting
5315 // autoscroll. However, the selection change is important for middle
5316 // mouse past. Therefore, we should allow users to take the traditional
5317 // behavior back by themselves unless middle click paste is enabled or
5318 // autoscrolling is disabled.
5319 if (!Preferences::GetBool("middlemouse.paste", false) &&
5320 Preferences::GetBool("general.autoScroll", false) &&
5321 Preferences::GetBool("general.autoscroll.prevent_to_collapse_selection_"
5322 "by_middle_mouse_down",
5323 false)) {
5324 return NS_OK;
5325 }
5326 }
5327
5328 if (isPrimaryButtonDown) {
5329 // Let Ctrl/Cmd + left mouse down do table selection instead of drag
5330 // initiation.
5331 nsCOMPtr<nsIContent> parentContent;
5332 int32_t contentOffset;
5333 TableSelectionMode target;
5334 nsresult rv = GetDataForTableSelection(
5335 frameselection, presShell, aMouseEvent, getter_AddRefs(parentContent),
5336 &contentOffset, &target);
5337 if (NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1))) && parentContent) {
5338 fc->SetDragState(true);
5339 return fc->HandleTableSelection(parentContent, contentOffset, target,
5340 aMouseEvent);
5341 }
5342 }
5343
5344 fc->SetDelayedCaretData(nullptr);
5345
5346 if (isPrimaryButtonDown) {
5347 // Check if any part of this frame is selected, and if the user clicked
5348 // inside the selected region, and if it's the left button. If so, we delay
5349 // starting a new selection since the user may be trying to drag the
5350 // selected region to some other app.
5351
5352 if (GetContent() && GetContent()->IsMaybeSelected()) {
5353 bool inSelection = false;
5354 UniquePtr<SelectionDetails> details = frameselection->LookUpSelection(
5355 offsets.content, 0, offsets.EndOffset(),
5356 nsFrameSelection::IgnoreNormalSelection::No);
5357
5358 //
5359 // If there are any details, check to see if the user clicked
5360 // within any selected region of the frame.
5361 //
5362
5363 for (SelectionDetails* curDetail = details.get(); curDetail;
5364 curDetail = curDetail->mNext.get()) {
5365 //
5366 // If the user clicked inside a selection, then just
5367 // return without doing anything. We will handle placing
5368 // the caret later on when the mouse is released. We ignore
5369 // the spellcheck, find and url formatting selections.
5370 //
5371 if (curDetail->mSelectionType != SelectionType::eSpellCheck &&
5372 curDetail->mSelectionType != SelectionType::eFind &&
5373 curDetail->mSelectionType != SelectionType::eURLSecondary &&
5374 curDetail->mSelectionType != SelectionType::eURLStrikeout &&
5375 curDetail->mSelectionType != SelectionType::eHighlight &&
5376 curDetail->mSelectionType != SelectionType::eTargetText &&
5377 curDetail->mStart <= offsets.StartOffset() &&
5378 offsets.EndOffset() <= curDetail->mEnd) {
5379 inSelection = true;
5380 }
5381 }
5382
5383 if (inSelection) {
5384 fc->SetDragState(false);
5385 fc->SetDelayedCaretData(aMouseEvent);
5386 return NS_OK;
5387 }
5388 }
5389
5390 fc->SetDragState(true);
5391 }
5392
5393 // Do not touch any nsIFrame members after this point without adding
5394 // weakFrame checks.
5395 const nsFrameSelection::FocusMode focusMode = [&]() {
5396 // If "Shift" and "Ctrl" are both pressed, "Shift" is given precedence. This
5397 // mimics the old behaviour.
5398 const bool isShift =
5399 aMouseEvent->IsShift() &&
5400 // If Shift + secondary button press shoud open context menu without a
5401 // contextmenu event, user wants to open context menu like as a
5402 // secondary button press without Shift key.
5403 !(isSecondaryButton &&
5404 StaticPrefs::dom_event_contextmenu_shift_suppresses_event());
5405 if (isShift) {
5406 // If clicked in a link when focused content is editable, we should
5407 // collapse selection in the link for compatibility with Blink.
5408 if (isEditor) {
5409 for (Element* element : mContent->InclusiveAncestorsOfType<Element>()) {
5410 if (element->IsLink()) {
5411 return nsFrameSelection::FocusMode::kCollapseToNewPoint;
5412 }
5413 }
5414 }
5415 return nsFrameSelection::FocusMode::kExtendSelection;
5416 }
5417
5418 if (isPrimaryButtonDown && control) {
5419 return nsFrameSelection::FocusMode::kMultiRangeSelection;
5420 }
5421
5422 return nsFrameSelection::FocusMode::kCollapseToNewPoint;
5423 }();
5424
5425 nsresult rv = fc->HandleClick(
5426 MOZ_KnownLive(offsets.content)(offsets.content) /* bug 1636889 */, offsets.StartOffset(),
5427 offsets.EndOffset(), focusMode, offsets.associate);
5428 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5429 return rv;
5430 }
5431
5432 // We don't handle mouse button up if it's middle button.
5433 if (isPrimaryButtonDown && offsets.offset != offsets.secondaryOffset) {
5434 fc->MaintainSelection();
5435 }
5436
5437 if (isPrimaryButtonDown && isEditor && !aMouseEvent->IsShift() &&
5438 (offsets.EndOffset() - offsets.StartOffset()) == 1) {
5439 // A single node is selected and we aren't extending an existing selection,
5440 // which means the user clicked directly on an object (either
5441 // `user-select: all` or a non-text node without children). Therefore,
5442 // disable selection extension during mouse moves.
5443 // XXX This is a bit hacky; shouldn't editor be able to deal with this?
5444 fc->SetDragState(false);
5445 }
5446
5447 return NS_OK;
5448}
5449
5450bool nsIFrame::MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
5451 const nsFrameSelection& aFrameSelection,
5452 WidgetMouseEvent& aSecondaryButtonEvent,
5453 const nsIContent& aContentAtEventPoint, int32_t aOffsetAtEventPoint) const {
5454 MOZ_ASSERT(aSecondaryButtonEvent.mButton == MouseButton::eSecondary)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aSecondaryButtonEvent.mButton == MouseButton::eSecondary
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aSecondaryButtonEvent.mButton == MouseButton::eSecondary
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"aSecondaryButtonEvent.mButton == MouseButton::eSecondary", "./../../../layout/generic/nsIFrame.cpp"
, 5454); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aSecondaryButtonEvent.mButton == MouseButton::eSecondary"
")"); do { MOZ_CrashSequence(__null, 5454); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5455
5456 if (NS_WARN_IF(aOffsetAtEventPoint < 0)NS_warn_if_impl(aOffsetAtEventPoint < 0, "aOffsetAtEventPoint < 0"
, "./../../../layout/generic/nsIFrame.cpp", 5456)
) {
5457 return false;
5458 }
5459
5460 const bool contentIsEditable = aContentAtEventPoint.IsEditable();
5461 const TextControlElement* const contentAsTextControl =
5462 TextControlElement::FromNodeOrNull(
5463 aContentAtEventPoint.IsTextControlElement()
5464 ? &aContentAtEventPoint
5465 : aContentAtEventPoint.GetClosestNativeAnonymousSubtreeRoot());
5466 const Selection& selection = aFrameSelection.NormalSelection();
5467 const bool selectionIsCollapsed =
5468 selection.AreNormalAndCrossShadowBoundaryRangesCollapsed();
5469 // If right click in a selection range, we should not collapse
5470 // selection.
5471 if (!selectionIsCollapsed && nsContentUtils::IsPointInSelection(
5472 selection, aContentAtEventPoint,
5473 static_cast<uint32_t>(aOffsetAtEventPoint),
5474 true /* aAllowCrossShadowBoundary */)) {
5475 return false;
5476 }
5477 const bool wantToPreventMoveCaret =
5478 StaticPrefs::
5479 ui_mouse_right_click_move_caret_stop_if_in_focused_editable_node() &&
5480 selectionIsCollapsed && (contentIsEditable || contentAsTextControl);
5481 const bool wantToPreventCollapseSelection =
5482 StaticPrefs::
5483 ui_mouse_right_click_collapse_selection_stop_if_non_collapsed_selection() &&
5484 !selectionIsCollapsed;
5485 if (wantToPreventMoveCaret || wantToPreventCollapseSelection) {
5486 // If currently selection is limited in an editing host, we should not
5487 // collapse selection nor move caret if the clicked point is in the
5488 // ancestor limiter. Otherwise, this mouse click moves focus from the
5489 // editing host to different one or blur the editing host. In this case,
5490 // we need to update selection because keeping current selection in the
5491 // editing host looks like it's not blurred.
5492 // FIXME: If the active editing host is the document element, editor
5493 // does not set ancestor limiter properly. Fix it in the editor side.
5494 if (nsIContent* ancestorLimiter = selection.GetAncestorLimiter()) {
5495 MOZ_ASSERT(ancestorLimiter->IsEditable())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ancestorLimiter->IsEditable())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(ancestorLimiter->IsEditable
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("ancestorLimiter->IsEditable()", "./../../../layout/generic/nsIFrame.cpp"
, 5495); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ancestorLimiter->IsEditable()"
")"); do { MOZ_CrashSequence(__null, 5495); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5496 return !aContentAtEventPoint.IsInclusiveDescendantOf(ancestorLimiter);
5497 }
5498 }
5499 // If selection is editable and `stop_if_in_focused_editable_node` pref is
5500 // set to true, user does not want to move caret to right click place if
5501 // clicked in the focused text control element.
5502 if (wantToPreventMoveCaret && contentAsTextControl &&
5503 contentAsTextControl == nsFocusManager::GetFocusedElementStatic()) {
5504 return false;
5505 }
5506 // If currently selection is not limited in an editing host, we should
5507 // collapse selection only when this click moves focus to an editing
5508 // host because we need to update selection in this case.
5509 if (wantToPreventCollapseSelection && !contentIsEditable) {
5510 return false;
5511 }
5512
5513 return !StaticPrefs::
5514 ui_mouse_right_click_collapse_selection_stop_if_non_editable_node() ||
5515 // The user does not want to collapse selection into non-editable
5516 // content by a right button click.
5517 contentIsEditable ||
5518 // Treat clicking in a text control as always clicked on editable
5519 // content because we want a hack only for clicking in normal text
5520 // nodes which is outside any editing hosts.
5521 contentAsTextControl;
5522}
5523
5524void nsIFrame::HandleContextMenuEventToSelectWordOrLink(
5525 const WidgetMouseEvent& aContextMenuEvent) {
5526 MOZ_ASSERT(aContextMenuEvent.mMessage == eContextMenu)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aContextMenuEvent.mMessage == eContextMenu)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aContextMenuEvent.mMessage == eContextMenu))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aContextMenuEvent.mMessage == eContextMenu"
, "./../../../layout/generic/nsIFrame.cpp", 5526); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aContextMenuEvent.mMessage == eContextMenu"
")"); do { MOZ_CrashSequence(__null, 5526); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5527
5528 if (!StaticPrefs::ui_mouse_right_click_select_under_cursor()) {
5529 return;
5530 }
5531
5532 // A menu opened from the keyboard acts on the selection the user already
5533 // made, and has no click point to select at.
5534 if (aContextMenuEvent.IsContextMenuKeyEvent()) {
5535 return;
5536 }
5537
5538 if (!ShouldHandleSelectionMovementEvents(ForSelectionStart::Yes)) {
5539 return;
5540 }
5541
5542 const nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5543 &aContextMenuEvent, RelativeTo{this});
5544 ContentOffsets offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
5545 if (!offsets.content) {
5546 return;
5547 }
5548
5549 const RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
5550 if (!frameSelection) {
5551 return;
5552 }
5553
5554 if (!SelectingWordOrLinkAtEventPointAllowed(
5555 *frameSelection, aContextMenuEvent, pt, *offsets.content,
5556 offsets.StartOffset())) {
5557 return;
5558 }
5559
5560 SelectWordOrLinkAtPoint(pt,
5561 MOZ_KnownLive(*offsets.content)(*offsets.content) /* bug 1636889 */);
5562}
5563
5564bool nsIFrame::SelectingWordOrLinkAtEventPointAllowed(
5565 const nsFrameSelection& aFrameSelection,
5566 const WidgetMouseEvent& aContextMenuEvent, const nsPoint& aPoint,
5567 const nsIContent& aContentAtEventPoint, int32_t aOffsetAtEventPoint) const {
5568 MOZ_ASSERT(aContextMenuEvent.mMessage == eContextMenu)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aContextMenuEvent.mMessage == eContextMenu)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aContextMenuEvent.mMessage == eContextMenu))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aContextMenuEvent.mMessage == eContextMenu"
, "./../../../layout/generic/nsIFrame.cpp", 5568); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aContextMenuEvent.mMessage == eContextMenu"
")"); do { MOZ_CrashSequence(__null, 5568); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5569
5570 const bool contentIsEditable = aContentAtEventPoint.IsEditable();
5571 if (contentIsEditable &&
5572 !StaticPrefs::ui_mouse_right_click_select_in_editable()) {
5573 return false;
5574 }
5575
5576 // Shift + secondary button press has already extended or collapsed the
5577 // selection on mouse down, so the user is pointing at a boundary rather than
5578 // at a word.
5579 if (aContextMenuEvent.IsShift()) {
5580 return false;
5581 }
5582
5583 if (NS_WARN_IF(aOffsetAtEventPoint < 0)NS_warn_if_impl(aOffsetAtEventPoint < 0, "aOffsetAtEventPoint < 0"
, "./../../../layout/generic/nsIFrame.cpp", 5583)
) {
5584 return false;
5585 }
5586
5587 const Selection& selection = aFrameSelection.NormalSelection();
5588 // A click inside the selection keeps it, so that the context menu acts on
5589 // what the user selected rather than on what they happened to click.
5590 if (nsContentUtils::IsPointInSelection(
5591 selection, aContentAtEventPoint,
5592 static_cast<uint32_t>(aOffsetAtEventPoint),
5593 true /* aAllowCrossShadowBoundary */)) {
5594 return false;
5595 }
5596
5597 // GetContentOffsetsFromPoint() snaps to the closest text, so the click may
5598 // have landed next to the text rather than on it, e.g. in the padding of a
5599 // block. Only a click on the text itself selects.
5600 const nsIFrame* const frameAtPoint =
5601 nsLayoutUtils::GetFrameForPoint(RelativeTo{this}, aPoint);
5602 return frameAtPoint && frameAtPoint->IsTextFrame();
5603}
5604
5605nsresult nsIFrame::SelectWordOrLinkAtPoint(
5606 const nsPoint& aPoint, const nsIContent& aContentAtEventPoint) {
5607 Element* linkToSelect = nullptr;
5608 for (Element* element :
5609 aContentAtEventPoint.InclusiveFlatTreeAncestorsOfType<Element>()) {
5610 if (element->IsLink()) {
5611 linkToSelect = element;
5612 break;
5613 }
5614 }
5615 if (!linkToSelect) {
5616 return SelectByTypeAtPoint(aPoint, eSelectWord, eSelectWord, 0);
5617 }
5618
5619 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
5620 if (!frameSelection) {
5621 return NS_OK;
5622 }
5623 // Passing different start and end offsets is how HandleClick() selects a
5624 // range rather than collapsing, so this covers every child of the link.
5625 const uint32_t endOffset = linkToSelect->GetChildCount();
5626 nsCOMPtr<nsIContent> link = linkToSelect;
5627 return frameSelection->HandleClick(
5628 link, 0u, endOffset, nsFrameSelection::FocusMode::kCollapseToNewPoint,
5629 CaretAssociationHint::After);
5630}
5631
5632nsIFrame::ContentOffsets nsIFrame::GetContentOffsetsFromPointForSelection(
5633 const nsPoint& aPoint) {
5634 // A text control's own frames use its independent selection, where its
5635 // editor's anonymous content belongs.
5636 const nsFrameSelection* const frameSelection = GetConstFrameSelection();
5637 const Element* const independentSelectionRoot =
5638 frameSelection ? frameSelection->GetIndependentSelectionRootElement()
5639 : nullptr;
5640 ContentOffsets offsets = GetContentOffsetsFromPoint(
5641 aPoint, independentSelectionRoot
5642 ? SKIP_HIDDEN
5643 : SKIP_HIDDEN | IGNORE_NATIVE_ANONYMOUS_SUBTREE);
5644 if (offsets.content && independentSelectionRoot &&
5645 !independentSelectionRoot->Contains(offsets.content)) {
5646 // The text control's independent selection cannot use offsets outside
5647 // its editor, e.g. if a press on its padding resolves to an ancestor
5648 // with `user-select: all`.
5649 return ContentOffsets();
5650 }
5651 return offsets;
5652}
5653
5654nsresult nsIFrame::SelectByTypeAtPoint(const nsPoint& aPoint,
5655 nsSelectionAmount aBeginAmountType,
5656 nsSelectionAmount aEndAmountType,
5657 uint32_t aSelectFlags) {
5658 // No point in selecting if selection is turned off
5659 if (!ShouldHandleSelectionMovementEvents()) {
5660 return NS_OK;
5661 }
5662
5663 ContentOffsets offsets = GetContentOffsetsFromPointForSelection(aPoint);
5664 if (!offsets.content) {
5665 return NS_ERROR_FAILURE;
5666 }
5667
5668 FrameAndOffset frameAndOffset = SelectionMovementUtils::GetFrameForNodeOffset(
5669 offsets.content, offsets.offset, offsets.associate);
5670 if (!frameAndOffset) {
5671 return NS_ERROR_FAILURE;
5672 }
5673 return frameAndOffset->PeekBackwardAndForwardForSelection(
5674 aBeginAmountType, aEndAmountType,
5675 static_cast<int32_t>(frameAndOffset.mOffsetInFrameContent),
5676 aBeginAmountType != eSelectWord, aSelectFlags);
5677}
5678
5679/**
5680 * Multiple Mouse Press -- line or paragraph selection -- for the frame.
5681 * Wouldn't it be nice if this didn't have to be hardwired into Frame code?
5682 */
5683NS_IMETHODIMPnsresult
5684nsIFrame::HandleMultiplePress(nsPresContext* aPresContext,
5685 WidgetGUIEvent* aEvent,
5686 nsEventStatus* aEventStatus, bool aControlHeld) {
5687 NS_ENSURE_ARG_POINTER(aEvent)do { if ((__builtin_expect(!!(!(aEvent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEvent" ") failed", nullptr
, "./../../../layout/generic/nsIFrame.cpp", 5687); return NS_ERROR_INVALID_POINTER
; } } while (false)
;
5688 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "./../../../layout/generic/nsIFrame.cpp", 5688); return
NS_ERROR_INVALID_POINTER; } } while (false)
;
5689
5690 if (nsEventStatus_eConsumeNoDefault == *aEventStatus ||
5691 !ShouldHandleSelectionMovementEvents()) {
5692 return NS_OK;
5693 }
5694
5695 // Find out whether we're doing line or paragraph selection.
5696 // If browser.triple_click_selects_paragraph is true, triple-click selects
5697 // paragraph. Otherwise, triple-click selects line, and quadruple-click
5698 // selects paragraph (on platforms that support quadruple-click).
5699 nsSelectionAmount beginAmount, endAmount;
5700 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
5701 if (!mouseEvent) {
5702 return NS_OK;
5703 }
5704
5705 if (mouseEvent->mClickCount == 4) {
5706 beginAmount = endAmount = eSelectParagraph;
5707 } else if (mouseEvent->mClickCount == 3) {
5708 if (Preferences::GetBool("browser.triple_click_selects_paragraph")) {
5709 beginAmount = endAmount = eSelectParagraph;
5710 } else {
5711 beginAmount = eSelectBeginLine;
5712 endAmount = eSelectEndLine;
5713 }
5714 } else if (mouseEvent->mClickCount == 2) {
5715 // We only want inline frames; PeekBackwardAndForward dislikes blocks
5716 beginAmount = endAmount = eSelectWord;
5717 } else {
5718 return NS_OK;
5719 }
5720
5721 nsPoint relPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5722 mouseEvent, RelativeTo{this});
5723 return SelectByTypeAtPoint(relPoint, beginAmount, endAmount,
5724 (aControlHeld ? SELECT_ACCUMULATE : 0));
5725}
5726
5727nsresult nsIFrame::PeekBackwardAndForwardForSelection(
5728 nsSelectionAmount aAmountBack, nsSelectionAmount aAmountForward,
5729 int32_t aStartPos, bool aJumpLines, uint32_t aSelectFlags) {
5730 nsIFrame* baseFrame = this;
5731 int32_t baseOffset = aStartPos;
5732 nsresult rv;
5733
5734 PeekOffsetOptions peekOffsetOptions{PeekOffsetOption::StopAtScroller};
5735 if (aJumpLines) {
5736 peekOffsetOptions += PeekOffsetOption::JumpLines;
5737 }
5738
5739 Element* const ancestorLimiter = [&]() -> Element* {
5740 const nsFrameSelection* const frameSelection = GetConstFrameSelection();
5741 return frameSelection
5742 ? frameSelection
5743 ->GetAncestorLimiterOrIndependentSelectionRootElement()
5744 : nullptr;
5745 }();
5746
5747 if (aAmountBack == eSelectWord) {
5748 // To avoid selecting the previous word when at start of word,
5749 // first move one character forward.
5750 PeekOffsetStruct pos(eSelectCharacter, eDirNext, aStartPos, nsPoint(0, 0),
5751 peekOffsetOptions, eDefaultBehavior, ancestorLimiter);
5752 rv = PeekOffset(&pos);
5753 if (NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1)))) {
5754 baseFrame = pos.mResultFrame;
5755 baseOffset = pos.mContentOffset;
5756 }
5757 }
5758
5759 // Search backward for a boundary.
5760 PeekOffsetStruct startpos(aAmountBack, eDirPrevious, baseOffset,
5761 nsPoint(0, 0), peekOffsetOptions, eDefaultBehavior,
5762 ancestorLimiter);
5763 rv = baseFrame->PeekOffset(&startpos);
5764 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5765 return rv;
5766 }
5767
5768 // If the backward search stayed within the same frame, search forward from
5769 // that position for the end boundary; but if it crossed out to a sibling or
5770 // ancestor, start from the original position.
5771 if (startpos.mResultFrame == baseFrame) {
5772 baseOffset = startpos.mContentOffset;
5773 } else {
5774 baseFrame = this;
5775 baseOffset = aStartPos;
5776 }
5777
5778 PeekOffsetStruct endpos(aAmountForward, eDirNext, baseOffset, nsPoint(0, 0),
5779 peekOffsetOptions, eDefaultBehavior, ancestorLimiter);
5780 rv = baseFrame->PeekOffset(&endpos);
5781 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5782 return rv;
5783 }
5784
5785 // Keep frameSelection alive.
5786 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
5787
5788 const nsFrameSelection::FocusMode focusMode =
5789 (aSelectFlags & SELECT_ACCUMULATE)
5790 ? nsFrameSelection::FocusMode::kMultiRangeSelection
5791 : nsFrameSelection::FocusMode::kCollapseToNewPoint;
5792 rv = frameSelection->HandleClick(
5793 MOZ_KnownLive(startpos.mResultContent)(startpos.mResultContent) /* bug 1636889 */,
5794 startpos.mContentOffset, startpos.mContentOffset, focusMode,
5795 CaretAssociationHint::After);
5796 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5797 return rv;
5798 }
5799
5800 rv = frameSelection->HandleClick(
5801 MOZ_KnownLive(endpos.mResultContent)(endpos.mResultContent) /* bug 1636889 */,
5802 endpos.mContentOffset, endpos.mContentOffset,
5803 nsFrameSelection::FocusMode::kExtendSelection,
5804 CaretAssociationHint::Before);
5805 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5806 return rv;
5807 }
5808 if (aAmountBack == eSelectWord) {
5809 frameSelection->SetClickSelectionType(ClickSelectionType::Double);
5810 } else if (aAmountBack == eSelectParagraph) {
5811 frameSelection->SetClickSelectionType(ClickSelectionType::Triple);
5812 }
5813
5814 // maintain selection
5815 return frameSelection->MaintainSelection(aAmountBack);
5816}
5817
5818NS_IMETHODIMPnsresult nsIFrame::HandleDrag(nsPresContext* aPresContext,
5819 WidgetGUIEvent* aEvent,
5820 nsEventStatus* aEventStatus) {
5821 MOZ_ASSERT(aEvent->mClass == eMouseEventClass,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aEvent->mClass == eMouseEventClass)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(aEvent->mClass == eMouseEventClass))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aEvent->mClass == eMouseEventClass"
" (" "HandleDrag can only handle mouse event" ")", "./../../../layout/generic/nsIFrame.cpp"
, 5822); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEvent->mClass == eMouseEventClass"
") (" "HandleDrag can only handle mouse event" ")"); do { MOZ_CrashSequence
(__null, 5822); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
5822 "HandleDrag can only handle mouse event")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aEvent->mClass == eMouseEventClass)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(aEvent->mClass == eMouseEventClass))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aEvent->mClass == eMouseEventClass"
" (" "HandleDrag can only handle mouse event" ")", "./../../../layout/generic/nsIFrame.cpp"
, 5822); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEvent->mClass == eMouseEventClass"
") (" "HandleDrag can only handle mouse event" ")"); do { MOZ_CrashSequence
(__null, 5822); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
5823
5824 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "./../../../layout/generic/nsIFrame.cpp", 5824); return
NS_ERROR_INVALID_POINTER; } } while (false)
;
5825
5826 RefPtr<nsFrameSelection> frameselection = GetFrameSelection();
5827 if (!frameselection) {
5828 return NS_OK;
5829 }
5830
5831 bool mouseDown = frameselection->GetDragState();
5832 if (!mouseDown) {
5833 return NS_OK;
5834 }
5835
5836 nsIFrame* scrollbar =
5837 nsLayoutUtils::GetClosestFrameOfType(this, LayoutFrameType::Scrollbar);
5838 if (!scrollbar && !ShouldHandleSelectionMovementEvents()) {
5839 // XXX Do we really need to exclude non-selectable content here?
5840 // GetContentOffsetsFromPoint can handle it just fine, although some
5841 // other stuff might not like it.
5842 return NS_OK;
5843 }
5844
5845 frameselection->StopAutoScrollTimer();
5846
5847 // Check if we are dragging in a table cell
5848 nsCOMPtr<nsIContent> parentContent;
5849 int32_t contentOffset;
5850 TableSelectionMode target;
5851 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
5852 mozilla::PresShell* presShell = aPresContext->PresShell();
5853 nsresult result;
5854 result = GetDataForTableSelection(frameselection, presShell, mouseEvent,
5855 getter_AddRefs(parentContent),
5856 &contentOffset, &target);
5857
5858 AutoWeakFrame weakThis = this;
5859 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) && parentContent) {
5860 result = frameselection->HandleTableSelection(parentContent, contentOffset,
5861 target, mouseEvent);
5862 if (NS_WARN_IF(NS_FAILED(result))NS_warn_if_impl(((bool)(__builtin_expect(!!(NS_FAILED_impl(result
)), 0))), "NS_FAILED(result)", "./../../../layout/generic/nsIFrame.cpp"
, 5862)
) {
5863 return result;
5864 }
5865 } else {
5866 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mouseEvent,
5867 RelativeTo{this});
5868 frameselection->HandleDrag(this, pt);
5869 }
5870
5871 // The frameselection object notifies selection listeners synchronously above
5872 // which might have killed us.
5873 if (!weakThis.IsAlive()) {
5874 return NS_OK;
5875 }
5876
5877 // Get the nearest scroll container frame.
5878 ScrollContainerFrame* scrollContainerFrame =
5879 nsLayoutUtils::GetNearestScrollContainerFrame(
5880 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
5881 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
5882
5883 if (scrollContainerFrame) {
5884 nsIFrame* capturingFrame = scrollContainerFrame->GetScrolledFrame();
5885 if (capturingFrame) {
5886 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5887 mouseEvent, RelativeTo{capturingFrame});
5888 frameselection->StartAutoScrollTimer(capturingFrame, pt, 30);
5889 }
5890 }
5891
5892 return NS_OK;
5893}
5894
5895/**
5896 * This static method handles part of the nsIFrame::HandleRelease in a way
5897 * which doesn't rely on the nsIFrame object to stay alive.
5898 */
5899MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult HandleFrameSelection(
5900 nsFrameSelection* aFrameSelection, nsIFrame::ContentOffsets& aOffsets,
5901 bool aHandleTableSel, int32_t aContentOffsetForTableSel,
5902 TableSelectionMode aTargetForTableSel,
5903 nsIContent* aParentContentForTableSel, WidgetGUIEvent* aEvent,
5904 const nsEventStatus* aEventStatus) {
5905 if (!aFrameSelection) {
5906 return NS_OK;
5907 }
5908
5909 nsresult rv = NS_OK;
5910
5911 if (nsEventStatus_eConsumeNoDefault != *aEventStatus) {
5912 if (!aHandleTableSel) {
5913 if (!aOffsets.content || !aFrameSelection->HasDelayedCaretData()) {
5914 return NS_ERROR_FAILURE;
5915 }
5916
5917 // We are doing this to simulate what we would have done on HandlePress.
5918 // We didn't do it there to give the user an opportunity to drag
5919 // the text, but since they didn't drag, we want to place the
5920 // caret.
5921 // However, we'll use the mouse position from the release, since:
5922 // * it's easier
5923 // * that's the normal click position to use (although really, in
5924 // the normal case, small movements that don't count as a drag
5925 // can do selection)
5926 aFrameSelection->SetDragState(true);
5927
5928 const nsFrameSelection::FocusMode focusMode =
5929 aFrameSelection->IsShiftDownInDelayedCaretData()
5930 ? nsFrameSelection::FocusMode::kExtendSelection
5931 : nsFrameSelection::FocusMode::kCollapseToNewPoint;
5932 rv = aFrameSelection->HandleClick(
5933 MOZ_KnownLive(aOffsets.content)(aOffsets.content) /* bug 1636889 */,
5934 aOffsets.StartOffset(), aOffsets.EndOffset(), focusMode,
5935 aOffsets.associate);
5936 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5937 return rv;
5938 }
5939 } else if (aParentContentForTableSel) {
5940 aFrameSelection->SetDragState(false);
5941 rv = aFrameSelection->HandleTableSelection(
5942 aParentContentForTableSel, aContentOffsetForTableSel,
5943 aTargetForTableSel, aEvent->AsMouseEvent());
5944 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5945 return rv;
5946 }
5947 }
5948 aFrameSelection->SetDelayedCaretData(nullptr);
5949 }
5950
5951 aFrameSelection->SetDragState(false);
5952 aFrameSelection->StopAutoScrollTimer();
5953
5954 return NS_OK;
5955}
5956
5957NS_IMETHODIMPnsresult nsIFrame::HandleRelease(nsPresContext* aPresContext,
5958 WidgetGUIEvent* aEvent,
5959 nsEventStatus* aEventStatus) {
5960 if (aEvent->mClass != eMouseEventClass) {
5961 return NS_OK;
5962 }
5963
5964 nsIFrame* activeFrame = GetActiveSelectionFrame(aPresContext, this);
5965
5966 nsCOMPtr<nsIContent> captureContent = PresShell::GetCapturingContent();
5967
5968 const bool selectionOff = !ShouldHandleSelectionMovementEvents();
5969
5970 RefPtr<nsFrameSelection> frameselection;
5971 ContentOffsets offsets;
5972 nsCOMPtr<nsIContent> parentContent;
5973 int32_t contentOffsetForTableSel = 0;
5974 TableSelectionMode targetForTableSel = TableSelectionMode::None;
5975 bool handleTableSelection = true;
5976
5977 if (!selectionOff) {
5978 frameselection = GetFrameSelection();
5979 if (nsEventStatus_eConsumeNoDefault != *aEventStatus && frameselection) {
5980 // Check if the frameselection recorded the mouse going down.
5981 // If not, the user must have clicked in a part of the selection.
5982 // Place the caret before continuing!
5983
5984 if (frameselection->MouseDownRecorded()) {
5985 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5986 aEvent, RelativeTo{this});
5987 offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
5988 handleTableSelection = false;
5989 } else {
5990 GetDataForTableSelection(frameselection, PresShell(),
5991 aEvent->AsMouseEvent(),
5992 getter_AddRefs(parentContent),
5993 &contentOffsetForTableSel, &targetForTableSel);
5994 }
5995 }
5996 }
5997
5998 // We might be capturing in some other document and the event just happened to
5999 // trickle down here. Make sure that document's frame selection is notified.
6000 // Note, this may cause the current nsIFrame object to be deleted, bug 336592.
6001 RefPtr<nsFrameSelection> frameSelection;
6002 if (activeFrame != this &&
6003 activeFrame->ShouldHandleSelectionMovementEvents()) {
6004 frameSelection = activeFrame->GetFrameSelection();
6005 }
6006
6007 // Also check the selection of the capturing content which might be in a
6008 // different document.
6009 if (!frameSelection && captureContent) {
6010 if (Document* doc = captureContent->GetComposedDoc()) {
6011 mozilla::PresShell* capturingPresShell = doc->GetPresShell();
6012 if (capturingPresShell &&
6013 capturingPresShell != PresContext()->GetPresShell()) {
6014 frameSelection = capturingPresShell->FrameSelection();
6015 }
6016 }
6017 }
6018
6019 if (frameSelection) {
6020 AutoWeakFrame wf(this);
6021 frameSelection->SetDragState(false);
6022 frameSelection->StopAutoScrollTimer();
6023 if (wf.IsAlive()) {
6024 ScrollContainerFrame* scrollContainerFrame =
6025 nsLayoutUtils::GetNearestScrollContainerFrame(
6026 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
6027 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
6028 if (scrollContainerFrame) {
6029 // Perform any additional scrolling needed to maintain CSS snap point
6030 // requirements when autoscrolling is over.
6031 scrollContainerFrame->ScrollSnap();
6032 }
6033 }
6034 }
6035
6036 // Do not call any methods of the current object after this point!!!
6037 // The object is perhaps dead!
6038
6039 return selectionOff ? NS_OK
6040 : HandleFrameSelection(
6041 frameselection, offsets, handleTableSelection,
6042 contentOffsetForTableSel, targetForTableSel,
6043 parentContent, aEvent, aEventStatus);
6044}
6045
6046struct MOZ_STACK_CLASS FrameContentRange {
6047 FrameContentRange(nsIContent* aContent, int32_t aStart, int32_t aEnd)
6048 : content(aContent), start(aStart), end(aEnd) {}
6049 nsCOMPtr<nsIContent> content;
6050 int32_t start;
6051 int32_t end;
6052};
6053
6054static bool IsRelevantBlockFrame(const nsIFrame* aFrame) {
6055 if (!aFrame->IsBlockOutside() && !aFrame->IsTableCaption()) {
6056 return false;
6057 }
6058 if (aFrame->GetContent() &&
6059 aFrame->GetContent()->IsInNativeAnonymousSubtree() &&
6060 !aFrame->GetContent()->HasBeenInUAWidget()) {
6061 // This helps skipping things like scrollbar parts.
6062 return false;
6063 }
6064 auto pseudoType = aFrame->Style()->GetPseudoType();
6065 if (PseudoStyle::IsAnonBox(pseudoType)) {
6066 // Table cell contents should be considered block boundaries for this
6067 // purpose.
6068 return pseudoType == PseudoStyleType::MozCellContent;
6069 }
6070 return true;
6071}
6072
6073// Retrieve the content offsets of a frame
6074static FrameContentRange GetRangeForFrame(const nsIFrame* aFrame,
6075 bool includeReplaced = false) {
6076 nsIContent* content = aFrame->GetContent();
6077 if (!content) {
6078 NS_WARNING("Frame has no content")NS_DebugBreak(NS_DEBUG_WARNING, "Frame has no content", nullptr
, "./../../../layout/generic/nsIFrame.cpp", 6078)
;
6079 return FrameContentRange(nullptr, -1, -1);
6080 }
6081
6082 LayoutFrameType type = aFrame->Type();
6083 if (type == LayoutFrameType::Text) {
6084 auto [offset, offsetEnd] = aFrame->GetOffsets();
6085 return FrameContentRange(content, offset, offsetEnd);
6086 }
6087
6088 if (type == LayoutFrameType::Br) {
6089 nsIContent* parent = content->GetParent();
6090 const int32_t beginOffset = parent->ComputeIndexOf_Deprecated(content);
6091 return FrameContentRange(parent, beginOffset, beginOffset);
6092 }
6093
6094 while (content->IsRootOfNativeAnonymousSubtree()) {
6095 content = content->GetParent();
6096 }
6097
6098 if (!includeReplaced && aFrame->IsReplaced()) {
6099 if (auto* parent = content->GetParent()) {
6100 // TODO(emilio): Revise this in presence of Shadow DOM / display:
6101 // contents, it's likely that we don't want to just walk the light tree,
6102 // and we need to change the representation of FrameContentRange.
6103 Maybe<uint32_t> index = parent->ComputeIndexOf(content);
6104 MOZ_ASSERT(index.isSome())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(index.isSome())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(index.isSome()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("index.isSome()"
, "./../../../layout/generic/nsIFrame.cpp", 6104); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "index.isSome()" ")"); do { MOZ_CrashSequence
(__null, 6104); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
6105 return FrameContentRange(parent, static_cast<int32_t>(*index),
6106 static_cast<int32_t>(*index + 1));
6107 }
6108 }
6109
6110 return FrameContentRange(content, 0, content->GetChildCount());
6111}
6112
6113// The FrameTarget represents the closest frame to a point that can be selected
6114// The frame is the frame represented, frameEdge says whether one end of the
6115// frame is the result (in which case different handling is needed), and
6116// afterFrame says which end is represented if frameEdge is true
6117struct FrameTarget {
6118 explicit operator bool() const { return !!frame; }
6119
6120 nsIFrame* frame = nullptr;
6121 bool frameEdge = false;
6122 bool afterFrame = false;
6123};
6124
6125// See function implementation for information
6126static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
6127 const nsPoint& aPoint,
6128 uint32_t aFlags);
6129
6130static bool SelfIsSelectable(nsIFrame* aFrame, nsIFrame* aParentFrame,
6131 uint32_t aFlags) {
6132 // We should not move selection into a native anonymous subtree when handling
6133 // selection outside it.
6134 if ((aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE) &&
6135 aParentFrame->GetClosestNativeAnonymousSubtreeRoot() !=
6136 aFrame->GetClosestNativeAnonymousSubtreeRoot()) {
6137 return false;
6138 }
6139 if ((aFlags & nsIFrame::SKIP_HIDDEN) &&
6140 (!aFrame->StyleVisibility()->IsVisible() ||
6141 aFrame->IsHiddenByContentVisibilityOnAnyAncestor(
6142 nsIFrame::IncludeContentVisibility::Hidden))) {
6143 return false;
6144 }
6145 if (aFrame->IsGeneratedContentFrame()) {
6146 return false;
6147 }
6148 // XXX Why do we ignore `aFlag & nsIFrame::IGNORE_SELECTION_STYLE`?
6149 if (aFrame->Style()->UserSelect() == StyleUserSelect::None) {
6150 return false;
6151 }
6152 if (aFrame->IsEmpty() &&
6153 (!aFrame->IsTextFrame() || !aFrame->ContentIsEditable())) {
6154 // FIXME(emilio): Historically we haven't treated empty frames as
6155 // selectable, but also we had special-cases so that editable empty text
6156 // frames returned false from IsEmpty(). Sort this out (probably by
6157 // removing the IsEmpty() condition altogether).
6158 return false;
6159 }
6160 return true;
6161}
6162
6163static bool FrameContentCanHaveParentSelectionRange(nsIFrame* aFrame) {
6164 // If we are only near (not directly over) then don't traverse frames with
6165 // independent selection (e.g. text controls, see bug 268497). Note that this
6166 // prevents any of the users of this method from entering form controls.
6167 // XXX We might want some way to allow using the up-arrow to go into a form
6168 // control, but the focus didn't work right anyway; it'd probably be enough
6169 // if the left and right arrows could enter textboxes (which I don't believe
6170 // they can at the moment)
6171 if (aFrame->IsTextInputFrame()) {
6172 return false;
6173 }
6174 return !aFrame->IsGeneratedContentFrame();
6175}
6176
6177static bool SelectionDescendToKids(nsIFrame* aFrame) {
6178 if (!FrameContentCanHaveParentSelectionRange(aFrame)) {
6179 return false;
6180 }
6181 auto style = aFrame->Style()->UserSelect();
6182 return style != StyleUserSelect::All && style != StyleUserSelect::None;
6183}
6184
6185static FrameTarget GetSelectionClosestFrameForChild(nsIFrame* aChild,
6186 const nsPoint& aPoint,
6187 uint32_t aFlags) {
6188 nsIFrame* parent = aChild->GetParent();
6189 if (SelectionDescendToKids(aChild)) {
6190 nsPoint pt = aPoint - aChild->GetOffsetTo(parent);
6191 return GetSelectionClosestFrame(aChild, pt, aFlags);
6192 }
6193 return FrameTarget{aChild, false, false};
6194}
6195
6196// When the cursor needs to be at the beginning of a block, it shouldn't be
6197// before the first child. A click on a block whose first child is a block
6198// should put the cursor in the child. The cursor shouldn't be between the
6199// blocks, because that's not where it's expected.
6200// Note that this method is guaranteed to succeed.
6201static FrameTarget DrillDownToSelectionFrame(nsIFrame* aFrame, bool aEndFrame,
6202 uint32_t aFlags) {
6203 if (SelectionDescendToKids(aFrame)) {
6204 nsIFrame* result = nullptr;
6205 nsIFrame* frame = aFrame->PrincipalChildList().FirstChild();
6206 if (!aEndFrame) {
6207 while (frame && !SelfIsSelectable(frame, aFrame, aFlags)) {
6208 frame = frame->GetNextSibling();
6209 }
6210 if (frame) {
6211 result = frame;
6212 }
6213 } else {
6214 // Because the frame tree is singly linked, to find the last frame,
6215 // we have to iterate through all the frames
6216 // XXX I have a feeling this could be slow for long blocks, although
6217 // I can't find any slowdowns
6218 while (frame) {
6219 if (SelfIsSelectable(frame, aFrame, aFlags)) {
6220 result = frame;
6221 }
6222 frame = frame->GetNextSibling();
6223 }
6224 }
6225 if (result) {
6226 return DrillDownToSelectionFrame(result, aEndFrame, aFlags);
6227 }
6228 }
6229 // If the current frame has no targetable children, target the current frame
6230 return FrameTarget{aFrame, true, aEndFrame};
6231}
6232
6233// This method finds the closest valid FrameTarget on a given line; if there is
6234// no valid FrameTarget on the line, it returns a null FrameTarget
6235static FrameTarget GetSelectionClosestFrameForLine(
6236 nsBlockFrame* aParent, nsBlockFrame::LineIterator aLine,
6237 const nsPoint& aPoint, uint32_t aFlags) {
6238 // Account for end of lines (any iterator from the block is valid)
6239 if (aLine == aParent->LinesEnd()) {
6240 return DrillDownToSelectionFrame(aParent, true, aFlags);
6241 }
6242 nsIFrame* closestFromIStart = nullptr;
6243 nsIFrame* closestFromIEnd = nullptr;
6244 nscoord closestIStart = aLine->IStart(), closestIEnd = aLine->IEnd();
6245 WritingMode wm = aLine->mWritingMode;
6246 LogicalPoint pt(wm, aPoint, aLine->mContainerSize);
6247 bool canSkipBr = false;
6248 bool lastFrameWasEditable = false;
6249 for (nsIFrame* frame : aLine->ChildFrames()) {
6250 // Skip brFrames. Can only skip if the line contains at least
6251 // one selectable and non-empty frame before. Also, avoid skipping brs if
6252 // the previous thing had a different editableness than us, since then we
6253 // may end up not being able to select after it if the br is the last thing
6254 // on the line.
6255 if (!SelfIsSelectable(frame, aParent, aFlags) ||
6256 (canSkipBr && frame->IsBrFrame() &&
6257 lastFrameWasEditable == frame->GetContent()->IsEditable())) {
6258 continue;
6259 }
6260 canSkipBr = true;
6261 lastFrameWasEditable =
6262 frame->GetContent() && frame->GetContent()->IsEditable();
6263 LogicalRect frameRect =
6264 LogicalRect(wm, frame->GetRect(), aLine->mContainerSize);
6265 if (pt.I(wm) >= frameRect.IStart(wm)) {
6266 if (pt.I(wm) < frameRect.IEnd(wm)) {
6267 return GetSelectionClosestFrameForChild(frame, aPoint, aFlags);
6268 }
6269 if (frameRect.IEnd(wm) >= closestIStart) {
6270 closestFromIStart = frame;
6271 closestIStart = frameRect.IEnd(wm);
6272 }
6273 } else {
6274 if (frameRect.IStart(wm) <= closestIEnd) {
6275 closestFromIEnd = frame;
6276 closestIEnd = frameRect.IStart(wm);
6277 }
6278 }
6279 }
6280 if (!closestFromIStart && !closestFromIEnd) {
6281 // We should only get here if there are no selectable frames on a line
6282 // XXX Do we need more elaborate handling here?
6283 return FrameTarget();
6284 }
6285 if (closestFromIStart &&
6286 (!closestFromIEnd ||
6287 (abs(pt.I(wm) - closestIStart) <= abs(pt.I(wm) - closestIEnd)))) {
6288 return GetSelectionClosestFrameForChild(closestFromIStart, aPoint, aFlags);
6289 }
6290 return GetSelectionClosestFrameForChild(closestFromIEnd, aPoint, aFlags);
6291}
6292
6293// This method is for the special handling we do for block frames; they're
6294// special because they represent paragraphs and because they are organized
6295// into lines, which have bounds that are not stored elsewhere in the
6296// frame tree. Returns a null FrameTarget for frames which are not
6297// blocks or blocks with no lines except editable one.
6298static FrameTarget GetSelectionClosestFrameForBlock(nsIFrame* aFrame,
6299 const nsPoint& aPoint,
6300 uint32_t aFlags) {
6301 nsBlockFrame* bf = do_QueryFrame(aFrame);
6302 if (!bf) {
6303 return FrameTarget();
6304 }
6305
6306 // This code searches for the correct line
6307 nsBlockFrame::LineIterator end = bf->LinesEnd();
6308 nsBlockFrame::LineIterator curLine = bf->LinesBegin();
6309 nsBlockFrame::LineIterator closestLine = end;
6310
6311 if (curLine != end) {
6312 // Convert aPoint into a LogicalPoint in the writing-mode of this block
6313 WritingMode wm = curLine->mWritingMode;
6314 LogicalPoint pt(wm, aPoint, curLine->mContainerSize);
6315 do {
6316 // Check to see if our point lies within the line's block-direction bounds
6317 nscoord BCoord = pt.B(wm) - curLine->BStart();
6318 nscoord BSize = curLine->BSize();
6319 if (BCoord >= 0 && BCoord < BSize) {
6320 closestLine = curLine;
6321 break; // We found the line; stop looking
6322 }
6323 if (BCoord < 0) {
6324 break;
6325 }
6326 ++curLine;
6327 } while (curLine != end);
6328
6329 if (closestLine == end) {
6330 nsBlockFrame::LineIterator prevLine = curLine.prev();
6331 nsBlockFrame::LineIterator nextLine = curLine;
6332 // Avoid empty lines
6333 while (nextLine != end && nextLine->IsEmpty()) {
6334 ++nextLine;
6335 }
6336 while (prevLine != end && prevLine->IsEmpty()) {
6337 --prevLine;
6338 }
6339
6340 // This hidden pref dictates whether a point above or below all lines
6341 // comes up with a line or the beginning or end of the frame; 0 on
6342 // Windows, 1 on other platforms by default at the writing of this code
6343 int32_t dragOutOfFrame =
6344 Preferences::GetInt("browser.drag_out_of_frame_style");
6345
6346 if (prevLine == end) {
6347 if (dragOutOfFrame == 1 || nextLine == end) {
6348 return DrillDownToSelectionFrame(aFrame, false, aFlags);
6349 }
6350 closestLine = nextLine;
6351 } else if (nextLine == end) {
6352 if (dragOutOfFrame == 1) {
6353 return DrillDownToSelectionFrame(aFrame, true, aFlags);
6354 }
6355 closestLine = prevLine;
6356 } else { // Figure out which line is closer
6357 if (pt.B(wm) - prevLine->BEnd() < nextLine->BStart() - pt.B(wm)) {
6358 closestLine = prevLine;
6359 } else {
6360 closestLine = nextLine;
6361 }
6362 }
6363 }
6364 }
6365
6366 do {
6367 if (auto target =
6368 GetSelectionClosestFrameForLine(bf, closestLine, aPoint, aFlags)) {
6369 return target;
6370 }
6371 ++closestLine;
6372 } while (closestLine != end);
6373
6374 // Fall back to just targeting the last targetable place
6375 return DrillDownToSelectionFrame(aFrame, true, aFlags);
6376}
6377
6378// Use frame edge for grid, flex, table, and non-editable images. Choose the
6379// edge based on the point position past the frame rect. If past the middle,
6380// caret should be at end, otherwise at start. This behavior matches Blink.
6381//
6382// TODO(emilio): Can we use this code path for all other frames? We only get
6383// there when we didn't find selectable children... Editable images need _not_
6384// to use the frame edge tho, see below.
6385static bool UseFrameEdge(nsIFrame* aFrame) {
6386 if (aFrame->IsFlexOrGridContainer() || aFrame->IsTableFrame()) {
6387 return true;
6388 }
6389 // FIXME(bug 713387): The text frame check here shouldn't be needed.
6390 if (aFrame->IsReplaced() && !aFrame->IsTextFrame() &&
6391 !aFrame->GetContent()->IsEditable()) {
6392 // Editable replaced elements are a special-case because editing relies
6393 // on clicking on an editable image selecting it, for it to show resizers.
6394 return true;
6395 }
6396 return false;
6397}
6398
6399static FrameTarget LastResortFrameTargetForFrame(nsIFrame* aFrame,
6400 const nsPoint& aPoint) {
6401 if (!UseFrameEdge(aFrame)) {
6402 return {aFrame, false, false};
6403 }
6404 const auto& rect = aFrame->GetRectRelativeToSelf();
6405 nscoord reference;
6406 nscoord middle;
6407 if (aFrame->GetWritingMode().IsVertical()) {
6408 reference = aPoint.y;
6409 middle = rect.Height() / 2;
6410 } else {
6411 reference = aPoint.x;
6412 middle = rect.Width() / 2;
6413 }
6414 const bool afterFrame = reference > middle;
6415 return {aFrame, true, afterFrame};
6416}
6417
6418// GetSelectionClosestFrame is the helper function that calculates the closest
6419// frame to the given point.
6420// It doesn't completely account for offset styles, so needs to be used in
6421// restricted environments.
6422// Cannot handle overlapping frames correctly, so it should receive the output
6423// of GetFrameForPoint
6424// Guaranteed to return a valid FrameTarget.
6425// aPoint is relative to aFrame.
6426static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
6427 const nsPoint& aPoint,
6428 uint32_t aFlags) {
6429 // Handle blocks; if the frame isn't a block, the method fails
6430 if (auto target = GetSelectionClosestFrameForBlock(aFrame, aPoint, aFlags)) {
6431 return target;
6432 }
6433
6434 if (aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE &&
6435 !FrameContentCanHaveParentSelectionRange(aFrame)) {
6436 return LastResortFrameTargetForFrame(aFrame, aPoint);
6437 }
6438
6439 if (nsIFrame* kid = aFrame->PrincipalChildList().FirstChild()) {
6440 // Go through all the child frames to find the closest one
6441 nsIFrame::FrameWithDistance closest = {nullptr, nscoord_MAX, nscoord_MAX};
6442 for (; kid; kid = kid->GetNextSibling()) {
6443 if (!SelfIsSelectable(kid, aFrame, aFlags)) {
6444 continue;
6445 }
6446
6447 kid->FindCloserFrameForSelection(aPoint, &closest);
6448 }
6449 if (closest.mFrame) {
6450 if (closest.mFrame->IsInSVGTextSubtree()) {
6451 return FrameTarget{closest.mFrame, false, false};
6452 }
6453 return GetSelectionClosestFrameForChild(closest.mFrame, aPoint, aFlags);
6454 }
6455 }
6456
6457 return LastResortFrameTargetForFrame(aFrame, aPoint);
6458}
6459
6460static nsIFrame::ContentOffsets OffsetsForSingleFrame(nsIFrame* aFrame,
6461 const nsPoint& aPoint) {
6462 nsIFrame::ContentOffsets offsets;
6463 FrameContentRange range = GetRangeForFrame(aFrame);
6464 offsets.content = range.content;
6465 // If there are continuations (meaning it's not one rectangle), this is the
6466 // best this function can do
6467 if (aFrame->GetNextContinuation() || aFrame->GetPrevContinuation()) {
6468 offsets.offset = range.start;
6469 offsets.secondaryOffset = range.end;
6470 offsets.associate = CaretAssociationHint::After;
6471 return offsets;
6472 }
6473
6474 // Figure out whether the offsets should be over, after, or before the frame
6475 nsRect rect(nsPoint(0, 0), aFrame->GetSize());
6476
6477 bool isBlock = !aFrame->StyleDisplay()->IsInlineFlow();
6478 bool isRtl = (aFrame->StyleVisibility()->mDirection == StyleDirection::Rtl);
6479 if ((isBlock && rect.y < aPoint.y) ||
6480 (!isBlock && ((isRtl && rect.x + rect.width / 2 > aPoint.x) ||
6481 (!isRtl && rect.x + rect.width / 2 < aPoint.x)))) {
6482 offsets.offset = range.end;
6483 if (rect.Contains(aPoint)) {
6484 offsets.secondaryOffset = range.start;
6485 } else {
6486 offsets.secondaryOffset = range.end;
6487 }
6488 } else {
6489 offsets.offset = range.start;
6490 if (rect.Contains(aPoint)) {
6491 offsets.secondaryOffset = range.end;
6492 } else {
6493 offsets.secondaryOffset = range.start;
6494 }
6495 }
6496 offsets.associate = offsets.offset == range.start
6497 ? CaretAssociationHint::After
6498 : CaretAssociationHint::Before;
6499 return offsets;
6500}
6501
6502static nsIFrame* AdjustFrameForSelectionStyles(nsIFrame* aFrame) {
6503 nsIFrame* adjustedFrame = aFrame;
6504 for (nsIFrame* frame = aFrame; frame; frame = frame->GetParent()) {
6505 // These are the conditions that make all children not able to handle
6506 // a cursor.
6507 auto userSelect = frame->Style()->UserSelect();
6508 if (userSelect != StyleUserSelect::Auto &&
6509 userSelect != StyleUserSelect::All) {
6510 break;
6511 }
6512 if (userSelect == StyleUserSelect::All ||
6513 frame->IsGeneratedContentFrame()) {
6514 adjustedFrame = frame;
6515 }
6516 }
6517 return adjustedFrame;
6518}
6519
6520nsIFrame::ContentOffsets nsIFrame::GetContentOffsetsFromPoint(
6521 const nsPoint& aPoint, uint32_t aFlags) {
6522 nsIFrame* adjustedFrame;
6523 if (aFlags & IGNORE_SELECTION_STYLE) {
6524 adjustedFrame = this;
6525 } else {
6526 // This section of code deals with special selection styles. Note that
6527 // -moz-all exists, even though it doesn't need to be explicitly handled.
6528 //
6529 // The offset is forced not to end up in generated content; content offsets
6530 // cannot represent content outside of the document's content tree.
6531
6532 adjustedFrame = AdjustFrameForSelectionStyles(this);
6533
6534 // `user-select: all` needs special handling, because clicking on it should
6535 // lead to the whole frame being selected.
6536 if (adjustedFrame->Style()->UserSelect() == StyleUserSelect::All) {
6537 nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
6538 return OffsetsForSingleFrame(adjustedFrame, adjustedPoint);
6539 }
6540
6541 // For other cases, try to find a closest frame starting from the parent of
6542 // the unselectable frame
6543 if (adjustedFrame != this) {
6544 adjustedFrame = adjustedFrame->GetParent();
6545 }
6546 }
6547
6548 nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
6549
6550 FrameTarget closest =
6551 GetSelectionClosestFrame(adjustedFrame, adjustedPoint, aFlags);
6552
6553 // If the correct offset is at one end of a frame, use offset-based
6554 // calculation method
6555 if (closest.frameEdge) {
6556 ContentOffsets offsets;
6557 bool includeReplaced = (aFlags & INCLUDE_REPLACED) != 0;
6558 FrameContentRange range = GetRangeForFrame(closest.frame, includeReplaced);
6559 offsets.content = range.content;
6560 if (closest.afterFrame) {
6561 offsets.offset = range.end;
6562 } else {
6563 offsets.offset = range.start;
6564 }
6565 offsets.secondaryOffset = offsets.offset;
6566 offsets.associate = offsets.offset == range.start
6567 ? CaretAssociationHint::After
6568 : CaretAssociationHint::Before;
6569 return offsets;
6570 }
6571
6572 nsPoint pt;
6573 if (closest.frame != this) {
6574 if (closest.frame->IsInSVGTextSubtree()) {
6575 pt = nsLayoutUtils::TransformAncestorPointToFrame(
6576 RelativeTo{closest.frame}, aPoint, RelativeTo{this});
6577 } else {
6578 pt = aPoint - closest.frame->GetOffsetTo(this);
6579 }
6580 } else {
6581 pt = aPoint;
6582 }
6583 return closest.frame->CalcContentOffsetsFromFramePoint(pt);
6584
6585 // XXX should I add some kind of offset standardization?
6586 // consider <b>xxxxx</b><i>zzzzz</i>; should any click between the last
6587 // x and first z put the cursor in the same logical position in addition
6588 // to the same visual position?
6589}
6590
6591nsIFrame::ContentOffsets nsIFrame::CalcContentOffsetsFromFramePoint(
6592 const nsPoint& aPoint) {
6593 return OffsetsForSingleFrame(this, aPoint);
6594}
6595
6596bool nsIFrame::AssociateImage(const StyleImage& aImage) {
6597 imgRequestProxy* req = aImage.GetImageRequest();
6598 if (!req) {
6599 return false;
6600 }
6601
6602 PresContext()->Document()->EnsureStyleImageLoader().AssociateRequestToFrame(
6603 req, this);
6604 return true;
6605}
6606
6607void nsIFrame::DisassociateImage(const StyleImage& aImage) {
6608 imgRequestProxy* req = aImage.GetImageRequest();
6609 if (!req) {
6610 return;
6611 }
6612
6613 PresContext()
6614 ->Document()
6615 ->EnsureStyleImageLoader()
6616 .DisassociateRequestFromFrame(req, this);
6617}
6618
6619const ComputedStyle* nsIFrame::UsedStyleForImages() const {
6620 if (IsCanvasFrame()) {
6621 // XXXdholbert Maybe we should use FindCanvasBackground here (instead of
6622 // FindBackground), since we're inside an IsCanvasFrame check? Though then
6623 // we'd also have to copypaste or abstract-away the multi-part root-frame
6624 // lookup that the canvas-flavored API requires.
6625 return nsCSSRendering::FindBackground(this);
6626 }
6627 return Style();
6628}
6629
6630// The touch-action CSS property applies to: all elements except: non-replaced
6631// inline elements, table rows, row groups, table columns, and column groups.
6632StyleTouchAction nsIFrame::UsedTouchAction() const {
6633 if (IsLineParticipant()) {
6634 return StyleTouchAction::AUTO;
6635 }
6636 auto& disp = *StyleDisplay();
6637 if (disp.IsInternalTableStyleExceptCell()) {
6638 return StyleTouchAction::AUTO;
6639 }
6640 return disp.mTouchAction;
6641}
6642
6643nsIFrame::Cursor nsIFrame::GetCursor(const nsPoint&) {
6644 StyleCursorKind kind = StyleUI()->Cursor().keyword;
6645 if (kind == StyleCursorKind::Auto) {
6646 // If this is editable, I-beam cursor is better for most elements.
6647 kind = (mContent && mContent->IsEditable()) ? StyleCursorKind::Text
6648 : StyleCursorKind::Default;
6649 }
6650 if (kind == StyleCursorKind::Text && GetWritingMode().IsVertical()) {
6651 // Per CSS UI spec, UA may treat value 'text' as
6652 // 'vertical-text' for vertical text.
6653 kind = StyleCursorKind::VerticalText;
6654 }
6655
6656 return Cursor{kind, AllowCustomCursorImage::Yes};
6657}
6658
6659// Resize and incremental reflow
6660
6661/* virtual */
6662void nsIFrame::MarkIntrinsicISizesDirty() {
6663 // If we're a flex item, clear our flex-item-specific cached measurements
6664 // (which likely depended on our now-stale intrinsic isize).
6665 if (IsFlexItem()) {
6666 nsFlexContainerFrame::MarkCachedFlexMeasurementsDirty(this);
6667 }
6668
6669 if (IsGridItem()) {
6670 nsGridContainerFrame::MarkCachedGridMeasurementsDirty(this);
6671 }
6672
6673 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT)) {
6674 nsFontInflationData::MarkFontInflationDataTextDirty(this);
6675 }
6676}
6677
6678void nsIFrame::MarkSubtreeDirty() {
6679 if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
6680 return;
6681 }
6682 // Unconditionally mark given frame dirty.
6683 AddStateBits(NS_FRAME_IS_DIRTY);
6684
6685 // Mark all descendants dirty, unless:
6686 // - Already dirty.
6687 // - TableColGroup
6688 AutoTArray<nsIFrame*, 32> stack;
6689 for (const auto& childLists : ChildLists()) {
6690 for (nsIFrame* kid : childLists.mList) {
6691 stack.AppendElement(kid);
6692 }
6693 }
6694 while (!stack.IsEmpty()) {
6695 nsIFrame* f = stack.PopLastElement();
6696 if (f->HasAnyStateBits(NS_FRAME_IS_DIRTY) || f->IsTableColGroupFrame()) {
6697 continue;
6698 }
6699
6700 f->AddStateBits(NS_FRAME_IS_DIRTY);
6701
6702 for (const auto& childLists : f->ChildLists()) {
6703 for (nsIFrame* kid : childLists.mList) {
6704 stack.AppendElement(kid);
6705 }
6706 }
6707 }
6708}
6709
6710void nsIFrame::MarkPrincipalChildrenDirty() {
6711 for (nsIFrame* childFrame : PrincipalChildList()) {
6712 childFrame->MarkSubtreeDirty();
6713 }
6714}
6715
6716/* virtual */
6717void nsIFrame::AddInlineMinISize(const IntrinsicSizeInput& aInput,
6718 InlineMinISizeData* aData) {
6719 // Note: we are one of the children that mPercentageBasisForChildren was
6720 // prepared for (i.e. our parent frame prepares the percentage basis for us,
6721 // not for our own children). Hence it's fine that we're resolving our
6722 // percentages sizes against this basis in IntrinsicForContainer().
6723 nscoord isize = nsLayoutUtils::IntrinsicForContainer(
6724 aInput.mContext, this, IntrinsicISizeType::MinISize,
6725 aInput.mPercentageBasisForChildren);
6726 aData->DefaultAddInlineMinISize(this, isize);
6727}
6728
6729/* virtual */
6730void nsIFrame::AddInlinePrefISize(const IntrinsicSizeInput& aInput,
6731 nsIFrame::InlinePrefISizeData* aData) {
6732 // Note: we are one of the children that mPercentageBasisForChildren was
6733 // prepared for (i.e. our parent frame prepares the percentage basis for us,
6734 // not for our own children). Hence it's fine that we're resolving our
6735 // percentages sizes against this basis in IntrinsicForContainer().
6736 nscoord isize = nsLayoutUtils::IntrinsicForContainer(
6737 aInput.mContext, this, IntrinsicISizeType::PrefISize,
6738 aInput.mPercentageBasisForChildren);
6739 aData->DefaultAddInlinePrefISize(isize);
6740}
6741
6742void nsIFrame::InlineMinISizeData::DefaultAddInlineMinISize(nsIFrame* aFrame,
6743 nscoord aISize,
6744 bool aAllowBreak) {
6745 auto parent = aFrame->GetParent();
6746 MOZ_ASSERT(parent, "Must have a parent if we get here!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(parent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("parent" " (" "Must have a parent if we get here!"
")", "./../../../layout/generic/nsIFrame.cpp", 6746); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "parent" ") (" "Must have a parent if we get here!"
")"); do { MOZ_CrashSequence(__null, 6746); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6747 const bool mayBreak = aAllowBreak && !aFrame->CanContinueTextRun() &&
6748 !parent->Style()->ShouldSuppressLineBreak() &&
6749 parent->StyleText()->WhiteSpaceCanWrap(parent);
6750 if (mayBreak) {
6751 OptionallyBreak();
6752 }
6753 mTrailingWhitespace = 0;
6754 mSkipWhitespace = false;
6755 mCurrentLine += aISize;
6756 mAtStartOfLine = false;
6757 if (mayBreak) {
6758 OptionallyBreak();
6759 }
6760}
6761
6762void nsIFrame::InlinePrefISizeData::DefaultAddInlinePrefISize(nscoord aISize) {
6763 mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, aISize);
6764 mTrailingWhitespace = 0;
6765 mSkipWhitespace = false;
6766 mLineIsEmpty = false;
6767}
6768
6769void nsIFrame::InlineMinISizeData::ForceBreak() {
6770 mCurrentLine -= mTrailingWhitespace;
6771 mPrevLines = std::max(mPrevLines, mCurrentLine);
6772 mCurrentLine = mTrailingWhitespace = 0;
6773
6774 for (const FloatInfo& floatInfo : mFloats) {
6775 mPrevLines = std::max(floatInfo.ISize(), mPrevLines);
6776 }
6777 mFloats.Clear();
6778 mSkipWhitespace = true;
6779}
6780
6781void nsIFrame::InlineMinISizeData::OptionallyBreak(nscoord aHyphenWidth) {
6782 // If we can fit more content into a smaller width by staying on this
6783 // line (because we're still at a negative offset due to negative
6784 // text-indent or negative margin), don't break. Otherwise, do the
6785 // same as ForceBreak. it doesn't really matter when we accumulate
6786 // floats.
6787 if (mCurrentLine + aHyphenWidth < 0 || mAtStartOfLine) {
6788 return;
6789 }
6790 mCurrentLine += aHyphenWidth;
6791 ForceBreak();
6792}
6793
6794void nsIFrame::InlinePrefISizeData::ForceBreak(UsedClear aClearType) {
6795 // If this force break is not clearing any float, we can leave all the
6796 // floats to the next force break.
6797 if (!mFloats.IsEmpty() && aClearType != UsedClear::None) {
6798 // Preferred isize accumulated for floats that have already
6799 // been cleared past
6800 nscoord floatsDone = 0;
6801 // Preferred isize accumulated for floats that have not yet
6802 // been cleared past
6803 nscoord floatsCurLeft = 0, floatsCurRight = 0;
6804
6805 for (const FloatInfo& floatInfo : mFloats) {
6806 const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
6807 auto cbWM = floatInfo.Frame()->GetParent()->GetWritingMode();
6808 UsedClear clearType = floatDisp->UsedClear(cbWM);
6809 if (clearType == UsedClear::Left || clearType == UsedClear::Right ||
6810 clearType == UsedClear::Both) {
6811 nscoord floatsCur = NSCoordSaturatingAdd(floatsCurLeft, floatsCurRight);
6812 if (floatsCur > floatsDone) {
6813 floatsDone = floatsCur;
6814 }
6815 if (clearType != UsedClear::Right) {
6816 floatsCurLeft = 0;
6817 }
6818 if (clearType != UsedClear::Left) {
6819 floatsCurRight = 0;
6820 }
6821 }
6822
6823 UsedFloat floatStyle = floatDisp->UsedFloat(cbWM);
6824 nscoord& floatsCur =
6825 floatStyle == UsedFloat::Left ? floatsCurLeft : floatsCurRight;
6826 nscoord floatISize = floatInfo.ISize();
6827 // Negative-width floats don't change the available space so they
6828 // shouldn't change our intrinsic line isize either.
6829 floatsCur = NSCoordSaturatingAdd(floatsCur, std::max(0, floatISize));
6830 }
6831
6832 nscoord floatsCur = NSCoordSaturatingAdd(floatsCurLeft, floatsCurRight);
6833 if (floatsCur > floatsDone) {
6834 floatsDone = floatsCur;
6835 }
6836
6837 mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, floatsDone);
6838
6839 if (aClearType == UsedClear::Both) {
6840 mFloats.Clear();
6841 } else {
6842 // If the break type does not clear all floats, it means there may
6843 // be some floats whose isize should contribute to the intrinsic
6844 // isize of the next line. The code here scans the current mFloats
6845 // and keeps floats which are not cleared by this break. Note that
6846 // floats may be cleared directly or indirectly. See below.
6847 nsTArray<FloatInfo> newFloats;
6848 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == UsedClear::Left || aClearType == UsedClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == UsedClear::Left || aClearType == UsedClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == UsedClear::Left || aClearType == UsedClear::Right"
" (" "Other values should have been handled in other branches"
")", "./../../../layout/generic/nsIFrame.cpp", 6850); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aClearType == UsedClear::Left || aClearType == UsedClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { MOZ_CrashSequence(__null, 6850); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6849 aClearType == UsedClear::Left || aClearType == UsedClear::Right,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == UsedClear::Left || aClearType == UsedClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == UsedClear::Left || aClearType == UsedClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == UsedClear::Left || aClearType == UsedClear::Right"
" (" "Other values should have been handled in other branches"
")", "./../../../layout/generic/nsIFrame.cpp", 6850); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aClearType == UsedClear::Left || aClearType == UsedClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { MOZ_CrashSequence(__null, 6850); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6850 "Other values should have been handled in other branches")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == UsedClear::Left || aClearType == UsedClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == UsedClear::Left || aClearType == UsedClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == UsedClear::Left || aClearType == UsedClear::Right"
" (" "Other values should have been handled in other branches"
")", "./../../../layout/generic/nsIFrame.cpp", 6850); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aClearType == UsedClear::Left || aClearType == UsedClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { MOZ_CrashSequence(__null, 6850); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6851 UsedFloat clearFloatType =
6852 aClearType == UsedClear::Left ? UsedFloat::Left : UsedFloat::Right;
6853 // Iterate the array in reverse so that we can stop when there are
6854 // no longer any floats we need to keep. See below.
6855 for (FloatInfo& floatInfo : Reversed(mFloats)) {
6856 const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
6857 auto cbWM = floatInfo.Frame()->GetParent()->GetWritingMode();
6858 if (floatDisp->UsedFloat(cbWM) != clearFloatType) {
6859 newFloats.AppendElement(floatInfo);
6860 } else {
6861 // This is a float on the side that this break directly clears
6862 // which means we're not keeping it in mFloats. However, if
6863 // this float clears floats on the opposite side (via a value
6864 // of either 'both' or one of 'left'/'right'), any remaining
6865 // (earlier) floats on that side would be indirectly cleared
6866 // as well. Thus, we should break out of this loop and stop
6867 // considering earlier floats to be kept in mFloats.
6868 UsedClear clearType = floatDisp->UsedClear(cbWM);
6869 if (clearType != aClearType && clearType != UsedClear::None) {
6870 break;
6871 }
6872 }
6873 }
6874 newFloats.Reverse();
6875 mFloats = std::move(newFloats);
6876 }
6877 }
6878
6879 mCurrentLine =
6880 NSCoordSaturatingSubtract(mCurrentLine, mTrailingWhitespace, nscoord_MAX);
6881 mPrevLines = std::max(mPrevLines, mCurrentLine);
6882 mCurrentLine = mTrailingWhitespace = 0;
6883 mSkipWhitespace = true;
6884 mLineIsEmpty = true;
6885}
6886
6887static nscoord ResolvePadding(const LengthPercentage& aStyle,
6888 nscoord aPercentageBasis) {
6889 return nsLayoutUtils::ResolveToLength<true>(aStyle, aPercentageBasis);
6890}
6891
6892static nscoord ResolveMargin(const AnchorResolvedMargin& aStyle,
6893 nscoord aPercentageBasis) {
6894 if (!aStyle->IsLengthPercentage()) {
6895 return nscoord(0);
6896 }
6897 return nsLayoutUtils::ResolveToLength<false>(aStyle->AsLengthPercentage(),
6898 aPercentageBasis);
6899}
6900static nsIFrame::IntrinsicSizeOffsetData IntrinsicSizeOffsets(
6901 nsIFrame* aFrame, nscoord aPercentageBasis, bool aForISize) {
6902 nsIFrame::IntrinsicSizeOffsetData result;
6903 WritingMode wm = aFrame->GetWritingMode();
6904 bool verticalAxis = aForISize == wm.IsVertical();
6905 const auto* styleMargin = aFrame->StyleMargin();
6906 const auto anchorResolutionParams = AnchorPosResolutionParams::From(aFrame);
6907 if (verticalAxis) {
6908 result.margin +=
6909 ResolveMargin(styleMargin->GetMargin(eSideTop, anchorResolutionParams),
6910 aPercentageBasis);
6911 result.margin += ResolveMargin(
6912 styleMargin->GetMargin(eSideBottom, anchorResolutionParams),
6913 aPercentageBasis);
6914 } else {
6915 result.margin +=
6916 ResolveMargin(styleMargin->GetMargin(eSideLeft, anchorResolutionParams),
6917 aPercentageBasis);
6918 result.margin += ResolveMargin(
6919 styleMargin->GetMargin(eSideRight, anchorResolutionParams),
6920 aPercentageBasis);
6921 }
6922
6923 const auto& padding = aFrame->StylePadding()->mPadding;
6924 if (verticalAxis) {
6925 result.padding += ResolvePadding(padding.Get(eSideTop), aPercentageBasis);
6926 result.padding +=
6927 ResolvePadding(padding.Get(eSideBottom), aPercentageBasis);
6928 } else {
6929 result.padding += ResolvePadding(padding.Get(eSideLeft), aPercentageBasis);
6930 result.padding += ResolvePadding(padding.Get(eSideRight), aPercentageBasis);
6931 }
6932
6933 const nsStyleBorder* styleBorder = aFrame->StyleBorder();
6934 if (verticalAxis) {
6935 result.border += styleBorder->GetComputedBorderWidth(eSideTop);
6936 result.border += styleBorder->GetComputedBorderWidth(eSideBottom);
6937 } else {
6938 result.border += styleBorder->GetComputedBorderWidth(eSideLeft);
6939 result.border += styleBorder->GetComputedBorderWidth(eSideRight);
6940 }
6941
6942 const nsStyleDisplay* disp = aFrame->StyleDisplay();
6943 if (aFrame->IsThemed(disp)) {
6944 nsPresContext* presContext = aFrame->PresContext();
6945
6946 LayoutDeviceIntMargin border = presContext->Theme()->GetWidgetBorder(
6947 presContext->DeviceContext(), aFrame, disp->EffectiveAppearance());
6948 result.border = presContext->DevPixelsToAppUnits(
6949 verticalAxis ? border.TopBottom() : border.LeftRight());
6950
6951 LayoutDeviceIntMargin padding;
6952 if (presContext->Theme()->GetWidgetPadding(
6953 presContext->DeviceContext(), aFrame, disp->EffectiveAppearance(),
6954 &padding)) {
6955 result.padding = presContext->DevPixelsToAppUnits(
6956 verticalAxis ? padding.TopBottom() : padding.LeftRight());
6957 }
6958 }
6959 return result;
6960}
6961
6962/* virtual */ nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicISizeOffsets(
6963 nscoord aPercentageBasis) {
6964 return IntrinsicSizeOffsets(this, aPercentageBasis, true);
6965}
6966
6967nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicBSizeOffsets(
6968 nscoord aPercentageBasis) {
6969 return IntrinsicSizeOffsets(this, aPercentageBasis, false);
6970}
6971
6972/* virtual */
6973IntrinsicSize nsIFrame::GetIntrinsicSize() {
6974 // Defaults to no intrinsic size.
6975 return IntrinsicSize();
6976}
6977
6978AspectRatio nsIFrame::GetAspectRatio() const {
6979 // Per spec, 'aspect-ratio' property applies to all elements except inline
6980 // boxes and internal ruby or table boxes.
6981 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio
6982 // For those frame types that don't support aspect-ratio, they must not have
6983 // the natural ratio, so this early return is fine.
6984 if (!SupportsAspectRatio()) {
6985 return AspectRatio();
6986 }
6987
6988 const StyleAspectRatio& ar = StylePosition()->mAspectRatio;
6989 const bool hasRatio = ar.HasRatio();
6990 // If aspect-ratio is zero or infinite, it's a degenerate ratio and behaves
6991 // as auto.
6992 // https://drafts.csswg.org/css-sizing-4/#valdef-aspect-ratio-ratio
6993 // Non-auto. Return the preferred aspect ratio from the aspect-ratio style.
6994 if (hasRatio && !ar.auto_) {
6995 if (auto ratio = ar.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::Yes)) {
6996 return ratio;
6997 }
6998 }
6999
7000 if (auto intrinsicRatio = GetIntrinsicRatio()) {
7001 return intrinsicRatio;
7002 }
7003
7004 if (hasRatio) {
7005 // This returns a 0 ratio for degenerate rations, like the auto case below.
7006 return ar.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::No);
7007 }
7008
7009 return AspectRatio();
7010}
7011
7012/* virtual */
7013AspectRatio nsIFrame::GetIntrinsicRatio() const { return AspectRatio(); }
7014
7015static bool ShouldApplyAutomaticMinimumOnInlineAxis(
7016 WritingMode aWM, bool aIsScrollableOverflow,
7017 const AnchorPosResolutionParams& aParams,
7018 const nsStylePosition* aPosition) {
7019 // Apply the automatic minimum size for aspect ratio:
7020 // Note: The replaced elements shouldn't be here, so we only check the scroll
7021 // container.
7022 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-minimum
7023 return !aIsScrollableOverflow && aPosition->MinISize(aWM, aParams)->IsAuto();
7024}
7025
7026/* virtual */
7027nsIFrame::SizeComputationResult nsIFrame::ComputeSize(
7028 const SizeComputationInput& aSizingInput, WritingMode aWM,
7029 const LogicalSize& aCBSize, nscoord aAvailableISize,
7030 const LogicalSize& aMargin, const LogicalSize& aBorderPadding,
7031 const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) {
7032 MOZ_ASSERT(!GetIntrinsicRatio(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetIntrinsicRatio())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetIntrinsicRatio()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!GetIntrinsicRatio()"
" (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")", "./../../../layout/generic/nsIFrame.cpp", 7034); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!GetIntrinsicRatio()" ") (" "Please override this method and call "
"nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { MOZ_CrashSequence(__null, 7034); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7033 "Please override this method and call "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetIntrinsicRatio())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetIntrinsicRatio()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!GetIntrinsicRatio()"
" (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")", "./../../../layout/generic/nsIFrame.cpp", 7034); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!GetIntrinsicRatio()" ") (" "Please override this method and call "
"nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { MOZ_CrashSequence(__null, 7034); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7034 "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetIntrinsicRatio())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetIntrinsicRatio()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!GetIntrinsicRatio()"
" (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")", "./../../../layout/generic/nsIFrame.cpp", 7034); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!GetIntrinsicRatio()" ") (" "Please override this method and call "
"nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { MOZ_CrashSequence(__null, 7034); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7035 LogicalSize result =
7036 ComputeAutoSize(aSizingInput, aWM, aCBSize, aAvailableISize, aMargin,
7037 aBorderPadding, aSizeOverrides, aFlags);
7038 const nsStylePosition* stylePos = StylePosition();
7039 const nsStyleDisplay* disp = StyleDisplay();
7040 const auto anchorResolutionParams = AnchorPosResolutionParams::From(
7041 this, aSizingInput.mAnchorPosResolutionCache);
7042 auto aspectRatioUsage = AspectRatioUsage::None;
7043
7044 const auto boxSizingAdjust = stylePos->mBoxSizing == StyleBoxSizing::BorderBox
7045 ? aBorderPadding
7046 : LogicalSize(aWM);
7047 const auto& aspectRatio = aSizeOverrides.mAspectRatio
7048 ? *aSizeOverrides.mAspectRatio
7049 : GetAspectRatio();
7050 const auto styleISize =
7051 aSizeOverrides.mStyleISize
7052 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleISize)
7053 : stylePos->ISize(aWM, anchorResolutionParams);
7054 // For bsize, we consider overrides *and then* we resolve 'stretch' to a
7055 // nscoord value, for convenience (so that we can assume that either
7056 // isAutoBSize is true, or styleBSize is of type LengthPercentage()).
7057 const auto styleBSize = [&] {
7058 auto styleBSizeConsideringOverrides =
7059 aSizeOverrides.mStyleBSize
7060 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleBSize)
7061 : stylePos->BSize(aWM, anchorResolutionParams);
7062 if (styleBSizeConsideringOverrides->BehavesLikeStretchOnBlockAxis() &&
7063 aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
7064 // We've got a 'stretch' BSize; resolve it to a length:
7065 nscoord stretchBSize = nsLayoutUtils::ComputeStretchSize(
7066 aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM),
7067 stylePos->mBoxSizing);
7068 // Note(dshin): This allocates.
7069 return AnchorResolvedSizeHelper::LengthPercentage(
7070 LengthPercentage::FromAppUnits(stretchBSize));
7071 }
7072 return styleBSizeConsideringOverrides;
7073 }();
7074
7075 auto parentFrame = GetParent();
7076 auto alignCB = parentFrame;
7077 bool isGridItem = IsGridItem();
7078 const bool isSubgrid = IsSubgrid();
7079 if (parentFrame && parentFrame->IsTableWrapperFrame() && IsTableFrame()) {
7080 // An inner table frame is sized as a grid item if its table wrapper is,
7081 // because they actually have the same CB (the wrapper's CB).
7082 // @see ReflowInput::InitCBReflowInput
7083 auto tableWrapper = GetParent();
7084 auto grandParent = tableWrapper->GetParent();
7085 isGridItem = grandParent->IsGridContainerFrame() &&
7086 !tableWrapper->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
7087 if (isGridItem) {
7088 // When resolving justify/align-self below, we want to use the grid
7089 // container's justify/align-items value and WritingMode.
7090 alignCB = grandParent;
7091 }
7092 }
7093
7094 // flexItemMainAxis is set if this frame is a flex item in a modern flexbox
7095 // layout. It indicates which logical axis (in this frame's own WM)
7096 // corresponds to its flex container's main axis.
7097 Maybe<LogicalAxis> flexItemMainAxis;
7098 if (IsFlexItem() && !parentFrame->HasAnyStateBits(
7099 NS_STATE_FLEX_IS_EMULATING_LEGACY_WEBKIT_BOX)) {
7100 flexItemMainAxis = Some(nsFlexContainerFrame::IsItemInlineAxisMainAxis(this)
7101 ? LogicalAxis::Inline
7102 : LogicalAxis::Block);
7103 }
7104
7105 const bool isAutoISize = styleISize->IsAuto();
7106 const bool isAutoBSize =
7107 nsLayoutUtils::IsAutoBSize(*styleBSize, aCBSize.BSize(aWM));
7108
7109 MOZ_ASSERT(isAutoBSize || styleBSize->IsLengthPercentage(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAutoBSize || styleBSize->IsLengthPercentage())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(isAutoBSize || styleBSize->IsLengthPercentage()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAutoBSize || styleBSize->IsLengthPercentage()"
" (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
, "./../../../layout/generic/nsIFrame.cpp", 7112); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "isAutoBSize || styleBSize->IsLengthPercentage()"
") (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
); do { MOZ_CrashSequence(__null, 7112); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7110 "We should have resolved away any non-'auto'-like flavors "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAutoBSize || styleBSize->IsLengthPercentage())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(isAutoBSize || styleBSize->IsLengthPercentage()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAutoBSize || styleBSize->IsLengthPercentage()"
" (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
, "./../../../layout/generic/nsIFrame.cpp", 7112); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "isAutoBSize || styleBSize->IsLengthPercentage()"
") (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
); do { MOZ_CrashSequence(__null, 7112); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7111 "of styleBSize into a LengthPercentage. (If this fails, we "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAutoBSize || styleBSize->IsLengthPercentage())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(isAutoBSize || styleBSize->IsLengthPercentage()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAutoBSize || styleBSize->IsLengthPercentage()"
" (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
, "./../../../layout/generic/nsIFrame.cpp", 7112); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "isAutoBSize || styleBSize->IsLengthPercentage()"
") (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
); do { MOZ_CrashSequence(__null, 7112); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7112 "might run afoul of some AsLengthPercentage() call below.)")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAutoBSize || styleBSize->IsLengthPercentage())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(isAutoBSize || styleBSize->IsLengthPercentage()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAutoBSize || styleBSize->IsLengthPercentage()"
" (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
, "./../../../layout/generic/nsIFrame.cpp", 7112); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "isAutoBSize || styleBSize->IsLengthPercentage()"
") (" "We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)" ")"
); do { MOZ_CrashSequence(__null, 7112); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7113
7114 // Compute inline-axis size
7115 const bool isSubgriddedInInlineAxis =
7116 isSubgrid && static_cast<nsGridContainerFrame*>(this)->IsColSubgrid();
7117
7118 // Per https://drafts.csswg.org/css-grid/#subgrid-box-alignment, if we are
7119 // subgridded in the inline-axis, ignore our style inline-size, and stretch to
7120 // fill the CB.
7121 const bool shouldComputeISize = !isAutoISize && !isSubgriddedInInlineAxis;
7122 if (shouldComputeISize) {
7123 auto iSizeResult = ComputeISizeValue(
7124 aSizingInput.mRenderingContext, aWM, aCBSize, aMargin, aBorderPadding,
7125 *styleISize, *styleBSize, aspectRatio, aFlags);
7126 result.ISize(aWM) = iSizeResult.mISize;
7127 aspectRatioUsage = iSizeResult.mAspectRatioUsage;
7128 } else if (MOZ_UNLIKELY(isGridItem)(__builtin_expect(!!(isGridItem), 0)) && !IsTrueOverflowContainer()) {
7129 // 'auto' inline-size for grid-level box - fill the CB for 'stretch' /
7130 // 'normal' and clamp it to the CB if requested:
7131 bool isStretchAligned = false;
7132 bool mayUseAspectRatio = aspectRatio && !isAutoBSize;
7133 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap) &&
7134 !StyleMargin()->HasInlineAxisAuto(aWM, anchorResolutionParams) &&
7135 !alignCB->IsMasonry(aWM, LogicalAxis::Inline)) {
7136 auto inlineAxisAlignment = stylePos->UsedSelfAlignment(
7137 aWM, LogicalAxis::Inline, alignCB->GetWritingMode(),
7138 alignCB->Style());
7139 isStretchAligned = inlineAxisAlignment == StyleAlignFlags::STRETCH ||
7140 (inlineAxisAlignment == StyleAlignFlags::NORMAL &&
7141 !mayUseAspectRatio);
7142 }
7143
7144 // Apply the preferred aspect ratio for alignments other than *stretch* and
7145 // *normal without aspect ratio*.
7146 // The spec says all other values should size the items as fit-content, and
7147 // the intrinsic size should respect the preferred aspect ratio, so we also
7148 // apply aspect ratio for all other values.
7149 // https://drafts.csswg.org/css-grid/#grid-item-sizing
7150 if (!isStretchAligned && mayUseAspectRatio) {
7151 result.ISize(aWM) = ComputeISizeValueFromAspectRatio(
7152 aWM, aCBSize, boxSizingAdjust, styleBSize->AsLengthPercentage(),
7153 aspectRatio);
7154 aspectRatioUsage = AspectRatioUsage::ToComputeISize;
7155 }
7156
7157 if (isStretchAligned ||
7158 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize)) {
7159 auto iSizeToFillCB =
7160 std::max(nscoord(0), aCBSize.ISize(aWM) - aBorderPadding.ISize(aWM) -
7161 aMargin.ISize(aWM));
7162 if (isStretchAligned || result.ISize(aWM) > iSizeToFillCB) {
7163 result.ISize(aWM) = iSizeToFillCB;
7164 }
7165 }
7166 } else if (aspectRatio && !isAutoBSize) {
7167 // Note: if both the inline size and the block size are auto, the block axis
7168 // is the ratio-dependent axis by default. That means we only need to
7169 // transfer the resolved inline size via aspect-ratio to block axis later in
7170 // this method, but not the other way around.
7171 //
7172 // In this branch, we transfer the non-auto block size via aspect-ration to
7173 // inline axis.
7174 result.ISize(aWM) = ComputeISizeValueFromAspectRatio(
7175 aWM, aCBSize, boxSizingAdjust, styleBSize->AsLengthPercentage(),
7176 aspectRatio);
7177 aspectRatioUsage = AspectRatioUsage::ToComputeISize;
7178 }
7179
7180 // Calculate and apply transferred min & max size contraints.
7181 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-size-transfers
7182 //
7183 // Note: The basic principle is that sizing constraints transfer through the
7184 // aspect-ratio to the other side to preserve the aspect ratio to the extent
7185 // that they can without violating any sizes specified explicitly on that
7186 // affected axis.
7187 //
7188 // FIXME: The spec words may not be correct, so we may have to update this
7189 // tentative solution once this spec issue gets resolved. Here, we clamp the
7190 // flex base size by the transferred min and max sizes, and don't include
7191 // the transferred min & max sizes into its used min & max sizes. So this
7192 // lets us match other browsers' current behaviors.
7193 // https://github.com/w3c/csswg-drafts/issues/6071
7194 //
7195 // Note: This may make more sense if we clamp the flex base size in
7196 // FlexItem::ResolveFlexBaseSizeFromAspectRatio(). However, the result should
7197 // be identical. FlexItem::ResolveFlexBaseSizeFromAspectRatio() only handles
7198 // the case of the definite cross size, and the definite cross size is clamped
7199 // by the min & max cross sizes below in this function. This means its flex
7200 // base size has been clamped by the transferred min & max size already after
7201 // generating the flex items. So here we make the code more general for both
7202 // definite cross size and indefinite cross size.
7203 const bool isDefiniteISize = styleISize->IsLengthPercentage();
7204 const auto minBSizeCoord = stylePos->MinBSize(aWM, anchorResolutionParams);
7205 const auto maxBSizeCoord = stylePos->MaxBSize(aWM, anchorResolutionParams);
7206 const bool isAutoMinBSize =
7207 nsLayoutUtils::IsAutoBSize(*minBSizeCoord, aCBSize.BSize(aWM));
7208 const bool isAutoMaxBSize =
7209 nsLayoutUtils::IsAutoBSize(*maxBSizeCoord, aCBSize.BSize(aWM));
7210 if (aspectRatio && !isDefiniteISize) {
7211 // Note: the spec mentions that
7212 // 1. This transferred minimum is capped by any definite preferred or
7213 // maximum size in the destination axis.
7214 // 2. This transferred maximum is floored by any definite preferred or
7215 // minimum size in the destination axis.
7216 //
7217 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-size-transfers
7218 //
7219 // The spec requires us to clamp these by the specified size (it calls it
7220 // the preferred size). However, we actually don't need to worry about that,
7221 // because we are here only if the inline size is indefinite.
7222 //
7223 // We do not need to clamp the transferred minimum and maximum as long as we
7224 // always apply the transferred min/max size before the explicit min/max
7225 // size; the result will be identical.
7226 const nscoord transferredMinISize =
7227 isAutoMinBSize ? 0
7228 : ComputeISizeValueFromAspectRatio(
7229 aWM, aCBSize, boxSizingAdjust,
7230 minBSizeCoord->AsLengthPercentage(), aspectRatio);
7231 const nscoord transferredMaxISize =
7232 isAutoMaxBSize ? nscoord_MAX
7233 : ComputeISizeValueFromAspectRatio(
7234 aWM, aCBSize, boxSizingAdjust,
7235 maxBSizeCoord->AsLengthPercentage(), aspectRatio);
7236
7237 result.ISize(aWM) =
7238 CSSMinMax(result.ISize(aWM), transferredMinISize, transferredMaxISize);
7239 }
7240
7241 // Flex items ignore their min & max sizing properties in their flex
7242 // container's main-axis. (Those properties get applied later in the flexbox
7243 // algorithm.)
7244 const bool isFlexItemInlineAxisMainAxis =
7245 flexItemMainAxis && *flexItemMainAxis == LogicalAxis::Inline;
7246 // Grid items that are subgridded in inline-axis also ignore their min & max
7247 // sizing properties in that axis.
7248 const bool shouldIgnoreMinMaxISize =
7249 isFlexItemInlineAxisMainAxis || isSubgriddedInInlineAxis;
7250 const auto maxISizeCoord = stylePos->MaxISize(aWM, anchorResolutionParams);
7251 nscoord maxISize = NS_UNCONSTRAINEDSIZE;
7252 if (!maxISizeCoord->IsNone() && !shouldIgnoreMinMaxISize) {
7253 maxISize = ComputeISizeValue(aSizingInput.mRenderingContext, aWM, aCBSize,
7254 aMargin, aBorderPadding, *maxISizeCoord,
7255 *styleBSize, aspectRatio, aFlags)
7256 .mISize;
7257 result.ISize(aWM) = std::min(maxISize, result.ISize(aWM));
7258 }
7259
7260 const nscoord bSizeAsPercentageBasis = ComputeBSizeValueAsPercentageBasis(
7261 *styleBSize, *minBSizeCoord, *maxBSizeCoord, aCBSize.BSize(aWM),
7262 boxSizingAdjust.BSize(aWM), aMargin.BSize(aWM),
7263 aBorderPadding.BSize(aWM));
7264 const IntrinsicSizeInput input(
7265 aSizingInput.mRenderingContext,
7266 Some(aCBSize.ConvertTo(GetWritingMode(), aWM)),
7267 Some(LogicalSize(aWM, NS_UNCONSTRAINEDSIZE, bSizeAsPercentageBasis)
7268 .ConvertTo(GetWritingMode(), aWM)));
7269 const auto minISizeCoord = stylePos->MinISize(aWM, anchorResolutionParams);
7270 nscoord minISize;
7271 if (!minISizeCoord->IsAuto() && !shouldIgnoreMinMaxISize) {
7272 minISize = ComputeISizeValue(aSizingInput.mRenderingContext, aWM, aCBSize,
7273 aMargin, aBorderPadding, *minISizeCoord,
7274 *styleBSize, aspectRatio, aFlags)
7275 .mISize;
7276 } else if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize
)), 0))
7277 aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize
)), 0))
) {
7278 // This implements "Implied Minimum Size of Grid Items".
7279 // https://drafts.csswg.org/css-grid/#min-size-auto
7280 minISize = std::min(maxISize, GetMinISize(input));
7281 if (styleISize->IsLengthPercentage()) {
7282 minISize = std::min(minISize, result.ISize(aWM));
7283 } else if (aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize)) {
7284 // "if the grid item spans only grid tracks that have a fixed max track
7285 // sizing function, its automatic minimum size in that dimension is
7286 // further clamped to less than or equal to the size necessary to fit
7287 // its margin box within the resulting grid area (flooring at zero)"
7288 // https://drafts.csswg.org/css-grid/#min-size-auto
7289 auto maxMinISize =
7290 std::max(nscoord(0), aCBSize.ISize(aWM) - aBorderPadding.ISize(aWM) -
7291 aMargin.ISize(aWM));
7292 minISize = std::min(minISize, maxMinISize);
7293 }
7294 } else if (aspectRatioUsage == AspectRatioUsage::ToComputeISize &&
7295 ShouldApplyAutomaticMinimumOnInlineAxis(
7296 aWM, disp->IsScrollableOverflow(), anchorResolutionParams,
7297 stylePos)) {
7298 // This means we successfully applied aspect-ratio and now need to check
7299 // if we need to apply the automatic content-based minimum size:
7300 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-minimum
7301 MOZ_ASSERT(!HasReplacedSizing(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasReplacedSizing())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasReplacedSizing()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!HasReplacedSizing()"
" (" "aspect-ratio minimums should not apply to replaced elements"
")", "./../../../layout/generic/nsIFrame.cpp", 7302); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasReplacedSizing()" ") (" "aspect-ratio minimums should not apply to replaced elements"
")"); do { MOZ_CrashSequence(__null, 7302); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7302 "aspect-ratio minimums should not apply to replaced elements")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasReplacedSizing())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasReplacedSizing()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("!HasReplacedSizing()"
" (" "aspect-ratio minimums should not apply to replaced elements"
")", "./../../../layout/generic/nsIFrame.cpp", 7302); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasReplacedSizing()" ") (" "aspect-ratio minimums should not apply to replaced elements"
")"); do { MOZ_CrashSequence(__null, 7302); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7303 // The inline size computed by aspect-ratio shouldn't less than the
7304 // min-content size, which should be capped by its maximum inline size.
7305 minISize = std::min(GetMinISize(input), maxISize);
7306 } else {
7307 // Treat "min-width: auto" as 0.
7308 // NOTE: Technically, "auto" is supposed to behave like "min-content" on
7309 // flex items. However, we don't need to worry about that here, because
7310 // flex items' min-sizes are intentionally ignored until the flex
7311 // container explicitly considers them during space distribution.
7312 minISize = 0;
7313 }
7314 result.ISize(aWM) = std::max(minISize, result.ISize(aWM));
7315
7316 // Compute block-axis size
7317 // (but not if we have auto bsize -- then, we'll just stick with the bsize
7318 // that we already calculated in the initial ComputeAutoSize() call. However,
7319 // if we have a valid preferred aspect ratio, we still have to compute the
7320 // block size because aspect ratio affects the intrinsic content size.)
7321 const bool isSubgriddedInBlockAxis =
7322 isSubgrid && static_cast<nsGridContainerFrame*>(this)->IsRowSubgrid();
7323
7324 // Per https://drafts.csswg.org/css-grid/#subgrid-box-alignment, if we are
7325 // subgridded in the block-axis, ignore our style block-size, and stretch to
7326 // fill the CB.
7327 const bool shouldComputeBSize = !isAutoBSize && !isSubgriddedInBlockAxis;
7328 if (shouldComputeBSize) {
7329 result.BSize(aWM) = nsLayoutUtils::ComputeBSizeValue(
7330 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
7331 styleBSize->AsLengthPercentage());
7332 } else if (MOZ_UNLIKELY(isGridItem)(__builtin_expect(!!(isGridItem), 0)) && styleBSize->IsAuto() &&
7333 !aFlags.contains(ComputeSizeFlag::IsGridMeasuringReflow) &&
7334 !IsTrueOverflowContainer() &&
7335 !alignCB->IsMasonry(aWM, LogicalAxis::Block)) {
7336 auto cbSize = aCBSize.BSize(aWM);
7337 if (cbSize != NS_UNCONSTRAINEDSIZE) {
7338 // 'auto' block-size for grid-level box - fill the CB for 'stretch' /
7339 // 'normal' and clamp it to the CB if requested:
7340 bool isStretchAligned = false;
7341 bool mayUseAspectRatio =
7342 aspectRatio && result.ISize(aWM) != NS_UNCONSTRAINEDSIZE;
7343 if (!StyleMargin()->HasBlockAxisAuto(aWM, anchorResolutionParams)) {
7344 auto blockAxisAlignment = stylePos->UsedSelfAlignment(
7345 aWM, LogicalAxis::Block, alignCB->GetWritingMode(),
7346 alignCB->Style());
7347 isStretchAligned = blockAxisAlignment == StyleAlignFlags::STRETCH ||
7348 (blockAxisAlignment == StyleAlignFlags::NORMAL &&
7349 !mayUseAspectRatio);
7350 }
7351
7352 // Apply the preferred aspect ratio for alignments other than *stretch*
7353 // and *normal without aspect ratio*.
7354 // The spec says all other values should size the items as fit-content,
7355 // and the intrinsic size should respect the preferred aspect ratio, so
7356 // we also apply aspect ratio for all other values.
7357 // https://drafts.csswg.org/css-grid/#grid-item-sizing
7358 if (!isStretchAligned && mayUseAspectRatio) {
7359 result.BSize(aWM) = aspectRatio.ComputeRatioDependentSize(
7360 LogicalAxis::Block, aWM, result.ISize(aWM), boxSizingAdjust);
7361 MOZ_ASSERT(aspectRatioUsage == AspectRatioUsage::None)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aspectRatioUsage == AspectRatioUsage::None)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aspectRatioUsage == AspectRatioUsage::None))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aspectRatioUsage == AspectRatioUsage::None"
, "./../../../layout/generic/nsIFrame.cpp", 7361); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aspectRatioUsage == AspectRatioUsage::None"
")"); do { MOZ_CrashSequence(__null, 7361); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7362 aspectRatioUsage = AspectRatioUsage::ToComputeBSize;
7363 }
7364
7365 if (isStretchAligned ||
7366 aFlags.contains(ComputeSizeFlag::BClampMarginBoxMinSize)) {
7367 auto bSizeToFillCB = nsLayoutUtils::ComputeStretchContentBoxBSize(
7368 cbSize, aMargin.BSize(aWM), aBorderPadding.BSize(aWM));
7369 if (isStretchAligned || (result.BSize(aWM) != NS_UNCONSTRAINEDSIZE &&
7370 result.BSize(aWM) > bSizeToFillCB)) {
7371 result.BSize(aWM) = bSizeToFillCB;
7372 }
7373 }
7374 }
7375 } else if (aspectRatio) {
7376 // If both inline and block dimensions are auto, the block axis is the
7377 // ratio-dependent axis by default.
7378 // If we have a super large inline size, aspect-ratio should still be
7379 // applied (so aspectRatioUsage flag is set as expected). That's why we
7380 // apply aspect-ratio unconditionally for auto block size here.
7381 result.BSize(aWM) = aspectRatio.ComputeRatioDependentSize(
7382 LogicalAxis::Block, aWM, result.ISize(aWM), boxSizingAdjust);
7383 MOZ_ASSERT(aspectRatioUsage == AspectRatioUsage::None)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aspectRatioUsage == AspectRatioUsage::None)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aspectRatioUsage == AspectRatioUsage::None))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aspectRatioUsage == AspectRatioUsage::None"
, "./../../../layout/generic/nsIFrame.cpp", 7383); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aspectRatioUsage == AspectRatioUsage::None"
")"); do { MOZ_CrashSequence(__null, 7383); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7384 aspectRatioUsage = AspectRatioUsage::ToComputeBSize;
7385 }
7386
7387 if (result.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
7388 // Flex items ignore their min & max sizing properties in their flex
7389 // container's main-axis. (Those properties get applied later in the flexbox
7390 // algorithm.)
7391 const bool isFlexItemBlockAxisMainAxis =
7392 flexItemMainAxis && *flexItemMainAxis == LogicalAxis::Block;
7393 // Grid items that are subgridded in block-axis also ignore their min & max
7394 // sizing properties in that axis.
7395 const bool shouldIgnoreMinMaxBSize =
7396 isFlexItemBlockAxisMainAxis || isSubgriddedInBlockAxis;
7397 if (!isAutoMaxBSize && !shouldIgnoreMinMaxBSize) {
7398 nscoord maxBSize = nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7399 aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM),
7400 boxSizingAdjust.BSize(aWM), *maxBSizeCoord);
7401 result.BSize(aWM) = std::min(maxBSize, result.BSize(aWM));
7402 }
7403
7404 if (!isAutoMinBSize && !shouldIgnoreMinMaxBSize) {
7405 nscoord minBSize = nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7406 aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM),
7407 boxSizingAdjust.BSize(aWM), *minBSizeCoord);
7408 result.BSize(aWM) = std::max(minBSize, result.BSize(aWM));
7409 }
7410 }
7411
7412 if (IsThemed(disp)) {
7413 nsPresContext* pc = PresContext();
7414 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
7415 pc, this, disp->EffectiveAppearance());
7416
7417 // Convert themed widget's physical dimensions to logical coords
7418 LogicalSize size(aWM, LayoutDeviceIntSize::ToAppUnits(
7419 widget, pc->AppUnitsPerDevPixel()));
7420
7421 // GetMinimumWidgetSize() returns border-box; we need content-box.
7422 size -= aBorderPadding;
7423
7424 if (size.BSize(aWM) > result.BSize(aWM)) {
7425 result.BSize(aWM) = size.BSize(aWM);
7426 }
7427 if (size.ISize(aWM) > result.ISize(aWM)) {
7428 result.ISize(aWM) = size.ISize(aWM);
7429 }
7430 }
7431
7432 result.ISize(aWM) = std::max(0, result.ISize(aWM));
7433 result.BSize(aWM) = std::max(0, result.BSize(aWM));
7434
7435 return {result, aspectRatioUsage};
7436}
7437
7438nscoord nsIFrame::ComputeBSizeValueAsPercentageBasis(
7439 const StyleSize& aStyleBSize, const StyleSize& aStyleMinBSize,
7440 const StyleMaxSize& aStyleMaxBSize, nscoord aCBBSize,
7441 nscoord aContentEdgeToBoxSizingBSize, nscoord aMargin,
7442 nscoord aBorderPadding) {
7443 if (nsLayoutUtils::IsAutoBSize(aStyleBSize, aCBBSize)) {
7444 return NS_UNCONSTRAINEDSIZE;
7445 }
7446
7447 const nscoord bSize = nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7448 aCBBSize, aMargin, aBorderPadding, aContentEdgeToBoxSizingBSize,
7449 aStyleBSize);
7450
7451 const nscoord minBSize =
7452 nsLayoutUtils::IsAutoBSize(aStyleMinBSize, aCBBSize)
7453 ? 0
7454 : nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7455 aCBBSize, aMargin, aBorderPadding, aContentEdgeToBoxSizingBSize,
7456 aStyleMinBSize);
7457
7458 const nscoord maxBSize =
7459 nsLayoutUtils::IsAutoBSize(aStyleMaxBSize, aCBBSize)
7460 ? NS_UNCONSTRAINEDSIZE
7461 : nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7462 aCBBSize, aMargin, aBorderPadding, aContentEdgeToBoxSizingBSize,
7463 aStyleMaxBSize);
7464
7465 return CSSMinMax(bSize, minBSize, maxBSize);
7466}
7467
7468nsRect nsIFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const {
7469 return InkOverflowRect();
7470}
7471
7472/* virtual */
7473nsresult nsIFrame::GetPrefWidthTightBounds(gfxContext* aContext, nscoord* aX,
7474 nscoord* aXMost) {
7475 return NS_ERROR_NOT_IMPLEMENTED;
7476}
7477
7478/* virtual */
7479LogicalSize nsIFrame::ComputeAutoSize(
7480 const SizeComputationInput& aSizingInput, WritingMode aWM,
7481 const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
7482 const mozilla::LogicalSize& aMargin,
7483 const mozilla::LogicalSize& aBorderPadding,
7484 const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) {
7485 if (IsAbsolutelyPositionedWithDefiniteContainingBlock()) {
7486 return ComputeAbsolutePosAutoSize(aSizingInput, aWM, aCBSize,
7487 aAvailableISize, aMargin, aBorderPadding,
7488 aSizeOverrides, aFlags);
7489 }
7490
7491 // Use basic shrink-wrapping as a default implementation.
7492 LogicalSize result(aWM, 0xdeadbeef, NS_UNCONSTRAINEDSIZE);
7493
7494 const auto anchorResolutionParams = AnchorPosResolutionParams::From(this);
7495 // don't bother setting it if the result won't be used
7496 const auto styleISize =
7497 aSizeOverrides.mStyleISize
7498 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleISize)
7499 : StylePosition()->ISize(aWM, anchorResolutionParams);
7500 if (styleISize->IsAuto()) {
7501 nscoord availBased = nsLayoutUtils::ComputeStretchContentBoxISize(
7502 aAvailableISize, aMargin.ISize(aWM), aBorderPadding.ISize(aWM));
7503 const auto* stylePos = StylePosition();
7504 const auto styleBSize =
7505 aSizeOverrides.mStyleBSize
7506 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleBSize)
7507 : stylePos->BSize(aWM, anchorResolutionParams);
7508 const LogicalSize contentEdgeToBoxSizing =
7509 stylePos->mBoxSizing == StyleBoxSizing::BorderBox ? aBorderPadding
7510 : LogicalSize(aWM);
7511 const nscoord bSize = ComputeBSizeValueAsPercentageBasis(
7512 *styleBSize, *stylePos->MinBSize(aWM, anchorResolutionParams),
7513 *stylePos->MaxBSize(aWM, anchorResolutionParams), aCBSize.BSize(aWM),
7514 contentEdgeToBoxSizing.BSize(aWM), aMargin.BSize(aWM),
7515 aBorderPadding.BSize(aWM));
7516 const IntrinsicSizeInput input(
7517 aSizingInput.mRenderingContext,
7518 Some(aCBSize.ConvertTo(GetWritingMode(), aWM)),
7519 Some(LogicalSize(aWM, NS_UNCONSTRAINEDSIZE, bSize)
7520 .ConvertTo(GetWritingMode(), aWM)));
7521 result.ISize(aWM) = ShrinkISizeToFit(input, availBased, aFlags);
7522 }
7523 return result;
7524}
7525
7526bool nsIFrame::IsAbsolutelyPositionedWithDefiniteContainingBlock() const {
7527 // TODO(dshin, Bug 1927861): Even if an absolute container should have a
7528 // definite size, in a continuation context, the full extent of the containing
7529 // block is not known.
7530 return MOZ_UNLIKELY(IsAbsolutelyPositioned())(__builtin_expect(!!(IsAbsolutelyPositioned()), 0)) && !GetPrevInFlow();
7531}
7532
7533LogicalSize nsIFrame::ComputeAbsolutePosAutoSize(
7534 const SizeComputationInput& aSizingInput, WritingMode aWM,
7535 const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
7536 const mozilla::LogicalSize& aMargin,
7537 const mozilla::LogicalSize& aBorderPadding,
7538 const StyleSizeOverrides& aSizeOverrides, const ComputeSizeFlags& aFlags) {
7539 MOZ_ASSERT(IsAbsolutelyPositionedWithDefiniteContainingBlock(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsAbsolutelyPositionedWithDefiniteContainingBlock())
>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsAbsolutelyPositionedWithDefiniteContainingBlock())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("IsAbsolutelyPositionedWithDefiniteContainingBlock()"
" (" "Asking for absolute auto size when not absolute" ")", "./../../../layout/generic/nsIFrame.cpp"
, 7540); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsAbsolutelyPositionedWithDefiniteContainingBlock()"
") (" "Asking for absolute auto size when not absolute" ")")
; do { MOZ_CrashSequence(__null, 7540); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7540 "Asking for absolute auto size when not absolute")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsAbsolutelyPositionedWithDefiniteContainingBlock())
>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsAbsolutelyPositionedWithDefiniteContainingBlock())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("IsAbsolutelyPositionedWithDefiniteContainingBlock()"
" (" "Asking for absolute auto size when not absolute" ")", "./../../../layout/generic/nsIFrame.cpp"
, 7540); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsAbsolutelyPositionedWithDefiniteContainingBlock()"
") (" "Asking for absolute auto size when not absolute" ")")
; do { MOZ_CrashSequence(__null, 7540); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7541 // Ideally, this is an assertion, but the containing block could just be
7542 // really big.
7543 NS_WARNING_ASSERTION(aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE &&do { if (!(aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE &&
aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE)) { NS_DebugBreak
(NS_DEBUG_WARNING, "Absolute containing block size not definite?"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE && aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE"
, "./../../../layout/generic/nsIFrame.cpp", 7545); } } while (
false)
7544 aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE,do { if (!(aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE &&
aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE)) { NS_DebugBreak
(NS_DEBUG_WARNING, "Absolute containing block size not definite?"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE && aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE"
, "./../../../layout/generic/nsIFrame.cpp", 7545); } } while (
false)
7545 "Absolute containing block size not definite?")do { if (!(aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE &&
aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE)) { NS_DebugBreak
(NS_DEBUG_WARNING, "Absolute containing block size not definite?"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE && aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE"
, "./../../../layout/generic/nsIFrame.cpp", 7545); } } while (
false)
;
7546 LogicalSize result(aWM, static_cast<nscoord>(0xdeadbeef),
7547 NS_UNCONSTRAINEDSIZE);
7548
7549 const auto* stylePos = StylePosition();
7550 const auto anchorResolutionParams =
7551 AnchorPosOffsetResolutionParams::UseCBFrameSize(
7552 AnchorPosResolutionParams::From(&aSizingInput));
7553 const auto& styleISize =
7554 aSizeOverrides.mStyleISize
7555 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleISize)
7556 : stylePos->ISize(aWM, anchorResolutionParams.mBaseParams);
7557 const auto& styleBSize =
7558 aSizeOverrides.mStyleBSize
7559 ? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleBSize)
7560 : stylePos->BSize(aWM, anchorResolutionParams.mBaseParams);
7561 const auto iStartOffsetIsAuto =
7562 stylePos
7563 ->GetAnchorResolvedInset(LogicalSide::IStart, aWM,
7564 anchorResolutionParams)
7565 ->IsAuto();
7566 const auto iEndOffsetIsAuto =
7567 stylePos
7568 ->GetAnchorResolvedInset(LogicalSide::IEnd, aWM,
7569 anchorResolutionParams)
7570 ->IsAuto();
7571 const auto bStartOffsetIsAuto =
7572 stylePos
7573 ->GetAnchorResolvedInset(LogicalSide::BStart, aWM,
7574 anchorResolutionParams)
7575 ->IsAuto();
7576 const auto bEndOffsetIsAuto =
7577 stylePos
7578 ->GetAnchorResolvedInset(LogicalSide::BEnd, aWM,
7579 anchorResolutionParams)
7580 ->IsAuto();
7581 const auto boxSizingAdjust = stylePos->mBoxSizing == StyleBoxSizing::BorderBox
7582 ? aBorderPadding
7583 : LogicalSize(aWM);
7584 auto shouldStretch = [](StyleAlignFlags aAlignment, const nsIFrame* aFrame,
7585 bool aStartIsAuto, bool aEndIsAuto) {
7586 if (aStartIsAuto || aEndIsAuto) {
7587 // Note(dshin, bug 1930427): This is not part of the current spec [1];
7588 // however, no one implements the new inset behaviour [2], and the old
7589 // behaviour [3] ends up computing the static size if both or one inset is
7590 // auto.
7591 //
7592 // [1]: https://drafts.csswg.org/css-position-3/#abspos-auto-size
7593 // [2]: https://drafts.csswg.org/css-position-3/#resolving-insets
7594 // [3]: https://drafts.csswg.org/css-position-3/#abspos-old
7595 return false;
7596 }
7597 // Don't care about flag bits for auto-sizing.
7598 aAlignment &= ~StyleAlignFlags::FLAG_BITS;
7599
7600 if (aAlignment == StyleAlignFlags::STRETCH) {
7601 return true;
7602 }
7603
7604 if (aAlignment == StyleAlignFlags::NORMAL) {
7605 // Some replaced elements behave as semi-replaced elements - we want them
7606 // to stretch (See bug 1740580).
7607 return !aFrame->HasReplacedSizing() && !aFrame->IsTableWrapperFrame();
7608 }
7609
7610 return false;
7611 };
7612
7613 // i.e. Absolute containing block
7614
7615 // Self alignment properties translate `auto` to normal for this purpose.
7616 // https://drafts.csswg.org/css-align-3/#valdef-justify-self-auto
7617 nsContainerFrame* contFrame = static_cast<nsContainerFrame*>(this);
7618 const StylePositionArea posArea = stylePos->mPositionArea;
7619 const auto containerWM = GetParent()->GetWritingMode();
7620 auto containerAxis = [&](LogicalAxis aSubjectAxis) {
7621 return aWM.ConvertAxisTo(aSubjectAxis, containerWM);
7622 };
7623 const auto inlineSelfAlign =
7624 contFrame->CSSAlignmentForAbsPosChildWithinContainingBlock(
7625 aSizingInput, containerAxis(LogicalAxis::Inline), posArea, aCBSize);
7626 const auto blockSelfAlign =
7627 contFrame->CSSAlignmentForAbsPosChildWithinContainingBlock(
7628 aSizingInput, containerAxis(LogicalAxis::Block), posArea, aCBSize);
7629 const auto iShouldStretch = shouldStretch(
7630 inlineSelfAlign, this, iStartOffsetIsAuto, iEndOffsetIsAuto);
7631 const auto bShouldStretch =
7632 shouldStretch(blockSelfAlign, this, bStartOffsetIsAuto, bEndOffsetIsAuto);
7633 const auto iSizeIsAuto = styleISize->IsAuto();
7634 // Note(dshin, bug 1789477): `auto` in the context of abs-element uses
7635 // stretch-fit sizing, given specific alignment conditions [1]. Effectively,
7636 // `auto` is `stretch`. `nsLayoutUtils::IsAutoBSize` is not the right tool
7637 // here, since the mapping is explicit, and it's incorrect to e.g. map
7638 // `fit-content` to `stretch`.
7639 // `-moz-available` behaves like `auto` in general, so map the same way.
7640 // When Bug 567039 brings `-moz-available` into alignment with `stretch`, this
7641 // special check can be removed. TODO(dshin): we're probably duplicating the
7642 // `stretch` logic here, since `stretch` is `stretch-fit` sizing [2].
7643 //
7644 // [1]: https://drafts.csswg.org/css-position/#abspos-auto-size
7645 // [2]: https://drafts.csswg.org/css-sizing-4/#valdef-width-stretch
7646 const auto bSizeIsAuto = styleBSize->IsAuto() || styleBSize->IsMozAvailable();
7647 if (bSizeIsAuto && bShouldStretch) {
7648 result.BSize(aWM) = nsLayoutUtils::ComputeStretchContentBoxBSize(
7649 aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM));
7650 }
7651 if (iSizeIsAuto) {
7652 if (iShouldStretch) {
7653 // inline-size to make our margin-box fill the containing block:
7654 result.ISize(aWM) = nsLayoutUtils::ComputeStretchContentBoxISize(
7655 aCBSize.ISize(aWM), aMargin.ISize(aWM), aBorderPadding.ISize(aWM));
7656 } else {
7657 // inline-size to make our margin-box fill aAvailableISize:
7658 nscoord availBased = nsLayoutUtils::ComputeStretchContentBoxISize(
7659 aAvailableISize, aMargin.ISize(aWM), aBorderPadding.ISize(aWM));
7660
7661 const nscoord bSize = ComputeBSizeValueAsPercentageBasis(
7662 styleBSize->IsAuto() && result.BSize(aWM) != NS_UNCONSTRAINEDSIZE
7663 ? StyleSize::FromAppUnits(result.BSize(aWM))
7664 : *styleBSize,
7665 *stylePos->MinBSize(aWM, anchorResolutionParams.mBaseParams),
7666 *stylePos->MaxBSize(aWM, anchorResolutionParams.mBaseParams),
7667 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM), aMargin.BSize(aWM),
7668 aBorderPadding.BSize(aWM));
7669
7670 const IntrinsicSizeInput input(
7671 aSizingInput.mRenderingContext,
7672 Some(aCBSize.ConvertTo(GetWritingMode(), aWM)),
7673 Some(LogicalSize(aWM, NS_UNCONSTRAINEDSIZE, bSize)
7674 .ConvertTo(GetWritingMode(), aWM)));
7675 result.ISize(aWM) = ShrinkISizeToFit(input, availBased, aFlags);
7676 }
7677 }
7678
7679 const auto& aspectRatio = aSizeOverrides.mAspectRatio
7680 ? *aSizeOverrides.mAspectRatio
7681 : GetAspectRatio();
7682 if (aspectRatio) {
7683 auto aspectRatioUsage = AspectRatioUsage::None;
7684 if (iSizeIsAuto != bSizeIsAuto) {
7685 // Auto axis is dependent.
7686 if (iSizeIsAuto) {
7687 aspectRatioUsage = AspectRatioUsage::ToComputeBSize;
7688 } else {
7689 aspectRatioUsage = AspectRatioUsage::ToComputeISize;
7690 }
7691 } else if (iSizeIsAuto) {
7692 // Both axes are `auto`.
7693 if (iShouldStretch != bShouldStretch) {
7694 // If an axis has stretch, that behaves like a definite size.
7695 aspectRatioUsage = iShouldStretch ? AspectRatioUsage::ToComputeBSize
7696 : AspectRatioUsage::ToComputeISize;
7697 } else if (!iShouldStretch) {
7698 // If one axis has `auto` inset, that is the ratio dependent axis,
7699 // otherwise the block axis is.
7700 const bool inlineInsetHasAuto = iStartOffsetIsAuto || iEndOffsetIsAuto;
7701 const bool blockInsetHasAuto = bStartOffsetIsAuto || bEndOffsetIsAuto;
7702 aspectRatioUsage = inlineInsetHasAuto && !blockInsetHasAuto
7703 ? AspectRatioUsage::ToComputeISize
7704 : AspectRatioUsage::ToComputeBSize;
7705 }
7706 }
7707
7708 if (aspectRatioUsage == AspectRatioUsage::ToComputeBSize &&
7709 !bShouldStretch) {
7710 result.BSize(aWM) = aspectRatio.ComputeRatioDependentSize(
7711 LogicalAxis::Block, aWM, result.ISize(aWM), boxSizingAdjust);
7712 } else if (aspectRatioUsage == AspectRatioUsage::ToComputeISize &&
7713 !iShouldStretch && result.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
7714 result.ISize(aWM) = aspectRatio.ComputeRatioDependentSize(
7715 LogicalAxis::Inline, aWM, result.BSize(aWM), boxSizingAdjust);
7716 }
7717 }
7718
7719 return result;
7720}
7721
7722nscoord nsIFrame::ShrinkISizeToFit(const IntrinsicSizeInput& aInput,
7723 nscoord aISizeInCB,
7724 ComputeSizeFlags aFlags) {
7725 // If we're a container for font size inflation, then shrink
7726 // wrapping inside of us should not apply font size inflation.
7727 AutoMaybeDisableFontInflation an(this);
7728
7729 nscoord result;
7730 nscoord minISize = GetMinISize(aInput);
7731 if (minISize > aISizeInCB) {
7732 const bool clamp = aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize);
7733 result = MOZ_UNLIKELY(clamp)(__builtin_expect(!!(clamp), 0)) ? aISizeInCB : minISize;
7734 } else {
7735 nscoord prefISize = GetPrefISize(aInput);
7736 if (prefISize > aISizeInCB) {
7737 result = aISizeInCB;
7738 } else {
7739 result = prefISize;
7740 }
7741 }
7742 return result;
7743}
7744
7745nscoord nsIFrame::IntrinsicISizeFromInline(const IntrinsicSizeInput& aInput,
7746 IntrinsicISizeType aType) {
7747 MOZ_ASSERT(!IsContainerForFontSizeInflation(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsContainerForFontSizeInflation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsContainerForFontSizeInflation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!IsContainerForFontSizeInflation()" " (" "Should not be a container for font size inflation!"
")", "./../../../layout/generic/nsIFrame.cpp", 7748); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsContainerForFontSizeInflation()" ") (" "Should not be a container for font size inflation!"
")"); do { MOZ_CrashSequence(__null, 7748); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7748 "Should not be a container for font size inflation!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsContainerForFontSizeInflation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsContainerForFontSizeInflation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!IsContainerForFontSizeInflation()" " (" "Should not be a container for font size inflation!"
")", "./../../../layout/generic/nsIFrame.cpp", 7748); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsContainerForFontSizeInflation()" ") (" "Should not be a container for font size inflation!"
")"); do { MOZ_CrashSequence(__null, 7748); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7749
7750 if (aType == IntrinsicISizeType::MinISize) {
7751 InlineMinISizeData data;
7752 AddInlineMinISize(aInput, &data);
7753 data.ForceBreak();
7754 return data.mPrevLines;
7755 }
7756
7757 InlinePrefISizeData data;
7758 AddInlinePrefISize(aInput, &data);
7759 data.ForceBreak();
7760 return data.mPrevLines;
7761}
7762
7763nscoord nsIFrame::ComputeISizeValueFromAspectRatio(
7764 WritingMode aWM, const LogicalSize& aCBSize,
7765 const LogicalSize& aContentEdgeToBoxSizing, const LengthPercentage& aBSize,
7766 const AspectRatio& aAspectRatio) const {
7767 MOZ_ASSERT(aAspectRatio, "Must have a valid AspectRatio!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aAspectRatio)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aAspectRatio))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aAspectRatio" " ("
"Must have a valid AspectRatio!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 7767); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAspectRatio"
") (" "Must have a valid AspectRatio!" ")"); do { MOZ_CrashSequence
(__null, 7767); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
7768 const nscoord bSize = nsLayoutUtils::ComputeBSizeValue(
7769 aCBSize.BSize(aWM), aContentEdgeToBoxSizing.BSize(aWM), aBSize);
7770 return aAspectRatio.ComputeRatioDependentSize(LogicalAxis::Inline, aWM, bSize,
7771 aContentEdgeToBoxSizing);
7772}
7773
7774nsIFrame::ISizeComputationResult nsIFrame::ComputeISizeValue(
7775 gfxContext* aRenderingContext, const WritingMode aWM,
7776 const LogicalSize& aCBSize, const LogicalSize& aMargin,
7777 const LogicalSize& aBorderPadding, ExtremumLength aSize,
7778 Maybe<nscoord> aAvailableISizeOverride, const StyleSize& aStyleBSize,
7779 const AspectRatio& aAspectRatio, ComputeSizeFlags aFlags) {
7780 const auto* stylePos = StylePosition();
7781 const LogicalSize contentEdgeToBoxSizing =
7782 stylePos->mBoxSizing == StyleBoxSizing::BorderBox ? aBorderPadding
7783 : LogicalSize(aWM);
7784 auto GetAvailableISize = [&]() {
7785 return aCBSize.ISize(aWM) - aMargin.ISize(aWM) - aBorderPadding.ISize(aWM);
7786 };
7787
7788 // If 'this' is a container for font size inflation, then shrink
7789 // wrapping inside of it should not apply font size inflation.
7790 AutoMaybeDisableFontInflation an(this);
7791 // If we have an aspect-ratio and a definite block size, we should use them to
7792 // resolve the sizes with intrinsic keywords.
7793 // https://github.com/w3c/csswg-drafts/issues/5032
7794 Maybe<nscoord> iSizeFromAspectRatio = [&]() -> Maybe<nscoord> {
7795 if (aSize == ExtremumLength::MozAvailable ||
7796 aSize == ExtremumLength::Stretch) {
7797 return Nothing();
7798 }
7799 if (!aAspectRatio) {
7800 return Nothing();
7801 }
7802 if (nsLayoutUtils::IsAutoBSize(aStyleBSize, aCBSize.BSize(aWM))) {
7803 return Nothing();
7804 }
7805 const nscoord bSize = nsLayoutUtils::ComputeBSizeValueHandlingStretch(
7806 aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM),
7807 contentEdgeToBoxSizing.BSize(aWM), aStyleBSize);
7808 return Some(aAspectRatio.ComputeRatioDependentSize(
7809 LogicalAxis::Inline, aWM, bSize, contentEdgeToBoxSizing));
7810 }();
7811
7812 const auto anchorResolutionParams = AnchorPosResolutionParams::From(this);
7813 const nscoord bSize = ComputeBSizeValueAsPercentageBasis(
7814 aStyleBSize, *stylePos->MinBSize(aWM, anchorResolutionParams),
7815 *stylePos->MaxBSize(aWM, anchorResolutionParams), aCBSize.BSize(aWM),
7816 contentEdgeToBoxSizing.BSize(aWM), aMargin.BSize(aWM),
7817 aBorderPadding.BSize(aWM));
7818 const IntrinsicSizeInput input(
7819 aRenderingContext, Some(aCBSize.ConvertTo(GetWritingMode(), aWM)),
7820 Some(LogicalSize(aWM, NS_UNCONSTRAINEDSIZE, bSize)
7821 .ConvertTo(GetWritingMode(), aWM)));
7822 nscoord result;
7823 switch (aSize) {
7824 case ExtremumLength::MaxContent:
7825 result =
7826 iSizeFromAspectRatio ? *iSizeFromAspectRatio : GetPrefISize(input);
7827 NS_ASSERTION(result >= 0, "inline-size less than zero")do { if (!(result >= 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "inline-size less than zero", "result >= 0", "./../../../layout/generic/nsIFrame.cpp"
, 7827); MOZ_PretendNoReturn(); } } while (0)
;
7828 return {result, iSizeFromAspectRatio ? AspectRatioUsage::ToComputeISize
7829 : AspectRatioUsage::None};
7830 case ExtremumLength::MinContent:
7831 result =
7832 iSizeFromAspectRatio ? *iSizeFromAspectRatio : GetMinISize(input);
7833 NS_ASSERTION(result >= 0, "inline-size less than zero")do { if (!(result >= 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "inline-size less than zero", "result >= 0", "./../../../layout/generic/nsIFrame.cpp"
, 7833); MOZ_PretendNoReturn(); } } while (0)
;
7834 if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
7835 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
) {
7836 result = std::min(GetAvailableISize(), result);
7837 }
7838 return {result, iSizeFromAspectRatio ? AspectRatioUsage::ToComputeISize
7839 : AspectRatioUsage::None};
7840 case ExtremumLength::FitContentFunction:
7841 case ExtremumLength::FitContent: {
7842 nscoord pref = NS_UNCONSTRAINEDSIZE;
7843 nscoord min = 0;
7844 if (iSizeFromAspectRatio) {
7845 // The min-content and max-content size are identical and equal to the
7846 // size computed from the block size and the aspect ratio.
7847 pref = min = *iSizeFromAspectRatio;
7848 } else {
7849 pref = GetPrefISize(input);
7850 min = GetMinISize(input);
7851 }
7852
7853 const nscoord fill = aAvailableISizeOverride ? *aAvailableISizeOverride
7854 : GetAvailableISize();
7855 if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
7856 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
) {
7857 min = std::min(min, fill);
7858 }
7859 result = std::max(min, std::min(pref, fill));
7860 NS_ASSERTION(result >= 0, "inline-size less than zero")do { if (!(result >= 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "inline-size less than zero", "result >= 0", "./../../../layout/generic/nsIFrame.cpp"
, 7860); MOZ_PretendNoReturn(); } } while (0)
;
7861 return {result};
7862 }
7863 case ExtremumLength::MozAvailable:
7864 case ExtremumLength::Stretch:
7865 return {GetAvailableISize()};
7866 }
7867 MOZ_ASSERT_UNREACHABLE("Unknown extremum length?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Unknown extremum length?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 7867); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown extremum length?" ")"); do
{ MOZ_CrashSequence(__null, 7867); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
7868 return {};
7869}
7870
7871nscoord nsIFrame::ComputeISizeValue(const WritingMode aWM,
7872 const LogicalSize& aCBSize,
7873 const LogicalSize& aContentEdgeToBoxSizing,
7874 const LengthPercentage& aSize) const {
7875 LAYOUT_WARN_IF_FALSE(do { if ((__builtin_expect(!!(mozilla::detail::log_test(sLayoutLog
, mozilla::LogLevel::Warning)), 0)) && !(aCBSize.ISize
(aWM) != NS_UNCONSTRAINEDSIZE)) { mozilla::detail::LayoutLogWarning
("have unconstrained inline-size; this should only result from "
"very large sizes, not attempts at intrinsic inline-size " "calculation"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE", "./../../../layout/generic/nsIFrame.cpp"
, 7879); } } while (0)
7876 aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE,do { if ((__builtin_expect(!!(mozilla::detail::log_test(sLayoutLog
, mozilla::LogLevel::Warning)), 0)) && !(aCBSize.ISize
(aWM) != NS_UNCONSTRAINEDSIZE)) { mozilla::detail::LayoutLogWarning
("have unconstrained inline-size; this should only result from "
"very large sizes, not attempts at intrinsic inline-size " "calculation"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE", "./../../../layout/generic/nsIFrame.cpp"
, 7879); } } while (0)
7877 "have unconstrained inline-size; this should only result from "do { if ((__builtin_expect(!!(mozilla::detail::log_test(sLayoutLog
, mozilla::LogLevel::Warning)), 0)) && !(aCBSize.ISize
(aWM) != NS_UNCONSTRAINEDSIZE)) { mozilla::detail::LayoutLogWarning
("have unconstrained inline-size; this should only result from "
"very large sizes, not attempts at intrinsic inline-size " "calculation"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE", "./../../../layout/generic/nsIFrame.cpp"
, 7879); } } while (0)
7878 "very large sizes, not attempts at intrinsic inline-size "do { if ((__builtin_expect(!!(mozilla::detail::log_test(sLayoutLog
, mozilla::LogLevel::Warning)), 0)) && !(aCBSize.ISize
(aWM) != NS_UNCONSTRAINEDSIZE)) { mozilla::detail::LayoutLogWarning
("have unconstrained inline-size; this should only result from "
"very large sizes, not attempts at intrinsic inline-size " "calculation"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE", "./../../../layout/generic/nsIFrame.cpp"
, 7879); } } while (0)
7879 "calculation")do { if ((__builtin_expect(!!(mozilla::detail::log_test(sLayoutLog
, mozilla::LogLevel::Warning)), 0)) && !(aCBSize.ISize
(aWM) != NS_UNCONSTRAINEDSIZE)) { mozilla::detail::LayoutLogWarning
("have unconstrained inline-size; this should only result from "
"very large sizes, not attempts at intrinsic inline-size " "calculation"
, "aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE", "./../../../layout/generic/nsIFrame.cpp"
, 7879); } } while (0)
;
7880 NS_ASSERTION(aCBSize.ISize(aWM) >= 0, "inline-size less than zero")do { if (!(aCBSize.ISize(aWM) >= 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "inline-size less than zero", "aCBSize.ISize(aWM) >= 0",
"./../../../layout/generic/nsIFrame.cpp", 7880); MOZ_PretendNoReturn
(); } } while (0)
;
7881
7882 nscoord result = aSize.Resolve(aCBSize.ISize(aWM));
7883 // The result of a calc() expression might be less than 0; we
7884 // should clamp at runtime (below). (Percentages and coords that
7885 // are less than 0 have already been dropped by the parser.)
7886 result -= aContentEdgeToBoxSizing.ISize(aWM);
7887 return std::max(0, result);
7888}
7889
7890void nsIFrame::DidReflow(nsPresContext* aPresContext,
7891 const ReflowInput* aReflowInput) {
7892 NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("nsIFrame::DidReflow"))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("nsIFrame::DidReflow"
); } } while (0)
;
7893
7894 if (IsHiddenByContentVisibilityOfInFlowParentForLayout()) {
7895 RemoveStateBits(NS_FRAME_IN_REFLOW);
7896 return;
7897 }
7898
7899 SVGObserverUtils::InvalidateDirectRenderingObservers(this);
7900
7901 RemoveStateBits(NS_FRAME_IN_REFLOW | NS_FRAME_FIRST_REFLOW |
7902 NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
7903
7904 // Clear bits that were used in ReflowInput::InitResizeFlags (see
7905 // comment there for why we can't clear it there).
7906 SetHasBSizeChange(false);
7907 SetHasPaddingChange(false);
7908
7909 // Notify the percent bsize observer if there is a percent bsize.
7910 // The observer may be able to initiate another reflow with a computed
7911 // bsize. This happens in the case where a table cell has no computed
7912 // bsize but can fabricate one when the cell bsize is known.
7913 if (aReflowInput && aReflowInput->mPercentBSizeObserver && !GetPrevInFlow()) {
7914 const auto bsize = aReflowInput->mStylePosition->BSize(
7915 aReflowInput->GetWritingMode(),
7916 AnchorPosResolutionParams::From(aReflowInput));
7917 if (bsize->HasPercent()) {
7918 aReflowInput->mPercentBSizeObserver->NotifyPercentBSize(*aReflowInput);
7919 }
7920 }
7921
7922 aPresContext->ReflowedFrame();
7923}
7924
7925/* virtual */
7926bool nsIFrame::CanContinueTextRun() const {
7927 // By default, a frame will *not* allow a text run to be continued
7928 // through it.
7929 return false;
7930}
7931
7932void nsIFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize,
7933 const ReflowInput& aReflowInput,
7934 nsReflowStatus& aStatus) {
7935 MarkInReflow();
7936 DO_GLOBAL_REFLOW_COUNT("nsFrame")aPresContext->CountReflows(("nsFrame"), (nsIFrame*)this);;
7937 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!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 7937); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
MOZ_CrashSequence(__null, 7937); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
7938 aDesiredSize.ClearSize();
7939}
7940
7941bool nsIFrame::IsContentDisabled() const {
7942 auto* element = nsGenericHTMLElement::FromNodeOrNull(GetContent());
7943 return element && element->IsDisabled();
7944}
7945
7946bool nsIFrame::IsContentRelevant() const {
7947 MOZ_ASSERT(StyleDisplay()->ContentVisibility(*this) ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
, "./../../../layout/generic/nsIFrame.cpp", 7948); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { MOZ_CrashSequence(__null, 7948); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7948 StyleContentVisibility::Auto)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
, "./../../../layout/generic/nsIFrame.cpp", 7948); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { MOZ_CrashSequence(__null, 7948); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7949
7950 auto* element = Element::FromNodeOrNull(GetContent());
7951 MOZ_ASSERT(element)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(element)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(element))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("element", "./../../../layout/generic/nsIFrame.cpp"
, 7951); AnnotateMozCrashReason("MOZ_ASSERT" "(" "element" ")"
); do { MOZ_CrashSequence(__null, 7951); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7952
7953 Maybe<ContentRelevancy> relevancy = element->GetContentRelevancy();
7954 return relevancy.isSome() && !relevancy->isEmpty();
7955}
7956
7957bool nsIFrame::HidesContent(
7958 const EnumSet<IncludeContentVisibility>& aInclude) const {
7959 auto effectiveContentVisibility = StyleDisplay()->ContentVisibility(*this);
7960 if (aInclude.contains(IncludeContentVisibility::Hidden) &&
7961 effectiveContentVisibility == StyleContentVisibility::Hidden) {
7962 return true;
7963 }
7964
7965 if (aInclude.contains(IncludeContentVisibility::Auto) &&
7966 effectiveContentVisibility == StyleContentVisibility::Auto) {
7967 return !IsContentRelevant();
7968 }
7969
7970 return false;
7971}
7972
7973bool nsIFrame::HidesContentForLayout() const {
7974 return HidesContent() && !PresShell()->IsForcingLayoutForHiddenContent(this);
7975}
7976
7977bool nsIFrame::IsHiddenByContentVisibilityOfInFlowParentForLayout() const {
7978 const auto* parent = GetInFlowParent();
7979 // The anonymous children owned by parent are important for properly sizing
7980 // their parents.
7981 return parent && parent->HidesContentForLayout() &&
7982 !(parent->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES) &&
7983 Style()->IsAnonBox());
7984}
7985
7986nsIFrame* nsIFrame::GetClosestContentVisibilityAncestor(
7987 const EnumSet<IncludeContentVisibility>& aInclude) const {
7988 // Before we walk the frame tree: check PresShell bookkeeping to see if there
7989 // exists *any* frame with a content-visibility value that matches aInclude.
7990 mozilla::PresShell* ps = PresShell();
7991 bool doesAnySuchFrameExist =
7992 (aInclude.contains(IncludeContentVisibility::Hidden) &&
7993 ps->HasContentVisibilityHiddenFrames()) ||
7994 (aInclude.contains(IncludeContentVisibility::Auto) &&
7995 ps->HasContentVisibilityAutoFrames());
7996
7997 if (!doesAnySuchFrameExist) {
7998 return nullptr;
7999 }
8000
8001 auto* parent = GetInFlowParent();
8002 bool isAnonymousBlock = Style()->IsAnonBox() && parent &&
8003 parent->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES);
8004 for (nsIFrame* cur = parent; cur; cur = cur->GetInFlowParent()) {
8005 if (!isAnonymousBlock && cur->HidesContent(aInclude)) {
8006 return cur;
8007 }
8008
8009 // Anonymous boxes are not hidden by the content-visibility of their first
8010 // non-anonymous ancestor, but can be hidden by ancestors further up the
8011 // tree.
8012 isAnonymousBlock = false;
8013 }
8014
8015 return nullptr;
8016}
8017
8018static bool IsClosedDetailsSlot(const Element* aElement) {
8019 const auto* slot = HTMLSlotElement::FromNodeOrNull(aElement);
8020 if (!slot || slot->HasName()) {
8021 return false;
8022 }
8023 const auto* details =
8024 HTMLDetailsElement::FromNodeOrNull(slot->GetContainingShadowHost());
8025 return details && !details->GetBoolAttr(nsGkAtoms::open);
8026}
8027
8028bool nsIFrame::IsHiddenUntilFoundOrClosedDetails() const {
8029 for (const auto* f = this; f; f = f->GetInFlowParent()) {
8030 if (f->HidesContent(nsIFrame::IncludeContentVisibility::Hidden)) {
8031 if (const auto* element = Element::FromNode(f->GetContent());
8032 element &&
8033 !element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
8034 nsGkAtoms::untilFound, eIgnoreCase) &&
8035 !IsClosedDetailsSlot(element)) {
8036 return false;
8037 }
8038 }
8039 }
8040 return true;
8041}
8042
8043bool nsIFrame::IsHiddenByContentVisibilityOnAnyAncestor(
8044 const EnumSet<IncludeContentVisibility>& aInclude) const {
8045 return !!GetClosestContentVisibilityAncestor(aInclude);
8046}
8047
8048bool nsIFrame::HasSelectionInSubtree() {
8049 if (IsSelected()) {
8050 return true;
8051 }
8052
8053 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
8054 if (!frameSelection) {
8055 return false;
8056 }
8057
8058 const Selection& selection = frameSelection->NormalSelection();
8059
8060 for (uint32_t i = 0; i < selection.RangeCount(); i++) {
8061 auto* range = selection.GetRangeAt(i);
8062 MOZ_ASSERT(range)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(range)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(range))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("range", "./../../../layout/generic/nsIFrame.cpp"
, 8062); AnnotateMozCrashReason("MOZ_ASSERT" "(" "range" ")")
; do { MOZ_CrashSequence(__null, 8062); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8063
8064 const auto* commonAncestorNode =
8065 range->GetRegisteredClosestCommonInclusiveAncestor();
8066 if (commonAncestorNode &&
8067 commonAncestorNode->IsInclusiveDescendantOf(GetContent())) {
8068 return true;
8069 }
8070 }
8071
8072 return false;
8073}
8074
8075bool nsIFrame::UpdateIsRelevantContent(
8076 const ContentRelevancy& aRelevancyToUpdate) {
8077 MOZ_ASSERT(StyleDisplay()->ContentVisibility(*this) ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
, "./../../../layout/generic/nsIFrame.cpp", 8078); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { MOZ_CrashSequence(__null, 8078); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
8078 StyleContentVisibility::Auto)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility
::Auto))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
, "./../../../layout/generic/nsIFrame.cpp", 8078); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { MOZ_CrashSequence(__null, 8078); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8079
8080 auto* element = Element::FromNodeOrNull(GetContent());
8081 MOZ_ASSERT(element)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(element)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(element))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("element", "./../../../layout/generic/nsIFrame.cpp"
, 8081); AnnotateMozCrashReason("MOZ_ASSERT" "(" "element" ")"
); do { MOZ_CrashSequence(__null, 8081); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8082
8083 ContentRelevancy newRelevancy;
8084 Maybe<ContentRelevancy> oldRelevancy = element->GetContentRelevancy();
8085 if (oldRelevancy.isSome()) {
8086 newRelevancy = *oldRelevancy;
8087 }
8088
8089 auto setRelevancyValue = [&](ContentRelevancyReason reason, bool value) {
8090 if (value) {
8091 newRelevancy += reason;
8092 } else {
8093 newRelevancy -= reason;
8094 }
8095 };
8096
8097 if (!oldRelevancy ||
8098 aRelevancyToUpdate.contains(ContentRelevancyReason::Visible)) {
8099 Maybe<bool> visible = element->GetVisibleForContentVisibility();
8100 if (visible.isSome()) {
8101 setRelevancyValue(ContentRelevancyReason::Visible, *visible);
8102 }
8103 }
8104
8105 if (!oldRelevancy ||
8106 aRelevancyToUpdate.contains(ContentRelevancyReason::FocusInSubtree)) {
8107 setRelevancyValue(ContentRelevancyReason::FocusInSubtree,
8108 element->State().HasAtLeastOneOfStates(
8109 ElementState::FOCUS_WITHIN | ElementState::FOCUS));
8110 }
8111
8112 if (!oldRelevancy ||
8113 aRelevancyToUpdate.contains(ContentRelevancyReason::Selected)) {
8114 setRelevancyValue(ContentRelevancyReason::Selected,
8115 HasSelectionInSubtree());
8116 }
8117
8118 // If the proximity to the viewport has not been determined yet,
8119 // and neither the element nor its contents are focused or selected,
8120 // we should wait for the determination of the proximity. Otherwise,
8121 // there might be a redundant contentvisibilityautostatechange event.
8122 // See https://github.com/w3c/csswg-drafts/issues/9803
8123 bool isProximityToViewportDetermined =
8124 oldRelevancy ? true : element->GetVisibleForContentVisibility().isSome();
8125 if (!isProximityToViewportDetermined && newRelevancy.isEmpty()) {
8126 return false;
8127 }
8128
8129 bool overallRelevancyChanged =
8130 !oldRelevancy || oldRelevancy->isEmpty() != newRelevancy.isEmpty();
8131 if (!oldRelevancy || *oldRelevancy != newRelevancy) {
8132 element->SetContentRelevancy(newRelevancy);
8133 }
8134
8135 if (!overallRelevancyChanged) {
8136 return false;
8137 }
8138
8139 HandleLastRememberedSize();
8140 PresContext()->SetNeedsToUpdateHiddenByContentVisibilityForAnimations();
8141 PresShell()->FrameNeedsReflow(
8142 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
8143 InvalidateFrame();
8144
8145 ContentVisibilityAutoStateChangeEventInit init;
8146 init.mSkipped = newRelevancy.isEmpty();
8147 RefPtr<ContentVisibilityAutoStateChangeEvent> event =
8148 ContentVisibilityAutoStateChangeEvent::Constructor(
8149 element, u"contentvisibilityautostatechange"_ns, init);
8150
8151 // Per
8152 // https://drafts.csswg.org/css-contain/#content-visibility-auto-state-changed
8153 // "This event is dispatched by posting a task at the time when the state
8154 // change occurs."
8155 auto asyncDispatcher =
8156 MakeRefPtr<AsyncEventDispatcher>(element, event.forget());
8157 DebugOnly<nsresult> rv = asyncDispatcher->PostDOMEvent();
8158 NS_ASSERTION(NS_SUCCEEDED(rv), "AsyncEventDispatcher failed to dispatch")do { if (!(((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1
))))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "AsyncEventDispatcher failed to dispatch"
, "NS_SUCCEEDED(rv)", "./../../../layout/generic/nsIFrame.cpp"
, 8158); MOZ_PretendNoReturn(); } } while (0)
;
8159 return true;
8160}
8161
8162nsresult nsIFrame::CharacterDataChanged(const CharacterDataChangeInfo&) {
8163 MOZ_ASSERT_UNREACHABLE("should only be called for text frames")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"should only be called for text frames" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8163); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "should only be called for text frames"
")"); do { MOZ_CrashSequence(__null, 8163); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8164 return NS_OK;
8165}
8166
8167nsresult nsIFrame::AttributeChanged(int32_t aNameSpaceID, nsAtom* aAttribute,
8168 AttrModType) {
8169 return NS_OK;
8170}
8171
8172nsIFrame* nsIFrame::GetPrevContinuation() const { return nullptr; }
8173
8174void nsIFrame::SetPrevContinuation(nsIFrame*) {
8175 MOZ_ASSERT_UNREACHABLE("Not splittable!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Not splittable!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8175); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { MOZ_CrashSequence
(__null, 8175); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8176}
8177
8178nsIFrame* nsIFrame::GetNextContinuation() const { return nullptr; }
8179
8180void nsIFrame::SetNextContinuation(nsIFrame*) {
8181 MOZ_ASSERT_UNREACHABLE("Not splittable!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Not splittable!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8181); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { MOZ_CrashSequence
(__null, 8181); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8182}
8183
8184nsIFrame* nsIFrame::GetPrevInFlow() const { return nullptr; }
8185
8186void nsIFrame::SetPrevInFlow(nsIFrame*) {
8187 MOZ_ASSERT_UNREACHABLE("Not splittable!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Not splittable!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8187); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { MOZ_CrashSequence
(__null, 8187); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8188}
8189
8190nsIFrame* nsIFrame::GetNextInFlow() const { return nullptr; }
8191
8192void nsIFrame::SetNextInFlow(nsIFrame*) {
8193 MOZ_ASSERT_UNREACHABLE("Not splittable!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Not splittable!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8193); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { MOZ_CrashSequence
(__null, 8193); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8194}
8195
8196nsIFrame* nsIFrame::GetTailContinuation() {
8197 nsIFrame* frame = this;
8198 while (frame->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
8199 frame = frame->GetPrevContinuation();
8200 NS_ASSERTION(frame, "first continuation can't be overflow container")do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "first continuation can't be overflow container"
, "frame", "./../../../layout/generic/nsIFrame.cpp", 8200); MOZ_PretendNoReturn
(); } } while (0)
;
8201 }
8202 for (nsIFrame* next = frame->GetNextContinuation();
8203 next && !next->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
8204 next = frame->GetNextContinuation()) {
8205 frame = next;
8206 }
8207
8208 MOZ_ASSERT(frame, "illegal state in continuation chain.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(frame))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("frame" " (" "illegal state in continuation chain."
")", "./../../../layout/generic/nsIFrame.cpp", 8208); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "frame" ") (" "illegal state in continuation chain."
")"); do { MOZ_CrashSequence(__null, 8208); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8209 return frame;
8210}
8211
8212nsIWidget* nsIFrame::GetOwnWidget() const {
8213 if (IsMenuPopupFrame()) {
8214 return static_cast<const nsMenuPopupFrame*>(this)->GetWidget();
8215 }
8216 if (!GetParent()) {
8217 return PresShell()->GetOwnWidget();
8218 }
8219 return nullptr;
8220}
8221
8222// aPosition should be a function that returns the position of a frame relative
8223// to its parent.
8224template <typename PositionGetter>
8225static nsPoint OffsetCalculator(const nsIFrame* aThis, const nsIFrame* aOther,
8226 PositionGetter&& aPosition) {
8227 static_assert(std::is_invocable_r_v<nsPoint, PositionGetter, const nsIFrame*>,
8228 "aPosition must be callable as nsPoint(const nsIFrame*)");
8229
8230 MOZ_ASSERT(aOther, "Must have frame for destination coordinate system!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aOther)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aOther))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aOther" " (" "Must have frame for destination coordinate system!"
")", "./../../../layout/generic/nsIFrame.cpp", 8230); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aOther" ") (" "Must have frame for destination coordinate system!"
")"); do { MOZ_CrashSequence(__null, 8230); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8231
8232 NS_ASSERTION(aThis->PresContext() == aOther->PresContext(),do { if (!(aThis->PresContext() == aOther->PresContext(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "GetOffsetTo called on frames in different documents"
, "aThis->PresContext() == aOther->PresContext()", "./../../../layout/generic/nsIFrame.cpp"
, 8233); MOZ_PretendNoReturn(); } } while (0)
8233 "GetOffsetTo called on frames in different documents")do { if (!(aThis->PresContext() == aOther->PresContext(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "GetOffsetTo called on frames in different documents"
, "aThis->PresContext() == aOther->PresContext()", "./../../../layout/generic/nsIFrame.cpp"
, 8233); MOZ_PretendNoReturn(); } } while (0)
;
8234
8235 nsPoint offset(0, 0);
8236 const nsIFrame* f;
8237 for (f = aThis; f != aOther && f; f = f->GetParent()) {
8238 offset += aPosition(f);
8239 }
8240
8241 if (f != aOther) {
8242 // Looks like aOther wasn't an ancestor of |this|. So now we have
8243 // the root-frame-relative position of |this| in |offset|. Convert back
8244 // to the coordinates of aOther
8245 while (aOther) {
8246 offset -= aPosition(aOther);
8247 aOther = aOther->GetParent();
8248 }
8249 }
8250
8251 return offset;
8252}
8253
8254nsPoint nsIFrame::GetOffsetTo(const nsIFrame* aOther) const {
8255 return OffsetCalculator(this, aOther, [](const nsIFrame* aFrame) {
8256 return aFrame->GetPosition();
8257 });
8258}
8259
8260nsPoint nsIFrame::GetOffsetToRootFrame() const {
8261 return GetOffsetTo(PresShell()->GetRootFrame());
8262}
8263
8264nsPoint nsIFrame::GetOffsetToIgnoringScrolling(const nsIFrame* aOther) const {
8265 return OffsetCalculator(this, aOther, [](const nsIFrame* aFrame) {
8266 return aFrame->GetPositionIgnoringScrolling();
8267 });
8268}
8269
8270nsPoint nsIFrame::GetOffsetToIgnoringScrollingAndSticky(
8271 const nsIFrame* aOther) const {
8272 return OffsetCalculator(this, aOther, [](const nsIFrame* aFrame) {
8273 return aFrame->GetPositionIgnoringScrollingAndSticky();
8274 });
8275}
8276
8277nsPoint nsIFrame::GetScrollOffsetTo(const nsIFrame* aOther) const {
8278 return OffsetCalculator(this, aOther, [](const nsIFrame* aFrame) {
8279 return aFrame->GetPositionIgnoringScrollingAndSticky() -
8280 aFrame->GetPosition();
8281 });
8282}
8283
8284nsPoint nsIFrame::GetOffsetToCrossDoc(const nsIFrame* aOther) const {
8285 return GetOffsetToCrossDoc(aOther, PresContext()->AppUnitsPerDevPixel());
8286}
8287
8288nsPoint nsIFrame::GetOffsetToCrossDoc(const nsIFrame* aOther,
8289 const int32_t aAPD) const {
8290 MOZ_ASSERT(aOther, "Must have frame for destination coordinate system!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aOther)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aOther))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aOther" " (" "Must have frame for destination coordinate system!"
")", "./../../../layout/generic/nsIFrame.cpp", 8290); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aOther" ") (" "Must have frame for destination coordinate system!"
")"); do { MOZ_CrashSequence(__null, 8290); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8291 MOZ_DIAGNOSTIC_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->GetRootPresContext() == aOther->
PresContext()->GetRootPresContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PresContext()->GetRootPresContext
() == aOther->PresContext()->GetRootPresContext()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
" (" "trying to get the offset between frames in different document "
"hierarchies?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8295); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { MOZ_CrashSequence(__null, 8295); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
8292 PresContext()->GetRootPresContext() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->GetRootPresContext() == aOther->
PresContext()->GetRootPresContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PresContext()->GetRootPresContext
() == aOther->PresContext()->GetRootPresContext()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
" (" "trying to get the offset between frames in different document "
"hierarchies?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8295); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { MOZ_CrashSequence(__null, 8295); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
8293 aOther->PresContext()->GetRootPresContext(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->GetRootPresContext() == aOther->
PresContext()->GetRootPresContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PresContext()->GetRootPresContext
() == aOther->PresContext()->GetRootPresContext()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
" (" "trying to get the offset between frames in different document "
"hierarchies?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8295); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { MOZ_CrashSequence(__null, 8295); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
8294 "trying to get the offset between frames in different document "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->GetRootPresContext() == aOther->
PresContext()->GetRootPresContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PresContext()->GetRootPresContext
() == aOther->PresContext()->GetRootPresContext()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
" (" "trying to get the offset between frames in different document "
"hierarchies?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8295); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { MOZ_CrashSequence(__null, 8295); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
8295 "hierarchies?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PresContext()->GetRootPresContext() == aOther->
PresContext()->GetRootPresContext())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PresContext()->GetRootPresContext
() == aOther->PresContext()->GetRootPresContext()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
" (" "trying to get the offset between frames in different document "
"hierarchies?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8295); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { MOZ_CrashSequence(__null, 8295); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
8296
8297 const nsIFrame* root = nullptr;
8298 // offset will hold the final offset
8299 // docOffset holds the currently accumulated offset at the current APD, it
8300 // will be converted and added to offset when the current APD changes.
8301 nsPoint offset(0, 0), docOffset(0, 0);
8302 const nsIFrame* f = this;
8303 int32_t currAPD = PresContext()->AppUnitsPerDevPixel();
8304 while (f && f != aOther) {
8305 docOffset += f->GetPosition();
8306 nsIFrame* parent = f->GetParent();
8307 if (parent) {
8308 f = parent;
8309 } else {
8310 nsPoint newOffset(0, 0);
8311 root = f;
8312 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f, &newOffset);
8313 int32_t newAPD = f ? f->PresContext()->AppUnitsPerDevPixel() : 0;
8314 if (!f || newAPD != currAPD) {
8315 // Convert docOffset to the right APD and add it to offset.
8316 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
8317 docOffset.x = docOffset.y = 0;
8318 }
8319 currAPD = newAPD;
8320 docOffset += newOffset;
8321 }
8322 }
8323 if (f == aOther) {
8324 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
8325 } else {
8326 // Looks like aOther wasn't an ancestor of |this|. So now we have
8327 // the root-document-relative position of |this| in |offset|. Subtract the
8328 // root-document-relative position of |aOther| from |offset|.
8329 // This call won't try to recurse again because root is an ancestor of
8330 // aOther.
8331 nsPoint negOffset = aOther->GetOffsetToCrossDoc(root, aAPD);
8332 offset -= negOffset;
8333 }
8334
8335 return offset;
8336}
8337
8338CSSIntRect nsIFrame::GetScreenRect() const {
8339 return CSSIntRect::FromAppUnitsToNearest(GetScreenRectInAppUnits());
8340}
8341
8342nsRect nsIFrame::GetScreenRectInAppUnits() const {
8343 nsPresContext* presContext = PresContext();
8344 nsIFrame* rootFrame = presContext->PresShell()->GetRootFrame();
8345 nsPoint rootScreenPos(0, 0);
8346 nsPoint rootFrameOffsetInParent(0, 0);
8347 nsIFrame* rootFrameParent = nsLayoutUtils::GetCrossDocParentFrameInProcess(
8348 rootFrame, &rootFrameOffsetInParent);
8349 if (rootFrameParent) {
8350 nsRect parentScreenRectAppUnits =
8351 rootFrameParent->GetScreenRectInAppUnits();
8352 nsPresContext* parentPresContext = rootFrameParent->PresContext();
8353 double parentScale = double(presContext->AppUnitsPerDevPixel()) /
8354 parentPresContext->AppUnitsPerDevPixel();
8355 nsPoint rootPt =
8356 parentScreenRectAppUnits.TopLeft() + rootFrameOffsetInParent;
8357 rootScreenPos.x = NS_round(parentScale * rootPt.x);
8358 rootScreenPos.y = NS_round(parentScale * rootPt.y);
8359 } else if (nsCOMPtr<nsIWidget> rootWidget = presContext->GetRootWidget()) {
8360 LayoutDeviceIntPoint rootDevPx = rootWidget->WidgetToScreenOffset();
8361 rootScreenPos.x = presContext->DevPixelsToAppUnits(rootDevPx.x);
8362 rootScreenPos.y = presContext->DevPixelsToAppUnits(rootDevPx.y);
8363 }
8364
8365 return nsRect(rootScreenPos + GetOffsetTo(rootFrame), GetSize());
8366}
8367
8368nsIWidget* nsIFrame::GetNearestWidget() const {
8369 if (!HasAnyStateBits(NS_FRAME_IN_POPUP)) {
8370 return PresContext()->GetRootWidget();
8371 }
8372 nsPoint unused;
8373 return GetNearestWidget(unused);
8374}
8375
8376nsIWidget* nsIFrame::GetNearestWidget(nsPoint& aOffset) const {
8377 aOffset.MoveTo(0, 0);
8378 nsIFrame* frame = const_cast<nsIFrame*>(this);
8379 const auto targetAPD = PresContext()->AppUnitsPerDevPixel();
8380 auto curAPD = targetAPD;
8381 do {
8382 if (auto* widget = frame->GetOwnWidget()) {
8383 aOffset = aOffset.ScaleToOtherAppUnits(curAPD, targetAPD);
8384 return widget;
8385 }
8386 aOffset += frame->GetPosition();
8387 nsPoint crossDocOffset;
8388 frame =
8389 nsLayoutUtils::GetCrossDocParentFrameInProcess(frame, &crossDocOffset);
8390 if (!frame) {
8391 break;
8392 }
8393 auto newAPD = frame->PresContext()->AppUnitsPerDevPixel();
8394 aOffset = aOffset.ScaleToOtherAppUnits(curAPD, newAPD);
8395 aOffset += crossDocOffset;
8396 curAPD = newAPD;
8397 } while (true);
8398 aOffset = aOffset.ScaleToOtherAppUnits(curAPD, targetAPD);
8399 return PresContext()->GetRootWidget();
8400}
8401
8402Matrix4x4Flagged nsIFrame::GetTransformMatrix(
8403 ViewportType aViewportType, RelativeTo aStopAtAncestor,
8404 nsIFrame** aOutAncestor, TransformMatrixFlags aFlags) const {
8405 MOZ_ASSERT(aOutAncestor, "Need a place to put the ancestor!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aOutAncestor)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aOutAncestor))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("aOutAncestor" " ("
"Need a place to put the ancestor!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 8405); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aOutAncestor"
") (" "Need a place to put the ancestor!" ")"); do { MOZ_CrashSequence
(__null, 8405); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8406
8407 auto GetPositionMaybeIgnoringScrolling = [aFlags](const nsIFrame* aFrame) {
8408 return aFlags.contains(TransformMatrixFlag::IgnoreScrolling)
8409 ? aFrame->GetPositionIgnoringScrollingAndSticky()
8410 : aFrame->GetPosition();
8411 };
8412
8413 /* If we're transformed, we want to hand back the combination
8414 * transform/translate matrix that will apply our current transform, then
8415 * shift us to our parent.
8416 */
8417 const bool isTransformed = IsTransformed();
8418 const nsIFrame* zoomedContentRoot = nullptr;
8419 if (aStopAtAncestor.mViewportType == ViewportType::Visual) {
8420 zoomedContentRoot = ViewportUtils::IsZoomedContentRoot(this);
8421 if (zoomedContentRoot) {
8422 MOZ_ASSERT(aViewportType != ViewportType::Visual)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aViewportType != ViewportType::Visual)>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(aViewportType != ViewportType::Visual))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aViewportType != ViewportType::Visual"
, "./../../../layout/generic/nsIFrame.cpp", 8422); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aViewportType != ViewportType::Visual" ")"
); do { MOZ_CrashSequence(__null, 8422); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8423 }
8424 }
8425
8426 if (isTransformed || zoomedContentRoot) {
8427 MOZ_ASSERT(GetParent())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetParent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(GetParent()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("GetParent()", "./../../../layout/generic/nsIFrame.cpp"
, 8427); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetParent()"
")"); do { MOZ_CrashSequence(__null, 8427); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8428 Matrix4x4Flagged result;
8429 int32_t scaleFactor = aFlags.contains(TransformMatrixFlag::InCSSUnits)
8430 ? AppUnitsPerCSSPixel()
8431 : PresContext()->AppUnitsPerDevPixel();
8432
8433 /* Compute the delta to the parent, which we need because we are converting
8434 * coordinates to our parent.
8435 */
8436 if (isTransformed) {
8437 // Note: this converts from Matrix4x4 to Matrix4x4Flagged.
8438 result = nsDisplayTransform::GetResultingTransformMatrix(
8439 this, nsPoint(), scaleFactor,
8440 nsDisplayTransform::INCLUDE_PERSPECTIVE);
8441 }
8442
8443 // The offset from a zoomed content root to its parent (e.g. from
8444 // a canvas frame to a scroll frame) is in layout coordinates, so
8445 // apply it before applying any layout-to-visual transform.
8446 *aOutAncestor = GetParent();
8447 nsPoint delta = GetPositionMaybeIgnoringScrolling(this);
8448 /* Combine the raw transform with a translation to our parent. */
8449 result.PostTranslate(NSAppUnitsToFloatPixels(delta.x, scaleFactor),
8450 NSAppUnitsToFloatPixels(delta.y, scaleFactor), 0.0f);
8451
8452 if (zoomedContentRoot) {
8453 Matrix4x4Flagged layoutToVisual;
8454 if (aFlags.contains(TransformMatrixFlag::InCSSUnits)) {
8455 layoutToVisual = ViewportUtils::GetVisualToLayoutTransform(
8456 zoomedContentRoot->GetContent())
8457 .Inverse()
8458 .ToUnknownMatrix();
8459 } else {
8460 layoutToVisual =
8461 ViewportUtils::GetVisualToLayoutTransform<LayoutDevicePixel>(
8462 zoomedContentRoot->GetContent())
8463 .Inverse()
8464 .ToUnknownMatrix();
8465 }
8466 result = result * layoutToVisual;
8467 }
8468
8469 return result;
8470 }
8471
8472 // We are not transformed, so the returned transform is just going to be a
8473 // translation up to whatever ancestor we decide to stop at.
8474
8475 nsPoint crossdocOffset;
8476 *aOutAncestor =
8477 nsLayoutUtils::GetCrossDocParentFrameInProcess(this, &crossdocOffset);
8478
8479 /* Otherwise, we're not transformed. In that case, we'll walk up the frame
8480 * tree until we either hit the root frame or something that may be
8481 * transformed. We'll then change coordinates into that frame, since we're
8482 * guaranteed that nothing in-between can be transformed. First, however,
8483 * we have to check to see if we have a parent. If not, we'll set the
8484 * outparam to null (indicating that there's nothing left) and will hand back
8485 * the identity matrix.
8486 */
8487 if (!*aOutAncestor) {
8488 return Matrix4x4Flagged();
8489 }
8490
8491 /* Keep iterating while the frame can't possibly be transformed. */
8492 const nsIFrame* current = this;
8493 auto shouldStopAt = [](const nsIFrame* aCurrent, RelativeTo& aStopAtAncestor,
8494 nsIFrame* aOutAncestor, TransformMatrixFlags aFlags) {
8495 return aOutAncestor->IsTransformed() ||
8496 ((aStopAtAncestor.mViewportType == ViewportType::Visual) &&
8497 ViewportUtils::IsZoomedContentRoot(aOutAncestor)) ||
8498 (aFlags.contains(
8499 TransformMatrixFlag::StopAtStackingContextAndDisplayPort) &&
8500 (aOutAncestor->IsStackingContext() ||
8501 DisplayPortUtils::FrameHasDisplayPort(aOutAncestor, aCurrent)));
8502 };
8503
8504 // We run the GetOffsetToCrossDoc code here as an optimization, instead of
8505 // walking the parent chain here and then asking GetOffsetToCrossDoc to walk
8506 // the same parent chain and compute the offset.
8507 const int32_t finalAPD = PresContext()->AppUnitsPerDevPixel();
8508 // offset accumulates the offset at finalAPD.
8509 nsPoint offset = GetPositionMaybeIgnoringScrolling(this);
8510
8511 int32_t currAPD = (*aOutAncestor)->PresContext()->AppUnitsPerDevPixel();
8512 // docOffset accumulates the current offset at currAPD, and then flushes to
8513 // offset at finalAPD when the APD changes or we finish.
8514 nsPoint docOffset = crossdocOffset;
8515 MOZ_ASSERT(crossdocOffset == nsPoint(0, 0) || !GetParent())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(crossdocOffset == nsPoint(0, 0) || !GetParent())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(crossdocOffset == nsPoint(0, 0) || !GetParent()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("crossdocOffset == nsPoint(0, 0) || !GetParent()"
, "./../../../layout/generic/nsIFrame.cpp", 8515); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "crossdocOffset == nsPoint(0, 0) || !GetParent()"
")"); do { MOZ_CrashSequence(__null, 8515); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8516
8517 while (*aOutAncestor != aStopAtAncestor.mFrame &&
8518 !shouldStopAt(current, aStopAtAncestor, *aOutAncestor, aFlags)) {
8519 docOffset += GetPositionMaybeIgnoringScrolling(*aOutAncestor);
8520
8521 nsIFrame* parent = (*aOutAncestor)->GetParent();
8522 if (!parent) {
8523 crossdocOffset.x = crossdocOffset.y = 0;
8524 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(*aOutAncestor,
8525 &crossdocOffset);
8526
8527 int32_t newAPD =
8528 parent ? parent->PresContext()->AppUnitsPerDevPixel() : currAPD;
8529 if (!parent || newAPD != currAPD) {
8530 // Convert docOffset to finalAPD and add it to offset.
8531 offset += docOffset.ScaleToOtherAppUnits(currAPD, finalAPD);
8532 docOffset.x = docOffset.y = 0;
8533 }
8534 currAPD = newAPD;
8535 docOffset += crossdocOffset;
8536
8537 if (!parent) {
8538 break;
8539 }
8540 }
8541
8542 current = *aOutAncestor;
8543 *aOutAncestor = parent;
8544 }
8545 offset += docOffset.ScaleToOtherAppUnits(currAPD, finalAPD);
8546
8547 NS_ASSERTION(*aOutAncestor, "Somehow ended up with a null ancestor...?")do { if (!(*aOutAncestor)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Somehow ended up with a null ancestor...?", "*aOutAncestor"
, "./../../../layout/generic/nsIFrame.cpp", 8547); MOZ_PretendNoReturn
(); } } while (0)
;
8548
8549 int32_t scaleFactor = aFlags.contains(TransformMatrixFlag::InCSSUnits)
8550 ? AppUnitsPerCSSPixel()
8551 : PresContext()->AppUnitsPerDevPixel();
8552 return Matrix4x4Flagged::Translation2d(
8553 NSAppUnitsToFloatPixels(offset.x, scaleFactor),
8554 NSAppUnitsToFloatPixels(offset.y, scaleFactor));
8555}
8556
8557static void InvalidateRenderingObservers(nsIFrame* aDisplayRoot,
8558 nsIFrame* aFrame,
8559 bool aFrameChanged = true) {
8560 MOZ_ASSERT(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
, "./../../../layout/generic/nsIFrame.cpp", 8560); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
")"); do { MOZ_CrashSequence(__null, 8560); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8561 SVGObserverUtils::InvalidateDirectRenderingObservers(aFrame);
8562 nsIFrame* parent = aFrame;
8563 while (parent != aDisplayRoot &&
8564 (parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(parent)) &&
8565 !parent->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
8566 SVGObserverUtils::InvalidateDirectRenderingObservers(parent);
8567 }
8568
8569 if (!aFrameChanged) {
8570 return;
8571 }
8572
8573 aFrame->MarkNeedsDisplayItemRebuild();
8574}
8575
8576static void SchedulePaintInternal(
8577 nsIFrame* aDisplayRoot, nsIFrame* aFrame,
8578 nsIFrame::PaintType aType = nsIFrame::PAINT_DEFAULT) {
8579 MOZ_ASSERT(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
, "./../../../layout/generic/nsIFrame.cpp", 8579); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
")"); do { MOZ_CrashSequence(__null, 8579); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8580 nsPresContext* pres = aDisplayRoot->PresContext()->GetRootPresContext();
8581
8582 // No need to schedule a paint for an external document since they aren't
8583 // painted directly.
8584 if (!pres || (pres->Document() && pres->Document()->IsResourceDoc())) {
8585 return;
8586 }
8587 if (!pres->GetContainerWeak()) {
8588 NS_WARNING("Shouldn't call SchedulePaint in a detached pres context")NS_DebugBreak(NS_DEBUG_WARNING, "Shouldn't call SchedulePaint in a detached pres context"
, nullptr, "./../../../layout/generic/nsIFrame.cpp", 8588)
;
8589 return;
8590 }
8591
8592 pres->PresShell()->SchedulePaint();
8593
8594 if (aType == nsIFrame::PAINT_DEFAULT) {
8595 aDisplayRoot->AddStateBits(NS_FRAME_UPDATE_LAYER_TREE);
8596 }
8597}
8598
8599static void InvalidateFrameInternal(nsIFrame* aFrame, bool aHasDisplayItem,
8600 bool aRebuildDisplayItems) {
8601 if (aHasDisplayItem) {
8602 aFrame->AddStateBits(NS_FRAME_NEEDS_PAINT);
8603 }
8604
8605 if (aRebuildDisplayItems) {
8606 aFrame->MarkNeedsDisplayItemRebuild();
8607 }
8608 SVGObserverUtils::InvalidateDirectRenderingObservers(aFrame);
8609 bool needsSchedulePaint = false;
8610 if (nsLayoutUtils::IsPopup(aFrame)) {
8611 needsSchedulePaint = true;
8612 } else {
8613 nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(aFrame);
8614 while (parent &&
8615 !parent->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
8616 if (aHasDisplayItem && !parent->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
8617 parent->AddStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT);
8618 }
8619 SVGObserverUtils::InvalidateDirectRenderingObservers(parent);
8620
8621 // If we're inside a popup, then we need to make sure that we
8622 // call schedule paint so that the NS_FRAME_UPDATE_LAYER_TREE
8623 // flag gets added to the popup display root frame.
8624 if (nsLayoutUtils::IsPopup(parent)) {
8625 needsSchedulePaint = true;
8626 break;
8627 }
8628 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(parent);
8629 }
8630 if (!parent) {
8631 needsSchedulePaint = true;
8632 }
8633 }
8634 if (!aHasDisplayItem) {
8635 return;
8636 }
8637 if (needsSchedulePaint) {
8638 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(aFrame);
8639 SchedulePaintInternal(displayRoot, aFrame);
8640 }
8641 if (aFrame->HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
8642 aFrame->RemoveProperty(nsIFrame::InvalidationRect());
8643 aFrame->RemoveStateBits(NS_FRAME_HAS_INVALID_RECT);
8644 }
8645}
8646
8647void nsIFrame::InvalidateFrameSubtree(bool aRebuildDisplayItems /* = true */) {
8648 InvalidateFrame(0, aRebuildDisplayItems);
8649
8650 if (HasAnyStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT)) {
8651 return;
8652 }
8653
8654 AddStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT);
8655
8656 for (const auto& childList : CrossDocChildLists()) {
8657 for (nsIFrame* child : childList.mList) {
8658 // Don't explicitly rebuild display items for our descendants,
8659 // since we should be marked and it implicitly includes all
8660 // descendants.
8661 child->InvalidateFrameSubtree(false);
8662 }
8663 }
8664}
8665
8666void nsIFrame::ClearInvalidationStateBits() {
8667 if (HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
8668 for (const auto& childList : CrossDocChildLists()) {
8669 for (nsIFrame* child : childList.mList) {
8670 child->ClearInvalidationStateBits();
8671 }
8672 }
8673 }
8674
8675 RemoveStateBits(NS_FRAME_NEEDS_PAINT | NS_FRAME_DESCENDANT_NEEDS_PAINT |
8676 NS_FRAME_ALL_DESCENDANTS_NEED_PAINT);
8677}
8678
8679bool HasRetainedDataFor(const nsIFrame* aFrame, uint32_t aDisplayItemKey) {
8680 if (RefPtr<WebRenderUserData> data =
8681 GetWebRenderUserData<WebRenderFallbackData>(aFrame,
8682 aDisplayItemKey)) {
8683 return true;
8684 }
8685
8686 return false;
8687}
8688
8689void nsIFrame::InvalidateFrame(uint32_t aDisplayItemKey,
8690 bool aRebuildDisplayItems /* = true */) {
8691 bool hasDisplayItem =
8692 !aDisplayItemKey || HasRetainedDataFor(this, aDisplayItemKey);
8693 InvalidateFrameInternal(this, hasDisplayItem, aRebuildDisplayItems);
8694}
8695
8696void nsIFrame::InvalidateFrameWithRect(const nsRect& aRect,
8697 uint32_t aDisplayItemKey,
8698 bool aRebuildDisplayItems /* = true */) {
8699 if (aRect.IsEmpty()) {
8700 return;
8701 }
8702 bool hasDisplayItem =
8703 !aDisplayItemKey || HasRetainedDataFor(this, aDisplayItemKey);
8704 bool alreadyInvalid = false;
8705 if (!HasAnyStateBits(NS_FRAME_NEEDS_PAINT)) {
8706 InvalidateFrameInternal(this, hasDisplayItem, aRebuildDisplayItems);
8707 } else {
8708 alreadyInvalid = true;
8709 }
8710
8711 if (!hasDisplayItem) {
8712 return;
8713 }
8714
8715 nsRect* rect;
8716 if (HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
8717 rect = GetProperty(InvalidationRect());
8718 MOZ_ASSERT(rect)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(rect)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(rect))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("rect", "./../../../layout/generic/nsIFrame.cpp"
, 8718); AnnotateMozCrashReason("MOZ_ASSERT" "(" "rect" ")");
do { MOZ_CrashSequence(__null, 8718); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8719 } else {
8720 if (alreadyInvalid) {
8721 return;
8722 }
8723 rect = new nsRect();
8724 AddProperty(InvalidationRect(), rect);
8725 AddStateBits(NS_FRAME_HAS_INVALID_RECT);
8726 }
8727
8728 *rect = rect->Union(aRect);
8729}
8730
8731bool nsIFrame::IsInvalid(nsRect& aRect) {
8732 if (!HasAnyStateBits(NS_FRAME_NEEDS_PAINT)) {
8733 return false;
8734 }
8735
8736 if (HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
8737 nsRect* rect = GetProperty(InvalidationRect());
8738 NS_ASSERTION(do { if (!(rect)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must have an invalid rect if NS_FRAME_HAS_INVALID_RECT is set!"
, "rect", "./../../../layout/generic/nsIFrame.cpp", 8739); MOZ_PretendNoReturn
(); } } while (0)
8739 rect, "Must have an invalid rect if NS_FRAME_HAS_INVALID_RECT is set!")do { if (!(rect)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must have an invalid rect if NS_FRAME_HAS_INVALID_RECT is set!"
, "rect", "./../../../layout/generic/nsIFrame.cpp", 8739); MOZ_PretendNoReturn
(); } } while (0)
;
8740 aRect = *rect;
8741 } else {
8742 aRect.SetEmpty();
8743 }
8744 return true;
8745}
8746
8747void nsIFrame::SchedulePaint(PaintType aType, bool aFrameChanged) {
8748 if (PresShell()->IsPaintingSuppressed()) {
8749 // We can't have any display items yet, and when we unsuppress we will
8750 // invalidate the root frame.
8751 return;
8752 }
8753 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
8754 InvalidateRenderingObservers(displayRoot, this, aFrameChanged);
8755 SchedulePaintInternal(displayRoot, this, aType);
8756}
8757
8758void nsIFrame::SchedulePaintWithoutInvalidatingObservers(PaintType aType) {
8759 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
8760 SchedulePaintInternal(displayRoot, this, aType);
8761}
8762
8763void nsIFrame::InvalidateLayer(DisplayItemType aDisplayItemKey,
8764 const nsIntRect* aDamageRect,
8765 const nsRect* aFrameDamageRect,
8766 uint32_t aFlags /* = 0 */) {
8767 NS_ASSERTION(aDisplayItemKey > DisplayItemType::TYPE_ZERO, "Need a key")do { if (!(aDisplayItemKey > DisplayItemType::TYPE_ZERO)) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Need a key", "aDisplayItemKey > DisplayItemType::TYPE_ZERO"
, "./../../../layout/generic/nsIFrame.cpp", 8767); MOZ_PretendNoReturn
(); } } while (0)
;
8768
8769 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
8770 InvalidateRenderingObservers(displayRoot, this, false);
8771
8772 // Check if frame supports WebRender's async update
8773 if ((aFlags & UPDATE_IS_ASYNC) &&
8774 WebRenderUserData::SupportsAsyncUpdate(this)) {
8775 // WebRender does not use layer, then return nullptr.
8776 return;
8777 }
8778
8779 if (aFrameDamageRect && aFrameDamageRect->IsEmpty()) {
8780 return;
8781 }
8782
8783 // In the bug 930056, dialer app startup but not shown on the
8784 // screen because sometimes we don't have any retainned data
8785 // for remote type displayitem and thus Repaint event is not
8786 // triggered. So, always invalidate in this case.
8787 DisplayItemType displayItemKey = aDisplayItemKey;
8788 if (aDisplayItemKey == DisplayItemType::TYPE_REMOTE) {
8789 displayItemKey = DisplayItemType::TYPE_ZERO;
8790 }
8791
8792 if (aFrameDamageRect) {
8793 InvalidateFrameWithRect(*aFrameDamageRect,
8794 static_cast<uint32_t>(displayItemKey));
8795 } else {
8796 InvalidateFrame(static_cast<uint32_t>(displayItemKey));
8797 }
8798}
8799
8800static nsRect ComputeEffectsRect(nsIFrame* aFrame, const nsRect& aOverflowRect,
8801 const nsSize& aNewSize) {
8802 nsRect r = aOverflowRect;
8803
8804 if (aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
8805 // For SVG frames, we only need to account for filters.
8806 // TODO: We could also take account of clipPath and mask to reduce the
8807 // ink overflow, but that's not essential.
8808 if (aFrame->StyleEffects()->HasFilters()) {
8809 aFrame->SetOrUpdateDeletableProperty(nsIFrame::PreEffectsBBoxProperty(),
8810 r);
8811 r = SVGUtils::GetPostFilterInkOverflowRect(aFrame, aOverflowRect);
8812 }
8813 return r;
8814 }
8815
8816 // box-shadow
8817 r.UnionRect(r, nsLayoutUtils::GetBoxShadowRectForFrame(aFrame, aNewSize));
8818
8819 // border-image-outset.
8820 // We need to include border-image-outset because it can cause the
8821 // border image to be drawn beyond the border box.
8822
8823 // (1) It's important we not check whether there's a border-image
8824 // since the style hint for a change in border image doesn't cause
8825 // reflow, and that's probably more important than optimizing the
8826 // overflow areas for the silly case of border-image-outset without
8827 // border-image
8828 // (2) It's important that we not check whether the border-image
8829 // is actually loaded, since that would require us to reflow when
8830 // the image loads.
8831 const nsStyleBorder* styleBorder = aFrame->StyleBorder();
8832 nsMargin outsetMargin = styleBorder->GetImageOutset();
8833
8834 if (outsetMargin != nsMargin(0, 0, 0, 0)) {
8835 nsRect outsetRect(nsPoint(0, 0), aNewSize);
8836 outsetRect.Inflate(outsetMargin);
8837 r.UnionRect(r, outsetRect);
8838 }
8839
8840 // Note that we don't remove the outlineInnerRect if a frame loses outline
8841 // style. That would require an extra property lookup for every frame,
8842 // or a new frame state bit to track whether a property had been stored,
8843 // or something like that. It's not worth doing that here. At most it's
8844 // only one heap-allocated rect per frame and it will be cleaned up when
8845 // the frame dies.
8846
8847 if (SVGIntegrationUtils::UsingOverflowAffectingEffects(aFrame)) {
8848 aFrame->SetOrUpdateDeletableProperty(nsIFrame::PreEffectsBBoxProperty(), r);
8849 r = SVGIntegrationUtils::ComputePostEffectsInkOverflowRect(aFrame, r);
8850 }
8851
8852 return r;
8853}
8854
8855void nsIFrame::SetPosition(const nsPoint& aPt) {
8856 if (mRect.TopLeft() == aPt) {
8857 return;
8858 }
8859 mRect.MoveTo(aPt);
8860 MarkNeedsDisplayItemRebuild();
8861}
8862
8863void nsIFrame::MovePositionBy(const nsPoint& aTranslation) {
8864 nsPoint position = GetNormalPosition() + aTranslation;
8865
8866 const nsMargin* computedOffsets = nullptr;
8867 if (IsRelativelyOrStickyPositioned()) {
8868 computedOffsets = GetProperty(nsIFrame::ComputedOffsetProperty());
8869 }
8870 ReflowInput::ApplyRelativePositioning(
8871 this, computedOffsets ? *computedOffsets : nsMargin(), &position);
8872 SetPosition(position);
8873}
8874
8875nsRect nsIFrame::GetNormalRect() const {
8876 return nsRect(GetNormalPosition(), GetSize());
8877}
8878
8879nsRect nsIFrame::GetBoundingClientRect() {
8880 return nsLayoutUtils::GetAllInFlowRectsUnion(
8881 this, nsLayoutUtils::GetContainingBlockForClientRect(this),
8882 nsLayoutUtils::GetAllInFlowRectsFlag::AccountForTransforms);
8883}
8884
8885nsPoint nsIFrame::GetPositionIgnoringScrolling() const {
8886 return GetParent() ? GetParent()->GetPositionOfChildIgnoringScrolling(this)
8887 : GetPosition();
8888}
8889
8890nsPoint nsIFrame::GetPositionIgnoringScrollingAndSticky() const {
8891 if (IsStickyPositioned()) {
8892 if (const auto* ssc = StickyScrollContainer::GetForFrame(this)) {
8893 return GetNormalPosition() +
8894 ssc->ComputeTranslationIgnoringScrolling(this);
8895 }
8896 }
8897 return GetPositionIgnoringScrolling();
8898}
8899
8900nsRect nsIFrame::GetOverflowRect(OverflowType aType) const {
8901 // Note that in some cases the overflow area might not have been
8902 // updated (yet) to reflect any outline set on the frame or the area
8903 // of child frames. That's OK because any reflow that updates these
8904 // areas will invalidate the appropriate area, so any (mis)uses of
8905 // this method will be fixed up.
8906
8907 if (mOverflow.mType == OverflowStorageType::Large) {
8908 // there is an overflow rect, and it's not stored as deltas but as
8909 // a separately-allocated rect
8910 return GetOverflowAreasProperty()->Overflow(aType);
8911 }
8912
8913 if (aType == OverflowType::Ink &&
8914 mOverflow.mType != OverflowStorageType::None) {
8915 return InkOverflowFromDeltas();
8916 }
8917
8918 return GetRectRelativeToSelf();
8919}
8920
8921OverflowAreas nsIFrame::GetOverflowAreas() const {
8922 if (mOverflow.mType == OverflowStorageType::Large) {
8923 // there is an overflow rect, and it's not stored as deltas but as
8924 // a separately-allocated rect
8925 return *GetOverflowAreasProperty();
8926 }
8927
8928 return OverflowAreas(InkOverflowFromDeltas(),
8929 nsRect(nsPoint(0, 0), GetSize()));
8930}
8931
8932OverflowAreas nsIFrame::GetOverflowAreasRelativeToSelf() const {
8933 if (IsTransformed()) {
8934 if (OverflowAreas* preTransformOverflows =
8935 GetProperty(PreTransformOverflowAreasProperty())) {
8936 return *preTransformOverflows;
8937 }
8938 }
8939 return GetOverflowAreas();
8940}
8941
8942OverflowAreas nsIFrame::GetOverflowAreasRelativeToParent() const {
8943 return GetOverflowAreas() + GetPosition();
8944}
8945
8946OverflowAreas nsIFrame::GetActualAndNormalOverflowAreasRelativeToParent()
8947 const {
8948 if (MOZ_UNLIKELY(IsAbsolutelyPositioned())(__builtin_expect(!!(IsAbsolutelyPositioned()), 0))) {
8949 const auto* referenceData = GetProperty(AnchorPosReferences());
8950 if (!referenceData || !referenceData->mRememberedScrollOffset ||
8951 referenceData->mDefaultScrollShift == nsPoint()) {
8952 return GetOverflowAreasRelativeToParent();
8953 }
8954 // Including the default scroll shift in the scrollable overflow would
8955 // change the scroll range that produced it. So, like sticky positioned
8956 // frames below, use the position without the default scroll shift for both
8957 // overflow areas, and add the current position only to the ink overflow,
8958 // which is where we paint.
8959 //
8960 // Per spec, "after layout has been performed for abspos, it is additionally
8961 // shifted by the default scroll shift, as if affected by a transform". We
8962 // store the shifts the other way around. UpdateScrollShift() moves the
8963 // frame by subtracting the scroll shift from the frame's current position,
8964 // and stores it back, so GetPosition() is the final position with the
8965 // default scroll shift applied. To get the unshifted position, we undo the
8966 // default scroll shift by adding it back.
8967 // https://drafts.csswg.org/css-anchor-position-1/#default-scroll-shift
8968 const nsPoint unshiftedPosition =
8969 GetPosition() + referenceData->mDefaultScrollShift;
8970 const OverflowAreas overflows = GetOverflowAreas();
8971 OverflowAreas result(overflows.InkOverflow() + GetPosition(), nsRect());
8972 result.UnionWith(overflows + unshiftedPosition);
8973 return result;
8974 }
8975
8976 if (MOZ_LIKELY(!IsRelativelyOrStickyPositioned())(__builtin_expect(!!(!IsRelativelyOrStickyPositioned()), 1))) {
8977 return GetOverflowAreasRelativeToParent();
8978 }
8979
8980 const OverflowAreas overflows = GetOverflowAreas();
8981 OverflowAreas actualAndNormalOverflows = overflows + GetNormalPosition();
8982 if (IsRelativelyPositioned()) {
8983 actualAndNormalOverflows.UnionWith(overflows + GetPosition());
8984 } else {
8985 // For sticky positioned elements, we only use the normal position for the
8986 // scrollable overflow. This avoids circular dependencies between sticky
8987 // positioned elements and their scroll container. (The scroll position and
8988 // the scroll container's size impact the sticky position, so we don't want
8989 // the sticky position to impact them.)
8990 MOZ_ASSERT(IsStickyPositioned())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsStickyPositioned())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsStickyPositioned()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("IsStickyPositioned()"
, "./../../../layout/generic/nsIFrame.cpp", 8990); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "IsStickyPositioned()" ")"); do { MOZ_CrashSequence
(__null, 8990); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
8991 actualAndNormalOverflows.UnionWith(
8992 OverflowAreas(overflows.InkOverflow() + GetPosition(), nsRect()));
8993 }
8994 return actualAndNormalOverflows;
8995}
8996
8997nsRect nsIFrame::ScrollableOverflowRectRelativeToParent() const {
8998 return ScrollableOverflowRect() + GetPosition();
8999}
9000
9001nsRect nsIFrame::InkOverflowRectRelativeToParent() const {
9002 return InkOverflowRect() + GetPosition();
9003}
9004
9005nsRect nsIFrame::ScrollableOverflowRectRelativeToSelf() const {
9006 if (IsTransformed()) {
9007 if (OverflowAreas* preTransformOverflows =
9008 GetProperty(PreTransformOverflowAreasProperty())) {
9009 return preTransformOverflows->ScrollableOverflow();
9010 }
9011 }
9012 return ScrollableOverflowRect();
9013}
9014
9015nsRect nsIFrame::InkOverflowRectRelativeToSelf() const {
9016 if (IsTransformed()) {
9017 if (OverflowAreas* preTransformOverflows =
9018 GetProperty(PreTransformOverflowAreasProperty())) {
9019 return preTransformOverflows->InkOverflow();
9020 }
9021 }
9022 return InkOverflowRect();
9023}
9024
9025nsRect nsIFrame::PreEffectsInkOverflowRect() const {
9026 nsRect* r = GetProperty(nsIFrame::PreEffectsBBoxProperty());
9027 return r ? *r : InkOverflowRectRelativeToSelf();
9028}
9029
9030bool nsIFrame::UpdateOverflow() {
9031 MOZ_ASSERT(FrameMaintainsOverflow(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(FrameMaintainsOverflow())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(FrameMaintainsOverflow()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("FrameMaintainsOverflow()"
" (" "Non-display SVG do not maintain ink overflow rects" ")"
, "./../../../layout/generic/nsIFrame.cpp", 9032); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "FrameMaintainsOverflow()" ") (" "Non-display SVG do not maintain ink overflow rects"
")"); do { MOZ_CrashSequence(__null, 9032); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
9032 "Non-display SVG do not maintain ink overflow rects")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(FrameMaintainsOverflow())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(FrameMaintainsOverflow()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("FrameMaintainsOverflow()"
" (" "Non-display SVG do not maintain ink overflow rects" ")"
, "./../../../layout/generic/nsIFrame.cpp", 9032); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "FrameMaintainsOverflow()" ") (" "Non-display SVG do not maintain ink overflow rects"
")"); do { MOZ_CrashSequence(__null, 9032); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9033
9034 nsRect rect(nsPoint(0, 0), GetSize());
9035 OverflowAreas overflowAreas(rect, rect);
9036
9037 if (!ComputeCustomOverflow(overflowAreas)) {
9038 // If updating overflow wasn't supported by this frame, then it should
9039 // have scheduled any necessary reflows. We can return false to say nothing
9040 // changed, and wait for reflow to correct it.
9041 return false;
9042 }
9043
9044 UnionChildOverflow(overflowAreas);
9045
9046 if (FinishAndStoreOverflow(overflowAreas, GetSize())) {
9047 return true;
9048 }
9049
9050 // Frames that combine their 3d transform with their ancestors
9051 // only compute a pre-transform overflow rect, and then contribute
9052 // to the normal overflow rect of the preserve-3d root. Always return
9053 // true here so that we propagate changes up to the root for final
9054 // calculation.
9055 return Combines3DTransformWithAncestors();
9056}
9057
9058/* virtual */
9059bool nsIFrame::ComputeCustomOverflow(OverflowAreas& aOverflowAreas) {
9060 return true;
9061}
9062
9063bool nsIFrame::DoesClipChildrenInBothAxes() const {
9064 if (IsScrollContainerOrSubclass()) {
9065 return true;
9066 }
9067 const nsStyleDisplay* display = StyleDisplay();
9068 if (display->IsContainPaint() && SupportsContainLayoutAndPaint()) {
9069 return true;
9070 }
9071 return display->mOverflowX == StyleOverflow::Clip &&
9072 display->mOverflowY == StyleOverflow::Clip;
9073}
9074
9075/* virtual */
9076void nsIFrame::UnionChildOverflow(OverflowAreas& aOverflowAreas,
9077 bool aAsIfScrolled) {
9078 if (aAsIfScrolled || !DoesClipChildrenInBothAxes()) {
9079 nsLayoutUtils::UnionChildOverflow(this, aOverflowAreas);
9080 }
9081}
9082
9083// Return true if this form control element's preferred size property (but not
9084// percentage max size property) contains a percentage value that should be
9085// resolved against zero when calculating its min-content contribution in the
9086// corresponding axis.
9087//
9088// For proper replaced elements, the percentage value in both their max size
9089// property or preferred size property should be resolved against zero. This is
9090// handled in IsPercentageResolvedAgainstZero().
9091inline static bool FormControlShrinksForPercentSize(const nsIFrame* aFrame) {
9092 if (!aFrame->IsReplaced()) {
9093 // Quick test to reject most frames.
9094 return false;
9095 }
9096
9097 switch (aFrame->Type()) {
9098 case LayoutFrameType::Progress:
9099 case LayoutFrameType::Range:
9100 case LayoutFrameType::TextInput:
9101 case LayoutFrameType::ColorControl:
9102 case LayoutFrameType::ComboboxControl:
9103 case LayoutFrameType::ListControl:
9104 case LayoutFrameType::CheckboxRadio:
9105 case LayoutFrameType::FileControl:
9106 case LayoutFrameType::ImageControl:
9107 return true;
9108 default:
9109 // True buttons (<button>, backed by block/grid/flex frame) and most
9110 // button-flavored <inputs> (those backed by InputButtonControlFrame)
9111 // don't have this shrinking behavior. But color-inputs and comboboxes do;
9112 // and both of those derive from ButtonControlFrame. So: we can't easily
9113 // use do_QueryFrame to differentiate the buttons-that-do vs. the
9114 // buttons-that-don't. So we explicitly list the buttons-that-do by
9115 // LayoutFrameType above, and the others fall into this catch-all.
9116 return false;
9117 }
9118}
9119
9120bool nsIFrame::IsPercentageResolvedAgainstZero(
9121 const StyleSize& aStyleSize, const StyleMaxSize& aStyleMaxSize) const {
9122 const bool sizeHasPercent = aStyleSize.HasPercent();
9123 return ((sizeHasPercent || aStyleMaxSize.HasPercent()) &&
9124 HasReplacedSizing()) ||
9125 (sizeHasPercent && FormControlShrinksForPercentSize(this));
9126}
9127
9128// Summary of the Cyclic-Percentage Intrinsic Size Contribution Rules:
9129//
9130// Element Type | Replaced | Non-replaced
9131// Contribution Type | min-content max-content | min-content max-content
9132// ---------------------------------------------------------------------------
9133// min size | zero zero | zero zero
9134// max & preferred size | zero initial | initial initial
9135//
9136// https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution
9137bool nsIFrame::IsPercentageResolvedAgainstZero(const LengthPercentage& aSize,
9138 SizeProperty aProperty) const {
9139 // Early return to avoid calling the virtual function, IsFrameOfType().
9140 if (aProperty == SizeProperty::MinSize) {
9141 return true;
9142 }
9143
9144 const bool hasPercentOnReplaced = aSize.HasPercent() && HasReplacedSizing();
9145 if (aProperty == SizeProperty::MaxSize) {
9146 return hasPercentOnReplaced;
9147 }
9148
9149 MOZ_ASSERT(aProperty == SizeProperty::Size)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aProperty == SizeProperty::Size)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aProperty == SizeProperty::Size
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"aProperty == SizeProperty::Size", "./../../../layout/generic/nsIFrame.cpp"
, 9149); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aProperty == SizeProperty::Size"
")"); do { MOZ_CrashSequence(__null, 9149); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9150 return hasPercentOnReplaced ||
9151 (aSize.HasPercent() && FormControlShrinksForPercentSize(this));
9152}
9153
9154bool nsIFrame::IsBlockWrapper() const {
9155 auto pseudoType = Style()->GetPseudoType();
9156 return pseudoType == PseudoStyleType::MozBlockInsideInlineWrapper ||
9157 pseudoType == PseudoStyleType::MozCellContent ||
9158 pseudoType == PseudoStyleType::MozColumnSpanWrapper;
9159}
9160
9161bool nsIFrame::IsBlockFrameOrSubclass() const {
9162 const nsBlockFrame* thisAsBlock = do_QueryFrame(this);
9163 return !!thisAsBlock;
9164}
9165
9166bool nsIFrame::IsInlineFrameOrSubclass() const {
9167 const nsInlineFrame* asInline = do_QueryFrame(this);
9168 return !!asInline;
9169}
9170
9171bool nsIFrame::IsImageFrameOrSubclass() const {
9172 const nsImageFrame* asImage = do_QueryFrame(this);
9173 return !!asImage;
9174}
9175
9176// Unlike its neighbours this must not use do_QueryFrame(), because
9177// IMPL_FAST_QUERYFRAME routes do_QueryFrame<ScrollContainerFrame> through here.
9178bool nsIFrame::IsScrollContainerOrSubclass() const {
9179 const bool result =
9180 IsScrollContainerFrame() || IsListControlFrame() || IsTextInputFrame();
9181 MOZ_ASSERT(result == !!QueryFrame(ScrollContainerFrame::kFrameIID))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(result == !!QueryFrame(ScrollContainerFrame::kFrameIID
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(result == !!QueryFrame(ScrollContainerFrame::kFrameIID
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("result == !!QueryFrame(ScrollContainerFrame::kFrameIID)", "./../../../layout/generic/nsIFrame.cpp"
, 9181); AnnotateMozCrashReason("MOZ_ASSERT" "(" "result == !!QueryFrame(ScrollContainerFrame::kFrameIID)"
")"); do { MOZ_CrashSequence(__null, 9181); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9182 return result;
9183}
9184
9185bool nsIFrame::IsSubgrid() const {
9186 return IsGridContainerFrame() &&
9187 static_cast<const nsGridContainerFrame*>(this)->IsSubgrid();
9188}
9189
9190static nsIFrame* GetNearestBlockContainer(nsIFrame* frame) {
9191 while (!frame->IsBlockContainer()) {
9192 frame = frame->GetParent();
9193 NS_ASSERTION(do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "How come we got to the root frame without seeing a containing block?"
, "frame", "./../../../layout/generic/nsIFrame.cpp", 9195); MOZ_PretendNoReturn
(); } } while (0)
9194 frame,do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "How come we got to the root frame without seeing a containing block?"
, "frame", "./../../../layout/generic/nsIFrame.cpp", 9195); MOZ_PretendNoReturn
(); } } while (0)
9195 "How come we got to the root frame without seeing a containing block?")do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "How come we got to the root frame without seeing a containing block?"
, "frame", "./../../../layout/generic/nsIFrame.cpp", 9195); MOZ_PretendNoReturn
(); } } while (0)
;
9196 }
9197 return frame;
9198}
9199
9200bool nsIFrame::IsBlockContainer() const {
9201 // The block wrappers we use to wrap blocks inside inlines aren't
9202 // described in the CSS spec. We need to make them not be containing
9203 // blocks.
9204 // Since the parent of such a block is either a normal block or
9205 // another such pseudo, this shouldn't cause anything bad to happen.
9206 // Also the anonymous blocks inside table cells are not containing blocks.
9207 //
9208 // If we ever start skipping table row groups from being containing blocks,
9209 // you need to remove the StickyScrollContainer hack referencing bug 1421660.
9210 // Table rows are not containing blocks either
9211 return !IsLineParticipant() && !IsBlockWrapper() && !IsTableRowFrame();
9212}
9213
9214nsIFrame* nsIFrame::GetContainingBlock(
9215 uint32_t aFlags, const nsStyleDisplay* aStyleDisplay) const {
9216 MOZ_ASSERT(aStyleDisplay == StyleDisplay())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStyleDisplay == StyleDisplay())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStyleDisplay == StyleDisplay
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aStyleDisplay == StyleDisplay()", "./../../../layout/generic/nsIFrame.cpp"
, 9216); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStyleDisplay == StyleDisplay()"
")"); do { MOZ_CrashSequence(__null, 9216); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9217
9218 // Keep this in sync with MightBeContainingBlockFor in ReflowInput.cpp.
9219
9220 if (!GetParent()) {
9221 return nullptr;
9222 }
9223 // MathML frames might have absolute positioning style, but they would
9224 // still be in-flow. So we have to check to make sure that the frame
9225 // is really out-of-flow too.
9226 nsIFrame* f;
9227 if (IsAbsolutelyPositioned(aStyleDisplay)) {
9228 f = GetParent(); // the parent is always the containing block
9229 } else {
9230 f = GetNearestBlockContainer(GetParent());
9231 }
9232
9233 if (aFlags & SKIP_SCROLLED_FRAME && f &&
9234 f->Style()->GetPseudoType() == PseudoStyleType::MozScrolledContent) {
9235 f = f->GetParent();
9236 }
9237 return f;
9238}
9239
9240#ifdef DEBUG_FRAME_DUMP1
9241
9242Maybe<uint32_t> nsIFrame::ContentIndexInContainer(const nsIFrame* aFrame) {
9243 if (nsIContent* content = aFrame->GetContent()) {
9244 return content->ComputeIndexInParentContent();
9245 }
9246 return Nothing();
9247}
9248
9249nsAutoCString nsIFrame::ListTag(bool aListOnlyDeterministic) const {
9250 nsAutoString tmp;
9251 GetFrameName(tmp);
9252
9253 nsAutoCString tag;
9254 tag += NS_ConvertUTF16toUTF8(tmp);
9255 ListPtr(tag, aListOnlyDeterministic, this, "@");
9256 return tag;
9257}
9258
9259std::string nsIFrame::ConvertToString(const LogicalRect& aRect,
9260 const WritingMode aWM, ListFlags aFlags) {
9261 if (aFlags.contains(ListFlag::DisplayInCSSPixels)) {
9262 // Abuse CSSRect to store all LogicalRect's dimensions in CSS pixels.
9263 return ToString(mozilla::CSSRect(CSSPixel::FromAppUnits(aRect.IStart(aWM)),
9264 CSSPixel::FromAppUnits(aRect.BStart(aWM)),
9265 CSSPixel::FromAppUnits(aRect.ISize(aWM)),
9266 CSSPixel::FromAppUnits(aRect.BSize(aWM))));
9267 }
9268 return ToString(aRect);
9269}
9270
9271std::string nsIFrame::ConvertToString(const LogicalSize& aSize,
9272 const WritingMode aWM, ListFlags aFlags) {
9273 if (aFlags.contains(ListFlag::DisplayInCSSPixels)) {
9274 // Abuse CSSSize to store all LogicalSize's dimensions in CSS pixels.
9275 return ToString(CSSSize(CSSPixel::FromAppUnits(aSize.ISize(aWM)),
9276 CSSPixel::FromAppUnits(aSize.BSize(aWM))));
9277 }
9278 return ToString(aSize);
9279}
9280
9281// Debugging
9282void nsIFrame::ListGeneric(nsACString& aTo, const char* aPrefix,
9283 ListFlags aFlags) const {
9284 aTo += aPrefix;
9285 const bool onlyDeterministic =
9286 aFlags.contains(ListFlag::OnlyListDeterministicInfo);
9287 aTo += ListTag(onlyDeterministic);
9288 if (!onlyDeterministic) {
9289 if (GetParent()) {
9290 aTo += nsPrintfCString(" parent=%p", static_cast<void*>(GetParent()));
9291 }
9292 if (GetNextSibling()) {
9293 aTo += nsPrintfCString(" next=%p", static_cast<void*>(GetNextSibling()));
9294 }
9295 }
9296 if (GetPrevContinuation()) {
9297 bool fluid = GetPrevInFlow() == GetPrevContinuation();
9298 aTo += nsPrintfCString(" prev-%s", fluid ? "in-flow" : "continuation");
9299 ListPtr(aTo, aFlags, GetPrevContinuation());
9300 }
9301 if (GetNextContinuation()) {
9302 bool fluid = GetNextInFlow() == GetNextContinuation();
9303 aTo += nsPrintfCString(" next-%s", fluid ? "in-flow" : "continuation");
9304 ListPtr(aTo, aFlags, GetNextContinuation());
9305 }
9306 if (const nsAtom* const autoPageValue =
9307 GetProperty(AutoPageValueProperty())) {
9308 aTo += " AutoPage=";
9309 aTo += nsAtomCString(autoPageValue);
9310 }
9311 if (const nsIFrame::PageValues* const pageValues =
9312 GetProperty(PageValuesProperty())) {
9313 aTo += " PageValues={";
9314 if (pageValues->mStartPageValue) {
9315 aTo += nsAtomCString(pageValues->mStartPageValue);
9316 } else {
9317 aTo += "<null>";
9318 }
9319 aTo += ", ";
9320 if (pageValues->mEndPageValue) {
9321 aTo += nsAtomCString(pageValues->mEndPageValue);
9322 } else {
9323 aTo += "<null>";
9324 }
9325 aTo += "}";
9326 }
9327 void* IBsibling = GetProperty(IBSplitSibling());
9328 if (IBsibling) {
9329 aTo += nsPrintfCString(" IBSplitSibling");
9330 ListPtr(aTo, aFlags, IBsibling);
9331 }
9332 void* IBprevsibling = GetProperty(IBSplitPrevSibling());
9333 if (IBprevsibling) {
9334 aTo += nsPrintfCString(" IBSplitPrevSibling");
9335 ListPtr(aTo, aFlags, IBprevsibling);
9336 }
9337 if (nsLayoutUtils::FontSizeInflationEnabled(PresContext())) {
9338 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT)) {
9339 aTo += nsPrintfCString(" FFR");
9340 if (nsFontInflationData* data =
9341 nsFontInflationData::FindFontInflationDataFor(this)) {
9342 aTo += nsPrintfCString(
9343 ",enabled=%s,UIS=%s", data->InflationEnabled() ? "yes" : "no",
9344 ConvertToString(data->UsableISize(), aFlags).c_str());
9345 }
9346 }
9347 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)) {
9348 aTo += nsPrintfCString(" FIC");
9349 }
9350 aTo += nsPrintfCString(" FI=%f", nsLayoutUtils::FontSizeInflationFor(this));
9351 }
9352 aTo += nsPrintfCString(" %s", ConvertToString(mRect, aFlags).c_str());
9353
9354 mozilla::WritingMode wm = GetWritingMode();
9355 if (wm.IsVertical() || wm.IsBidiRTL()) {
9356 aTo +=
9357 nsPrintfCString(" wm=%s logical-size=(%s)", ToString(wm).c_str(),
9358 ConvertToString(GetLogicalSize(), wm, aFlags).c_str());
9359 }
9360
9361 nsIFrame* parent = GetParent();
9362 if (parent) {
9363 WritingMode pWM = parent->GetWritingMode();
9364 if (pWM.IsVertical() || pWM.IsBidiRTL()) {
9365 nsSize containerSize = parent->mRect.Size();
9366 LogicalRect lr(pWM, mRect, containerSize);
9367 aTo += nsPrintfCString(" parent-wm=%s cs=(%s) logical-rect=%s",
9368 ToString(pWM).c_str(),
9369 ConvertToString(containerSize, aFlags).c_str(),
9370 ConvertToString(lr, pWM, aFlags).c_str());
9371 }
9372 }
9373 nsIFrame* f = const_cast<nsIFrame*>(this);
9374 if (f->HasOverflowAreas()) {
9375 nsRect io = f->InkOverflowRect();
9376 if (!io.IsEqualEdges(mRect)) {
9377 aTo += nsPrintfCString(" ink-overflow=%s",
9378 ConvertToString(io, aFlags).c_str());
9379 }
9380 nsRect so = f->ScrollableOverflowRect();
9381 if (!so.IsEqualEdges(mRect)) {
9382 aTo += nsPrintfCString(" scr-overflow=%s",
9383 ConvertToString(so, aFlags).c_str());
9384 }
9385 }
9386 if (OverflowAreas* preTransformOverflows =
9387 f->GetProperty(PreTransformOverflowAreasProperty())) {
9388 nsRect io = preTransformOverflows->InkOverflow();
9389 if (!io.IsEqualEdges(mRect) &&
9390 (!f->HasOverflowAreas() || !io.IsEqualEdges(f->InkOverflowRect()))) {
9391 aTo += nsPrintfCString(" pre-transform-ink-overflow=%s",
9392 ConvertToString(io, aFlags).c_str());
9393 }
9394 nsRect so = preTransformOverflows->ScrollableOverflow();
9395 if (!so.IsEqualEdges(mRect) &&
9396 (!f->HasOverflowAreas() ||
9397 !so.IsEqualEdges(f->ScrollableOverflowRect()))) {
9398 aTo += nsPrintfCString(" pre-transform-scr-overflow=%s",
9399 ConvertToString(so, aFlags).c_str());
9400 }
9401 }
9402 bool hasNormalPosition;
9403 nsPoint normalPosition = GetNormalPosition(&hasNormalPosition);
9404 if (hasNormalPosition) {
9405 aTo += nsPrintfCString(" normal-position=%s",
9406 ConvertToString(normalPosition, aFlags).c_str());
9407 }
9408 if (HasProperty(BidiDataProperty())) {
9409 FrameBidiData bidi = GetBidiData();
9410 aTo += nsPrintfCString(" bidi(%d,%d,%d)", bidi.baseLevel.Value(),
9411 bidi.embeddingLevel.Value(),
9412 bidi.precedingControl.Value());
9413 }
9414 if (IsTransformed()) {
9415 aTo += nsPrintfCString(" transformed");
9416 }
9417 if (ChildrenHavePerspective()) {
9418 aTo += nsPrintfCString(" perspective");
9419 }
9420 if (Extend3DContext()) {
9421 aTo += nsPrintfCString(" extend-3d");
9422 }
9423 if (Combines3DTransformWithAncestors()) {
9424 aTo += nsPrintfCString(" combines-3d-transform-with-ancestors");
9425 }
9426 if (mContent) {
9427 if (!onlyDeterministic) {
9428 aTo += nsPrintfCString(" [content=%p]", static_cast<void*>(mContent));
9429 }
9430 if (IsPrimaryFrame() && DisplayPortUtils::HasDisplayPort(mContent)) {
9431 // Anon boxes and continuations point to the same content - Just print on
9432 // primary frame.
9433 aTo += "[displayport]"_ns;
9434 }
9435 }
9436 if (!onlyDeterministic) {
9437 aTo += nsPrintfCString("[cs=%p]", static_cast<void*>(mComputedStyle));
9438 }
9439 if (mComputedStyle) {
9440 const auto pseudoType = mComputedStyle->GetPseudoType();
9441 const auto pseudoTypeStr = ToString(pseudoType);
9442 if (!pseudoTypeStr.empty()) {
9443 aTo += nsPrintfCString("[%s]", pseudoTypeStr.c_str());
9444 }
9445 }
9446
9447 auto contentVisibility = StyleDisplay()->ContentVisibility(*this);
9448 if (contentVisibility != StyleContentVisibility::Visible) {
9449 aTo += nsPrintfCString(" [content-visibility=");
9450 if (contentVisibility == StyleContentVisibility::Auto) {
9451 aTo += "auto, "_ns;
9452 } else if (contentVisibility == StyleContentVisibility::Hidden) {
9453 aTo += "hidden, "_ns;
9454 }
9455
9456 if (HidesContent()) {
9457 aTo += "HidesContent=hidden"_ns;
9458 } else {
9459 aTo += "HidesContent=visibile"_ns;
9460 }
9461 aTo += "]";
9462 }
9463
9464 if (IsFrameModified()) {
9465 aTo += nsPrintfCString(" modified");
9466 }
9467
9468 if (HasModifiedDescendants()) {
9469 aTo += nsPrintfCString(" has-modified-descendants");
9470 }
9471}
9472
9473void nsIFrame::List(FILE* out, const char* aPrefix, ListFlags aFlags) const {
9474 nsCString str;
9475 ListGeneric(str, aPrefix, aFlags);
9476 fprintf_stderr(out, "%s\n", str.get());
9477}
9478
9479void nsIFrame::ListTextRuns(FILE* out) const {
9480 nsTHashSet<const void*> seen;
9481 ListTextRuns(out, seen);
9482}
9483
9484void nsIFrame::ListTextRuns(FILE* out, nsTHashSet<const void*>& aSeen) const {
9485 for (const auto& childList : ChildLists()) {
9486 for (const nsIFrame* kid : childList.mList) {
9487 kid->ListTextRuns(out, aSeen);
9488 }
9489 }
9490}
9491
9492void nsIFrame::ListMatchedRules(FILE* out, const char* aPrefix) const {
9493 AutoTArray<StyleMatchingDeclarationBlock, 8> decls;
9494 Servo_ComputedValues_GetMatchingDeclarations(
9495 Style(), /* with_starting_style = */ false, &decls);
9496 for (const StyleMatchingDeclarationBlock& block : decls) {
9497 nsAutoCString ruleText;
9498 Servo_DeclarationBlock_GetCssText(block.block, &ruleText);
9499 fprintf_stderr(out, "%s%s\n", aPrefix, ruleText.get());
9500 }
9501}
9502
9503void nsIFrame::ListWithMatchedRules(FILE* out, const char* aPrefix) const {
9504 fprintf_stderr(out, "%s%s\n", aPrefix, ListTag().get());
9505
9506 nsCString rulePrefix;
9507 rulePrefix += aPrefix;
9508 rulePrefix += " ";
9509 ListMatchedRules(out, rulePrefix.get());
9510}
9511
9512nsresult nsIFrame::GetFrameName(nsAString& aResult) const {
9513 return MakeFrameName(u"Frame"_ns, aResult);
9514}
9515
9516nsresult nsIFrame::MakeFrameName(const nsAString& aType,
9517 nsAString& aResult) const {
9518 aResult = aType;
9519 if (mContent && !mContent->IsText()) {
9520 nsAutoString buf;
9521 mContent->NodeInfo()->NameAtom()->ToString(buf);
9522 if (nsAtom* id = mContent->GetID()) {
9523 buf.AppendLiteral(" id=");
9524 buf.Append(nsDependentAtomString(id));
9525 }
9526 if (IsSubDocumentFrame()) {
9527 nsAutoString src;
9528 mContent->AsElement()->GetAttr(nsGkAtoms::src, src);
9529 buf.AppendLiteral(" src=");
9530 buf.Append(src);
9531 }
9532 aResult.Append('(');
9533 aResult.Append(buf);
9534 aResult.Append(')');
9535 }
9536 aResult.Append('(');
9537 Maybe<uint32_t> index = ContentIndexInContainer(this);
9538 if (index.isSome()) {
9539 aResult.AppendInt(*index);
9540 } else {
9541 aResult.AppendInt(-1);
9542 }
9543 aResult.Append(')');
9544 return NS_OK;
9545}
9546
9547void nsIFrame::DumpFrameTree() const { DumpFrameTree(false); }
9548
9549void nsIFrame::DumpFrameTree(bool aListOnlyDeterministic) const {
9550 ListFlags flags;
9551 if (aListOnlyDeterministic) {
9552 flags += ListFlag::OnlyListDeterministicInfo;
9553 }
9554 PresShell()->GetRootFrame()->List(stderrstderr, "", flags);
9555}
9556
9557void nsIFrame::DumpFrameTreeInCSSPixels() const {
9558 DumpFrameTreeInCSSPixels(false);
9559}
9560
9561void nsIFrame::DumpFrameTreeInCSSPixels(bool aListOnlyDeterministic) const {
9562 ListFlags flags{ListFlag::DisplayInCSSPixels};
9563 if (aListOnlyDeterministic) {
9564 flags += ListFlag::OnlyListDeterministicInfo;
9565 }
9566 PresShell()->GetRootFrame()->List(stderrstderr, "", flags);
9567}
9568
9569void nsIFrame::DumpFrameTreeLimited() const { List(stderrstderr); }
9570void nsIFrame::DumpFrameTreeLimitedInCSSPixels() const {
9571 List(stderrstderr, "", ListFlag::DisplayInCSSPixels);
9572}
9573
9574#endif
9575
9576static bool IsFragmentedPageContent(const nsIFrame* aFrame) {
9577 MOZ_ASSERT(aFrame->IsPageContentFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->IsPageContentFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aFrame->IsPageContentFrame
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->IsPageContentFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 9577); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->IsPageContentFrame()"
")"); do { MOZ_CrashSequence(__null, 9577); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9578 return aFrame->GetPrevInFlow() || aFrame->GetNextInFlow();
9579}
9580
9581static bool IsReplicatedFixedPos(const nsIFrame* aFrame) {
9582 return aFrame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
9583 nsLayoutUtils::IsReallyFixedPos(aFrame) &&
9584 IsFragmentedPageContent(aFrame->GetParent());
9585}
9586
9587// FIXME(emilio, bug 1633685): We should ideally figure out how to properly
9588// restyle replicated fixed pos frames... We seem to assume everywhere that they
9589// can't get restyled at the moment...
9590bool nsIFrame::IsInReplicatedFixedPosTree() const {
9591 if (!PresContext()->IsPaginated()) {
9592 return false;
9593 }
9594 for (const nsIFrame* f = this; f; f = f->GetParent()) {
9595 if (IsReplicatedFixedPos(f)) {
9596 return true;
9597 }
9598 }
9599 return false;
9600}
9601
9602bool nsIFrame::ContainsReplicatedFixedPosPlaceholders() const {
9603 if (!PresContext()->IsPaginated()) {
9604 return false;
9605 }
9606 // Assumption here is that, in the common case, this will be faster than a
9607 // whole subtree walk.
9608 auto* ancestorPageContent =
9609 nsLayoutUtils::GetClosestFrameOfType(this, LayoutFrameType::PageContent);
9610 if (!ancestorPageContent || !IsFragmentedPageContent(ancestorPageContent)) {
9611 return false;
9612 }
9613 for (auto* f : ancestorPageContent->GetChildList(ChildListID::Absolute)) {
9614 if (!IsReplicatedFixedPos(f)) {
9615 continue;
9616 }
9617 auto* ph = f->GetPlaceholderFrame();
9618 if (NS_WARN_IF(!ph)NS_warn_if_impl(!ph, "!ph", "./../../../layout/generic/nsIFrame.cpp"
, 9618)
) {
9619 continue;
9620 }
9621 if (nsLayoutUtils::IsProperAncestorFrame(this, ph)) {
9622 return true;
9623 }
9624 }
9625 return false;
9626}
9627
9628bool nsIFrame::IsVisibleForPainting() const {
9629 return StyleVisibility()->IsVisible();
9630}
9631
9632bool nsIFrame::IsVisibleOrCollapsedForPainting() const {
9633 return StyleVisibility()->IsVisibleOrCollapsed();
9634}
9635
9636/* virtual */
9637bool nsIFrame::IsEmpty() {
9638 return IsHiddenByContentVisibilityOfInFlowParentForLayout();
9639}
9640
9641bool nsIFrame::CachedIsEmpty() {
9642 NS_ASSERTION(!HasAnyStateBits(NS_FRAME_IS_DIRTY) ||do { if (!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must only be called on reflowed lines or those hidden by "
"content-visibility.", "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
, "./../../../layout/generic/nsIFrame.cpp", 9645); MOZ_PretendNoReturn
(); } } while (0)
9643 IsHiddenByContentVisibilityOfInFlowParentForLayout(),do { if (!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must only be called on reflowed lines or those hidden by "
"content-visibility.", "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
, "./../../../layout/generic/nsIFrame.cpp", 9645); MOZ_PretendNoReturn
(); } } while (0)
9644 "Must only be called on reflowed lines or those hidden by "do { if (!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must only be called on reflowed lines or those hidden by "
"content-visibility.", "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
, "./../../../layout/generic/nsIFrame.cpp", 9645); MOZ_PretendNoReturn
(); } } while (0)
9645 "content-visibility.")do { if (!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must only be called on reflowed lines or those hidden by "
"content-visibility.", "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
, "./../../../layout/generic/nsIFrame.cpp", 9645); MOZ_PretendNoReturn
(); } } while (0)
;
9646 return IsEmpty();
9647}
9648
9649/* virtual */
9650bool nsIFrame::IsSelfEmpty() {
9651 return IsHiddenByContentVisibilityOfInFlowParentForLayout();
9652}
9653
9654nsISelectionController* nsIFrame::GetSelectionController() const {
9655 if (nsTextControlFrame* const tcf = GetContainingTextControlFrame()) {
9656 return tcf->ControlElement()->GetSelectionController();
9657 }
9658 return static_cast<nsISelectionController*>(PresShell());
9659}
9660
9661int16_t nsIFrame::GetDisplaySelection() const {
9662 nsISelectionController* const selCon = GetSelectionController();
9663 if (MOZ_UNLIKELY(!selCon)(__builtin_expect(!!(!selCon), 0))) {
9664 return nsISelectionController::SELECTION_OFF;
9665 }
9666 int16_t display = nsISelectionController::SELECTION_OFF;
9667 selCon->GetDisplaySelection(&display);
9668 return display;
9669}
9670
9671already_AddRefed<nsFrameSelection> nsIFrame::GetFrameSelection() {
9672 RefPtr<nsFrameSelection> fs =
9673 const_cast<nsFrameSelection*>(GetConstFrameSelection());
9674 return fs.forget();
9675}
9676
9677const nsFrameSelection* nsIFrame::GetConstFrameSelection() const {
9678 if (nsTextControlFrame* tcf = GetContainingTextControlFrame()) {
9679 return tcf->GetOwnedFrameSelection();
9680 }
9681 return PresShell()->ConstFrameSelection();
9682}
9683
9684bool nsIFrame::IsFrameSelected() const {
9685 NS_ASSERTION(!GetContent() || GetContent()->IsMaybeSelected(),do { if (!(!GetContent() || GetContent()->IsMaybeSelected(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "use the public IsSelected() instead"
, "!GetContent() || GetContent()->IsMaybeSelected()", "./../../../layout/generic/nsIFrame.cpp"
, 9686); MOZ_PretendNoReturn(); } } while (0)
9686 "use the public IsSelected() instead")do { if (!(!GetContent() || GetContent()->IsMaybeSelected(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "use the public IsSelected() instead"
, "!GetContent() || GetContent()->IsMaybeSelected()", "./../../../layout/generic/nsIFrame.cpp"
, 9686); MOZ_PretendNoReturn(); } } while (0)
;
9687 if (const ShadowRoot* shadowRoot =
9688 GetContent()->GetShadowRootForSelection()) {
9689 return shadowRoot->IsSelected(0, shadowRoot->GetChildCount());
9690 }
9691 return GetContent()->IsSelected(0, GetContent()->GetChildCount());
9692}
9693
9694nsresult nsIFrame::GetPointFromOffset(int32_t inOffset, nsPoint* outPoint) {
9695 MOZ_ASSERT(outPoint != nullptr, "Null parameter")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(outPoint != nullptr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(outPoint != nullptr))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("outPoint != nullptr"
" (" "Null parameter" ")", "./../../../layout/generic/nsIFrame.cpp"
, 9695); AnnotateMozCrashReason("MOZ_ASSERT" "(" "outPoint != nullptr"
") (" "Null parameter" ")"); do { MOZ_CrashSequence(__null, 9695
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
9696 nsRect contentRect = GetContentRectRelativeToSelf();
9697 nsPoint pt = contentRect.TopLeft();
9698 if (mContent) {
9699 nsIContent* newContent = mContent->GetParent();
9700 if (newContent) {
9701 const int32_t newOffset = newContent->ComputeIndexOf_Deprecated(mContent);
9702
9703 // Find the direction of the frame from the EmbeddingLevelProperty,
9704 // which is the resolved bidi level set in
9705 // nsBidiPresUtils::ResolveParagraph (odd levels = right-to-left).
9706 // If the embedding level isn't set, just use the CSS direction
9707 // property.
9708 bool hasBidiData;
9709 FrameBidiData bidiData = GetProperty(BidiDataProperty(), &hasBidiData);
9710 bool isRTL = hasBidiData
9711 ? bidiData.embeddingLevel.IsRTL()
9712 : StyleVisibility()->mDirection == StyleDirection::Rtl;
9713 if ((!isRTL && inOffset > newOffset) ||
9714 (isRTL && inOffset <= newOffset)) {
9715 pt = contentRect.TopRight();
9716 }
9717 }
9718 }
9719 *outPoint = pt;
9720 return NS_OK;
9721}
9722
9723nsresult nsIFrame::GetCharacterRectsInRange(int32_t aInOffset, int32_t aLength,
9724 nsTArray<nsRect>& aOutRect) {
9725 /* no text */
9726 return NS_ERROR_FAILURE;
9727}
9728
9729nsresult nsIFrame::GetChildFrameContainingOffset(int32_t inContentOffset,
9730 bool inHint,
9731 int32_t* outFrameContentOffset,
9732 nsIFrame** outChildFrame) {
9733 MOZ_ASSERT(outChildFrame && outFrameContentOffset, "Null parameter")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(outChildFrame && outFrameContentOffset)>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(outChildFrame && outFrameContentOffset))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("outChildFrame && outFrameContentOffset"
" (" "Null parameter" ")", "./../../../layout/generic/nsIFrame.cpp"
, 9733); AnnotateMozCrashReason("MOZ_ASSERT" "(" "outChildFrame && outFrameContentOffset"
") (" "Null parameter" ")"); do { MOZ_CrashSequence(__null, 9733
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
9734 *outFrameContentOffset = (int32_t)inHint;
9735 // the best frame to reflect any given offset would be a visible frame if
9736 // possible i.e. we are looking for a valid frame to place the blinking caret
9737 nsRect rect = GetRect();
9738 if (!rect.width || !rect.height) {
9739 // if we have a 0 width or height then lets look for another frame that
9740 // possibly has the same content. If we have no frames in flow then just
9741 // let us return 'this' frame
9742 nsIFrame* nextFlow = GetNextInFlow();
9743 if (nextFlow) {
9744 return nextFlow->GetChildFrameContainingOffset(
9745 inContentOffset, inHint, outFrameContentOffset, outChildFrame);
9746 }
9747 }
9748 *outChildFrame = this;
9749 return NS_OK;
9750}
9751
9752//
9753// What I've pieced together about this routine:
9754// Starting with a block frame (from which a line frame can be gotten)
9755// and a line number, drill down and get the first/last selectable
9756// frame on that line, depending on aPos->mDirection.
9757// aOutSideLimit != 0 means ignore aLineStart, instead work from
9758// the end (if > 0) or beginning (if < 0).
9759//
9760static nsresult GetNextPrevLineFromBlockFrame(PeekOffsetStruct* aPos,
9761 nsIFrame* aBlockFrame,
9762 int32_t aLineStart,
9763 int8_t aOutSideLimit) {
9764 MOZ_ASSERT(aPos)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPos)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aPos))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("aPos", "./../../../layout/generic/nsIFrame.cpp"
, 9764); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPos" ")");
do { MOZ_CrashSequence(__null, 9764); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9765 MOZ_ASSERT(aBlockFrame)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aBlockFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aBlockFrame))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("aBlockFrame", "./../../../layout/generic/nsIFrame.cpp"
, 9765); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aBlockFrame"
")"); do { MOZ_CrashSequence(__null, 9765); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9766
9767 nsPresContext* pc = aBlockFrame->PresContext();
9768
9769 // magic numbers: aLineStart will be -1 for end of block, 0 will be start of
9770 // block.
9771
9772 aPos->mResultFrame = nullptr;
9773 aPos->mResultContent = nullptr;
9774 aPos->mAttach = aPos->mDirection == eDirNext ? CaretAssociationHint::After
9775 : CaretAssociationHint::Before;
9776
9777 AutoAssertNoDomMutations guard;
9778 nsILineIterator* it = aBlockFrame->GetLineIterator();
9779 if (!it) {
9780 return NS_ERROR_FAILURE;
9781 }
9782 int32_t searchingLine = aLineStart;
9783 int32_t countLines = it->GetNumLines();
9784 if (aOutSideLimit > 0) { // start at end
9785 searchingLine = countLines;
9786 } else if (aOutSideLimit < 0) { // start at beginning
9787 searchingLine = -1; //"next" will be 0
9788 } else if ((aPos->mDirection == eDirPrevious && searchingLine == 0) ||
9789 (aPos->mDirection == eDirNext &&
9790 searchingLine >= (countLines - 1))) {
9791 // Not found.
9792 return NS_ERROR_FAILURE;
9793 }
9794 nsIFrame* resultFrame = nullptr;
9795 nsIFrame* farStoppingFrame = nullptr; // we keep searching until we find a
9796 // "this" frame then we go to next line
9797 nsIFrame* nearStoppingFrame = nullptr; // if we are backing up from edge,
9798 // stop here
9799 bool isBeforeFirstFrame, isAfterLastFrame;
9800 bool found = false;
9801
9802 const bool forceInEditableRegion =
9803 aPos->mOptions.contains(PeekOffsetOption::ForceEditableRegion);
9804 while (!found) {
9805 if (aPos->mDirection == eDirPrevious) {
9806 searchingLine--;
9807 } else {
9808 searchingLine++;
9809 }
9810 if ((aPos->mDirection == eDirPrevious && searchingLine < 0) ||
9811 (aPos->mDirection == eDirNext && searchingLine >= countLines)) {
9812 // we need to jump to new block frame.
9813 return NS_ERROR_FAILURE;
9814 }
9815 {
9816 auto line = it->GetLine(searchingLine).unwrap();
9817 if (!line.mNumFramesOnLine) {
9818 continue;
9819 }
9820 nsIFrame* firstFrame = nullptr;
9821 nsIFrame* lastFrame = nullptr;
9822 nsIFrame* frame = line.mFirstFrameOnLine;
9823 int32_t i = line.mNumFramesOnLine;
9824 do {
9825 // If the caller wants a frame for a inclusive ancestor of the ancestor
9826 // limiter, ignore frames for outside the limiter.
9827 if (aPos->FrameContentIsInAncestorLimiter(frame)) {
9828 if (!firstFrame) {
9829 firstFrame = frame;
9830 }
9831 lastFrame = frame;
9832 }
9833 if (i == 1) {
9834 break;
9835 }
9836 frame = frame->GetNextSibling();
9837 if (!frame) {
9838 NS_ERROR("GetLine promised more frames than could be found")do { NS_DebugBreak(NS_DEBUG_ASSERTION, "GetLine promised more frames than could be found"
, "Error", "./../../../layout/generic/nsIFrame.cpp", 9838); MOZ_PretendNoReturn
(); } while (0)
;
9839 return NS_ERROR_FAILURE;
9840 }
9841 } while (--i);
9842 if (!lastFrame) {
9843 // If we're looking for an editable content frame, but all frames in the
9844 // line are not in the specified editing host, return error because we
9845 // must reach the editing host boundary.
9846 return NS_ERROR_FAILURE;
9847 }
9848 // Don't enter into native anonymous subtrees.
9849 if (!lastFrame->ContentIsRootOfNativeAnonymousSubtree()) {
9850 nsIFrame::GetLastLeaf(&lastFrame);
9851 }
9852
9853 if (aPos->mDirection == eDirNext) {
9854 nearStoppingFrame = firstFrame;
9855 farStoppingFrame = lastFrame;
9856 } else {
9857 nearStoppingFrame = lastFrame;
9858 farStoppingFrame = firstFrame;
9859 }
9860 }
9861 nsPoint offset = aBlockFrame->GetOffsetToRootFrame();
9862 nsPoint newDesiredPos =
9863 aPos->mDesiredCaretPos -
9864 offset; // get desired position into blockframe coords
9865 // TODO: nsILineIterator::FindFrameAt should take optional editing host
9866 // parameter and if it's set, it should return the nearest editable frame
9867 // for the editing host when the frame at the desired position is not
9868 // editable.
9869 nsresult rv = it->FindFrameAt(searchingLine, newDesiredPos, &resultFrame,
9870 &isBeforeFirstFrame, &isAfterLastFrame);
9871 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
9872 continue;
9873 }
9874
9875 if (resultFrame) {
9876 // If ancestor limiter is specified and we reached outside content of it,
9877 // return error because we reached its element boundary.
9878 if (!aPos->FrameContentIsInAncestorLimiter(resultFrame)) {
9879 return NS_ERROR_FAILURE;
9880 }
9881 // Check to see if this is ANOTHER blockframe inside the other one that
9882 // we should look inside.
9883 if (resultFrame->CanProvideLineIterator() &&
9884 IsRelevantBlockFrame(resultFrame)) {
9885 aPos->mResultFrame = resultFrame;
9886 return NS_OK;
9887 }
9888 // resultFrame is not a block frame
9889 Maybe<nsFrameIterator> frameIterator;
9890 frameIterator.emplace(
9891 pc, resultFrame, nsFrameIterator::Type::PostOrder,
9892 false, // aVisual
9893 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller),
9894 false, // aFollowOOFs
9895 false // aSkipPopupChecks
9896 );
9897
9898 auto FoundValidFrame = [forceInEditableRegion, aPos](
9899 const nsIFrame::ContentOffsets& aOffsets,
9900 const nsIFrame* aFrame) {
9901 if (!aOffsets.content) {
9902 return false;
9903 }
9904 if (!aFrame->IsSelectable()) {
9905 return false;
9906 }
9907 if (aPos->mAncestorLimiter &&
9908 !aOffsets.content->IsInclusiveDescendantOf(
9909 aPos->mAncestorLimiter)) {
9910 return false;
9911 }
9912 if (forceInEditableRegion && !aOffsets.content->IsEditable()) {
9913 return false;
9914 }
9915 return true;
9916 };
9917
9918 nsIFrame* storeOldResultFrame = resultFrame;
9919 while (!found) {
9920 nsPoint point;
9921 nsRect tempRect = resultFrame->GetRect();
9922 nsPoint offset = resultFrame->GetOffsetToRootFrame();
9923 if (resultFrame->GetWritingMode().IsVertical()) {
9924 point.y = aPos->mDesiredCaretPos.y;
9925 point.x = tempRect.width + offset.x;
9926 } else {
9927 point.y = tempRect.height + offset.y;
9928 point.x = aPos->mDesiredCaretPos.x;
9929 }
9930
9931 if (!resultFrame->IsViewportFrame()) {
9932 nsPoint offset = resultFrame->GetOffsetToRootFrame();
9933 nsIFrame::ContentOffsets offsets =
9934 resultFrame->GetContentOffsetsFromPoint(
9935 point - offset, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
9936 aPos->mResultContent = offsets.content;
9937 aPos->mContentOffset = offsets.offset;
9938 aPos->mAttach = offsets.associate;
9939 if (FoundValidFrame(offsets, resultFrame)) {
9940 found = true;
9941 break;
9942 }
9943 }
9944
9945 if (aPos->mDirection == eDirPrevious &&
9946 resultFrame == farStoppingFrame) {
9947 break;
9948 }
9949 if (aPos->mDirection == eDirNext && resultFrame == nearStoppingFrame) {
9950 break;
9951 }
9952 // always try previous on THAT line if that fails go the other way
9953 resultFrame = frameIterator->Traverse(/* aForward = */ false);
9954 if (!resultFrame) {
9955 return NS_ERROR_FAILURE;
9956 }
9957 }
9958
9959 if (!found) {
9960 resultFrame = storeOldResultFrame;
9961 frameIterator.reset();
9962 frameIterator.emplace(
9963 pc, resultFrame, nsFrameIterator::Type::Leaf,
9964 false, // aVisual
9965 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller),
9966 false, // aFollowOOFs
9967 false // aSkipPopupChecks
9968 );
9969 MOZ_ASSERT(frameIterator)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frameIterator)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(frameIterator))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("frameIterator",
"./../../../layout/generic/nsIFrame.cpp", 9969); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "frameIterator" ")"); do { MOZ_CrashSequence
(__null, 9969); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
9970 }
9971 while (!found) {
9972 nsPoint point = aPos->mDesiredCaretPos;
9973 nsPoint offset = resultFrame->GetOffsetToRootFrame();
9974 nsIFrame::ContentOffsets offsets =
9975 resultFrame->GetContentOffsetsFromPoint(
9976 point - offset, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
9977 aPos->mResultContent = offsets.content;
9978 aPos->mContentOffset = offsets.offset;
9979 aPos->mAttach = offsets.associate;
9980 if (FoundValidFrame(offsets, resultFrame)) {
9981 found = true;
9982 aPos->mAttach = resultFrame == farStoppingFrame
9983 ? CaretAssociationHint::Before
9984 : CaretAssociationHint::After;
9985 break;
9986 }
9987 if (aPos->mDirection == eDirPrevious &&
9988 resultFrame == nearStoppingFrame) {
9989 break;
9990 }
9991 if (aPos->mDirection == eDirNext && resultFrame == farStoppingFrame) {
9992 break;
9993 }
9994 // previous didnt work now we try "next"
9995 nsIFrame* tempFrame = frameIterator->Traverse(/* aForward = */ true);
9996 if (!tempFrame) {
9997 break;
9998 }
9999 resultFrame = tempFrame;
10000 }
10001 aPos->mResultFrame = resultFrame;
10002 } else {
10003 // we need to jump to new block frame.
10004 aPos->mAmount = eSelectLine;
10005 aPos->mStartOffset = 0;
10006 aPos->mAttach = aPos->mDirection == eDirNext
10007 ? CaretAssociationHint::Before
10008 : CaretAssociationHint::After;
10009 if (aPos->mDirection == eDirPrevious) {
10010 aPos->mStartOffset = -1; // start from end
10011 }
10012 return aBlockFrame->PeekOffset(aPos);
10013 }
10014 }
10015 return NS_OK;
10016}
10017
10018nsIFrame::CaretPosition nsIFrame::GetExtremeCaretPosition(bool aStart,
10019 uint32_t aFlags) {
10020 CaretPosition result;
10021
10022 FrameTarget targetFrame = DrillDownToSelectionFrame(this, !aStart, aFlags);
10023 FrameContentRange range = GetRangeForFrame(targetFrame.frame);
10024 result.mResultContent = range.content;
10025 result.mContentOffset = aStart ? range.start : range.end;
10026 return result;
10027}
10028
10029// If this is a preformatted text frame, see if it ends with a newline
10030static nsContentAndOffset FindLineBreakInText(nsIFrame* aFrame,
10031 nsDirection aDirection) {
10032 nsContentAndOffset result;
10033
10034 if (aFrame->IsGeneratedContentFrame() ||
10035 !aFrame->HasSignificantTerminalNewline()) {
10036 return result;
10037 }
10038
10039 int32_t endOffset = aFrame->GetOffsets().second;
10040 result.mContent = aFrame->GetContent();
10041 result.mOffset = endOffset - (aDirection == eDirPrevious ? 0 : 1);
10042 result.mIsTerminalNewlineInText = true;
10043 return result;
10044}
10045
10046// Find the first (or last) descendant of the given frame
10047// which is either a block-level frame or a BRFrame, or some other kind of break
10048// which stops the line.
10049static nsContentAndOffset FindLineBreakingFrame(nsIFrame* aFrame,
10050 nsDirection aDirection) {
10051 nsContentAndOffset result;
10052
10053 if (aFrame->IsGeneratedContentFrame()) {
10054 return result;
10055 }
10056
10057 // Treat form controls and other replaced inline level elements as inline
10058 // leaves.
10059 if (aFrame->IsReplaced() && aFrame->IsInlineOutside() &&
10060 !aFrame->IsBrFrame() && !aFrame->IsTextFrame()) {
10061 return result;
10062 }
10063
10064 // Check the frame itself
10065 // Fall through block-in-inline split frames because their mContent is
10066 // the content of the inline frames they were created from. The
10067 // first/last child of such frames is the real block frame we're
10068 // looking for.
10069 if ((IsRelevantBlockFrame(aFrame) &&
10070 !aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) ||
10071 aFrame->IsBrFrame()) {
10072 nsIContent* content = aFrame->GetContent();
10073 result.mContent = content->GetParent();
10074 // In some cases (bug 310589, bug 370174) we end up here with a null
10075 // content. This probably shouldn't ever happen, but since it sometimes
10076 // does, we want to avoid crashing here.
10077 NS_ASSERTION(result.mContent, "Unexpected orphan content")do { if (!(result.mContent)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Unexpected orphan content", "result.mContent", "./../../../layout/generic/nsIFrame.cpp"
, 10077); MOZ_PretendNoReturn(); } } while (0)
;
10078 if (result.mContent) {
10079 result.mOffset = result.mContent->ComputeIndexOf_Deprecated(content) +
10080 (aDirection == eDirPrevious ? 1 : 0);
10081 }
10082 return result;
10083 }
10084
10085 result = FindLineBreakInText(aFrame, aDirection);
10086 if (result.mContent) {
10087 return result;
10088 }
10089
10090 // Iterate over children and call ourselves recursively
10091 if (aDirection == eDirPrevious) {
10092 nsIFrame* child = aFrame->PrincipalChildList().LastChild();
10093 while (child && !result.mContent) {
10094 result = FindLineBreakingFrame(child, aDirection);
10095 child = child->GetPrevSibling();
10096 }
10097 } else { // eDirNext
10098 nsIFrame* child = aFrame->PrincipalChildList().FirstChild();
10099 while (child && !result.mContent) {
10100 result = FindLineBreakingFrame(child, aDirection);
10101 child = child->GetNextSibling();
10102 }
10103 }
10104 return result;
10105}
10106
10107enum class OffsetIsAtLineEdge : bool { No, Yes };
10108
10109static void SetPeekResultFromFrame(PeekOffsetStruct& aPos, nsIFrame* aFrame,
10110 int32_t aOffset,
10111 OffsetIsAtLineEdge aAtLineEdge) {
10112 FrameContentRange range = GetRangeForFrame(aFrame);
10113 aPos.mResultFrame = aFrame;
10114 aPos.mResultContent = range.content;
10115 // Output offset is relative to content, not frame
10116 aPos.mContentOffset =
10117 aOffset < 0 ? range.end + aOffset + 1 : range.start + aOffset;
10118 // Ensure we don't go past the range. This is important if aFrame is empty.
10119 aPos.mContentOffset = std::clamp(aPos.mContentOffset, range.start, range.end);
10120 if (aAtLineEdge == OffsetIsAtLineEdge::Yes) {
10121 aPos.mAttach = aPos.mContentOffset == range.start
10122 ? CaretAssociationHint::After
10123 : CaretAssociationHint::Before;
10124 }
10125}
10126
10127nsresult nsIFrame::PeekOffsetForParagraph(PeekOffsetStruct* aPos) {
10128 nsIFrame* frame = this;
10129 nsContentAndOffset blockFrameOrBR;
10130 blockFrameOrBR.mContent = nullptr;
10131 bool reachedLimit = IsRelevantBlockFrame(frame) || IsEditingHost(frame);
10132
10133 auto traverse = [&aPos](nsIFrame* current) {
10134 return aPos->mDirection == eDirPrevious ? current->GetPrevSibling()
10135 : current->GetNextSibling();
10136 };
10137
10138 // Go through containing frames until reaching a block frame.
10139 // In each step, search the previous (or next) siblings for the closest
10140 // "stop frame" (a block frame or a BRFrame).
10141 // If found, set it to be the selection boundary and abort.
10142 while (!reachedLimit) {
10143 nsIFrame* parent = frame->GetParent();
10144 // Treat a frame associated with the root content as if it were a block
10145 // frame.
10146 if (!frame->mContent || !frame->mContent->GetParent()) {
10147 reachedLimit = true;
10148 break;
10149 }
10150
10151 if (aPos->mDirection == eDirNext) {
10152 // Try to find our own line-break before looking at our siblings.
10153 blockFrameOrBR = FindLineBreakInText(frame, eDirNext);
10154 }
10155
10156 nsIFrame* sibling = traverse(frame);
10157 while (sibling && !blockFrameOrBR.mContent) {
10158 blockFrameOrBR = FindLineBreakingFrame(sibling, aPos->mDirection);
10159 sibling = traverse(sibling);
10160 }
10161 if (blockFrameOrBR.mContent) {
10162 aPos->mResultContent = blockFrameOrBR.mContent;
10163 aPos->mContentOffset = blockFrameOrBR.mOffset;
10164 if (blockFrameOrBR.mIsTerminalNewlineInText) {
10165 // The boundary sits on the edge between the text frame ending with the
10166 // newline and the one starting the next line, and it belongs to the
10167 // latter. Associating the caret with the end of the preceding line
10168 // instead leaves a later logical character move with nothing to do: it
10169 // only re-associates the caret without advancing the offset.
10170 aPos->mAttach = CaretAssociationHint::After;
10171 }
10172 break;
10173 }
10174 frame = parent;
10175 reachedLimit =
10176 frame && (IsRelevantBlockFrame(frame) || IsEditingHost(frame));
10177 }
10178
10179 if (reachedLimit) { // no "stop frame" found
10180 if (aPos->mOptions.contains(PeekOffsetOption::ForCaretMove)) {
10181 // For a caret move, drill down to a leaf so scroll-into-view geometry,
10182 // which only uses text-frame offsets when the focus node is a Text node,
10183 // gets a usable position. Frame children include flattened-tree
10184 // descendants, so this also covers shadow-DOM content that the element
10185 // branch below reaches via GetShadowRootForSelection.
10186 const bool atEnd = aPos->mDirection == eDirNext;
10187 FrameTarget targetFrame = DrillDownToSelectionFrame(
10188 frame, atEnd, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
10189 SetPeekResultFromFrame(*aPos, targetFrame.frame, atEnd ? -1 : 0,
10190 OffsetIsAtLineEdge::Yes);
10191 } else {
10192 // For selection (e.g. triple-click paragraph selection), the block
10193 // container itself is the expected boundary.
10194 aPos->mResultContent = frame->GetContent();
10195 if (aPos->mResultContent) {
10196 if (ShadowRoot* shadowRoot =
10197 aPos->mResultContent->GetShadowRootForSelection()) {
10198 // Even if there's no children for this node,
10199 // the elements inside the shadow root is still
10200 // selectable
10201 aPos->mResultContent = shadowRoot;
10202 }
10203 }
10204 if (aPos->mDirection == eDirPrevious) {
10205 aPos->mContentOffset = 0;
10206 } else if (aPos->mResultContent) {
10207 aPos->mContentOffset = aPos->mResultContent->GetChildCount();
10208 }
10209 }
10210 }
10211 return NS_OK;
10212}
10213
10214// Determine movement direction relative to frame
10215static bool IsMovingInFrameDirection(const nsIFrame* frame,
10216 nsDirection aDirection, bool aVisual) {
10217 bool isReverseDirection =
10218 aVisual && nsBidiPresUtils::IsReversedDirectionFrame(frame);
10219 return aDirection == (isReverseDirection ? eDirPrevious : eDirNext);
10220}
10221
10222// Determines "are we looking for a boundary between whitespace and
10223// non-whitespace (in the direction we're moving in)". It is true when moving
10224// forward and looking for a beginning of a word, or when moving backwards and
10225// looking for an end of a word.
10226static bool ShouldWordSelectionEatSpace(const PeekOffsetStruct& aPos) {
10227 if (aPos.mWordMovementType != eDefaultBehavior) {
10228 // aPos->mWordMovementType possible values:
10229 // eEndWord: eat the space if we're moving backwards
10230 // eStartWord: eat the space if we're moving forwards
10231 return (aPos.mWordMovementType == eEndWord) ==
10232 (aPos.mDirection == eDirPrevious);
10233 }
10234 // Use the hidden preference which is based on operating system
10235 // behavior. This pref only affects whether moving forward by word
10236 // should go to the end of this word or start of the next word. When
10237 // going backwards, the start of the word is always used, on every
10238 // operating system.
10239 return aPos.mDirection == eDirNext &&
10240 StaticPrefs::layout_word_select_eat_space_to_next_word();
10241}
10242
10243void nsIFrame::SelectablePeekReport::TransferTo(PeekOffsetStruct& aPos) const {
10244 return SetPeekResultFromFrame(aPos, mFrame, mOffset, OffsetIsAtLineEdge::No);
10245}
10246
10247nsIFrame::SelectablePeekReport::SelectablePeekReport(
10248 const mozilla::GenericErrorResult<nsresult>&& aErr) {
10249 MOZ_ASSERT(NS_FAILED(aErr.operator nsresult()))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(((bool)(__builtin_expect(!!(NS_FAILED_impl(aErr.operator
nsresult())), 0))))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(((bool)(__builtin_expect(!!(
NS_FAILED_impl(aErr.operator nsresult())), 0)))))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("((bool)(__builtin_expect(!!(NS_FAILED_impl(aErr.operator nsresult())), 0)))"
, "./../../../layout/generic/nsIFrame.cpp", 10249); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "((bool)(__builtin_expect(!!(NS_FAILED_impl(aErr.operator nsresult())), 0)))"
")"); do { MOZ_CrashSequence(__null, 10249); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10250 // Return an empty report
10251}
10252
10253nsresult nsIFrame::PeekOffsetForCharacter(PeekOffsetStruct* aPos,
10254 int32_t aOffset) {
10255 SelectablePeekReport current{this, aOffset};
10256
10257 nsIFrame::FrameSearchResult peekSearchState = CONTINUE;
10258
10259 const bool forceEditableRegion =
10260 aPos->mOptions.contains(PeekOffsetOption::ForceEditableRegion);
10261
10262 while (peekSearchState != FOUND) {
10263 const bool movingInFrameDirection = IsMovingInFrameDirection(
10264 current.mFrame, aPos->mDirection,
10265 aPos->mOptions.contains(PeekOffsetOption::Visual));
10266
10267 if (current.mJumpedLine) {
10268 // If we jumped lines, it's as if we found a character, but we still need
10269 // to eat non-renderable content on the new line.
10270 peekSearchState = current.PeekOffsetNoAmount(movingInFrameDirection);
10271 } else {
10272 PeekOffsetCharacterOptions options;
10273 options.mRespectClusters = aPos->mAmount == eSelectCluster;
10274 peekSearchState =
10275 current.PeekOffsetCharacter(movingInFrameDirection, options);
10276 if (peekSearchState == FOUND && forceEditableRegion &&
10277 !current.mFrame->ContentIsEditable()) {
10278 // Treat non-editable content as unselectable. Note that we may need to
10279 // set mJumpedLine propery even if it's not editable. Therefore, we
10280 // cannot skip the above call.
10281 peekSearchState = CONTINUE_UNSELECTABLE;
10282 }
10283 }
10284
10285 current.mMovedOverNonSelectableText |=
10286 peekSearchState == CONTINUE_UNSELECTABLE;
10287
10288 if (peekSearchState != FOUND) {
10289 SelectablePeekReport next = current.mFrame->GetFrameFromDirection(*aPos);
10290 if (next.Failed()) {
10291 return NS_ERROR_FAILURE;
10292 }
10293 next.mJumpedLine |= current.mJumpedLine;
10294 next.mMovedOverNonSelectableText |= current.mMovedOverNonSelectableText;
10295 next.mHasSelectableFrame |= current.mHasSelectableFrame;
10296 current = next;
10297 }
10298
10299 // Found frame, but because we moved over non selectable text we want
10300 // the offset to be at the frame edge. Note that if we are extending the
10301 // selection, this doesn't matter.
10302 if (peekSearchState == FOUND && current.mMovedOverNonSelectableText &&
10303 (!aPos->mOptions.contains(PeekOffsetOption::Extend) ||
10304 current.mHasSelectableFrame)) {
10305 auto [start, end] = current.mFrame->GetOffsets();
10306 current.mOffset = aPos->mDirection == eDirNext ? 0 : end - start;
10307 }
10308 }
10309
10310 // Set outputs
10311 current.TransferTo(*aPos);
10312 // If we're dealing with a text frame and moving backward positions us at
10313 // the end of that line, decrease the offset by one to make sure that
10314 // we're placed before the linefeed character on the previous line.
10315 if (current.mOffset < 0 && current.mJumpedLine &&
10316 aPos->mDirection == eDirPrevious &&
10317 current.mFrame->HasSignificantTerminalNewline() &&
10318 !current.mIgnoredBrFrame) {
10319 --aPos->mContentOffset;
10320 }
10321 return NS_OK;
10322}
10323
10324nsresult nsIFrame::PeekOffsetForWord(PeekOffsetStruct* aPos, int32_t aOffset) {
10325 SelectablePeekReport current{this, aOffset};
10326 bool shouldStopAtHardBreak =
10327 aPos->mWordMovementType == eDefaultBehavior &&
10328 StaticPrefs::layout_word_select_eat_space_to_next_word();
10329 bool wordSelectEatSpace = ShouldWordSelectionEatSpace(*aPos);
10330
10331 PeekWordState state;
10332 while (true) {
10333 bool movingInFrameDirection = IsMovingInFrameDirection(
10334 current.mFrame, aPos->mDirection,
10335 aPos->mOptions.contains(PeekOffsetOption::Visual));
10336
10337 FrameSearchResult searchResult = current.mFrame->PeekOffsetWord(
10338 movingInFrameDirection, wordSelectEatSpace,
10339 aPos->mOptions.contains(PeekOffsetOption::IsKeyboardSelect),
10340 &current.mOffset, &state,
10341 !aPos->mOptions.contains(PeekOffsetOption::PreserveSpaces));
10342 if (searchResult == FOUND) {
10343 break;
10344 }
10345
10346 SelectablePeekReport next = [&]() {
10347 PeekOffsetOptions options = aPos->mOptions;
10348 if (state.mSawInlineCharacter) {
10349 // If we've already found a character, we don't want to stop at
10350 // placeholder frame boundary if there is in the word.
10351 options += PeekOffsetOption::StopAtPlaceholder;
10352 }
10353 return current.mFrame->GetFrameFromDirection(aPos->mDirection, options,
10354 aPos->mAncestorLimiter);
10355 }();
10356 if (next.Failed()) {
10357 // If we've crossed the line boundary, check to make sure that we
10358 // have not consumed a trailing newline as whitespace if it's
10359 // significant.
10360 if (next.mJumpedLine && wordSelectEatSpace &&
10361 current.mFrame->HasSignificantTerminalNewline() &&
10362 current.mFrame->StyleText()->mWhiteSpaceCollapse !=
10363 StyleWhiteSpaceCollapse::PreserveBreaks) {
10364 current.mOffset -= 1;
10365 }
10366 break;
10367 }
10368
10369 if ((next.mJumpedLine || next.mFoundPlaceholder) && !wordSelectEatSpace &&
10370 state.mSawBeforeType) {
10371 // We can't jump lines if we're looking for whitespace following
10372 // non-whitespace, and we already encountered non-whitespace.
10373 break;
10374 }
10375
10376 if (shouldStopAtHardBreak && next.mJumpedHardBreak) {
10377 /**
10378 * Prev, always: Jump and stop right there
10379 * Next, saw inline: just stop
10380 * Next, no inline: Jump and consume whitespaces
10381 */
10382 if (aPos->mDirection == eDirPrevious) {
10383 // Try moving to the previous line if exists
10384 current.TransferTo(*aPos);
10385 current.mFrame->PeekOffsetForCharacter(aPos, current.mOffset);
10386 return NS_OK;
10387 }
10388 if (state.mSawInlineCharacter || current.mJumpedHardBreak) {
10389 if (current.mFrame->HasSignificantTerminalNewline()) {
10390 current.mOffset -= 1;
10391 }
10392 current.TransferTo(*aPos);
10393 return NS_OK;
10394 }
10395 // Mark the state as whitespace and continue
10396 state.Update(false, true);
10397 }
10398
10399 if (next.mJumpedLine) {
10400 state.mContext.Truncate();
10401 }
10402 current = next;
10403 // Jumping a line is equivalent to encountering whitespace
10404 // This affects only when it already met an actual character
10405 if (wordSelectEatSpace && next.mJumpedLine) {
10406 state.SetSawBeforeType();
10407 }
10408 }
10409
10410 // Set outputs
10411 current.TransferTo(*aPos);
10412 return NS_OK;
10413}
10414
10415static nsIFrame* GetFirstSelectableDescendantWithLineIterator(
10416 const PeekOffsetStruct& aPeekOffsetStruct, nsIFrame* aParentFrame) {
10417 const bool forceEditableRegion = aPeekOffsetStruct.mOptions.contains(
10418 PeekOffsetOption::ForceEditableRegion);
10419 auto FoundValidFrame = [aPeekOffsetStruct,
10420 forceEditableRegion](const nsIFrame* aFrame) {
10421 if (!aFrame->IsSelectable()) {
10422 return false;
10423 }
10424 if (!aPeekOffsetStruct.FrameContentIsInAncestorLimiter(aFrame)) {
10425 return false;
10426 }
10427 if (forceEditableRegion && !aFrame->ContentIsEditable()) {
10428 return false;
10429 }
10430 return true;
10431 };
10432
10433 for (nsIFrame* child : aParentFrame->PrincipalChildList()) {
10434 // some children may not be selectable, e.g. :before / :after pseudoelements
10435 // content with user-select: none, or contenteditable="false"
10436 // we need to skip them
10437 if (child->CanProvideLineIterator() && FoundValidFrame(child)) {
10438 return child;
10439 }
10440 if (nsIFrame* nested = GetFirstSelectableDescendantWithLineIterator(
10441 aPeekOffsetStruct, child)) {
10442 return nested;
10443 }
10444 }
10445 return nullptr;
10446}
10447
10448nsresult nsIFrame::PeekOffsetForLine(PeekOffsetStruct* aPos) {
10449 nsIFrame* blockFrame = this;
10450 nsresult result = NS_ERROR_FAILURE;
10451
10452 // outer loop
10453 // moving to a next block when no more blocks are available in a subtree
10454 AutoAssertNoDomMutations guard;
10455 while (NS_FAILED(result)((bool)(__builtin_expect(!!(NS_FAILED_impl(result)), 0)))) {
10456 auto [newBlock, lineFrame] = blockFrame->GetContainingBlockForLine(
10457 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller));
10458 if (!newBlock) {
10459 return NS_ERROR_FAILURE;
10460 }
10461 // FYI: If the editing host is an inline element, the block frame content
10462 // may be either not editable or editable but belonging to different editing
10463 // host.
10464 blockFrame = newBlock;
10465 nsILineIterator* iter = blockFrame->GetLineIterator();
10466 int32_t thisLine = iter->FindLineContaining(lineFrame);
10467 if (NS_WARN_IF(thisLine < 0)NS_warn_if_impl(thisLine < 0, "thisLine < 0", "./../../../layout/generic/nsIFrame.cpp"
, 10467)
) {
10468 return NS_ERROR_FAILURE;
10469 }
10470
10471 int8_t edgeCase = 0; // no edge case. This should look at thisLine
10472
10473 // this part will find a frame or a block frame. If it's a block frame
10474 // it will "drill down" to find a viable frame or it will return an
10475 // error.
10476 nsIFrame* lastFrame = this;
10477
10478 // inner loop - crawling the frames within a specific block subtree
10479 while (true) {
10480 result =
10481 GetNextPrevLineFromBlockFrame(aPos, blockFrame, thisLine, edgeCase);
10482 // we came back to same spot! keep going
10483 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) &&
10484 (!aPos->mResultFrame || aPos->mResultFrame == lastFrame)) {
10485 aPos->mResultFrame = nullptr;
10486 lastFrame = nullptr;
10487 if (aPos->mDirection == eDirPrevious) {
10488 thisLine--;
10489 } else {
10490 thisLine++;
10491 }
10492 continue;
10493 }
10494
10495 if (NS_FAILED(result)((bool)(__builtin_expect(!!(NS_FAILED_impl(result)), 0)))) {
10496 break;
10497 }
10498
10499 lastFrame = aPos->mResultFrame; // set last frame
10500 /* SPECIAL CHECK FOR NAVIGATION INTO TABLES
10501 * when we hit a frame which doesn't have line iterator, we need to
10502 * drill down and find a child with the line iterator to prevent the
10503 * crawling process to prematurely finish. Note that this is only sound if
10504 * we're guaranteed to not have multiple children implementing
10505 * LineIterator.
10506 *
10507 * So far known cases are:
10508 * 1) table wrapper (drill down into table row group)
10509 * 2) table cell (drill down into its only anon child)
10510 */
10511 const bool shouldDrillIntoChildren =
10512 aPos->mResultFrame->IsTableWrapperFrame() ||
10513 aPos->mResultFrame->IsTableCellFrame();
10514
10515 if (shouldDrillIntoChildren) {
10516 nsIFrame* child = GetFirstSelectableDescendantWithLineIterator(
10517 *aPos, aPos->mResultFrame);
10518 if (child) {
10519 aPos->mResultFrame = child;
10520 }
10521 }
10522
10523 if (!aPos->mResultFrame->CanProvideLineIterator()) {
10524 // no more selectable content at this level
10525 break;
10526 }
10527
10528 if (aPos->mResultFrame == blockFrame) {
10529 // Make sure block element is not the same as the one we had before.
10530 break;
10531 }
10532
10533 // we've struck another block element with selectable content!
10534 if (aPos->mDirection == eDirPrevious) {
10535 edgeCase = 1; // far edge, search from end backwards
10536 } else {
10537 edgeCase = -1; // near edge search from beginning onwards
10538 }
10539 thisLine = 0; // this line means nothing now.
10540 // everything else means something so keep looking "inside" the
10541 // block
10542 blockFrame = aPos->mResultFrame;
10543 }
10544 }
10545 return result;
10546}
10547
10548nsresult nsIFrame::PeekOffsetForLineEdge(PeekOffsetStruct* aPos) {
10549 // Adjusted so that the caret can't get confused when content changes
10550 nsIFrame* frame = AdjustFrameForSelectionStyles(this);
10551 // FIXME: Use PeekOffsetStruct::mAncestorLimiter instead.
10552 Element* editingHost = frame->GetContent()->GetEditingHost();
10553
10554 auto [blockFrame, lineFrame] = frame->GetContainingBlockForLine(
10555 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller));
10556 if (!blockFrame) {
10557 return NS_ERROR_FAILURE;
10558 }
10559 AutoAssertNoDomMutations guard;
10560 nsILineIterator* it = blockFrame->GetLineIterator();
10561 int32_t thisLine = it->FindLineContaining(lineFrame);
10562 if (thisLine < 0) {
10563 return NS_ERROR_FAILURE;
10564 }
10565
10566 nsIFrame* baseFrame = nullptr;
10567 bool endOfLine = eSelectEndLine == aPos->mAmount;
10568
10569 if (aPos->mOptions.contains(PeekOffsetOption::Visual) &&
10570 PresContext()->BidiEnabled()) {
10571 nsIFrame* firstFrame;
10572 bool isReordered;
10573 nsIFrame* lastFrame;
10574 MOZ_TRY(__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(it->CheckLineOrder(thisLine, &isReordered, &firstFrame
, &lastFrame)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
10575 it->CheckLineOrder(thisLine, &isReordered, &firstFrame, &lastFrame))__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(it->CheckLineOrder(thisLine, &isReordered, &firstFrame
, &lastFrame)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
;
10576 baseFrame = endOfLine ? lastFrame : firstFrame;
10577 } else {
10578 auto line = it->GetLine(thisLine).unwrap();
10579
10580 nsIFrame* frame = line.mFirstFrameOnLine;
10581 bool lastFrameWasEditable = false;
10582 for (int32_t count = line.mNumFramesOnLine; count;
10583 --count, frame = frame->GetNextSibling()) {
10584 if (frame->IsGeneratedContentFrame()) {
10585 continue;
10586 }
10587 // When jumping to the end of the line with the "end" key,
10588 // try to skip over brFrames
10589 if (endOfLine && line.mNumFramesOnLine > 1 && frame->IsBrFrame() &&
10590 lastFrameWasEditable == frame->GetContent()->IsEditable()) {
10591 continue;
10592 }
10593 lastFrameWasEditable =
10594 frame->GetContent() && frame->GetContent()->IsEditable();
10595 baseFrame = frame;
10596 if (!endOfLine) {
10597 break;
10598 }
10599 }
10600 }
10601 if (!baseFrame) {
10602 return NS_ERROR_FAILURE;
10603 }
10604 // Make sure we are not leaving our inline editing host if exists
10605 if (editingHost) {
10606 if (nsIFrame* frame = editingHost->GetPrimaryFrame()) {
10607 if (frame->IsInlineOutside() &&
10608 !editingHost->Contains(baseFrame->GetContent())) {
10609 baseFrame = frame;
10610 if (endOfLine) {
10611 baseFrame = baseFrame->LastContinuation();
10612 }
10613 }
10614 }
10615 }
10616 FrameTarget targetFrame = DrillDownToSelectionFrame(
10617 baseFrame, endOfLine, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
10618 SetPeekResultFromFrame(*aPos, targetFrame.frame, endOfLine ? -1 : 0,
10619 OffsetIsAtLineEdge::Yes);
10620 if (endOfLine && targetFrame.frame->HasSignificantTerminalNewline()) {
10621 // Do not position the caret after the terminating newline if we're
10622 // trying to move to the end of line (see bug 596506)
10623 --aPos->mContentOffset;
10624 }
10625 if (!aPos->mResultContent) {
10626 return NS_ERROR_FAILURE;
10627 }
10628 return NS_OK;
10629}
10630
10631nsresult nsIFrame::PeekOffset(PeekOffsetStruct* aPos) {
10632 MOZ_ASSERT(aPos)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aPos)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aPos))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("aPos", "./../../../layout/generic/nsIFrame.cpp"
, 10632); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPos" ")")
; do { MOZ_CrashSequence(__null, 10632); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
10633
10634 if (NS_WARN_IF(HasAnyStateBits(NS_FRAME_IS_DIRTY))NS_warn_if_impl(HasAnyStateBits(NS_FRAME_IS_DIRTY), "HasAnyStateBits(NS_FRAME_IS_DIRTY)"
, "./../../../layout/generic/nsIFrame.cpp", 10634)
) {
10635 // FIXME(Bug 1654362): <caption> currently can remain dirty.
10636 return NS_ERROR_UNEXPECTED;
10637 }
10638
10639 // Translate content offset to be relative to frame
10640 int32_t offset = aPos->mStartOffset - GetRangeForFrame(this).start;
10641
10642 switch (aPos->mAmount) {
10643 case eSelectCharacter:
10644 case eSelectCluster:
10645 return PeekOffsetForCharacter(aPos, offset);
10646 case eSelectWordNoSpace:
10647 // eSelectWordNoSpace means that we should not be eating any whitespace
10648 // when moving to the adjacent word. This means that we should set aPos->
10649 // mWordMovementType to eEndWord if we're moving forwards, and to
10650 // eStartWord if we're moving backwards.
10651 if (aPos->mDirection == eDirPrevious) {
10652 aPos->mWordMovementType = eStartWord;
10653 } else {
10654 aPos->mWordMovementType = eEndWord;
10655 }
10656 // Intentionally fall through the eSelectWord case.
10657 [[fallthrough]];
10658 case eSelectWord:
10659 return PeekOffsetForWord(aPos, offset);
10660 case eSelectLine:
10661 return PeekOffsetForLine(aPos);
10662 case eSelectBeginLine:
10663 case eSelectEndLine:
10664 return PeekOffsetForLineEdge(aPos);
10665 case eSelectParagraph:
10666 return PeekOffsetForParagraph(aPos);
10667 default: {
10668 NS_ASSERTION(false, "Invalid amount")do { if (!(false)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Invalid amount"
, "false", "./../../../layout/generic/nsIFrame.cpp", 10668); MOZ_PretendNoReturn
(); } } while (0)
;
10669 return NS_ERROR_FAILURE;
10670 }
10671 }
10672}
10673
10674nsIFrame::FrameSearchResult nsIFrame::PeekOffsetNoAmount(bool aForward,
10675 int32_t* aOffset) {
10676 NS_ASSERTION(aOffset && *aOffset <= 1, "aOffset out of range")do { if (!(aOffset && *aOffset <= 1)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "aOffset out of range", "aOffset && *aOffset <= 1"
, "./../../../layout/generic/nsIFrame.cpp", 10676); MOZ_PretendNoReturn
(); } } while (0)
;
10677 // Sure, we can stop right here.
10678 return FOUND;
10679}
10680
10681nsIFrame::FrameSearchResult nsIFrame::PeekOffsetCharacter(
10682 bool aForward, int32_t* aOffset, PeekOffsetCharacterOptions aOptions) {
10683 NS_ASSERTION(aOffset && *aOffset <= 1, "aOffset out of range")do { if (!(aOffset && *aOffset <= 1)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "aOffset out of range", "aOffset && *aOffset <= 1"
, "./../../../layout/generic/nsIFrame.cpp", 10683); MOZ_PretendNoReturn
(); } } while (0)
;
10684 int32_t startOffset = *aOffset;
10685 // A negative offset means "end of frame", which in our case means offset 1.
10686 if (startOffset < 0) {
10687 startOffset = 1;
10688 }
10689 if (aForward == (startOffset == 0)) {
10690 // We're before the frame and moving forward, or after it and moving
10691 // backwards: skip to the other side and we're done.
10692 *aOffset = 1 - startOffset;
10693 return FOUND;
10694 }
10695 return CONTINUE;
10696}
10697
10698nsIFrame::FrameSearchResult nsIFrame::PeekOffsetWord(
10699 bool aForward, bool aWordSelectEatSpace, bool aIsKeyboardSelect,
10700 int32_t* aOffset, PeekWordState* aState, bool /*aTrimSpaces*/) {
10701 NS_ASSERTION(aOffset && *aOffset <= 1, "aOffset out of range")do { if (!(aOffset && *aOffset <= 1)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "aOffset out of range", "aOffset && *aOffset <= 1"
, "./../../../layout/generic/nsIFrame.cpp", 10701); MOZ_PretendNoReturn
(); } } while (0)
;
10702 int32_t startOffset = *aOffset;
10703 // This isn't text, so truncate the context
10704 aState->mContext.Truncate();
10705 if (startOffset < 0) {
10706 startOffset = 1;
10707 }
10708 if (aForward == (startOffset == 0)) {
10709 // We're before the frame and moving forward, or after it and moving
10710 // backwards. If we're looking for non-whitespace, we found it (without
10711 // skipping this frame).
10712 if (!aState->mAtStart) {
10713 if (aState->mLastCharWasPunctuation) {
10714 // We're not punctuation, so this is a punctuation boundary.
10715 if (BreakWordBetweenPunctuation(aState, aForward, false, false,
10716 aIsKeyboardSelect)) {
10717 return FOUND;
10718 }
10719 } else {
10720 // This is not a punctuation boundary.
10721 if (aWordSelectEatSpace && aState->mSawBeforeType) {
10722 return FOUND;
10723 }
10724 }
10725 }
10726 // Otherwise skip to the other side and note that we encountered
10727 // non-whitespace.
10728 *aOffset = 1 - startOffset;
10729 aState->Update(false, // not punctuation
10730 false // not whitespace
10731 );
10732 if (!aWordSelectEatSpace) {
10733 aState->SetSawBeforeType();
10734 }
10735 }
10736 return CONTINUE;
10737}
10738
10739// static
10740bool nsIFrame::BreakWordBetweenPunctuation(const PeekWordState* aState,
10741 bool aForward, bool aPunctAfter,
10742 bool aWhitespaceAfter,
10743 bool aIsKeyboardSelect) {
10744 NS_ASSERTION(aPunctAfter != aState->mLastCharWasPunctuation,do { if (!(aPunctAfter != aState->mLastCharWasPunctuation)
) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Call this only at punctuation boundaries"
, "aPunctAfter != aState->mLastCharWasPunctuation", "./../../../layout/generic/nsIFrame.cpp"
, 10745); MOZ_PretendNoReturn(); } } while (0)
10745 "Call this only at punctuation boundaries")do { if (!(aPunctAfter != aState->mLastCharWasPunctuation)
) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Call this only at punctuation boundaries"
, "aPunctAfter != aState->mLastCharWasPunctuation", "./../../../layout/generic/nsIFrame.cpp"
, 10745); MOZ_PretendNoReturn(); } } while (0)
;
10746 if (aState->mLastCharWasWhitespace) {
10747 // We always stop between whitespace and punctuation
10748 return true;
10749 }
10750 if (!StaticPrefs::layout_word_select_stop_at_punctuation()) {
10751 // When this pref is false, we never stop at a punctuation boundary unless
10752 // it's followed by whitespace (in the relevant direction).
10753 return aWhitespaceAfter;
10754 }
10755 if (!aIsKeyboardSelect) {
10756 // mouse caret movement (e.g. word selection) always stops at every
10757 // punctuation boundary
10758 return true;
10759 }
10760 bool afterPunct = aForward ? aState->mLastCharWasPunctuation : aPunctAfter;
10761 if (!afterPunct) {
10762 // keyboard caret movement only stops after punctuation (in content order)
10763 return false;
10764 }
10765 // Stop only if we've seen some non-punctuation since the last whitespace;
10766 // don't stop after punctuation that follows whitespace.
10767 return aState->mSeenNonPunctuationSinceWhitespace;
10768}
10769
10770std::pair<nsIFrame*, nsIFrame*> nsIFrame::GetContainingBlockForLine(
10771 bool aLockScroll) const {
10772 const nsIFrame* parentFrame = this;
10773 const nsIFrame* frame;
10774 while (parentFrame) {
10775 frame = parentFrame;
10776 if (frame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
10777 // if we are searching for a frame that is not in flow we will not find
10778 // it. we must instead look for its placeholder
10779 if (frame->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
10780 // abspos continuations don't have placeholders, get the fif
10781 frame = frame->FirstInFlow();
10782 }
10783 frame = frame->GetPlaceholderFrame();
10784 if (!frame) {
10785 return std::pair(nullptr, nullptr);
10786 }
10787 }
10788 parentFrame = frame->GetParent();
10789 if (parentFrame) {
10790 if (aLockScroll && parentFrame->IsScrollContainerFrame()) {
10791 return std::pair(nullptr, nullptr);
10792 }
10793 if (parentFrame->CanProvideLineIterator()) {
10794 return std::pair(const_cast<nsIFrame*>(parentFrame),
10795 const_cast<nsIFrame*>(frame));
10796 }
10797 }
10798 }
10799 return std::pair(nullptr, nullptr);
10800}
10801
10802Result<bool, nsresult> nsIFrame::IsVisuallyAtLineEdge(
10803 nsILineIterator* aLineIterator, int32_t aLine, nsDirection aDirection) {
10804 auto line = aLineIterator->GetLine(aLine).unwrap();
10805
10806 const bool lineIsRTL = aLineIterator->IsLineIteratorFlowRTL();
10807
10808 nsIFrame *firstFrame = nullptr, *lastFrame = nullptr;
10809 bool isReordered = false;
10810 MOZ_TRY(aLineIterator->CheckLineOrder(aLine, &isReordered, &firstFrame,__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(aLineIterator->CheckLineOrder(aLine, &isReordered, &
firstFrame, &lastFrame)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
10811 &lastFrame))__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(aLineIterator->CheckLineOrder(aLine, &isReordered, &
firstFrame, &lastFrame)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
;
10812 if (!firstFrame || !lastFrame) {
10813 return true; // XXX: Why true? We check whether `this` is at the edge...
10814 }
10815
10816 nsIFrame* leftmostFrame = lineIsRTL ? lastFrame : firstFrame;
10817 nsIFrame* rightmostFrame = lineIsRTL ? firstFrame : lastFrame;
10818 auto FrameIsRTL = [](nsIFrame* aFrame) {
10819 return nsBidiPresUtils::FrameDirection(aFrame) ==
10820 mozilla::intl::BidiDirection::RTL;
10821 };
10822 if (!lineIsRTL == (aDirection == eDirPrevious)) {
10823 nsIFrame* maybeLeftmostFrame = leftmostFrame;
10824 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
10825 if (maybeLeftmostFrame == this) {
10826 return true;
10827 }
10828 // If left edge of the line starts with placeholder frames, we can ignore
10829 // them and should keep checking the following frames.
10830 if (!maybeLeftmostFrame->IsPlaceholderFrame()) {
10831 if ((FrameIsRTL(maybeLeftmostFrame) == lineIsRTL) ==
10832 (aDirection == eDirPrevious)) {
10833 nsIFrame::GetFirstLeaf(&maybeLeftmostFrame);
10834 } else {
10835 nsIFrame::GetLastLeaf(&maybeLeftmostFrame);
10836 }
10837 return maybeLeftmostFrame == this;
10838 }
10839 maybeLeftmostFrame = nsBidiPresUtils::GetFrameToRightOf(
10840 maybeLeftmostFrame, line.mFirstFrameOnLine, line.mNumFramesOnLine);
10841 if (!maybeLeftmostFrame) {
10842 return false;
10843 }
10844 }
10845 return false;
10846 }
10847
10848 nsIFrame* maybeRightmostFrame = rightmostFrame;
10849 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
10850 if (maybeRightmostFrame == this) {
10851 return true;
10852 }
10853 // If the line ends with placehlder frames, we can ignore them and should
10854 // keep checking the preceding frames.
10855 if (!maybeRightmostFrame->IsPlaceholderFrame()) {
10856 if ((FrameIsRTL(maybeRightmostFrame) == lineIsRTL) ==
10857 (aDirection == eDirPrevious)) {
10858 nsIFrame::GetFirstLeaf(&maybeRightmostFrame);
10859 } else {
10860 nsIFrame::GetLastLeaf(&maybeRightmostFrame);
10861 }
10862 return maybeRightmostFrame == this;
10863 }
10864 maybeRightmostFrame = nsBidiPresUtils::GetFrameToLeftOf(
10865 maybeRightmostFrame, line.mFirstFrameOnLine, line.mNumFramesOnLine);
10866 if (!maybeRightmostFrame) {
10867 return false;
10868 }
10869 }
10870 return false;
10871}
10872
10873Result<bool, nsresult> nsIFrame::IsLogicallyAtLineEdge(
10874 nsILineIterator* aLineIterator, int32_t aLine, nsDirection aDirection) {
10875 auto line = aLineIterator->GetLine(aLine).unwrap();
10876 if (!line.mNumFramesOnLine) {
10877 return false;
10878 }
10879 MOZ_ASSERT(line.mFirstFrameOnLine)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(line.mFirstFrameOnLine)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(line.mFirstFrameOnLine))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("line.mFirstFrameOnLine"
, "./../../../layout/generic/nsIFrame.cpp", 10879); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "line.mFirstFrameOnLine" ")"); do { MOZ_CrashSequence
(__null, 10879); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
10880
10881 if (aDirection == eDirPrevious) {
10882 nsIFrame* maybeFirstFrame = line.mFirstFrameOnLine;
10883 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
10884 if (maybeFirstFrame == this) {
10885 return true;
10886 }
10887 // If the line starts with placeholder frames, we can ignore them and
10888 // should keep checking the following frames.
10889 if (!maybeFirstFrame->IsPlaceholderFrame()) {
10890 nsIFrame::GetFirstLeaf(&maybeFirstFrame);
10891 return maybeFirstFrame == this;
10892 }
10893 maybeFirstFrame = maybeFirstFrame->GetNextSibling();
10894 if (!maybeFirstFrame) {
10895 return false;
10896 }
10897 }
10898 return false;
10899 }
10900
10901 // eDirNext
10902 nsIFrame* maybeLastFrame = line.GetLastFrameOnLine();
10903 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
10904 if (maybeLastFrame == this) {
10905 return true;
10906 }
10907 // If the line ends with placehlder frames, we can ignore them and should
10908 // keep checking the preceding frames.
10909 if (!maybeLastFrame->IsPlaceholderFrame()) {
10910 nsIFrame::GetLastLeaf(&maybeLastFrame);
10911 return maybeLastFrame == this;
10912 }
10913 maybeLastFrame = maybeLastFrame->GetPrevSibling();
10914 }
10915 return false;
10916}
10917
10918nsIFrame::SelectablePeekReport nsIFrame::GetFrameFromDirection(
10919 nsDirection aDirection, const PeekOffsetOptions& aOptions,
10920 const Element* aAncestorLimiter) {
10921 SelectablePeekReport result;
10922
10923 nsPresContext* presContext = PresContext();
10924 const bool needsVisualTraversal =
10925 aOptions.contains(PeekOffsetOption::Visual) && presContext->BidiEnabled();
10926 const bool followOofs =
10927 !aOptions.contains(PeekOffsetOption::StopAtPlaceholder);
10928 nsFrameIterator frameIterator(
10929 presContext, this, nsFrameIterator::Type::Leaf, needsVisualTraversal,
10930 aOptions.contains(PeekOffsetOption::StopAtScroller), followOofs,
10931 false, // aSkipPopupChecks
10932 aAncestorLimiter);
10933
10934 // Find the prev/next selectable frame
10935 bool selectable = false;
10936 nsIFrame* traversedFrame = this;
10937 AutoAssertNoDomMutations guard;
10938 const nsFrameSelection* frameSelection =
10939 GetContent() ? GetContent()->GetFrameSelection() : nullptr;
10940 while (!selectable) {
10941 auto [blockFrame, lineFrame] = traversedFrame->GetContainingBlockForLine(
10942 aOptions.contains(PeekOffsetOption::StopAtScroller));
10943 if (!blockFrame) {
10944 return result;
10945 }
10946
10947 nsILineIterator* it = blockFrame->GetLineIterator();
10948 int32_t thisLine = it->FindLineContaining(lineFrame);
10949 if (thisLine < 0) {
10950 return result;
10951 }
10952
10953 bool atLineEdge = MOZ_TRY(__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(needsVisualTraversal ? traversedFrame->IsVisuallyAtLineEdge
(it, thisLine, aDirection) : traversedFrame->IsLogicallyAtLineEdge
(it, thisLine, aDirection)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
10954 needsVisualTraversal__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(needsVisualTraversal ? traversedFrame->IsVisuallyAtLineEdge
(it, thisLine, aDirection) : traversedFrame->IsLogicallyAtLineEdge
(it, thisLine, aDirection)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
10955 ? traversedFrame->IsVisuallyAtLineEdge(it, thisLine, aDirection)__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(needsVisualTraversal ? traversedFrame->IsVisuallyAtLineEdge
(it, thisLine, aDirection) : traversedFrame->IsLogicallyAtLineEdge
(it, thisLine, aDirection)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
10956 : traversedFrame->IsLogicallyAtLineEdge(it, thisLine, aDirection))__extension__({ auto mozTryVarTempResult = ::mozilla::ToResult
(needsVisualTraversal ? traversedFrame->IsVisuallyAtLineEdge
(it, thisLine, aDirection) : traversedFrame->IsLogicallyAtLineEdge
(it, thisLine, aDirection)); if ((__builtin_expect(!!(mozTryVarTempResult
.isErr()), 0))) { return mozTryVarTempResult.propagateErr(); }
mozTryVarTempResult.unwrap(); })
;
10957 if (atLineEdge) {
10958 result.mJumpedLine = true;
10959 if (!aOptions.contains(PeekOffsetOption::JumpLines)) {
10960 return result; // we are done. cannot jump lines
10961 }
10962 int32_t lineToCheckWrap =
10963 aDirection == eDirPrevious ? thisLine - 1 : thisLine;
10964 if (lineToCheckWrap < 0 ||
10965 !it->GetLine(lineToCheckWrap).unwrap().mIsWrapped) {
10966 result.mJumpedHardBreak = true;
10967 }
10968 }
10969
10970 traversedFrame = frameIterator.Traverse(aDirection == eDirNext);
10971 if (!traversedFrame) {
10972 return result;
10973 }
10974
10975 if (aOptions.contains(PeekOffsetOption::StopAtPlaceholder) &&
10976 traversedFrame->IsPlaceholderFrame()) {
10977 // XXX If the placeholder frame does not have meaningful content, the user
10978 // may want to select as a word around the out-of-flow cotent. However,
10979 // non-text frame resets context in nsIFrame::PeekOffsetWord(). Therefore,
10980 // next text frame considers the new word starts from its edge. So, it's
10981 // not enough to implement such behavior with adding a check here whether
10982 // the real frame may change the word with its contents if it were not
10983 // out-of-flow.
10984 result.mFoundPlaceholder = true;
10985 return result;
10986 }
10987
10988 auto IsSelectableFrame = [aAncestorLimiter, aOptions,
10989 frameSelection](const nsIFrame* aFrame) {
10990 if (!aFrame->IsSelectable() || MOZ_UNLIKELY(!aFrame->GetContent())(__builtin_expect(!!(!aFrame->GetContent()), 0))) {
10991 return false;
10992 }
10993 // If the found frame content is managed by different nsFrameSelection, we
10994 // cannot select the frame content with current selection.
10995 if (frameSelection != aFrame->GetContent()->GetFrameSelection()) {
10996 return false;
10997 }
10998 if (MOZ_UNLIKELY(aAncestorLimiter &&(__builtin_expect(!!(aAncestorLimiter && !aAncestorLimiter
->GetPrimaryFrame()), 0))
10999 !aAncestorLimiter->GetPrimaryFrame())(__builtin_expect(!!(aAncestorLimiter && !aAncestorLimiter
->GetPrimaryFrame()), 0))
&&
11000 !aFrame->GetContent()->IsInclusiveFlatTreeDescendantOf(
11001 aAncestorLimiter)) {
11002 return false;
11003 }
11004 return !aOptions.contains(PeekOffsetOption::ForceEditableRegion) ||
11005 aFrame->GetContent()->IsEditable();
11006 };
11007
11008 // Skip br frames, but only if we can select something before hitting the
11009 // end of the line or a non-selectable region.
11010 if (atLineEdge && aDirection == eDirPrevious &&
11011 traversedFrame->IsBrFrame()) {
11012 for (nsIFrame* current = traversedFrame->GetPrevSibling(); current;
11013 current = current->GetPrevSibling()) {
11014 if (!current->IsBlockOutside() && IsSelectableFrame(current)) {
11015 if (!current->IsBrFrame()) {
11016 result.mIgnoredBrFrame = true;
11017 }
11018 break;
11019 }
11020 }
11021 if (result.mIgnoredBrFrame) {
11022 continue;
11023 }
11024 }
11025
11026 selectable = IsSelectableFrame(traversedFrame);
11027 if (MOZ_UNLIKELY(!frameSelection)(__builtin_expect(!!(!frameSelection), 0)) && selectable &&
11028 MOZ_LIKELY(traversedFrame->GetContent())(__builtin_expect(!!(traversedFrame->GetContent()), 1))) {
11029 frameSelection = traversedFrame->GetContent()->GetFrameSelection();
11030 }
11031 if (!selectable) {
11032 if (traversedFrame->IsSelectable()) {
11033 result.mHasSelectableFrame = true;
11034 }
11035 result.mMovedOverNonSelectableText = true;
11036 }
11037 } // while (!selectable)
11038
11039 result.mOffset = (aDirection == eDirNext) ? 0 : -1;
11040
11041 if (aOptions.contains(PeekOffsetOption::Visual) &&
11042 nsBidiPresUtils::IsReversedDirectionFrame(traversedFrame)) {
11043 // The new frame is reverse-direction, go to the other end
11044 result.mOffset = -1 - result.mOffset;
11045 }
11046 result.mFrame = traversedFrame;
11047 return result;
11048}
11049
11050nsIFrame::SelectablePeekReport nsIFrame::GetFrameFromDirection(
11051 const PeekOffsetStruct& aPos) {
11052 return GetFrameFromDirection(aPos.mDirection, aPos.mOptions,
11053 aPos.mAncestorLimiter);
11054}
11055
11056/* virtual */
11057void nsIFrame::ChildIsDirty(nsIFrame* aChild) {
11058 MOZ_ASSERT_UNREACHABLE(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"should never be called on a frame that doesn't " "inherit from nsContainerFrame"
")", "./../../../layout/generic/nsIFrame.cpp", 11060); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { MOZ_CrashSequence
(__null, 11060); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
11059 "should never be called on a frame that doesn't "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"should never be called on a frame that doesn't " "inherit from nsContainerFrame"
")", "./../../../layout/generic/nsIFrame.cpp", 11060); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { MOZ_CrashSequence
(__null, 11060); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
11060 "inherit from nsContainerFrame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"should never be called on a frame that doesn't " "inherit from nsContainerFrame"
")", "./../../../layout/generic/nsIFrame.cpp", 11060); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { MOZ_CrashSequence
(__null, 11060); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
11061}
11062
11063#ifdef ACCESSIBILITY1
11064a11y::AccType nsIFrame::AccessibleType() {
11065 if (IsTableCaption() && !GetRect().IsEmpty()) {
11066 return a11y::eHTMLCaptionType;
11067 }
11068 return a11y::eNoType;
11069}
11070#endif
11071
11072bool nsIFrame::ClearOverflowRects() {
11073 if (mOverflow.mType == OverflowStorageType::None) {
11074 return false;
11075 }
11076 if (mOverflow.mType == OverflowStorageType::Large) {
11077 RemoveProperty(OverflowAreasProperty());
11078 }
11079 mOverflow.mType = OverflowStorageType::None;
11080 return true;
11081}
11082
11083bool nsIFrame::SetOverflowAreas(const OverflowAreas& aOverflowAreas) {
11084 if (mOverflow.mType == OverflowStorageType::Large) {
11085 OverflowAreas* overflow = GetOverflowAreasProperty();
11086 bool changed = *overflow != aOverflowAreas;
11087 *overflow = aOverflowAreas;
11088
11089 // Don't bother with converting to the deltas form if we already
11090 // have a property.
11091 return changed;
11092 }
11093
11094 const nsRect& vis = aOverflowAreas.InkOverflow();
11095 uint32_t l = -vis.x, // left edge: positive delta is leftwards
11096 t = -vis.y, // top: positive is upwards
11097 r = vis.XMost() - mRect.width, // right: positive is rightwards
11098 b = vis.YMost() - mRect.height; // bottom: positive is downwards
11099 if (aOverflowAreas.ScrollableOverflow().IsEqualEdges(
11100 nsRect(nsPoint(0, 0), GetSize())) &&
11101 l <= InkOverflowDeltas::kMax && t <= InkOverflowDeltas::kMax &&
11102 r <= InkOverflowDeltas::kMax && b <= InkOverflowDeltas::kMax &&
11103 // we have to check these against zero because we *never* want to
11104 // set a frame as having no overflow in this function. This is
11105 // because FinishAndStoreOverflow calls this function prior to
11106 // SetRect based on whether the overflow areas match aNewSize.
11107 // In the case where the overflow areas exactly match mRect but
11108 // do not match aNewSize, we need to store overflow in a property
11109 // so that our eventual SetRect/SetSize will know that it has to
11110 // reset our overflow areas.
11111 (l | t | r | b) != 0) {
11112 InkOverflowDeltas oldDeltas = mOverflow.mInkOverflowDeltas;
11113 // It's a "small" overflow area so we store the deltas for each edge
11114 // directly in the frame, rather than allocating a separate rect.
11115 // If they're all zero, that's fine; we're setting things to
11116 // no-overflow.
11117 mOverflow.mInkOverflowDeltas.mLeft = l;
11118 mOverflow.mInkOverflowDeltas.mTop = t;
11119 mOverflow.mInkOverflowDeltas.mRight = r;
11120 mOverflow.mInkOverflowDeltas.mBottom = b;
11121 // There was no scrollable overflow before, and there isn't now.
11122 return oldDeltas != mOverflow.mInkOverflowDeltas;
11123 } else {
11124 bool changed =
11125 !aOverflowAreas.ScrollableOverflow().IsEqualEdges(
11126 nsRect(nsPoint(0, 0), GetSize())) ||
11127 !aOverflowAreas.InkOverflow().IsEqualEdges(InkOverflowFromDeltas());
11128
11129 // it's a large overflow area that we need to store as a property
11130 mOverflow.mType = OverflowStorageType::Large;
11131 AddProperty(OverflowAreasProperty(), new OverflowAreas(aOverflowAreas));
11132 return changed;
11133 }
11134}
11135
11136enum class ApplyTransform : bool { No, Yes };
11137
11138/**
11139 * Compute the outline inner rect (so without outline-width and outline-offset)
11140 * of aFrame, maybe iterating over its descendants, in aFrame's coordinate space
11141 * or its post-transform coordinate space (depending on aApplyTransform).
11142 */
11143static nsRect ComputeOutlineInnerRect(
11144 nsIFrame* aFrame, ApplyTransform aApplyTransform, bool& aOutValid,
11145 const nsSize* aSizeOverride = nullptr,
11146 const OverflowAreas* aOverflowOverride = nullptr) {
11147 const nsRect bounds(nsPoint(0, 0),
11148 aSizeOverride ? *aSizeOverride : aFrame->GetSize());
11149
11150 // The SVG container frames besides SVGTextFrame do not maintain
11151 // an accurate mRect. It will make the outline be larger than
11152 // we expect, we need to make them narrow to their children's outline.
11153 // aOutValid is set to false if the returned nsRect is not valid
11154 // and should not be included in the outline rectangle.
11155 aOutValid = !aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) ||
11156 !aFrame->IsSVGContainerFrame() || aFrame->IsSVGTextFrame();
11157
11158 nsRect u;
11159
11160 if (!aFrame->FrameMaintainsOverflow()) {
11161 return u;
11162 }
11163
11164 // Start from our border-box, transformed. See comment below about
11165 // transform of children.
11166 bool doTransform =
11167 aApplyTransform == ApplyTransform::Yes && aFrame->IsTransformed();
11168 TransformReferenceBox boundsRefBox(nullptr, bounds);
11169 if (doTransform) {
11170 u = nsDisplayTransform::TransformRect(bounds, aFrame, boundsRefBox);
11171 } else {
11172 u = bounds;
11173 }
11174
11175 if (aOutValid && !StaticPrefs::layout_outline_include_overflow()) {
11176 return u;
11177 }
11178
11179 // Only iterate through the children if the overflow areas suggest
11180 // that we might need to, and if the frame doesn't clip its overflow
11181 // anyway.
11182 if (aOverflowOverride) {
11183 if (!doTransform && bounds.IsEqualEdges(aOverflowOverride->InkOverflow()) &&
11184 bounds.IsEqualEdges(aOverflowOverride->ScrollableOverflow())) {
11185 return u;
11186 }
11187 } else {
11188 if (!doTransform && bounds.IsEqualEdges(aFrame->InkOverflowRect()) &&
11189 bounds.IsEqualEdges(aFrame->ScrollableOverflowRect())) {
11190 return u;
11191 }
11192 }
11193 const nsStyleDisplay* disp = aFrame->StyleDisplay();
11194 LayoutFrameType fType = aFrame->Type();
11195 if (fType == LayoutFrameType::ScrollContainer ||
11196 fType == LayoutFrameType::ListControl ||
11197 fType == LayoutFrameType::SVGOuterSVG) {
11198 return u;
11199 }
11200
11201 auto overflowClipAxes = aFrame->ShouldApplyOverflowClipping(disp);
11202 auto overflowClipMargin = aFrame->OverflowClipMargin(
11203 overflowClipAxes, /* aAllowNegative = */ false);
11204 if (overflowClipAxes == kPhysicalAxesBoth && overflowClipMargin.IsAllZero()) {
11205 return u;
11206 }
11207
11208 const nsStyleEffects* effects = aFrame->StyleEffects();
11209 Maybe<nsRect> clipPropClipRect =
11210 aFrame->GetClipPropClipRect(disp, effects, bounds.Size());
11211
11212 // Iterate over all children except pop-up, absolutely-positioned,
11213 // float, and overflow ones.
11214 const FrameChildListIDs skip = {FrameChildListID::Absolute,
11215 FrameChildListID::Float,
11216 FrameChildListID::Overflow};
11217 for (const auto& [list, listID] : aFrame->ChildLists()) {
11218 if (skip.contains(listID)) {
11219 continue;
11220 }
11221
11222 for (nsIFrame* child : list) {
11223 if (child->IsPlaceholderFrame()) {
11224 continue;
11225 }
11226
11227 // Note that passing ApplyTransform::Yes when
11228 // child->Combines3DTransformWithAncestors() returns true is incorrect if
11229 // our aApplyTransform is No... but the opposite would be as well.
11230 // This is because elements within a preserve-3d scene are always
11231 // transformed up to the top of the scene. This means we don't have a
11232 // mechanism for getting a transform up to an intermediate point within
11233 // the scene. We choose to over-transform rather than under-transform
11234 // because this is consistent with other overflow areas.
11235 bool validRect = true;
11236 nsRect childRect =
11237 ComputeOutlineInnerRect(child, ApplyTransform::Yes, validRect) +
11238 child->GetPosition();
11239
11240 if (!validRect) {
11241 continue;
11242 }
11243
11244 if (clipPropClipRect) {
11245 // Intersect with the clip before transforming.
11246 childRect.IntersectRect(childRect, *clipPropClipRect);
11247 }
11248
11249 // Note that we transform each child separately according to
11250 // aFrame's transform, and then union, which gives a different
11251 // (smaller) result from unioning and then transforming the
11252 // union. This doesn't match the way we handle overflow areas
11253 // with 2-D transforms, though it does match the way we handle
11254 // overflow areas in preserve-3d 3-D scenes.
11255 if (doTransform && !child->Combines3DTransformWithAncestors()) {
11256 childRect =
11257 nsDisplayTransform::TransformRect(childRect, aFrame, boundsRefBox);
11258 }
11259
11260 // If a SVGContainer has a non-SVGContainer child, we assign
11261 // its child's outline to this SVGContainer directly.
11262 if (!aOutValid && validRect) {
11263 u = childRect;
11264 aOutValid = true;
11265 } else {
11266 u = u.UnionEdges(childRect);
11267 }
11268 }
11269 }
11270
11271 if (!overflowClipAxes.isEmpty()) {
11272 OverflowAreas::ApplyOverflowClippingOnRect(u, bounds, overflowClipAxes,
11273 overflowClipMargin);
11274 }
11275 return u;
11276}
11277
11278static void ComputeAndIncludeOutlineArea(nsIFrame* aFrame,
11279 OverflowAreas& aOverflowAreas,
11280 const nsSize& aNewSize) {
11281 const nsStyleOutline* outline = aFrame->StyleOutline();
11282 if (!outline->ShouldPaintOutline()) {
11283 return;
11284 }
11285
11286 // When the outline property is set on a :-moz-block-inside-inline-wrapper
11287 // pseudo-element, it inherited that outline from the inline that was broken
11288 // because it contained a block. In that case, we don't want a really wide
11289 // outline if the block inside the inline is narrow, so union the actual
11290 // contents of the anonymous blocks.
11291 nsIFrame* frameForArea = aFrame;
11292 do {
11293 PseudoStyleType pseudoType = frameForArea->Style()->GetPseudoType();
11294 if (pseudoType != PseudoStyleType::MozBlockInsideInlineWrapper) {
11295 break;
11296 }
11297 // If we're done, we really want it and all its later siblings.
11298 frameForArea = frameForArea->PrincipalChildList().FirstChild();
11299 NS_ASSERTION(frameForArea, "anonymous block with no children?")do { if (!(frameForArea)) { NS_DebugBreak(NS_DEBUG_ASSERTION,
"anonymous block with no children?", "frameForArea", "./../../../layout/generic/nsIFrame.cpp"
, 11299); MOZ_PretendNoReturn(); } } while (0)
;
11300 } while (frameForArea);
11301
11302 // Find the union of the border boxes of all descendants, or in
11303 // the block-in-inline case, all descendants we care about.
11304 //
11305 // Note that the interesting perspective-related cases are taken
11306 // care of by the code that handles those issues for overflow
11307 // calling FinishAndStoreOverflow again, which in turn calls this
11308 // function again. We still need to deal with preserve-3d a bit.
11309 nsRect innerRect;
11310 bool validRect = false;
11311 if (frameForArea == aFrame) {
11312 innerRect = ComputeOutlineInnerRect(aFrame, ApplyTransform::No, validRect,
11313 &aNewSize, &aOverflowAreas);
11314 } else {
11315 for (; frameForArea; frameForArea = frameForArea->GetNextSibling()) {
11316 nsRect r =
11317 ComputeOutlineInnerRect(frameForArea, ApplyTransform::Yes, validRect);
11318
11319 // Adjust for offsets transforms up to aFrame's pre-transform
11320 // (i.e., normal) coordinate space; see comments in
11321 // UnionBorderBoxes for some of the subtlety here.
11322 for (nsIFrame *f = frameForArea, *parent = f->GetParent();
11323 /* see middle of loop */; f = parent, parent = f->GetParent()) {
11324 r += f->GetPosition();
11325 if (parent == aFrame) {
11326 break;
11327 }
11328 if (parent->IsTransformed() && !f->Combines3DTransformWithAncestors()) {
11329 TransformReferenceBox refBox(parent);
11330 r = nsDisplayTransform::TransformRect(r, parent, refBox);
11331 }
11332 }
11333
11334 innerRect.UnionRect(innerRect, r);
11335 }
11336 }
11337
11338 // Keep this code in sync with nsDisplayOutline::GetInnerRect.
11339 if (innerRect == aFrame->GetRectRelativeToSelf()) {
11340 aFrame->RemoveProperty(nsIFrame::OutlineInnerRectProperty());
11341 } else {
11342 aFrame->SetOrUpdateDeletableProperty(nsIFrame::OutlineInnerRectProperty(),
11343 innerRect);
11344 }
11345
11346 nsRect outerRect(innerRect);
11347 outerRect.Inflate(outline->EffectiveOffsetFor(outerRect));
11348
11349 if (outline->mOutlineStyle.IsAuto()) {
11350 nsPresContext* pc = aFrame->PresContext();
11351
11352 pc->Theme()->GetWidgetOverflow(pc->DeviceContext(), aFrame,
11353 StyleAppearance::FocusOutline, &outerRect);
11354 } else {
11355 outerRect.Inflate(outline->mOutlineWidth);
11356 }
11357
11358 nsRect& vo = aOverflowAreas.InkOverflow();
11359 vo = vo.UnionEdges(innerRect.Union(outerRect));
11360}
11361
11362bool nsIFrame::FinishAndStoreOverflow(OverflowAreas& aOverflowAreas,
11363 nsSize aNewSize,
11364 const nsStyleDisplay* aStyleDisplay) {
11365 MOZ_ASSERT(FrameMaintainsOverflow(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(FrameMaintainsOverflow())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(FrameMaintainsOverflow()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("FrameMaintainsOverflow()"
" (" "Don't call - overflow rects not maintained on these SVG frames"
")", "./../../../layout/generic/nsIFrame.cpp", 11366); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "FrameMaintainsOverflow()" ") (" "Don't call - overflow rects not maintained on these SVG frames"
")"); do { MOZ_CrashSequence(__null, 11366); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
11366 "Don't call - overflow rects not maintained on these SVG frames")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(FrameMaintainsOverflow())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(FrameMaintainsOverflow()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("FrameMaintainsOverflow()"
" (" "Don't call - overflow rects not maintained on these SVG frames"
")", "./../../../layout/generic/nsIFrame.cpp", 11366); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "FrameMaintainsOverflow()" ") (" "Don't call - overflow rects not maintained on these SVG frames"
")"); do { MOZ_CrashSequence(__null, 11366); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11367
11368 const nsStyleDisplay* disp = StyleDisplayWithOptionalParam(aStyleDisplay);
11369 bool hasTransform = IsTransformed();
11370
11371 nsRect bounds(nsPoint(), aNewSize);
11372 // Store the passed in overflow area if we are a preserve-3d frame or we have
11373 // a transform, and it's not just the frame bounds.
11374 if (hasTransform || Combines3DTransformWithAncestors()) {
11375 if (!aOverflowAreas.InkOverflow().IsEqualEdges(bounds) ||
11376 !aOverflowAreas.ScrollableOverflow().IsEqualEdges(bounds)) {
11377 SetOrUpdateDeletableProperty(nsIFrame::InitialOverflowProperty(),
11378 aOverflowAreas);
11379 } else {
11380 RemoveProperty(nsIFrame::InitialOverflowProperty());
11381 }
11382#ifdef DEBUG1
11383 SetProperty(nsIFrame::DebugInitialOverflowPropertyApplied(), true);
11384#endif
11385 } else {
11386#ifdef DEBUG1
11387 RemoveProperty(nsIFrame::DebugInitialOverflowPropertyApplied());
11388#endif
11389 }
11390
11391 const nsSize oldSize = mRect.Size();
11392 const bool sizeChanged = oldSize != aNewSize;
11393
11394 // Our frame size may not have been computed and set yet, but code under
11395 // functions such as ComputeEffectsRect (which we're about to call) use the
11396 // values that are stored in our frame rect to compute their results. We
11397 // need the results from those functions to be based on the frame size that
11398 // we *will* have, so we temporarily set our frame size here before calling
11399 // those functions.
11400 //
11401 // XXX Someone should document here why we revert the frame size before we
11402 // return rather than just leaving it set.
11403 //
11404 // We pass false here to avoid invalidating display items for this temporary
11405 // change. We sometimes reflow frames multiple times, with the final size
11406 // being the same as the initial. The single call to SetSize after reflow is
11407 // done will take care of invalidating display items if the size has actually
11408 // changed.
11409 SetSize(aNewSize, false);
11410
11411 if (sizeChanged && ChildrenHavePerspective(disp) &&
11412 RecomputePerspectiveChildrenOverflow(this)) {
11413 aOverflowAreas.SetAllTo(bounds);
11414 DebugOnly<bool> ok = ComputeCustomOverflow(aOverflowAreas);
11415 // ComputeCustomOverflow() should not return false, when
11416 // FrameMaintainsOverflow() returns true.
11417 MOZ_ASSERT(ok, "FrameMaintainsOverflow() != ComputeCustomOverflow()")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(ok)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(ok))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("ok" " (" "FrameMaintainsOverflow() != ComputeCustomOverflow()"
")", "./../../../layout/generic/nsIFrame.cpp", 11417); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "ok" ") (" "FrameMaintainsOverflow() != ComputeCustomOverflow()"
")"); do { MOZ_CrashSequence(__null, 11417); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11418 UnionChildOverflow(aOverflowAreas);
11419 }
11420
11421 const auto overflowClipAxes = ShouldApplyOverflowClipping(disp);
11422
11423 // This is now called FinishAndStoreOverflow() instead of
11424 // StoreOverflow() because frame-generic ways of adding overflow
11425 // can happen here, e.g. CSS2 outline and native theme.
11426 // If the overflow area width or height is nscoord_MAX, then a saturating
11427 // union may have encountered an overflow, so the overflow may not contain the
11428 // frame border-box. Don't warn in that case.
11429 // Don't warn for SVG either, since SVG doesn't need the overflow area
11430 // to contain the frame bounds.
11431#ifdef DEBUG1
11432 for (const auto otype : AllOverflowTypes()) {
11433 const nsRect& r = aOverflowAreas.Overflow(otype);
11434 NS_ASSERTION(aNewSize.width == 0 || aNewSize.height == 0 ||do { if (!(aNewSize.width == 0 || aNewSize.height == 0 || r.width
== nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits
(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize
)))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Computed overflow area must contain frame bounds"
, "aNewSize.width == 0 || aNewSize.height == 0 || r.width == nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize))"
, "./../../../layout/generic/nsIFrame.cpp", 11438); MOZ_PretendNoReturn
(); } } while (0)
11435 r.width == nscoord_MAX || r.height == nscoord_MAX ||do { if (!(aNewSize.width == 0 || aNewSize.height == 0 || r.width
== nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits
(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize
)))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Computed overflow area must contain frame bounds"
, "aNewSize.width == 0 || aNewSize.height == 0 || r.width == nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize))"
, "./../../../layout/generic/nsIFrame.cpp", 11438); MOZ_PretendNoReturn
(); } } while (0)
11436 HasAnyStateBits(NS_FRAME_SVG_LAYOUT) ||do { if (!(aNewSize.width == 0 || aNewSize.height == 0 || r.width
== nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits
(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize
)))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Computed overflow area must contain frame bounds"
, "aNewSize.width == 0 || aNewSize.height == 0 || r.width == nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize))"
, "./../../../layout/generic/nsIFrame.cpp", 11438); MOZ_PretendNoReturn
(); } } while (0)
11437 r.Contains(nsRect(nsPoint(), aNewSize)),do { if (!(aNewSize.width == 0 || aNewSize.height == 0 || r.width
== nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits
(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize
)))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Computed overflow area must contain frame bounds"
, "aNewSize.width == 0 || aNewSize.height == 0 || r.width == nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize))"
, "./../../../layout/generic/nsIFrame.cpp", 11438); MOZ_PretendNoReturn
(); } } while (0)
11438 "Computed overflow area must contain frame bounds")do { if (!(aNewSize.width == 0 || aNewSize.height == 0 || r.width
== nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits
(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize
)))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Computed overflow area must contain frame bounds"
, "aNewSize.width == 0 || aNewSize.height == 0 || r.width == nscoord_MAX || r.height == nscoord_MAX || HasAnyStateBits(NS_FRAME_SVG_LAYOUT) || r.Contains(nsRect(nsPoint(), aNewSize))"
, "./../../../layout/generic/nsIFrame.cpp", 11438); MOZ_PretendNoReturn
(); } } while (0)
;
11439 }
11440#endif
11441
11442 // Overflow area must always include the frame's top-left and bottom-right,
11443 // even if the frame rect is empty (so we can scroll to those positions).
11444 const bool shouldIncludeBounds = [&] {
11445 if (aNewSize.width == 0 && IsInlineFrame()) {
11446 // Pending a real fix for bug 426879, don't do this for inline frames with
11447 // zero width.
11448 return false;
11449 }
11450 if (HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
11451 // Do not do this for SVG either, since it will usually massively increase
11452 // the area unnecessarily (except for SVG that applies clipping, since
11453 // that's the pre-existing behavior, and breaks pre-rendering otherwise).
11454 // FIXME(bug 1770704): This check most likely wants to be removed or check
11455 // for specific frame types at least.
11456 return !overflowClipAxes.isEmpty();
11457 }
11458 return true;
11459 }();
11460
11461 if (shouldIncludeBounds) {
11462 for (const auto otype : AllOverflowTypes()) {
11463 nsRect& o = aOverflowAreas.Overflow(otype);
11464 o = o.UnionEdges(bounds);
11465 }
11466 }
11467
11468 // If we clip our children, clear accumulated overflow area in the affected
11469 // dimension(s). The children are actually clipped to the padding-box, but
11470 // since the overflow area should include the entire border-box, just set it
11471 // to the border-box size here.
11472 if (!overflowClipAxes.isEmpty()) {
11473 aOverflowAreas.ApplyClipping(
11474 bounds, overflowClipAxes,
11475 OverflowClipMargin(overflowClipAxes, /* aAllowNegative = */ false));
11476 }
11477
11478 ComputeAndIncludeOutlineArea(this, aOverflowAreas, aNewSize);
11479
11480 // Nothing in here should affect scrollable overflow.
11481 aOverflowAreas.InkOverflow() =
11482 ComputeEffectsRect(this, aOverflowAreas.InkOverflow(), aNewSize);
11483
11484 // Absolute position clipping
11485 const nsStyleEffects* effects = StyleEffects();
11486 Maybe<nsRect> clipPropClipRect = GetClipPropClipRect(disp, effects, aNewSize);
11487 if (clipPropClipRect) {
11488 for (const auto otype : AllOverflowTypes()) {
11489 nsRect& o = aOverflowAreas.Overflow(otype);
11490 o.IntersectRect(o, *clipPropClipRect);
11491 }
11492 }
11493
11494 /* If we're transformed, transform the overflow rect by the current
11495 * transformation. */
11496 if (hasTransform) {
11497 SetProperty(nsIFrame::PreTransformOverflowAreasProperty(),
11498 new OverflowAreas(aOverflowAreas));
11499
11500 if (Combines3DTransformWithAncestors()) {
11501 /* If we're a preserve-3d leaf frame, then our pre-transform overflow
11502 * should be correct. Our post-transform overflow is empty though, because
11503 * we only contribute to the overflow area of the preserve-3d root frame.
11504 * If we're an intermediate frame then the pre-transform overflow should
11505 * contain all our non-preserve-3d children, which is what we want. Again
11506 * we have no post-transform overflow.
11507 */
11508 aOverflowAreas.SetAllTo(nsRect());
11509 } else {
11510 TransformReferenceBox refBox(this);
11511 for (const auto otype : AllOverflowTypes()) {
11512 nsRect& o = aOverflowAreas.Overflow(otype);
11513 // If the overflow is empty, it can still have a non-zero length in one
11514 // axis. Transforming such axis-bound rect can cause the resulting rect
11515 // to be non-empty, e.g. by rotating the rect.
11516 if (!o.IsEmpty()) {
11517 o = nsDisplayTransform::TransformRect(o, this, refBox);
11518 }
11519 }
11520
11521 /* If we're the root of the 3d context, then we want to include the
11522 * overflow areas of all the participants. This won't have happened yet as
11523 * the code above set their overflow area to empty. Manually collect these
11524 * overflow areas now.
11525 */
11526 if (Extend3DContext(disp, effects)) {
11527 ComputePreserve3DChildrenOverflow(aOverflowAreas);
11528 }
11529 }
11530 } else {
11531 RemoveProperty(nsIFrame::PreTransformOverflowAreasProperty());
11532 }
11533
11534 /* Revert the size change in case some caller is depending on this. */
11535 SetSize(oldSize, false);
11536
11537 bool anyOverflowChanged;
11538 if (aOverflowAreas != OverflowAreas(bounds, bounds)) {
11539 anyOverflowChanged = SetOverflowAreas(aOverflowAreas);
11540 } else {
11541 anyOverflowChanged = ClearOverflowRects();
11542 }
11543
11544 if (anyOverflowChanged) {
11545 SVGObserverUtils::InvalidateDirectRenderingObservers(this);
11546 if (nsBlockFrame* block = do_QueryFrame(this)) {
11547 // NOTE(emilio): we need to use BeforeReflow::Yes, because we want to
11548 // invalidate in cases where we _used_ to have an overflow marker and no
11549 // longer do.
11550 if (TextOverflow::CanHaveOverflowMarkers(
11551 block, TextOverflow::BeforeReflow::Yes)) {
11552 DiscardDisplayItems(this, [](nsDisplayItem* aItem) {
11553 return aItem->GetType() == DisplayItemType::TYPE_TEXT_OVERFLOW;
11554 });
11555 SchedulePaint(PAINT_DEFAULT);
11556 }
11557 }
11558 }
11559 return anyOverflowChanged;
11560}
11561
11562bool nsIFrame::RecomputePerspectiveChildrenOverflow(
11563 const nsIFrame* aStartFrame) {
11564 bool changed = false;
11565 for (const auto& childList : ChildLists()) {
11566 for (nsIFrame* child : childList.mList) {
11567 if (!child->FrameMaintainsOverflow()) {
11568 continue; // frame does not maintain overflow rects
11569 }
11570 if (child->HasPerspective()) {
11571 OverflowAreas* initialOverflow =
11572 child->GetProperty(nsIFrame::InitialOverflowProperty());
11573 const nsRect bounds(nsPoint(), child->GetSize());
11574 OverflowAreas overflow;
11575 if (initialOverflow) {
11576 overflow = *initialOverflow;
11577 } else {
11578 overflow.SetAllTo(bounds);
11579 }
11580 changed |= child->FinishAndStoreOverflow(overflow, bounds.Size());
11581 } else if (child->GetContent() == aStartFrame->GetContent() ||
11582 child->GetClosestFlattenedTreeAncestorPrimaryFrame() ==
11583 aStartFrame) {
11584 // If a frame is using perspective, then the size used to compute
11585 // perspective-origin is the size of the frame belonging to its parent
11586 // style. We must find any descendant frames using our size
11587 // (by recursing into frames that have the same containing block)
11588 // to update their overflow rects too.
11589 if (child->RecomputePerspectiveChildrenOverflow(aStartFrame)) {
11590 changed = true;
11591 // Update the overflow for the child to take any changes from its
11592 // children into account.
11593 child->UpdateOverflow();
11594 }
11595 }
11596 }
11597 }
11598 return changed;
11599}
11600
11601void nsIFrame::ComputePreserve3DChildrenOverflow(
11602 OverflowAreas& aOverflowAreas) {
11603 // Find all descendants that participate in the 3d context, and include their
11604 // overflow. These descendants have an empty overflow, so won't have been
11605 // included in the normal overflow calculation. Any children that don't
11606 // participate have normal overflow, so will have been included already.
11607
11608 for (const auto& childList : ChildLists()) {
11609 for (nsIFrame* child : childList.mList) {
11610 // If this child participates in the 3d context, then take the
11611 // pre-transform region (which contains all descendants that aren't
11612 // participating in the 3d context) and transform it into the 3d context
11613 // root coordinate space.
11614 if (child->Combines3DTransformWithAncestors()) {
11615 OverflowAreas childOverflow = child->GetOverflowAreasRelativeToSelf();
11616 TransformReferenceBox refBox(child);
11617 for (const auto otype : AllOverflowTypes()) {
11618 nsRect& o = childOverflow.Overflow(otype);
11619 o = nsDisplayTransform::TransformRect(o, child, refBox);
11620 }
11621
11622 aOverflowAreas.UnionWith(childOverflow);
11623
11624 // If this child also extends the 3d context, then recurse into it
11625 // looking for more participants.
11626 if (child->Extend3DContext()) {
11627 child->ComputePreserve3DChildrenOverflow(aOverflowAreas);
11628 }
11629 }
11630 }
11631 }
11632}
11633
11634bool nsIFrame::ZIndexApplies() const {
11635 return StyleDisplay()->IsPositionedStyle() || IsFlexOrGridItem() ||
11636 IsMenuPopupFrame();
11637}
11638
11639Maybe<int32_t> nsIFrame::ZIndex() const {
11640 if (!ZIndexApplies()) {
11641 return Nothing();
11642 }
11643 const auto& zIndex = StylePosition()->mZIndex;
11644 if (zIndex.IsAuto()) {
11645 return Nothing();
11646 }
11647 return Some(zIndex.AsInteger());
11648}
11649
11650bool nsIFrame::IsScrollAnchor(ScrollAnchorContainer** aOutContainer) {
11651 if (!mInScrollAnchorChain) {
11652 return false;
11653 }
11654
11655 nsIFrame* f = this;
11656
11657 // FIXME(emilio, bug 1629280): We should find a non-null anchor if we have the
11658 // flag set, but bug 1629280 makes it so that we cannot really assert it /
11659 // make this just a `while (true)`, and uncomment the below assertion.
11660 while (auto* container = ScrollAnchorContainer::FindFor(f)) {
11661 // MOZ_ASSERT(f->IsInScrollAnchorChain());
11662 if (nsIFrame* anchor = container->AnchorNode()) {
11663 if (anchor != this) {
11664 return false;
11665 }
11666 if (aOutContainer) {
11667 *aOutContainer = container;
11668 }
11669 return true;
11670 }
11671
11672 f = container->Frame();
11673 }
11674
11675 return false;
11676}
11677
11678bool nsIFrame::IsInScrollAnchorChain() const { return mInScrollAnchorChain; }
11679
11680void nsIFrame::SetInScrollAnchorChain(bool aInChain) {
11681 mInScrollAnchorChain = aInChain;
11682}
11683
11684uint32_t nsIFrame::GetDepthInFrameTree() const {
11685 uint32_t result = 0;
11686 for (nsContainerFrame* ancestor = GetParent(); ancestor;
11687 ancestor = ancestor->GetParent()) {
11688 result++;
11689 }
11690 return result;
11691}
11692
11693/**
11694 * This function takes a frame that is part of a block-in-inline split,
11695 * and _if_ that frame is an anonymous block created by an ib split it
11696 * returns the block's preceding inline. This is needed because the
11697 * split inline's style is the parent of the anonymous block's style.
11698 *
11699 * If aFrame is not an anonymous block, null is returned.
11700 */
11701static nsIFrame* GetIBSplitSiblingForAnonymousBlock(const nsIFrame* aFrame) {
11702 MOZ_ASSERT(aFrame, "Must have a non-null frame!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aFrame))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aFrame" " (" "Must have a non-null frame!"
")", "./../../../layout/generic/nsIFrame.cpp", 11702); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aFrame" ") (" "Must have a non-null frame!"
")"); do { MOZ_CrashSequence(__null, 11702); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11703 NS_ASSERTION(aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT),do { if (!(aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "GetIBSplitSibling should only be called on ib-split frames"
, "aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)", "./../../../layout/generic/nsIFrame.cpp"
, 11704); MOZ_PretendNoReturn(); } } while (0)
11704 "GetIBSplitSibling should only be called on ib-split frames")do { if (!(aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "GetIBSplitSibling should only be called on ib-split frames"
, "aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)", "./../../../layout/generic/nsIFrame.cpp"
, 11704); MOZ_PretendNoReturn(); } } while (0)
;
11705
11706 if (aFrame->Style()->GetPseudoType() !=
11707 PseudoStyleType::MozBlockInsideInlineWrapper) {
11708 // it's not an anonymous block
11709 return nullptr;
11710 }
11711
11712 // Find the first continuation of the frame. (Ugh. This ends up
11713 // being O(N^2) when it is called O(N) times.)
11714 aFrame = aFrame->FirstContinuation();
11715
11716 /*
11717 * Now look up the nsGkAtoms::IBSplitPrevSibling
11718 * property.
11719 */
11720 nsIFrame* ibSplitSibling =
11721 aFrame->GetProperty(nsIFrame::IBSplitPrevSibling());
11722 NS_ASSERTION(ibSplitSibling, "Broken frame tree?")do { if (!(ibSplitSibling)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Broken frame tree?", "ibSplitSibling", "./../../../layout/generic/nsIFrame.cpp"
, 11722); MOZ_PretendNoReturn(); } } while (0)
;
11723 return ibSplitSibling;
11724}
11725
11726/**
11727 * Get the parent, corrected for the mangled frame tree resulting from
11728 * having a block within an inline. The result only differs from the
11729 * result of |GetParent| when |GetParent| returns an anonymous block
11730 * that was created for an element that was 'display: inline' because
11731 * that element contained a block.
11732 *
11733 * Also skip anonymous scrolled-content parents; inherit directly from the
11734 * outer scroll frame.
11735 *
11736 * Also skip NAC parents if the child frame is NAC.
11737 */
11738static nsIFrame* GetCorrectedParent(const nsIFrame* aFrame) {
11739 nsIFrame* parent = aFrame->GetParent();
11740 if (!parent) {
11741 return nullptr;
11742 }
11743
11744 // For a table caption we want the _inner_ table frame (unless it's anonymous)
11745 // as the style parent.
11746 if (aFrame->IsTableCaption()) {
11747 MOZ_ASSERT(parent->IsTableWrapperFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->IsTableWrapperFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(parent->IsTableWrapperFrame
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->IsTableWrapperFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 11747); AnnotateMozCrashReason("MOZ_ASSERT" "(" "parent->IsTableWrapperFrame()"
")"); do { MOZ_CrashSequence(__null, 11747); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11748 nsTableFrame* innerTable =
11749 static_cast<const nsTableWrapperFrame*>(parent)->InnerTableFrame();
11750 if (!innerTable->Style()->IsAnonBox()) {
11751 return innerTable;
11752 }
11753 }
11754
11755 // Table wrappers are always anon boxes; if we're in here for an outer
11756 // table, that actually means its the _inner_ table that wants to
11757 // know its parent. So get the pseudo of the inner in that case.
11758 auto pseudo = aFrame->Style()->GetPseudoType();
11759 if (pseudo == PseudoStyleType::MozTableWrapper) {
11760 MOZ_ASSERT(aFrame->IsTableWrapperFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->IsTableWrapperFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aFrame->IsTableWrapperFrame
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->IsTableWrapperFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 11760); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->IsTableWrapperFrame()"
")"); do { MOZ_CrashSequence(__null, 11760); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11761 nsTableFrame* innerTable =
11762 static_cast<const nsTableWrapperFrame*>(aFrame)->InnerTableFrame();
11763 pseudo = innerTable->Style()->GetPseudoType();
11764 }
11765
11766 // Prevent a NAC pseudo-element from inheriting from its NAC parent, and
11767 // inherit from the NAC generator element instead. (We exclude element-backed
11768 // pseudos from this check, since they're not NAC.)
11769 if (pseudo != PseudoStyleType::NotPseudo &&
11770 !PseudoStyle::IsElementBackedPseudo(pseudo)) {
11771 MOZ_ASSERT(aFrame->GetContent())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->GetContent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aFrame->GetContent()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("aFrame->GetContent()"
, "./../../../layout/generic/nsIFrame.cpp", 11771); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "aFrame->GetContent()" ")"); do { MOZ_CrashSequence
(__null, 11771); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
11772 Element* element = Element::FromNode(aFrame->GetContent());
11773 // Make sure to only do the fixup for anonymous content pseudos (i.e. avoid
11774 // fixup for ::first-line and such).
11775 if (element && !element->IsRootOfNativeAnonymousSubtree() &&
11776 element->GetPseudoElementType() == aFrame->Style()->GetPseudoType()) {
11777 while (parent->GetContent() &&
11778 !parent->GetContent()->IsRootOfNativeAnonymousSubtree()) {
11779 parent = parent->GetInFlowParent();
11780 }
11781 parent = parent->GetInFlowParent();
11782 }
11783 }
11784
11785 return nsIFrame::CorrectStyleParentFrame(parent, pseudo);
11786}
11787
11788/* static */
11789nsIFrame* nsIFrame::CorrectStyleParentFrame(nsIFrame* aProspectiveParent,
11790 PseudoStyleType aChildPseudo) {
11791 MOZ_ASSERT(aProspectiveParent, "Must have a prospective parent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aProspectiveParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aProspectiveParent))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aProspectiveParent"
" (" "Must have a prospective parent" ")", "./../../../layout/generic/nsIFrame.cpp"
, 11791); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aProspectiveParent"
") (" "Must have a prospective parent" ")"); do { MOZ_CrashSequence
(__null, 11791); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
11792
11793 if (aChildPseudo < PseudoStyleType::NotPseudo) {
11794 // Non-inheriting anon boxes have no style parent frame at all.
11795 if (PseudoStyle::IsNonInheritingAnonBox(aChildPseudo)) {
11796 return nullptr;
11797 }
11798
11799 // Other anon boxes are parented to their actual parent already, except
11800 // for non-elements. Those should not be treated as an anon box.
11801 if (PseudoStyle::IsAnonBox(aChildPseudo) &&
11802 !PseudoStyle::IsNonElement(aChildPseudo)) {
11803 NS_ASSERTION(aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper,do { if (!(aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have dealt with kids that have "
"NS_FRAME_PART_OF_IBSPLIT elsewhere", "aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper"
, "./../../../layout/generic/nsIFrame.cpp", 11805); MOZ_PretendNoReturn
(); } } while (0)
11804 "Should have dealt with kids that have "do { if (!(aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have dealt with kids that have "
"NS_FRAME_PART_OF_IBSPLIT elsewhere", "aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper"
, "./../../../layout/generic/nsIFrame.cpp", 11805); MOZ_PretendNoReturn
(); } } while (0)
11805 "NS_FRAME_PART_OF_IBSPLIT elsewhere")do { if (!(aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have dealt with kids that have "
"NS_FRAME_PART_OF_IBSPLIT elsewhere", "aChildPseudo != PseudoStyleType::MozBlockInsideInlineWrapper"
, "./../../../layout/generic/nsIFrame.cpp", 11805); MOZ_PretendNoReturn
(); } } while (0)
;
11806 return aProspectiveParent;
11807 }
11808 }
11809
11810 // Otherwise, walk up out of all anon boxes. For placeholder frames, walk out
11811 // of all pseudo-elements as well. Otherwise ReparentComputedStyle could
11812 // cause style data to be out of sync with the frame tree.
11813 nsIFrame* parent = aProspectiveParent;
11814 do {
11815 if (parent->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
11816 nsIFrame* sibling = GetIBSplitSiblingForAnonymousBlock(parent);
11817
11818 if (sibling) {
11819 // |parent| was a block in an {ib} split; use the inline as
11820 // |the style parent.
11821 parent = sibling;
11822 }
11823 }
11824
11825 if (!parent->Style()->IsPseudoOrAnonBox()) {
11826 return parent;
11827 }
11828
11829 if (!parent->Style()->IsAnonBox() && aChildPseudo != PseudoStyleType::MAX) {
11830 // nsPlaceholderFrame passes in PseudoStyleType::MAX for
11831 // aChildPseudo (even though that's not a valid pseudo-type) just to
11832 // trigger this behavior of walking up to the nearest non-pseudo
11833 // ancestor.
11834 return parent;
11835 }
11836
11837 parent = parent->GetInFlowParent();
11838 } while (parent);
11839
11840 if (aProspectiveParent->Style()->GetPseudoType() ==
11841 PseudoStyleType::MozViewportScroll) {
11842 // aProspectiveParent is the scrollframe for a viewport
11843 // and the kids are the anonymous scrollbars
11844 return aProspectiveParent;
11845 }
11846
11847 // We can get here if the root element is absolutely positioned.
11848 // We can't test for this very accurately, but it can only happen
11849 // when the prospective parent is a canvas frame.
11850 NS_ASSERTION(aProspectiveParent->IsCanvasFrame(),do { if (!(aProspectiveParent->IsCanvasFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Should have found a parent before this"
, "aProspectiveParent->IsCanvasFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 11851); MOZ_PretendNoReturn(); } } while (0)
11851 "Should have found a parent before this")do { if (!(aProspectiveParent->IsCanvasFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Should have found a parent before this"
, "aProspectiveParent->IsCanvasFrame()", "./../../../layout/generic/nsIFrame.cpp"
, 11851); MOZ_PretendNoReturn(); } } while (0)
;
11852 return nullptr;
11853}
11854
11855ComputedStyle* nsIFrame::DoGetParentComputedStyle(
11856 nsIFrame** aProviderFrame) const {
11857 *aProviderFrame = nullptr;
11858
11859 // Handle display:contents and the root frame, when there's no parent frame
11860 // to inherit from.
11861 if (MOZ_LIKELY(mContent)(__builtin_expect(!!(mContent), 1))) {
11862 Element* parentElement = mContent->GetFlattenedTreeParentElement();
11863 if (MOZ_LIKELY(parentElement)(__builtin_expect(!!(parentElement), 1))) {
11864 auto pseudo = Style()->GetPseudoType();
11865 if (pseudo == PseudoStyleType::NotPseudo || !mContent->IsElement() ||
11866 (!PseudoStyle::IsAnonBox(pseudo) &&
11867 // Ensure that we don't return the display:contents style
11868 // of the parent content for pseudos that have the same content
11869 // as their primary frame (like -moz-list-bullets do):
11870 IsPrimaryFrame()) ||
11871 /* if next is true then it's really a request for the table frame's
11872 parent context, see nsTable[Outer]Frame::GetParentComputedStyle. */
11873 pseudo == PseudoStyleType::MozTableWrapper) {
11874 // In some edge cases involving display: contents, we may end up here
11875 // for something that's pending to be reframed. In this case we return
11876 // the wrong style from here (because we've already lost track of it!),
11877 // but it's not a big deal as we're going to be reframed anyway.
11878 if (MOZ_LIKELY(parentElement->HasServoData())(__builtin_expect(!!(parentElement->HasServoData()), 1)) &&
11879 Servo_Element_IsDisplayContents(parentElement)) {
11880 RefPtr<ComputedStyle> style =
11881 ServoStyleSet::ResolveServoStyle(*parentElement);
11882 // NOTE(emilio): we return a weak reference because the element also
11883 // holds the style context alive. This is a bit silly (we could've
11884 // returned a weak ref directly), but it's probably not worth
11885 // optimizing, given this function has just one caller which is rare,
11886 // and this path is rare itself.
11887 return style;
11888 }
11889 }
11890 } else {
11891 if (Style()->GetPseudoType() == PseudoStyleType::NotPseudo) {
11892 // We're a frame for the root. We have no style parent.
11893 return nullptr;
11894 }
11895 }
11896 }
11897
11898 if (!HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
11899 /*
11900 * If this frame is an anonymous block created when an inline with a block
11901 * inside it got split, then the parent style is on its preceding inline. We
11902 * can get to it using GetIBSplitSiblingForAnonymousBlock.
11903 */
11904 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
11905 nsIFrame* ibSplitSibling = GetIBSplitSiblingForAnonymousBlock(this);
11906 if (ibSplitSibling) {
11907 return (*aProviderFrame = ibSplitSibling)->Style();
11908 }
11909 }
11910
11911 // If this frame is one of the blocks that split an inline, we must
11912 // return the "special" inline parent, i.e., the parent that this
11913 // frame would have if we didn't mangle the frame structure.
11914 *aProviderFrame = GetCorrectedParent(this);
11915 return *aProviderFrame ? (*aProviderFrame)->Style() : nullptr;
11916 }
11917
11918 // We're an out-of-flow frame. For out-of-flow frames, we must
11919 // resolve underneath the placeholder's parent. The placeholder is
11920 // reached from the first-in-flow.
11921 nsPlaceholderFrame* placeholder = FirstInFlow()->GetPlaceholderFrame();
11922 if (!placeholder) {
11923 MOZ_ASSERT_UNREACHABLE("no placeholder frame for out-of-flow frame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"no placeholder frame for out-of-flow frame" ")", "./../../../layout/generic/nsIFrame.cpp"
, 11923); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "no placeholder frame for out-of-flow frame"
")"); do { MOZ_CrashSequence(__null, 11923); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11924 *aProviderFrame = GetCorrectedParent(this);
11925 return *aProviderFrame ? (*aProviderFrame)->Style() : nullptr;
11926 }
11927 return placeholder->GetParentComputedStyleForOutOfFlow(aProviderFrame);
11928}
11929
11930void nsIFrame::GetLastLeaf(nsIFrame** aFrame) {
11931 if (!aFrame || !*aFrame) {
11932 return;
11933 }
11934 for (nsIFrame* maybeLastLeaf = (*aFrame)->PrincipalChildList().LastChild();
11935 maybeLastLeaf;) {
11936 nsIFrame* lastChildNotInSubTree = nullptr;
11937 for (nsIFrame* child = maybeLastLeaf; child;
11938 child = child->GetPrevSibling()) {
11939 // ignore anonymous elements, e.g. mozTableAdd* mozTableRemove*
11940 // see bug 278197 comment #12 #13 for details
11941 if (!child->ContentIsRootOfNativeAnonymousSubtree()) {
11942 lastChildNotInSubTree = child;
11943 break;
11944 }
11945 }
11946 if (!lastChildNotInSubTree) {
11947 return;
11948 }
11949 *aFrame = lastChildNotInSubTree;
11950 maybeLastLeaf = lastChildNotInSubTree->PrincipalChildList().LastChild();
11951 }
11952}
11953
11954void nsIFrame::GetFirstLeaf(nsIFrame** aFrame) {
11955 if (!aFrame || !*aFrame) {
11956 return;
11957 }
11958 nsIFrame* child = *aFrame;
11959 while (true) {
11960 child = child->PrincipalChildList().FirstChild();
11961 if (!child) {
11962 return; // nothing to do
11963 }
11964 *aFrame = child;
11965 }
11966}
11967
11968bool nsIFrame::IsFocusableDueToScrollFrame() {
11969 if (!IsScrollContainerFrame()) {
11970 if (nsFieldSetFrame* fieldset = do_QueryFrame(this)) {
11971 // TODO: Do we have similar special-cases like this where we can have
11972 // anonymous scrollable boxes hanging off a primary frame?
11973 if (nsIFrame* inner = fieldset->GetInner()) {
11974 return inner->IsFocusableDueToScrollFrame();
11975 }
11976 }
11977 return false;
11978 }
11979 if (!mContent->IsHTMLElement()) {
11980 return false;
11981 }
11982 if (Style()->IsPseudoElement()) {
11983 return false;
11984 }
11985 if (mContent->IsRootOfNativeAnonymousSubtree()) {
11986 return false;
11987 }
11988 if (!mContent->GetParent()) {
11989 return false;
11990 }
11991 if (mContent->AsElement()->HasAttr(nsGkAtoms::tabindex)) {
11992 return false;
11993 }
11994 // Elements with scrollable view are focusable with script & tabbable
11995 // Otherwise you couldn't scroll them with keyboard, which is an accessibility
11996 // issue (e.g. Section 508 rules) However, we don't make them to be focusable
11997 // with the mouse, because the extra focus outlines are considered
11998 // unnecessarily ugly. When clicked on, the selection position within the
11999 // element will be enough to make them keyboard scrollable.
12000 auto* scrollContainer = static_cast<ScrollContainerFrame*>(this);
12001 if (scrollContainer->GetScrollStyles().IsHiddenInBothDirections()) {
12002 return false;
12003 }
12004 if (scrollContainer->GetScrollRangeForUserInputEvents().IsEqualEdges(
12005 nsRect())) {
12006 return false;
12007 }
12008 return true;
12009}
12010
12011Focusable nsIFrame::IsFocusable(IsFocusableFlags aFlags) {
12012 // cannot focus content in print preview mode. Only the root can be focused,
12013 // but that's handled elsewhere.
12014 if (PresContext()->Type() == nsPresContext::eContext_PrintPreview) {
12015 return {};
12016 }
12017
12018 if (!mContent || !mContent->IsElement()) {
12019 return {};
12020 }
12021
12022 if (!(aFlags & IsFocusableFlags::IgnoreVisibility) &&
12023 !IsVisibleConsideringAncestors()) {
12024 return {};
12025 }
12026
12027 const StyleUserFocus uf = StyleUI()->UserFocus();
12028 if (uf == StyleUserFocus::None) {
12029 return {};
12030 }
12031 MOZ_ASSERT(!StyleUI()->IsInert(), "inert implies -moz-user-focus: none")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!StyleUI()->IsInert())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!StyleUI()->IsInert()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("!StyleUI()->IsInert()"
" (" "inert implies -moz-user-focus: none" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12031); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!StyleUI()->IsInert()"
") (" "inert implies -moz-user-focus: none" ")"); do { MOZ_CrashSequence
(__null, 12031); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
12032
12033 const PseudoStyleType pseudo = Style()->GetPseudoType();
12034 if (pseudo == PseudoStyleType::MozAnonymousItem) {
12035 return {};
12036 }
12037
12038 Focusable focusable;
12039 if (auto* xul = nsXULElement::FromNode(mContent)) {
12040 // As a legacy special-case, -moz-user-focus controls focusability and
12041 // tabability of XUL elements in some circumstances (which default to
12042 // -moz-user-focus: ignore).
12043 auto focusability = xul->GetXULFocusability(aFlags);
12044 focusable.mFocusable =
12045 focusability.mForcedFocusable.valueOr(uf == StyleUserFocus::Normal);
12046 if (focusable) {
12047 focusable.mTabIndex = focusability.mForcedTabIndexIfFocusable.valueOr(0);
12048 }
12049 } else {
12050 focusable = mContent->IsFocusableWithoutStyle(aFlags);
12051 }
12052
12053 if (focusable) {
12054 return focusable;
12055 }
12056
12057 // If we're focusing with the mouse we never focus scroll areas.
12058 if (!(aFlags & IsFocusableFlags::WithMouse) &&
12059 IsFocusableDueToScrollFrame()) {
12060 return {true, 0};
12061 }
12062
12063 // FIXME(emilio): some callers rely on somewhat broken return values
12064 // (focusable = false, but non-negative tab-index) from
12065 // IsFocusableWithoutStyle (for image maps in particular).
12066 return focusable;
12067}
12068
12069/**
12070 * @return true if this text frame ends with a newline character which is
12071 * treated as preformatted. It should return false if this is not a text frame.
12072 */
12073bool nsIFrame::HasSignificantTerminalNewline() const { return false; }
12074
12075static StyleAlignmentBaseline ConvertSVGDominantBaselineToAlignmentBaseline(
12076 StyleDominantBaseline aDominantBaseline) {
12077 // Most of these are approximate mappings.
12078 switch (aDominantBaseline) {
12079 case StyleDominantBaseline::Hanging:
12080 case StyleDominantBaseline::TextTop:
12081 return StyleAlignmentBaseline::TextTop;
12082 case StyleDominantBaseline::TextBottom:
12083 case StyleDominantBaseline::Ideographic:
12084 return StyleAlignmentBaseline::TextBottom;
12085 case StyleDominantBaseline::Central:
12086 case StyleDominantBaseline::Middle:
12087 case StyleDominantBaseline::Mathematical:
12088 return StyleAlignmentBaseline::Middle;
12089 case StyleDominantBaseline::Auto:
12090 case StyleDominantBaseline::Alphabetic:
12091 return StyleAlignmentBaseline::Baseline;
12092 default:
12093 MOZ_ASSERT_UNREACHABLE("unexpected aDominantBaseline value")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"unexpected aDominantBaseline value" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12093); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "unexpected aDominantBaseline value"
")"); do { MOZ_CrashSequence(__null, 12093); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12094 return StyleAlignmentBaseline::Baseline;
12095 }
12096}
12097
12098StyleDominantBaseline nsIFrame::DominantBaseline() const {
12099 auto dominantBaseline = StyleVisibility()->mDominantBaseline;
12100 if (dominantBaseline != StyleDominantBaseline::Auto) {
12101 return dominantBaseline;
12102 }
12103 // https://drafts.csswg.org/css-inline-3/#alignment-baseline-property
12104 // > Equivalent to alphabetic in horizontal writing modes and
12105 // > in vertical writing modes when text-orientation is sideways.
12106 // > Equivalent to central in vertical writing modes when
12107 // > text-orientation is mixed or upright.
12108 return GetWritingMode().IsCentralBaseline()
12109 ? StyleDominantBaseline::Central
12110 : StyleDominantBaseline::Alphabetic;
12111}
12112
12113StyleAlignmentBaseline nsIFrame::AlignmentBaseline() const {
12114 if (IsInSVGTextSubtree()) {
12115 // TODO Bug 2010721 - Implement alignment-baseline directly for SVG
12116 // text elements instead of only approximating from dominant-baseline.
12117 auto dominantBaseline = StyleVisibility()->mDominantBaseline;
12118 return ConvertSVGDominantBaselineToAlignmentBaseline(dominantBaseline);
12119 }
12120
12121 if (IsTableCellFrame()) {
12122 // The alignment-baseline / vertical-align property on a table cell is used
12123 // to align its children (see nsTableCellFrame::GetTableCellAlignment), but
12124 // does not affect the alignment of the cell itself within its row.
12125 return StyleAlignmentBaseline::Baseline;
12126 }
12127
12128 if (StyleDisplay()->mAlignmentBaseline == StyleAlignmentBaseline::Baseline) {
12129 // The CSS Inline Layout specification says `alignment-baseline: baseline`
12130 // uses the dominant baseline choice of the parent.
12131 auto dominantBaseline =
12132 GetParent() ? GetParent()->DominantBaseline() : DominantBaseline();
12133 switch (dominantBaseline) {
12134 case StyleDominantBaseline::TextBottom:
12135 return StyleAlignmentBaseline::TextBottom;
12136 case StyleDominantBaseline::Alphabetic:
12137 return StyleAlignmentBaseline::Alphabetic;
12138 case StyleDominantBaseline::Ideographic:
12139 return StyleAlignmentBaseline::Ideographic;
12140 case StyleDominantBaseline::Middle:
12141 return StyleAlignmentBaseline::Middle;
12142 case StyleDominantBaseline::Central:
12143 return StyleAlignmentBaseline::Central;
12144 case StyleDominantBaseline::Mathematical:
12145 return StyleAlignmentBaseline::Mathematical;
12146 case StyleDominantBaseline::Hanging:
12147 return StyleAlignmentBaseline::Hanging;
12148 case StyleDominantBaseline::TextTop:
12149 return StyleAlignmentBaseline::TextTop;
12150 case StyleDominantBaseline::Auto:
12151 MOZ_ASSERT_UNREACHABLE("Auto is resolved in DominantBaseline()")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Auto is resolved in DominantBaseline()" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12151); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Auto is resolved in DominantBaseline()"
")"); do { MOZ_CrashSequence(__null, 12151); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12152 break;
12153 }
12154 }
12155
12156 return StyleDisplay()->mAlignmentBaseline;
12157}
12158
12159void nsIFrame::UpdateStyleOfChildAnonBox(nsIFrame* aChildFrame,
12160 ServoRestyleState& aRestyleState) {
12161#ifdef DEBUG1
12162 nsIFrame* parent = aChildFrame->GetInFlowParent();
12163 if (aChildFrame->IsTableFrame()) {
12164 parent = parent->GetParent();
12165 }
12166 if (parent->IsLineFrame()) {
12167 parent = parent->GetParent();
12168 }
12169 MOZ_ASSERT(nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent
) == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(nsLayoutUtils::FirstContinuationOrIBSplitSibling
(parent) == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
" (" "This should only be used for children!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12170); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
") (" "This should only be used for children!" ")"); do { MOZ_CrashSequence
(__null, 12170); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
12170 "This should only be used for children!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent
) == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(nsLayoutUtils::FirstContinuationOrIBSplitSibling
(parent) == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
" (" "This should only be used for children!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12170); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
") (" "This should only be used for children!" ")"); do { MOZ_CrashSequence
(__null, 12170); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
12171#endif // DEBUG
12172 MOZ_ASSERT(!GetContent() || !aChildFrame->GetContent() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetContent() || !aChildFrame->GetContent() || aChildFrame
->GetContent() == GetContent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetContent() || !aChildFrame
->GetContent() || aChildFrame->GetContent() == GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
" (" "What content node is it a frame for?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12174); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { MOZ_CrashSequence
(__null, 12174); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
12173 aChildFrame->GetContent() == GetContent(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetContent() || !aChildFrame->GetContent() || aChildFrame
->GetContent() == GetContent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetContent() || !aChildFrame
->GetContent() || aChildFrame->GetContent() == GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
" (" "What content node is it a frame for?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12174); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { MOZ_CrashSequence
(__null, 12174); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
12174 "What content node is it a frame for?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!GetContent() || !aChildFrame->GetContent() || aChildFrame
->GetContent() == GetContent())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetContent() || !aChildFrame
->GetContent() || aChildFrame->GetContent() == GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
" (" "What content node is it a frame for?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12174); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { MOZ_CrashSequence
(__null, 12174); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
12175 MOZ_ASSERT(!aChildFrame->GetPrevContinuation(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aChildFrame->GetPrevContinuation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!aChildFrame->GetPrevContinuation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!aChildFrame->GetPrevContinuation()"
" (" "Only first continuations should end up here" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12176); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetPrevContinuation()"
") (" "Only first continuations should end up here" ")"); do
{ MOZ_CrashSequence(__null, 12176); __attribute__((nomerge))
::abort(); } while (false); } } while (false)
12176 "Only first continuations should end up here")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aChildFrame->GetPrevContinuation())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!aChildFrame->GetPrevContinuation()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!aChildFrame->GetPrevContinuation()"
" (" "Only first continuations should end up here" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12176); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetPrevContinuation()"
") (" "Only first continuations should end up here" ")"); do
{ MOZ_CrashSequence(__null, 12176); __attribute__((nomerge))
::abort(); } while (false); } } while (false)
;
12177
12178 // We could force the caller to pass in the pseudo, since some callers know it
12179 // statically... But this API is a bit nicer.
12180 auto pseudo = aChildFrame->Style()->GetPseudoType();
12181 MOZ_ASSERT(PseudoStyle::IsAnonBox(pseudo), "Child is not an anon box?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PseudoStyle::IsAnonBox(pseudo))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PseudoStyle::IsAnonBox(pseudo
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("PseudoStyle::IsAnonBox(pseudo)" " (" "Child is not an anon box?"
")", "./../../../layout/generic/nsIFrame.cpp", 12181); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "PseudoStyle::IsAnonBox(pseudo)" ") (" "Child is not an anon box?"
")"); do { MOZ_CrashSequence(__null, 12181); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12182 MOZ_ASSERT(!PseudoStyle::IsNonInheritingAnonBox(pseudo),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!PseudoStyle::IsNonInheritingAnonBox(pseudo))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!PseudoStyle::IsNonInheritingAnonBox(pseudo)))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
" (" "Why did the caller bother calling us?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12183); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
") (" "Why did the caller bother calling us?" ")"); do { MOZ_CrashSequence
(__null, 12183); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
12183 "Why did the caller bother calling us?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!PseudoStyle::IsNonInheritingAnonBox(pseudo))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!PseudoStyle::IsNonInheritingAnonBox(pseudo)))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
" (" "Why did the caller bother calling us?" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12183); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
") (" "Why did the caller bother calling us?" ")"); do { MOZ_CrashSequence
(__null, 12183); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
12184
12185 // Anon boxes inherit from their parent; that's us.
12186 RefPtr<ComputedStyle> newContext =
12187 aRestyleState.StyleSet().ResolveInheritingAnonymousBoxStyle(pseudo,
12188 Style());
12189
12190 nsChangeHint childHint =
12191 UpdateStyleOfOwnedChildFrame(aChildFrame, newContext, aRestyleState);
12192
12193 // Now that we've updated the style on aChildFrame, check whether it itself
12194 // has anon boxes to deal with.
12195 ServoRestyleState childrenState(*aChildFrame, aRestyleState, childHint,
12196 ServoRestyleState::CanUseHandledHints::Yes);
12197 aChildFrame->UpdateStyleOfOwnedAnonBoxes(childrenState);
12198
12199 // Assuming anon boxes don't have ::backdrop associated with them... if that
12200 // ever changes, we'd need to handle that here, like we do in
12201 // RestyleManager::ProcessPostTraversal
12202
12203 // We do need to handle block pseudo-elements here, though. Especially list
12204 // bullets.
12205 if (nsBlockFrame* block = do_QueryFrame(aChildFrame)) {
12206 block->UpdatePseudoElementStyles(childrenState);
12207 }
12208}
12209
12210/* static */
12211nsChangeHint nsIFrame::UpdateStyleOfOwnedChildFrame(
12212 nsIFrame* aChildFrame, ComputedStyle* aNewComputedStyle,
12213 ServoRestyleState& aRestyleState,
12214 const Maybe<ComputedStyle*>& aContinuationComputedStyle) {
12215 // Figure out whether we have an actual change. It's important that we do
12216 // this, for several reasons:
12217 //
12218 // 1) Even if all the child's changes are due to properties it inherits from
12219 // us, it's possible that no one ever asked us for those style structs and
12220 // hence changes to them aren't reflected in the changes handled at all.
12221 //
12222 // 2) Content can change stylesheets that change the styles of pseudos, and
12223 // extensions can add/remove stylesheets that change the styles of
12224 // anonymous boxes directly.
12225 uint32_t equalStructs; // Not used, actually.
12226 nsChangeHint childHint = aChildFrame->Style()->CalcStyleDifference(
12227 *aNewComputedStyle, &equalStructs);
12228
12229 // If aChildFrame is out of flow, then aRestyleState's "changes handled by the
12230 // parent" doesn't apply to it, because it may have some other parent in the
12231 // frame tree.
12232 if (!aChildFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
12233 childHint = NS_RemoveSubsumedHints(
12234 childHint, aRestyleState.ChangesHandledFor(aChildFrame));
12235 }
12236 if (childHint) {
12237 if (childHint & nsChangeHint_ReconstructFrame) {
12238 // If we generate a reconstruct here, remove any non-reconstruct hints we
12239 // may have already generated for this content.
12240 aRestyleState.ChangeList().PopChangesForContent(
12241 aChildFrame->GetContent());
12242 }
12243 aRestyleState.ChangeList().AppendChange(
12244 aChildFrame, aChildFrame->GetContent(), childHint);
12245 }
12246
12247 aChildFrame->SetComputedStyle(aNewComputedStyle);
12248 ComputedStyle* continuationStyle = aContinuationComputedStyle
12249 ? *aContinuationComputedStyle
12250 : aNewComputedStyle;
12251 for (nsIFrame* kid = aChildFrame->GetNextContinuation(); kid;
12252 kid = kid->GetNextContinuation()) {
12253 kid->SetComputedStyle(continuationStyle);
12254 }
12255
12256 return childHint;
12257}
12258
12259/* static */
12260void nsIFrame::AddInPopupStateBitToDescendants(nsIFrame* aFrame) {
12261 if (!aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP) &&
12262 aFrame->TrackingVisibility()) {
12263 // Assume all frames in popups are visible.
12264 aFrame->IncApproximateVisibleCount();
12265 }
12266
12267 aFrame->AddStateBits(NS_FRAME_IN_POPUP);
12268
12269 for (const auto& childList : aFrame->CrossDocChildLists()) {
12270 for (nsIFrame* child : childList.mList) {
12271 AddInPopupStateBitToDescendants(child);
12272 }
12273 }
12274}
12275
12276/* static */
12277void nsIFrame::RemoveInPopupStateBitFromDescendants(nsIFrame* aFrame) {
12278 if (!aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP) ||
12279 nsLayoutUtils::IsPopup(aFrame)) {
12280 return;
12281 }
12282
12283 aFrame->RemoveStateBits(NS_FRAME_IN_POPUP);
12284
12285 if (aFrame->TrackingVisibility()) {
12286 // We assume all frames in popups are visible, so this decrement balances
12287 // out the increment in AddInPopupStateBitToDescendants above.
12288 aFrame->DecApproximateVisibleCount();
12289 }
12290 for (const auto& childList : aFrame->CrossDocChildLists()) {
12291 for (nsIFrame* child : childList.mList) {
12292 RemoveInPopupStateBitFromDescendants(child);
12293 }
12294 }
12295}
12296
12297void nsIFrame::SetParent(nsContainerFrame* aParent) {
12298 // If our parent is a wrapper anon box, our new parent should be too. We
12299 // _can_ change parent if our parent is a wrapper anon box, because some
12300 // wrapper anon boxes can have continuations.
12301 MOZ_ASSERT_IF(ParentIsWrapperAnonBox(),do { if (ParentIsWrapperAnonBox()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(aParent->Style
()->IsInheritingAnonBox())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->Style()->IsInheritingAnonBox
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->Style()->IsInheritingAnonBox()", "./../../../layout/generic/nsIFrame.cpp"
, 12302); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->Style()->IsInheritingAnonBox()"
")"); do { MOZ_CrashSequence(__null, 12302); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false); } } while
(false)
12302 aParent->Style()->IsInheritingAnonBox())do { if (ParentIsWrapperAnonBox()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(aParent->Style
()->IsInheritingAnonBox())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent->Style()->IsInheritingAnonBox
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aParent->Style()->IsInheritingAnonBox()", "./../../../layout/generic/nsIFrame.cpp"
, 12302); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->Style()->IsInheritingAnonBox()"
")"); do { MOZ_CrashSequence(__null, 12302); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false); } } while
(false)
;
12303
12304 // Note that the current mParent may already be destroyed at this point.
12305 mParent = aParent;
12306 MOZ_ASSERT(!mParent || PresShell() == mParent->PresShell())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mParent || PresShell() == mParent->PresShell())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mParent || PresShell() == mParent->PresShell()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("!mParent || PresShell() == mParent->PresShell()"
, "./../../../layout/generic/nsIFrame.cpp", 12306); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!mParent || PresShell() == mParent->PresShell()"
")"); do { MOZ_CrashSequence(__null, 12306); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12307
12308 nsFrameState flagsToPropagateSameDoc =
12309 GetStateBits() & (NS_FRAME_CONTAINS_RELATIVE_BSIZE |
12310 NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE);
12311 if (flagsToPropagateSameDoc) {
12312 for (nsIFrame* f = aParent; f; f = f->GetParent()) {
12313 if (f->HasAllStateBits(flagsToPropagateSameDoc)) {
12314 break;
12315 }
12316 f->AddStateBits(flagsToPropagateSameDoc);
12317 }
12318 }
12319
12320 if (HasInvalidFrameInSubtree()) {
12321 for (nsIFrame* f = aParent;
12322 f && !f->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT |
12323 NS_FRAME_IS_NONDISPLAY);
12324 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
12325 f->AddStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT);
12326 }
12327 }
12328
12329 if (aParent->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
12330 AddInPopupStateBitToDescendants(this);
12331 } else {
12332 RemoveInPopupStateBitFromDescendants(this);
12333 }
12334
12335 // If our new parent only has invalid children, then we just invalidate
12336 // ourselves too. This is probably faster than clearing the flag all
12337 // the way up the frame tree.
12338 if (aParent->HasAnyStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT)) {
12339 InvalidateFrame();
12340 } else {
12341 SchedulePaint();
12342 }
12343}
12344
12345bool nsIFrame::IsStackingContext(const nsStyleDisplay* aStyleDisplay,
12346 const nsStyleEffects* aStyleEffects) {
12347 // Properties that influence the output of this function should be handled in
12348 // change_bits_for_longhand as well.
12349 if (HasOpacity(aStyleDisplay, aStyleEffects, nullptr)) {
12350 return true;
12351 }
12352 if (IsTransformed()) {
12353 return true;
12354 }
12355 auto willChange = aStyleDisplay->mWillChange.bits;
12356 if (aStyleDisplay->IsContainPaint() || aStyleDisplay->IsContainLayout() ||
12357 willChange & StyleWillChangeBits::CONTAIN) {
12358 if (SupportsContainLayoutAndPaint()) {
12359 return true;
12360 }
12361 }
12362
12363 if (ForcesStackingContextForViewTransition()) {
12364 return true;
12365 }
12366
12367 // strictly speaking, 'perspective' doesn't require visual atomicity,
12368 // but the spec says it acts like the rest of these
12369 if (aStyleDisplay->HasPerspectiveStyle() ||
12370 willChange & StyleWillChangeBits::PERSPECTIVE) {
12371 if (SupportsCSSTransforms()) {
12372 return true;
12373 }
12374 }
12375 if (!StylePosition()->mZIndex.IsAuto() ||
12376 willChange & StyleWillChangeBits::Z_INDEX) {
12377 if (ZIndexApplies()) {
12378 return true;
12379 }
12380 }
12381 // Elements captured in a view transition during a view transition or whose
12382 // view-transition-name computed value is not none (at any time) form a s
12383 // https://drafts.csswg.org/css-view-transitions-1/#named-and-transitioning
12384 return aStyleEffects->mMixBlendMode != StyleBlend::Normal ||
12385 SVGIntegrationUtils::UsingEffectsForFrame(this) ||
12386 aStyleDisplay->IsPositionForcingStackingContext() ||
12387 aStyleDisplay->mIsolation != StyleIsolation::Auto ||
12388 willChange & StyleWillChangeBits::STACKING_CONTEXT_UNCONDITIONAL;
12389}
12390
12391bool nsIFrame::IsStackingContext() {
12392 return IsStackingContext(StyleDisplay(), StyleEffects());
12393}
12394
12395static bool IsFrameRectScrolledOutOfView(const nsIFrame* aTarget,
12396 const nsRect& aTargetRect,
12397 const nsIFrame* aParent) {
12398 // The ancestor frame we are checking if it clips out aTargetRect relative to
12399 // aTarget.
12400 nsIFrame* clipParent = nullptr;
12401
12402 // find the first scrollable frame or root frame if we are in a fixed pos
12403 // subtree
12404 for (nsIFrame* f = const_cast<nsIFrame*>(aParent); f;
12405 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
12406 ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(f);
12407 if (scrollContainerFrame) {
12408 clipParent = f;
12409 break;
12410 }
12411 if (f->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
12412 nsLayoutUtils::IsReallyFixedPos(f)) {
12413 clipParent = f->GetParent();
12414 break;
12415 }
12416 }
12417
12418 if (!clipParent) {
12419 // Even if we couldn't find the nearest scrollable frame, it might mean we
12420 // are in an out-of-process iframe, try to see if |aTarget| frame is
12421 // scrolled out of view in an scrollable frame in a cross-process ancestor
12422 // document.
12423 return nsLayoutUtils::FrameRectIsScrolledOutOfViewInCrossProcess(
12424 aTarget, aTargetRect);
12425 }
12426
12427 nsRect clipRect = clipParent->InkOverflowRectRelativeToSelf();
12428 // We consider that the target is scrolled out if the scrollable (or root)
12429 // frame is empty.
12430 if (clipRect.IsEmpty()) {
12431 return true;
12432 }
12433
12434 nsRect transformedRect = nsLayoutUtils::TransformFrameRectToAncestor(
12435 aTarget, aTargetRect, clipParent);
12436
12437 if (transformedRect.IsEmpty()) {
12438 // If the transformed rect is empty it represents a line or a point that we
12439 // should check is outside the the scrollable rect.
12440 if (transformedRect.x > clipRect.XMost() ||
12441 transformedRect.y > clipRect.YMost() ||
12442 clipRect.x > transformedRect.XMost() ||
12443 clipRect.y > transformedRect.YMost()) {
12444 return true;
12445 }
12446 } else if (!transformedRect.Intersects(clipRect)) {
12447 return true;
12448 }
12449
12450 nsIFrame* parent = clipParent->GetParent();
12451 if (!parent) {
12452 return false;
12453 }
12454
12455 return IsFrameRectScrolledOutOfView(clipParent, transformedRect, parent);
12456}
12457
12458bool nsIFrame::IsScrolledOutOfView() const {
12459 nsRect rect = InkOverflowRectRelativeToSelf();
12460 return IsFrameRectScrolledOutOfView(this, rect, this);
12461}
12462
12463gfx::Matrix nsIFrame::ComputeWidgetTransform() const {
12464 const nsStyleUIReset* uiReset = StyleUIReset();
12465 if (uiReset->mMozWindowTransform.IsNone()) {
12466 return gfx::Matrix();
12467 }
12468
12469 TransformReferenceBox refBox(this);
12470
12471 int32_t appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
12472 gfx::Matrix4x4 matrix = nsStyleTransformMatrix::ReadTransforms(
12473 uiReset->mMozWindowTransform, refBox, float(appUnitsPerDevPixel),
12474 nsStyleTransformMatrix::Zoomed::Yes);
12475
12476 // Apply the transform-origin translation to the matrix.
12477 const StyleTransformOrigin& origin = StyleDisplay()->mTransformOrigin;
12478 Point transformOrigin = nsStyleTransformMatrix::Convert2DPosition(
12479 origin.horizontal, origin.vertical, refBox, appUnitsPerDevPixel);
12480 matrix.ChangeBasis(Point3D(transformOrigin.x, transformOrigin.y, 0));
12481
12482 gfx::Matrix result2d;
12483 if (!matrix.CanDraw2D(&result2d)) {
12484 // FIXME: It would be preferable to reject non-2D transforms at parse time.
12485 NS_WARNING(NS_DebugBreak(NS_DEBUG_WARNING, "-moz-window-transform does not describe a 2D transform, "
"but only 2d transforms are supported", nullptr, "./../../../layout/generic/nsIFrame.cpp"
, 12487)
12486 "-moz-window-transform does not describe a 2D transform, "NS_DebugBreak(NS_DEBUG_WARNING, "-moz-window-transform does not describe a 2D transform, "
"but only 2d transforms are supported", nullptr, "./../../../layout/generic/nsIFrame.cpp"
, 12487)
12487 "but only 2d transforms are supported")NS_DebugBreak(NS_DEBUG_WARNING, "-moz-window-transform does not describe a 2D transform, "
"but only 2d transforms are supported", nullptr, "./../../../layout/generic/nsIFrame.cpp"
, 12487)
;
12488 return gfx::Matrix();
12489 }
12490
12491 return result2d;
12492}
12493
12494void nsIFrame::DoUpdateStyleOfOwnedAnonBoxes(ServoRestyleState& aRestyleState) {
12495 // As a special case, we check for {ib}-split block frames here, rather
12496 // than have an nsInlineFrame::AppendDirectlyOwnedAnonBoxes implementation
12497 // that returns them.
12498 //
12499 // (If we did handle them in AppendDirectlyOwnedAnonBoxes, we would have to
12500 // return *all* of the in-flow {ib}-split block frames, not just the first
12501 // one. For restyling, we really just need the first in flow, and the other
12502 // user of the AppendOwnedAnonBoxes API, AllChildIterator, doesn't need to
12503 // know about them at all, since these block frames never create NAC. So we
12504 // avoid any unncessary hashtable lookups for the {ib}-split frames by calling
12505 // UpdateStyleOfOwnedAnonBoxesForIBSplit directly here.)
12506 if (IsInlineFrame()) {
12507 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
12508 static_cast<nsInlineFrame*>(this)->UpdateStyleOfOwnedAnonBoxesForIBSplit(
12509 aRestyleState);
12510 }
12511 return;
12512 }
12513
12514 AutoTArray<OwnedAnonBox, 4> frames;
12515 AppendDirectlyOwnedAnonBoxes(frames);
12516 for (OwnedAnonBox& box : frames) {
12517 if (box.mUpdateStyleFn) {
12518 box.mUpdateStyleFn(this, box.mAnonBoxFrame, aRestyleState);
12519 } else {
12520 UpdateStyleOfChildAnonBox(box.mAnonBoxFrame, aRestyleState);
12521 }
12522 }
12523}
12524
12525/* virtual */
12526void nsIFrame::AppendDirectlyOwnedAnonBoxes(nsTArray<OwnedAnonBox>& aResult) {
12527 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)"
, "./../../../layout/generic/nsIFrame.cpp", 12527); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)"
")"); do { MOZ_CrashSequence(__null, 12527); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12528 MOZ_ASSERT_UNREACHABLE(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Subclasses that have directly owned anonymous boxes should override "
"this method!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12530); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { MOZ_CrashSequence(__null, 12530); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
12529 "Subclasses that have directly owned anonymous boxes should override "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Subclasses that have directly owned anonymous boxes should override "
"this method!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12530); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { MOZ_CrashSequence(__null, 12530); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
12530 "this method!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Subclasses that have directly owned anonymous boxes should override "
"this method!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12530); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { MOZ_CrashSequence(__null, 12530); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
12531}
12532
12533void nsIFrame::DoAppendOwnedAnonBoxes(nsTArray<OwnedAnonBox>& aResult) {
12534 size_t i = aResult.Length();
12535 AppendDirectlyOwnedAnonBoxes(aResult);
12536
12537 // After appending the directly owned anonymous boxes of this frame to
12538 // aResult above, we need to check each of them to see if they own
12539 // any anonymous boxes themselves. Note that we keep progressing
12540 // through aResult, looking for additional entries in aResult from these
12541 // subsequent AppendDirectlyOwnedAnonBoxes calls. (Thus we can't
12542 // use a ranged for loop here.)
12543
12544 while (i < aResult.Length()) {
12545 nsIFrame* f = aResult[i].mAnonBoxFrame;
12546 if (f->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)) {
12547 f->AppendDirectlyOwnedAnonBoxes(aResult);
12548 }
12549 ++i;
12550 }
12551}
12552
12553nsIFrame::CaretPosition::CaretPosition() : mContentOffset(0) {}
12554
12555nsIFrame::CaretPosition::~CaretPosition() = default;
12556
12557bool nsIFrame::HasCSSAnimations() {
12558 auto* collection = AnimationCollection<CSSAnimation>::Get(this);
12559 return collection && !collection->mAnimations.IsEmpty();
12560}
12561
12562bool nsIFrame::HasCSSTransitions() {
12563 auto* collection = AnimationCollection<CSSTransition>::Get(this);
12564 return collection && !collection->mAnimations.IsEmpty();
12565}
12566
12567void nsIFrame::AddSizeOfExcludingThisForTree(nsWindowSizes& aSizes) const {
12568 aSizes.mLayoutFramePropertiesSize +=
12569 mProperties.SizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
12570
12571 // We don't do this for Gecko because this stuff is stored in the nsPresArena
12572 // and so measured elsewhere.
12573 if (!aSizes.mState.HaveSeenPtr(mComputedStyle)) {
12574 mComputedStyle->AddSizeOfIncludingThis(aSizes,
12575 &aSizes.mLayoutComputedValuesNonDom);
12576 }
12577
12578 for (const auto& childList : ChildLists()) {
12579 for (const nsIFrame* f : childList.mList) {
12580 f->AddSizeOfExcludingThisForTree(aSizes);
12581 }
12582 }
12583}
12584
12585nsRect nsIFrame::GetCompositorHitTestArea(nsDisplayListBuilder* aBuilder) {
12586 nsRect area;
12587
12588 ScrollContainerFrame* scrollContainerFrame =
12589 nsLayoutUtils::GetScrollContainerFrameFor(this);
12590 if (scrollContainerFrame) {
12591 // If this frame is the scrolled frame of a scroll container frame, then we
12592 // need to pick up the area corresponding to the overflow rect as well.
12593 // Otherwise the parts of the overflow that are not occupied by descendants
12594 // get skipped and the APZ code sends touch events to the content underneath
12595 // instead. See https://bugzilla.mozilla.org/show_bug.cgi?id=1127773#c15.
12596 area = ScrollableOverflowRect();
12597 } else {
12598 area = GetRectRelativeToSelf();
12599 }
12600
12601 if (!area.IsEmpty()) {
12602 return area + aBuilder->ToReferenceFrame(this);
12603 }
12604
12605 return area;
12606}
12607
12608CompositorHitTestInfo nsIFrame::GetCompositorHitTestInfo(
12609 nsDisplayListBuilder* aBuilder) {
12610 CompositorHitTestInfo result = CompositorHitTestInvisibleToHit;
12611 if (Style()->PointerEvents() == StylePointerEvents::None) {
12612 return result;
12613 }
12614 return GetCompositorHitTestInfoWithoutPointerEvents(aBuilder);
12615}
12616
12617CompositorHitTestInfo nsIFrame::GetCompositorHitTestInfoWithoutPointerEvents(
12618 nsDisplayListBuilder* aBuilder) {
12619 CompositorHitTestInfo result = CompositorHitTestInvisibleToHit;
12620
12621 if (aBuilder->IsInsidePointerEventsNoneDoc() ||
12622 aBuilder->IsInViewTransitionCapture()) {
12623 // Somewhere up the parent document chain is a subdocument with pointer-
12624 // events:none set on it, or we're getting captured in a view transition.
12625 return result;
12626 }
12627 if (!GetParent()) {
12628 MOZ_ASSERT(IsViewportFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsViewportFrame())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsViewportFrame()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("IsViewportFrame()"
, "./../../../layout/generic/nsIFrame.cpp", 12628); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "IsViewportFrame()" ")"); do { MOZ_CrashSequence
(__null, 12628); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
12629 // Viewport frames are never event targets, other frames, like canvas
12630 // frames, are the event targets for any regions viewport frames may cover.
12631 return result;
12632 }
12633 if (!StyleVisibility()->IsVisible()) {
12634 return result;
12635 }
12636
12637 // Anything that didn't match the above conditions is visible to hit-testing.
12638 result = CompositorHitTestFlags::eVisibleToHitTest;
12639 SVGUtils::MaskUsage maskUsage = SVGUtils::DetermineMaskUsage(this, false);
12640 if (maskUsage.UsingMaskOrClipPath()) {
12641 // If WebRender is enabled, simple clip-paths can be converted into WR
12642 // clips that WR knows how to hit-test against, so we don't need to mark
12643 // it as an irregular area.
12644 if (!maskUsage.IsSimpleClipShape()) {
12645 result += CompositorHitTestFlags::eIrregularArea;
12646 }
12647 }
12648
12649 if (aBuilder->IsBuildingNonLayerizedScrollbar()) {
12650 // Scrollbars may be painted into a layer below the actual layer they will
12651 // scroll, and therefore wheel events may be dispatched to the outer frame
12652 // instead of the intended scrollframe. To address this, we force a d-t-c
12653 // region on scrollbar frames that won't be placed in their own layer. See
12654 // bug 1213324 for details.
12655 result += CompositorHitTestFlags::eInactiveScrollframe;
12656 } else if (aBuilder->GetAncestorHasApzAwareEventHandler()) {
12657 result += CompositorHitTestFlags::eApzAwareListeners;
12658 } else if (IsRangeFrame()) {
12659 // Range frames handle touch events directly without having a touch listener
12660 // so we need to let APZ know that this area cares about events.
12661 result += CompositorHitTestFlags::eApzAwareListeners;
12662 }
12663
12664 if (aBuilder->IsTouchEventPrefEnabledDoc()) {
12665 // Inherit the touch-action flags from the parent, if there is one. We do
12666 // this because of how the touch-action on a frame combines the touch-action
12667 // from ancestor DOM elements. Refer to the documentation in
12668 // TouchActionHelper.cpp for details; this code is meant to be equivalent to
12669 // that code, but woven into the top-down recursive display list building
12670 // process.
12671 CompositorHitTestInfo inheritedTouchAction =
12672 aBuilder->GetInheritedCompositorHitTestInfo() &
12673 CompositorHitTestTouchActionMask;
12674
12675 nsIFrame* touchActionFrame = this;
12676 if (ScrollContainerFrame* scrollContainerFrame =
12677 nsLayoutUtils::GetScrollContainerFrameFor(this)) {
12678 ScrollStyles ss = scrollContainerFrame->GetScrollStyles();
12679 if (ss.mVertical != StyleOverflow::Hidden ||
12680 ss.mHorizontal != StyleOverflow::Hidden) {
12681 touchActionFrame = scrollContainerFrame;
12682 // On scrollframes, stop inheriting the pan-x and pan-y flags; instead,
12683 // reset them back to zero to allow panning on the scrollframe unless we
12684 // encounter an element that disables it that's inside the scrollframe.
12685 // This is equivalent to the |considerPanning| variable in
12686 // TouchActionHelper.cpp, but for a top-down traversal.
12687 CompositorHitTestInfo panMask(
12688 CompositorHitTestFlags::eTouchActionPanXDisabled,
12689 CompositorHitTestFlags::eTouchActionPanYDisabled);
12690 inheritedTouchAction -= panMask;
12691 }
12692 }
12693
12694 result += inheritedTouchAction;
12695
12696 const StyleTouchAction touchAction = touchActionFrame->UsedTouchAction();
12697 // The CSS allows the syntax auto | none | [pan-x || pan-y] | manipulation
12698 // so we can eliminate some combinations of things.
12699 if (touchAction == StyleTouchAction::AUTO) {
12700 // nothing to do
12701 } else if (touchAction & StyleTouchAction::MANIPULATION) {
12702 result += CompositorHitTestFlags::eTouchActionAnimatingZoomDisabled;
12703 } else {
12704 // This path handles the cases none | [pan-x || pan-y || pinch-zoom] so
12705 // double-tap is disabled in here.
12706 if (!(touchAction & StyleTouchAction::PINCH_ZOOM)) {
12707 result += CompositorHitTestFlags::eTouchActionPinchZoomDisabled;
12708 }
12709
12710 result += CompositorHitTestFlags::eTouchActionAnimatingZoomDisabled;
12711
12712 if (!(touchAction & StyleTouchAction::PAN_X)) {
12713 result += CompositorHitTestFlags::eTouchActionPanXDisabled;
12714 }
12715 if (!(touchAction & StyleTouchAction::PAN_Y)) {
12716 result += CompositorHitTestFlags::eTouchActionPanYDisabled;
12717 }
12718 if (touchAction & StyleTouchAction::NONE) {
12719 // all the touch-action disabling flags will already have been set above
12720 MOZ_ASSERT(result.contains(CompositorHitTestTouchActionMask))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(result.contains(CompositorHitTestTouchActionMask))>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(result.contains(CompositorHitTestTouchActionMask))))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("result.contains(CompositorHitTestTouchActionMask)"
, "./../../../layout/generic/nsIFrame.cpp", 12720); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "result.contains(CompositorHitTestTouchActionMask)"
")"); do { MOZ_CrashSequence(__null, 12720); __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
12721 }
12722 }
12723 }
12724
12725 const Maybe<ScrollDirection> scrollDirection =
12726 aBuilder->GetCurrentScrollbarDirection();
12727 if (scrollDirection.isSome()) {
12728 if (GetContent()->IsXULElement(nsGkAtoms::thumb)) {
12729 const bool thumbGetsLayer = aBuilder->GetCurrentScrollbarTarget() !=
12730 layers::ScrollableLayerGuid::NULL_SCROLL_ID;
12731 if (thumbGetsLayer) {
12732 result += CompositorHitTestFlags::eScrollbarThumb;
12733 } else {
12734 result += CompositorHitTestFlags::eInactiveScrollframe;
12735 }
12736 }
12737
12738 if (*scrollDirection == ScrollDirection::eVertical) {
12739 result += CompositorHitTestFlags::eScrollbarVertical;
12740 }
12741
12742 // includes the ScrollbarFrame, SliderFrame, anything else that
12743 // might be inside the xul:scrollbar
12744 result += CompositorHitTestFlags::eScrollbar;
12745 }
12746
12747 return result;
12748}
12749
12750// Returns true if we can guarantee there is no visible descendants.
12751static bool HasNoVisibleDescendants(const nsIFrame* aFrame) {
12752 for (const auto& childList : aFrame->ChildLists()) {
12753 for (nsIFrame* f : childList.mList) {
12754 if (nsPlaceholderFrame::GetRealFrameFor(f)
12755 ->IsVisibleOrMayHaveVisibleDescendants()) {
12756 return false;
12757 }
12758 }
12759 }
12760 return true;
12761}
12762
12763void nsIFrame::UpdateVisibleDescendantsState() {
12764 if (StyleVisibility()->IsVisible()) {
12765 // Notify invisible ancestors that a visible descendant exists now.
12766 nsIFrame* ancestor;
12767 for (ancestor = GetInFlowParent();
12768 ancestor && !ancestor->StyleVisibility()->IsVisible();
12769 ancestor = ancestor->GetInFlowParent()) {
12770 ancestor->mAllDescendantsAreInvisible = false;
12771 }
12772 } else {
12773 mAllDescendantsAreInvisible = HasNoVisibleDescendants(this);
12774 }
12775}
12776
12777PhysicalAxes nsIFrame::ShouldApplyOverflowClipping(
12778 const nsStyleDisplay* aDisp) const {
12779 MOZ_ASSERT(aDisp == StyleDisplay(), "Wrong display struct")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aDisp == StyleDisplay())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aDisp == StyleDisplay()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("aDisp == StyleDisplay()"
" (" "Wrong display struct" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12779); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aDisp == StyleDisplay()"
") (" "Wrong display struct" ")"); do { MOZ_CrashSequence(__null
, 12779); __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
12780
12781 if (IsScrollContainerOrSubclass()) {
12782 // Scrollers deal with overflow on their own.
12783 return {};
12784 }
12785
12786 // 'contain:paint', which we handle as 'overflow:clip' here. 'contain:paint'
12787 // should prevent all means of escaping that clipping (e.g. because it forms a
12788 // fixed-pos containing block).
12789 if (aDisp->IsContainPaint() && SupportsContainLayoutAndPaint()) {
12790 return kPhysicalAxesBoth;
12791 }
12792
12793 // and overflow: scrollable that we should interpret as clip
12794 if (aDisp->IsScrollableOverflow()) {
12795 // REVIEW: these are the frame types that set up clipping.
12796 LayoutFrameType type = Type();
12797 switch (type) {
12798 case LayoutFrameType::CheckboxRadio:
12799 case LayoutFrameType::ComboboxControl:
12800 case LayoutFrameType::Progress:
12801 case LayoutFrameType::Range:
12802 case LayoutFrameType::SubDocument:
12803 case LayoutFrameType::SVGForeignObject:
12804 case LayoutFrameType::SVGInnerSVG:
12805 case LayoutFrameType::SVGOuterSVG:
12806 case LayoutFrameType::SVGSymbol:
12807 case LayoutFrameType::Image:
12808 case LayoutFrameType::HTMLVideo:
12809 case LayoutFrameType::TableCell:
12810 return kPhysicalAxesBoth;
12811 case LayoutFrameType::Table:
12812 // Tables, for legacy reasons only clip when hidden in both directions,
12813 // and treat all other scrollable overflow values as `visible`.
12814 // This is (somewhat, since other browsers make this change at
12815 // computed-value time, see bug 1918789) interoperable css2-era
12816 // behavior. We might be able to change this, but not today.
12817 // See layout/reftests/table-overflow/bug785684-x.html
12818 return aDisp->mOverflowX == StyleOverflow::Hidden &&
12819 aDisp->mOverflowY == StyleOverflow::Hidden
12820 ? kPhysicalAxesBoth
12821 : PhysicalAxes();
12822 case LayoutFrameType::TextInput:
12823 // It has an anonymous scroll container frame that handles any overflow.
12824 return PhysicalAxes();
12825 default:
12826 break;
12827 }
12828 if (IsSuppressedScrollableBlockForPrint()) {
12829 return kPhysicalAxesBoth;
12830 }
12831 }
12832
12833 if (aDisp->mOverflowX == StyleOverflow::Clip ||
12834 aDisp->mOverflowY == StyleOverflow::Clip) {
12835 // FIXME: we could use GetViewportScrollStylesOverrideElement() here instead
12836 // if that worked correctly in a print context. (see bug 1654667)
12837 const auto* element = Element::FromNodeOrNull(GetContent());
12838 if (!element ||
12839 !PresContext()->ElementWouldPropagateScrollStyles(*element)) {
12840 PhysicalAxes axes;
12841 if (aDisp->mOverflowX == StyleOverflow::Clip) {
12842 axes += PhysicalAxis::Horizontal;
12843 }
12844 if (aDisp->mOverflowY == StyleOverflow::Clip) {
12845 axes += PhysicalAxis::Vertical;
12846 }
12847 return axes;
12848 }
12849 }
12850
12851 return PhysicalAxes();
12852}
12853
12854bool nsIFrame::IsSuppressedScrollableBlockForPrint() const {
12855 // This condition needs to match the suppressScrollFrame logic in the frame
12856 // constructor.
12857 if (!PresContext()->IsPaginated() || !IsBlockFrame() ||
12858 !StyleDisplay()->IsScrollableOverflow() ||
12859 !StyleDisplay()->IsBlockOutsideStyle() ||
12860 mContent->IsInNativeAnonymousSubtree()) {
12861 return false;
12862 }
12863 if (auto* element = Element::FromNode(mContent);
12864 element && PresContext()->ElementWouldPropagateScrollStyles(*element)) {
12865 return false;
12866 }
12867 return true;
12868}
12869
12870PhysicalAxes nsIFrame::GetAnchorPosCompensatingForScroll() const {
12871 if (!HasAnchorPosReference()) {
12872 return {};
12873 }
12874 const auto* prop = GetProperty(AnchorPosReferences());
12875 if (!prop) {
12876 return {};
12877 }
12878
12879 return prop->CompensatingForScrollAxes();
12880}
12881
12882bool nsIFrame::HasUnreflowedContainerQueryAncestor() const {
12883 // If this frame has done the first reflow, its ancestors are guaranteed to
12884 // have as well.
12885 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) ||
12886 !PresContext()->HasContainerQueryFrames()) {
12887 return false;
12888 }
12889 for (nsIFrame* cur = GetInFlowParent(); cur; cur = cur->GetInFlowParent()) {
12890 if (!cur->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
12891 // Done first reflow from this ancestor up, including query containers.
12892 return false;
12893 }
12894 if (cur->StyleDisplay()->IsQueryContainer()) {
12895 return true;
12896 }
12897 }
12898 // No query container from this frame up to root.
12899 return false;
12900}
12901
12902bool nsIFrame::ShouldBreakBefore(const BreakType aBreakType) const {
12903 const auto* display = StyleDisplay();
12904 return ShouldBreakBetween(display, display->mBreakBefore, aBreakType);
12905}
12906
12907bool nsIFrame::ShouldBreakAfter(const BreakType aBreakType) const {
12908 const auto* display = StyleDisplay();
12909 return ShouldBreakBetween(display, display->mBreakAfter, aBreakType);
12910}
12911
12912bool nsIFrame::ShouldBreakBetween(const nsStyleDisplay* aDisplay,
12913 const StyleBreakBetween aBreakBetween,
12914 const BreakType aBreakType) const {
12915 const bool shouldBreakBetween = [&] {
12916 switch (aBreakBetween) {
12917 case StyleBreakBetween::Always:
12918 return true;
12919 case StyleBreakBetween::Auto:
12920 case StyleBreakBetween::Avoid:
12921 return false;
12922 case StyleBreakBetween::Page:
12923 case StyleBreakBetween::Left:
12924 case StyleBreakBetween::Right:
12925 return aBreakType == BreakType::Page;
12926 }
12927 MOZ_ASSERT_UNREACHABLE("Unknown break-between value!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Unknown break-between value!" ")", "./../../../layout/generic/nsIFrame.cpp"
, 12927); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown break-between value!" ")"
); do { MOZ_CrashSequence(__null, 12927); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
12928 return false;
12929 }();
12930
12931 if (!shouldBreakBetween) {
12932 return false;
12933 }
12934 if (IsAbsolutelyPositioned(aDisplay)) {
12935 // 'break-before' and 'break-after' properties does not apply to
12936 // absolutely-positioned boxes.
12937 return false;
12938 }
12939 return true;
12940}
12941
12942#ifdef DEBUG1
12943static void GetTagName(nsIFrame* aFrame, nsIContent* aContent, int aResultSize,
12944 char* aResult) {
12945 if (aContent) {
12946 snprintf(aResult, aResultSize, "%s@%p",
12947 nsAtomCString(aContent->NodeInfo()->NameAtom()).get(), aFrame);
12948 } else {
12949 snprintf(aResult, aResultSize, "@%p", aFrame);
12950 }
12951}
12952
12953void nsIFrame::Trace(const char* aMethod, bool aEnter) {
12954 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
12955 char tagbuf[40];
12956 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
12957 printf_stderr("%s: %s %s", tagbuf, aEnter ? "enter" : "exit", aMethod);
12958 }
12959}
12960
12961void nsIFrame::Trace(const char* aMethod, bool aEnter,
12962 const nsReflowStatus& aStatus) {
12963 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
12964 char tagbuf[40];
12965 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
12966 printf_stderr("%s: %s %s, status=%scomplete%s", tagbuf,
12967 aEnter ? "enter" : "exit", aMethod,
12968 aStatus.IsIncomplete() ? "not" : "",
12969 (aStatus.NextInFlowNeedsReflow()) ? "+reflow" : "");
12970 }
12971}
12972
12973void nsIFrame::TraceMsg(const char* aFormatString, ...) {
12974 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
12975 // Format arguments into a buffer
12976 char argbuf[200];
12977 va_list ap;
12978 va_start(ap, aFormatString)__builtin_va_start(ap, aFormatString);
12979 VsprintfLiteral(argbuf, aFormatString, ap);
12980 va_end(ap)__builtin_va_end(ap);
12981
12982 char tagbuf[40];
12983 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
12984 printf_stderr("%s: %s", tagbuf, argbuf);
12985 }
12986}
12987
12988void nsIFrame::VerifyDirtyBitSet(const nsFrameList& aFrameList) {
12989 for (nsIFrame* f : aFrameList) {
12990 NS_ASSERTION(f->HasAnyStateBits(NS_FRAME_IS_DIRTY), "dirty bit not set")do { if (!(f->HasAnyStateBits(NS_FRAME_IS_DIRTY))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "dirty bit not set", "f->HasAnyStateBits(NS_FRAME_IS_DIRTY)"
, "./../../../layout/generic/nsIFrame.cpp", 12990); MOZ_PretendNoReturn
(); } } while (0)
;
12991 }
12992}
12993
12994// Validation of SideIsVertical.
12995# define CASE(side, result) \
12996 static_assert(SideIsVertical(side) == result, "SideIsVertical is wrong")
12997CASE(eSideTop, false);
12998CASE(eSideRight, true);
12999CASE(eSideBottom, false);
13000CASE(eSideLeft, true);
13001# undef CASE
13002
13003// Validation of HalfCornerIsX.
13004# define CASE(corner, result) \
13005 static_assert(HalfCornerIsX(corner) == result, "HalfCornerIsX is wrong")
13006CASE(eCornerTopLeftX, true);
13007CASE(eCornerTopLeftY, false);
13008CASE(eCornerTopRightX, true);
13009CASE(eCornerTopRightY, false);
13010CASE(eCornerBottomRightX, true);
13011CASE(eCornerBottomRightY, false);
13012CASE(eCornerBottomLeftX, true);
13013CASE(eCornerBottomLeftY, false);
13014# undef CASE
13015
13016// Validation of HalfToFullCorner.
13017# define CASE(corner, result) \
13018 static_assert(HalfToFullCorner(corner) == result, \
13019 "HalfToFullCorner is " \
13020 "wrong")
13021CASE(eCornerTopLeftX, eCornerTopLeft);
13022CASE(eCornerTopLeftY, eCornerTopLeft);
13023CASE(eCornerTopRightX, eCornerTopRight);
13024CASE(eCornerTopRightY, eCornerTopRight);
13025CASE(eCornerBottomRightX, eCornerBottomRight);
13026CASE(eCornerBottomRightY, eCornerBottomRight);
13027CASE(eCornerBottomLeftX, eCornerBottomLeft);
13028CASE(eCornerBottomLeftY, eCornerBottomLeft);
13029# undef CASE
13030
13031// Validation of FullToHalfCorner.
13032# define CASE(corner, vert, result) \
13033 static_assert(FullToHalfCorner(corner, vert) == result, \
13034 "FullToHalfCorner is wrong")
13035CASE(eCornerTopLeft, false, eCornerTopLeftX);
13036CASE(eCornerTopLeft, true, eCornerTopLeftY);
13037CASE(eCornerTopRight, false, eCornerTopRightX);
13038CASE(eCornerTopRight, true, eCornerTopRightY);
13039CASE(eCornerBottomRight, false, eCornerBottomRightX);
13040CASE(eCornerBottomRight, true, eCornerBottomRightY);
13041CASE(eCornerBottomLeft, false, eCornerBottomLeftX);
13042CASE(eCornerBottomLeft, true, eCornerBottomLeftY);
13043# undef CASE
13044
13045// Validation of SideToFullCorner.
13046# define CASE(side, second, result) \
13047 static_assert(SideToFullCorner(side, second) == result, \
13048 "SideToFullCorner is wrong")
13049CASE(eSideTop, false, eCornerTopLeft);
13050CASE(eSideTop, true, eCornerTopRight);
13051
13052CASE(eSideRight, false, eCornerTopRight);
13053CASE(eSideRight, true, eCornerBottomRight);
13054
13055CASE(eSideBottom, false, eCornerBottomRight);
13056CASE(eSideBottom, true, eCornerBottomLeft);
13057
13058CASE(eSideLeft, false, eCornerBottomLeft);
13059CASE(eSideLeft, true, eCornerTopLeft);
13060# undef CASE
13061
13062// Validation of SideToHalfCorner.
13063# define CASE(side, second, parallel, result) \
13064 static_assert(SideToHalfCorner(side, second, parallel) == result, \
13065 "SideToHalfCorner is wrong")
13066CASE(eSideTop, false, true, eCornerTopLeftX);
13067CASE(eSideTop, false, false, eCornerTopLeftY);
13068CASE(eSideTop, true, true, eCornerTopRightX);
13069CASE(eSideTop, true, false, eCornerTopRightY);
13070
13071CASE(eSideRight, false, false, eCornerTopRightX);
13072CASE(eSideRight, false, true, eCornerTopRightY);
13073CASE(eSideRight, true, false, eCornerBottomRightX);
13074CASE(eSideRight, true, true, eCornerBottomRightY);
13075
13076CASE(eSideBottom, false, true, eCornerBottomRightX);
13077CASE(eSideBottom, false, false, eCornerBottomRightY);
13078CASE(eSideBottom, true, true, eCornerBottomLeftX);
13079CASE(eSideBottom, true, false, eCornerBottomLeftY);
13080
13081CASE(eSideLeft, false, false, eCornerBottomLeftX);
13082CASE(eSideLeft, false, true, eCornerBottomLeftY);
13083CASE(eSideLeft, true, false, eCornerTopLeftX);
13084CASE(eSideLeft, true, true, eCornerTopLeftY);
13085# undef CASE
13086
13087#endif