Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp
Warning:line 3565, 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 -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=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -fcoverage-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -resource-dir /usr/lib/llvm-18/lib/clang/18 -include /var/lib/jenkins/workspace/firefox-scan-build/config/gcc_hidden.h -include /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /var/lib/jenkins/workspace/firefox-scan-build/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /var/lib/jenkins/workspace/firefox-scan-build/ipc/chromium/src -I /var/lib/jenkins/workspace/firefox-scan-build/layout/base -I /var/lib/jenkins/workspace/firefox-scan-build/layout/forms -I /var/lib/jenkins/workspace/firefox-scan-build/layout/painting -I /var/lib/jenkins/workspace/firefox-scan-build/layout/style -I /var/lib/jenkins/workspace/firefox-scan-build/layout/tables -I /var/lib/jenkins/workspace/firefox-scan-build/layout/xul -I /var/lib/jenkins/workspace/firefox-scan-build/docshell/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/html -I /var/lib/jenkins/workspace/firefox-scan-build/dom/xul -I /var/lib/jenkins/workspace/firefox-scan-build/gfx/cairo/cairo/src -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -I /usr/include/gtk-3.0 -I /usr/include/pango-1.0 -I /usr/include/glib-2.0 -I /usr/lib/x86_64-linux-gnu/glib-2.0/include -I /usr/include/sysprof-6 -I /usr/include/harfbuzz -I /usr/include/freetype2 -I /usr/include/libpng16 -I /usr/include/libmount -I /usr/include/blkid -I /usr/include/fribidi -I /usr/include/cairo -I /usr/include/pixman-1 -I /usr/include/gdk-pixbuf-2.0 -I /usr/include/x86_64-linux-gnu -I /usr/include/webp -I /usr/include/gio-unix-2.0 -I /usr/include/cloudproviders -I /usr/include/atk-1.0 -I /usr/include/at-spi2-atk/2.0 -I /usr/include/at-spi-2.0 -I /usr/include/dbus-1.0 -I /usr/lib/x86_64-linux-gnu/dbus-1.0/include -I /usr/include/gtk-3.0/unix-print -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-18/lib/clang/18/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-deprecated-this-capture -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -fdeprecated-macro -ferror-limit 19 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-aligned-allocation -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2024-07-21-021012-413605-1 -x c++ Unified_cpp_layout_generic2.cpp
1/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3/* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7/* base class of all rendering objects */
8
9#include "nsIFrame.h"
10
11#include <stdarg.h>
12#include <algorithm>
13
14#include "gfx2DGlue.h"
15#include "gfxUtils.h"
16#include "mozilla/Attributes.h"
17#include "mozilla/CaretAssociationHint.h"
18#include "mozilla/ComputedStyle.h"
19#include "mozilla/DebugOnly.h"
20#include "mozilla/DisplayPortUtils.h"
21#include "mozilla/EventForwards.h"
22#include "mozilla/FocusModel.h"
23#include "mozilla/dom/CSSAnimation.h"
24#include "mozilla/dom/CSSTransition.h"
25#include "mozilla/dom/ContentVisibilityAutoStateChangeEvent.h"
26#include "mozilla/dom/DocumentInlines.h"
27#include "mozilla/dom/AncestorIterator.h"
28#include "mozilla/dom/ElementInlines.h"
29#include "mozilla/dom/ImageTracker.h"
30#include "mozilla/dom/Selection.h"
31#include "mozilla/gfx/2D.h"
32#include "mozilla/gfx/PathHelpers.h"
33#include "mozilla/IntegerRange.h"
34#include "mozilla/intl/BidiEmbeddingLevel.h"
35#include "mozilla/Maybe.h"
36#include "mozilla/PresShell.h"
37#include "mozilla/PresShellInlines.h"
38#include "mozilla/ResultExtensions.h"
39#include "mozilla/ScrollContainerFrame.h"
40#include "mozilla/SelectionMovementUtils.h"
41#include "mozilla/Sprintf.h"
42#include "mozilla/StaticAnalysisFunctions.h"
43#include "mozilla/StaticPrefs_layout.h"
44#include "mozilla/StaticPrefs_print.h"
45#include "mozilla/StaticPrefs_ui.h"
46#include "mozilla/SVGMaskFrame.h"
47#include "mozilla/SVGObserverUtils.h"
48#include "mozilla/SVGTextFrame.h"
49#include "mozilla/SVGIntegrationUtils.h"
50#include "mozilla/SVGUtils.h"
51#include "mozilla/TextControlElement.h"
52#include "mozilla/ToString.h"
53#include "mozilla/Try.h"
54#include "mozilla/ViewportUtils.h"
55#include "mozilla/WritingModes.h"
56
57#include "nsCOMPtr.h"
58#include "nsFieldSetFrame.h"
59#include "nsFlexContainerFrame.h"
60#include "nsFocusManager.h"
61#include "nsFrameList.h"
62#include "nsPlaceholderFrame.h"
63#include "nsIBaseWindow.h"
64#include "nsIContent.h"
65#include "nsIContentInlines.h"
66#include "nsContentUtils.h"
67#include "nsCSSFrameConstructor.h"
68#include "nsCSSProps.h"
69#include "nsCSSPseudoElements.h"
70#include "nsCSSRendering.h"
71#include "nsAtom.h"
72#include "nsString.h"
73#include "nsReadableUtils.h"
74#include "nsTableWrapperFrame.h"
75#include "nsView.h"
76#include "nsViewManager.h"
77#include "nsPresContext.h"
78#include "nsPresContextInlines.h"
79#include "nsStyleConsts.h"
80#include "mozilla/Logging.h"
81#include "nsLayoutUtils.h"
82#include "LayoutLogging.h"
83#include "mozilla/RestyleManager.h"
84#include "nsImageFrame.h"
85#include "nsInlineFrame.h"
86#include "nsFrameSelection.h"
87#include "nsGkAtoms.h"
88#include "nsGridContainerFrame.h"
89#include "nsCSSAnonBoxes.h"
90#include "nsCanvasFrame.h"
91
92#include "nsFieldSetFrame.h"
93#include "nsFrameTraversal.h"
94#include "nsRange.h"
95#include "nsITextControlFrame.h"
96#include "nsNameSpaceManager.h"
97#include "nsIPercentBSizeObserver.h"
98#include "nsStyleStructInlines.h"
99
100#include "nsBidiPresUtils.h"
101#include "RubyUtils.h"
102#include "TextOverflow.h"
103#include "nsAnimationManager.h"
104
105// For triple-click pref
106#include "imgIRequest.h"
107#include "nsError.h"
108#include "nsContainerFrame.h"
109#include "nsBlockFrame.h"
110#include "nsDisplayList.h"
111#include "nsChangeHint.h"
112#include "nsSubDocumentFrame.h"
113#include "RetainedDisplayListBuilder.h"
114
115#include "gfxContext.h"
116#include "nsAbsoluteContainingBlock.h"
117#include "ScrollSnap.h"
118#include "StickyScrollContainer.h"
119#include "nsFontInflationData.h"
120#include "nsRegion.h"
121#include "nsIFrameInlines.h"
122#include "nsStyleChangeList.h"
123#include "nsWindowSizes.h"
124
125#ifdef ACCESSIBILITY1
126# include "nsAccessibilityService.h"
127#endif
128
129#include "mozilla/AsyncEventDispatcher.h"
130#include "mozilla/CSSClipPathInstance.h"
131#include "mozilla/EffectCompositor.h"
132#include "mozilla/EffectSet.h"
133#include "mozilla/EventListenerManager.h"
134#include "mozilla/EventStateManager.h"
135#include "mozilla/Preferences.h"
136#include "mozilla/LookAndFeel.h"
137#include "mozilla/MouseEvents.h"
138#include "mozilla/ServoStyleSet.h"
139#include "mozilla/ServoStyleSetInlines.h"
140#include "mozilla/css/ImageLoader.h"
141#include "mozilla/dom/HTMLBodyElement.h"
142#include "mozilla/dom/SVGPathData.h"
143#include "mozilla/dom/TouchEvent.h"
144#include "mozilla/gfx/Tools.h"
145#include "mozilla/layers/WebRenderUserData.h"
146#include "mozilla/layout/ScrollAnchorContainer.h"
147#include "nsPrintfCString.h"
148#include "ActiveLayerTracker.h"
149
150#include "nsITheme.h"
151
152using namespace mozilla;
153using namespace mozilla::css;
154using namespace mozilla::dom;
155using namespace mozilla::gfx;
156using namespace mozilla::layers;
157using namespace mozilla::layout;
158typedef nsAbsoluteContainingBlock::AbsPosReflowFlags AbsPosReflowFlags;
159using nsStyleTransformMatrix::TransformReferenceBox;
160
161nsIFrame* nsILineIterator::LineInfo::GetLastFrameOnLine() const {
162 if (!mNumFramesOnLine) {
163 return nullptr; // empty line, not illegal
164 }
165 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 165); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mFirstFrameOnLine"
")"); do { *((volatile int*)__null) = 165; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
166 nsIFrame* maybeLastFrame = mFirstFrameOnLine;
167 for ([[maybe_unused]] int32_t i : IntegerRange(mNumFramesOnLine - 1)) {
168 maybeLastFrame = maybeLastFrame->GetNextSibling();
169 if (NS_WARN_IF(!maybeLastFrame)NS_warn_if_impl(!maybeLastFrame, "!maybeLastFrame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 169)
) {
170 return nullptr;
171 }
172 }
173 return maybeLastFrame;
174}
175
176#ifdef HAVE_64BIT_BUILD1
177static_assert(sizeof(nsIFrame) == 120, "nsIFrame should remain small");
178#else
179static_assert(sizeof(void*) == 4, "Odd build config?");
180// FIXME(emilio): Investigate why win32 and android-arm32 have bigger sizes (80)
181// than Linux32 (76).
182static_assert(sizeof(nsIFrame) <= 80, "nsIFrame should remain small");
183#endif
184
185const mozilla::LayoutFrameType nsIFrame::sLayoutFrameTypes[kFrameClassCount] = {
186#define FRAME_ID(class_, type_, ...) mozilla::LayoutFrameType::type_,
187#define ABSTRACT_FRAME_ID(...)
188#include "mozilla/FrameIdList.h"
189#undef FRAME_ID
190#undef ABSTRACT_FRAME_ID
191};
192
193const nsIFrame::ClassFlags nsIFrame::sLayoutFrameClassFlags[kFrameClassCount] =
194 {
195#define FRAME_ID(class_, type_, flags_, ...) flags_,
196#define ABSTRACT_FRAME_ID(...)
197#include "mozilla/FrameIdList.h"
198#undef FRAME_ID
199#undef ABSTRACT_FRAME_ID
200};
201
202std::ostream& operator<<(std::ostream& aStream, const nsDirection& aDirection) {
203 return aStream << (aDirection == eDirNext ? "eDirNext" : "eDirPrevious");
204}
205
206struct nsContentAndOffset {
207 nsIContent* mContent = nullptr;
208 int32_t mOffset = 0;
209};
210
211#include "nsILineIterator.h"
212#include "prenv.h"
213
214// Utility function to set a nsRect-valued property table entry on aFrame,
215// reusing the existing storage if the property happens to be already set.
216template <typename T>
217static void SetOrUpdateRectValuedProperty(
218 nsIFrame* aFrame, FrameProperties::Descriptor<T> aProperty,
219 const nsRect& aNewValue) {
220 bool found;
221 nsRect* rectStorage = aFrame->GetProperty(aProperty, &found);
222 if (!found) {
223 rectStorage = new nsRect(aNewValue);
224 aFrame->AddProperty(aProperty, rectStorage);
225 } else {
226 *rectStorage = aNewValue;
227 }
228}
229
230FrameDestroyContext::~FrameDestroyContext() {
231 for (auto& content : mozilla::Reversed(mAnonymousContent)) {
232 mPresShell->NativeAnonymousContentRemoved(content);
233 content->UnbindFromTree();
234 }
235}
236
237// Formerly the nsIFrameDebug interface
238
239std::ostream& operator<<(std::ostream& aStream, const nsReflowStatus& aStatus) {
240 char complete = 'Y';
241 if (aStatus.IsIncomplete()) {
242 complete = 'N';
243 } else if (aStatus.IsOverflowIncomplete()) {
244 complete = 'O';
245 }
246
247 char brk = 'N';
248 if (aStatus.IsInlineBreakBefore()) {
249 brk = 'B';
250 } else if (aStatus.IsInlineBreakAfter()) {
251 brk = 'A';
252 }
253
254 aStream << "["
255 << "Complete=" << complete << ","
256 << "NIF=" << (aStatus.NextInFlowNeedsReflow() ? 'Y' : 'N') << ","
257 << "Break=" << brk << ","
258 << "FirstLetter=" << (aStatus.FirstLetterComplete() ? 'Y' : 'N')
259 << "]";
260 return aStream;
261}
262
263#ifdef DEBUG1
264
265/**
266 * Note: the log module is created during library initialization which
267 * means that you cannot perform logging before then.
268 */
269mozilla::LazyLogModule nsIFrame::sFrameLogModule("frame");
270
271#endif
272
273NS_DECLARE_FRAME_PROPERTY_DELETABLE(AbsoluteContainingBlockProperty,static const mozilla::FramePropertyDescriptor<nsAbsoluteContainingBlock
>* AbsoluteContainingBlockProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<nsAbsoluteContainingBlock
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
274 nsAbsoluteContainingBlock)static const mozilla::FramePropertyDescriptor<nsAbsoluteContainingBlock
>* AbsoluteContainingBlockProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<nsAbsoluteContainingBlock
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
275
276bool nsIFrame::HasAbsolutelyPositionedChildren() const {
277 return IsAbsoluteContainer() &&
278 GetAbsoluteContainingBlock()->HasAbsoluteFrames();
279}
280
281nsAbsoluteContainingBlock* nsIFrame::GetAbsoluteContainingBlock() const {
282 NS_ASSERTION(IsAbsoluteContainer(),do { if (!(IsAbsoluteContainer())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "The frame is not marked as an abspos container correctly",
"IsAbsoluteContainer()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 283); MOZ_PretendNoReturn(); } } while (0)
283 "The frame is not marked as an abspos container correctly")do { if (!(IsAbsoluteContainer())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "The frame is not marked as an abspos container correctly",
"IsAbsoluteContainer()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 283); MOZ_PretendNoReturn(); } } while (0)
;
284 nsAbsoluteContainingBlock* absCB =
285 GetProperty(AbsoluteContainingBlockProperty());
286 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 288); MOZ_PretendNoReturn(); } } while (0)
287 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 288); MOZ_PretendNoReturn(); } } while (0)
288 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 288); MOZ_PretendNoReturn(); } } while (0)
;
289 return absCB;
290}
291
292void nsIFrame::MarkAsAbsoluteContainingBlock() {
293 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 293); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
")"); do { *((volatile int*)__null) = 293; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
294 NS_ASSERTION(!GetProperty(AbsoluteContainingBlockProperty()),do { if (!(!GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Already has an abs-pos containing block property?"
, "!GetProperty(AbsoluteContainingBlockProperty())", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 295); MOZ_PretendNoReturn(); } } while (0)
295 "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())", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 295); MOZ_PretendNoReturn(); } } while (0)
;
296 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 297); MOZ_PretendNoReturn(); } } while (0)
297 "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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 297); MOZ_PretendNoReturn(); } } while (0)
;
298 AddStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
299 SetProperty(AbsoluteContainingBlockProperty(),
300 new nsAbsoluteContainingBlock(GetAbsoluteListID()));
301}
302
303void nsIFrame::MarkAsNotAbsoluteContainingBlock() {
304 NS_ASSERTION(!HasAbsolutelyPositionedChildren(), "Think of the children!")do { if (!(!HasAbsolutelyPositionedChildren())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Think of the children!", "!HasAbsolutelyPositionedChildren()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 304); MOZ_PretendNoReturn(); } } while (0)
;
305 NS_ASSERTION(GetProperty(AbsoluteContainingBlockProperty()),do { if (!(GetProperty(AbsoluteContainingBlockProperty()))) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Should have an abs-pos containing block property"
, "GetProperty(AbsoluteContainingBlockProperty())", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 306); MOZ_PretendNoReturn(); } } while (0)
306 "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())", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 306); MOZ_PretendNoReturn(); } } while (0)
;
307 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 308); MOZ_PretendNoReturn(); } } while (0)
308 "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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 308); MOZ_PretendNoReturn(); } } while (0)
;
309 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 309); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)"
")"); do { *((volatile int*)__null) = 309; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
310 RemoveStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
311 RemoveProperty(AbsoluteContainingBlockProperty());
312}
313
314bool nsIFrame::CheckAndClearPaintedState() {
315 bool result = HasAnyStateBits(NS_FRAME_PAINTED_THEBES);
316 RemoveStateBits(NS_FRAME_PAINTED_THEBES);
317
318 for (const auto& childList : ChildLists()) {
319 for (nsIFrame* child : childList.mList) {
320 if (child->CheckAndClearPaintedState()) {
321 result = true;
322 }
323 }
324 }
325 return result;
326}
327
328bool nsIFrame::CheckAndClearDisplayListState() {
329 bool result = BuiltDisplayList();
330 SetBuiltDisplayList(false);
331
332 for (const auto& childList : ChildLists()) {
333 for (nsIFrame* child : childList.mList) {
334 if (child->CheckAndClearDisplayListState()) {
335 result = true;
336 }
337 }
338 }
339 return result;
340}
341
342bool nsIFrame::IsVisibleConsideringAncestors(uint32_t aFlags) const {
343 if (!StyleVisibility()->IsVisible()) {
344 return false;
345 }
346
347 if (PresShell()->IsUnderHiddenEmbedderElement()) {
348 return false;
349 }
350
351 const nsIFrame* frame = this;
352 while (frame) {
353 nsView* view = frame->GetView();
354 if (view && view->GetVisibility() == ViewVisibility::Hide) {
355 return false;
356 }
357
358 if (frame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
359 return false;
360 }
361
362 // This method is used to determine if a frame is focusable, because it's
363 // called by nsIFrame::IsFocusable. `content-visibility: auto` should not
364 // force this frame to be unfocusable, so we only take into account
365 // `content-visibility: hidden` here.
366 if (this != frame &&
367 frame->HidesContent(IncludeContentVisibility::Hidden)) {
368 return false;
369 }
370
371 if (nsIFrame* parent = frame->GetParent()) {
372 frame = parent;
373 } else {
374 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame);
375 if (!parent) break;
376
377 if ((aFlags & nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY) == 0 &&
378 parent->PresContext()->IsChrome() &&
379 !frame->PresContext()->IsChrome()) {
380 break;
381 }
382
383 frame = parent;
384 }
385 }
386
387 return true;
388}
389
390void nsIFrame::FindCloserFrameForSelection(
391 const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
392 if (nsLayoutUtils::PointIsCloserToRect(aPoint, mRect,
393 aCurrentBestFrame->mXDistance,
394 aCurrentBestFrame->mYDistance)) {
395 aCurrentBestFrame->mFrame = this;
396 }
397}
398
399void nsIFrame::ElementStateChanged(mozilla::dom::ElementState aStates) {}
400
401void WeakFrame::Clear(mozilla::PresShell* aPresShell) {
402 if (aPresShell) {
403 aPresShell->RemoveWeakFrame(this);
404 }
405 mFrame = nullptr;
406}
407
408AutoWeakFrame::AutoWeakFrame(const WeakFrame& aOther)
409 : mPrev(nullptr), mFrame(nullptr) {
410 Init(aOther.GetFrame());
411}
412
413void AutoWeakFrame::Clear(mozilla::PresShell* aPresShell) {
414 if (aPresShell) {
415 aPresShell->RemoveAutoWeakFrame(this);
416 }
417 mFrame = nullptr;
418 mPrev = nullptr;
419}
420
421AutoWeakFrame::~AutoWeakFrame() {
422 Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
423}
424
425void AutoWeakFrame::Init(nsIFrame* aFrame) {
426 Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
427 mFrame = aFrame;
428 if (mFrame) {
429 mozilla::PresShell* presShell = mFrame->PresContext()->GetPresShell();
430 NS_WARNING_ASSERTION(presShell, "Null PresShell in AutoWeakFrame!")do { if (!(presShell)) { NS_DebugBreak(NS_DEBUG_WARNING, "Null PresShell in AutoWeakFrame!"
, "presShell", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 430); } } while (false)
;
431 if (presShell) {
432 presShell->AddAutoWeakFrame(this);
433 } else {
434 mFrame = nullptr;
435 }
436 }
437}
438
439void WeakFrame::Init(nsIFrame* aFrame) {
440 Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
441 mFrame = aFrame;
442 if (mFrame) {
443 mozilla::PresShell* presShell = mFrame->PresContext()->GetPresShell();
444 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 444); AnnotateMozCrashReason("MOZ_ASSERT" "(" "presShell" ") ("
"Null PresShell in WeakFrame!" ")"); do { *((volatile int*)__null
) = 444; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
445 if (presShell) {
446 presShell->AddWeakFrame(this);
447 } else {
448 mFrame = nullptr;
449 }
450 }
451}
452
453nsIFrame* NS_NewEmptyFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
454 return new (aPresShell) nsIFrame(aStyle, aPresShell->GetPresContext());
455}
456
457nsIFrame::~nsIFrame() {
458 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
<nsISupports, nsIFrame>::value, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogDtor((void*)this, "nsIFrame", sizeof
(*this)); } while (0)
;
459
460 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 nsFrame is being destroyed" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 461); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetVisibility() != Visibility::ApproximatelyVisible"
") (" "Visible nsFrame is being destroyed" ")"); do { *((volatile
int*)__null) = 461; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
461 "Visible nsFrame 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 nsFrame is being destroyed" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 461); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetVisibility() != Visibility::ApproximatelyVisible"
") (" "Visible nsFrame is being destroyed" ")"); do { *((volatile
int*)__null) = 461; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
462}
463
464NS_IMPL_FRAMEARENA_HELPERS(nsIFrame)void* nsIFrame ::operator new(size_t sz, mozilla::PresShell *
aShell) { return aShell->AllocateFrame(nsQueryFrame::nsIFrame_id
, sz); }
465
466// Dummy operator delete. Will never be called, but must be defined
467// to satisfy some C++ ABIs.
468void nsIFrame::operator delete(void*, size_t) {
469 MOZ_CRASH("nsIFrame::operator delete should never be called")do { do { } while (false); MOZ_ReportCrash("" "nsIFrame::operator delete should never be called"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 469); AnnotateMozCrashReason("MOZ_CRASH(" "nsIFrame::operator delete should never be called"
")"); do { *((volatile int*)__null) = 469; __attribute__((nomerge
)) ::abort(); } while (false); } while (false)
;
470}
471
472NS_QUERYFRAME_HEAD(nsIFrame)void* nsIFrame ::QueryFrame(FrameIID id) const { switch (id) {
473 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)); }
474NS_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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 474); 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
{ *((volatile int*)__null) = 474; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false); return nullptr; }
475
476/////////////////////////////////////////////////////////////////////////////
477// nsIFrame
478
479static bool IsFontSizeInflationContainer(nsIFrame* aFrame,
480 const nsStyleDisplay* aStyleDisplay) {
481 /*
482 * Font size inflation is built around the idea that we're inflating
483 * the fonts for a pan-and-zoom UI so that when the user scales up a
484 * block or other container to fill the width of the device, the fonts
485 * will be readable. To do this, we need to pick what counts as a
486 * container.
487 *
488 * From a code perspective, the only hard requirement is that frames
489 * that are line participants (nsIFrame::IsLineParticipant) are never
490 * containers, since line layout assumes that the inflation is consistent
491 * within a line.
492 *
493 * This is not an imposition, since we obviously want a bunch of text
494 * (possibly with inline elements) flowing within a block to count the
495 * block (or higher) as its container.
496 *
497 * We also want form controls, including the text in the anonymous
498 * content inside of them, to match each other and the text next to
499 * them, so they and their anonymous content should also not be a
500 * container.
501 *
502 * However, because we can't reliably compute sizes across XUL during
503 * reflow, any XUL frame with a XUL parent is always a container.
504 *
505 * There are contexts where it would be nice if some blocks didn't
506 * count as a container, so that, for example, an indented quotation
507 * didn't end up with a smaller font size. However, it's hard to
508 * distinguish these situations where we really do want the indented
509 * thing to count as a container, so we don't try, and blocks are
510 * always containers.
511 */
512
513 // The root frame should always be an inflation container.
514 if (!aFrame->GetParent()) {
515 return true;
516 }
517
518 nsIContent* content = aFrame->GetContent();
519 if (content && content->IsInNativeAnonymousSubtree()) {
520 // Native anonymous content shouldn't be a font inflation root,
521 // except for the canvas custom content container.
522 nsCanvasFrame* canvas = aFrame->PresShell()->GetCanvasFrame();
523 return canvas && canvas->GetCustomContentContainer() == content;
524 }
525
526 LayoutFrameType frameType = aFrame->Type();
527 bool isInline =
528 aFrame->GetDisplay().IsInlineFlow() || RubyUtils::IsRubyBox(frameType) ||
529 (aStyleDisplay->IsFloatingStyle() &&
530 frameType == LayoutFrameType::Letter) ||
531 // Given multiple frames for the same node, only the
532 // outer one should be considered a container.
533 // (Important, e.g., for nsSelectsAreaFrame.)
534 (aFrame->GetParent()->GetContent() == content) ||
535 (content &&
536 // Form controls shouldn't become inflation containers.
537 (content->IsAnyOfHTMLElements(nsGkAtoms::option, nsGkAtoms::optgroup,
538 nsGkAtoms::select, nsGkAtoms::input,
539 nsGkAtoms::button, nsGkAtoms::textarea)));
540 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
541 // 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
542 // 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
543 // 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
544 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
545 "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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 545); MOZ_PretendNoReturn(); } } while (0)
;
546 return !isInline;
547}
548
549static void MaybeScheduleReflowSVGNonDisplayText(nsIFrame* aFrame) {
550 if (!aFrame->IsInSVGTextSubtree()) {
551 return;
552 }
553
554 // We need to ensure that any non-display SVGTextFrames get reflowed when a
555 // child text frame gets new style. Thus we need to schedule a reflow in
556 // |DidSetComputedStyle|. We also need to call it from |DestroyFrom|,
557 // because otherwise we won't get notified when style changes to
558 // "display:none".
559 SVGTextFrame* svgTextFrame = static_cast<SVGTextFrame*>(
560 nsLayoutUtils::GetClosestFrameOfType(aFrame, LayoutFrameType::SVGText));
561 nsIFrame* anonBlock = svgTextFrame->PrincipalChildList().FirstChild();
562
563 // Note that we must check NS_FRAME_FIRST_REFLOW on our SVGTextFrame's
564 // anonymous block frame rather than our aFrame, since NS_FRAME_FIRST_REFLOW
565 // may be set on us if we're a new frame that has been inserted after the
566 // document's first reflow. (In which case this DidSetComputedStyle call may
567 // be happening under frame construction under a Reflow() call.)
568 if (!anonBlock || anonBlock->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
569 return;
570 }
571
572 if (!svgTextFrame->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) ||
573 svgTextFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)) {
574 return;
575 }
576
577 svgTextFrame->ScheduleReflowSVGNonDisplayText(
578 IntrinsicDirty::FrameAncestorsAndDescendants);
579}
580
581bool nsIFrame::IsPrimaryFrameOfRootOrBodyElement() const {
582 if (!IsPrimaryFrame()) {
583 return false;
584 }
585 nsIContent* content = GetContent();
586 Document* document = content->OwnerDoc();
587 return content == document->GetRootElement() ||
588 content == document->GetBodyElement();
589}
590
591bool nsIFrame::IsRenderedLegend() const {
592 if (auto* parent = GetParent(); parent && parent->IsFieldSetFrame()) {
593 return static_cast<nsFieldSetFrame*>(parent)->GetLegend() == this;
594 }
595 return false;
596}
597
598void nsIFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
599 nsIFrame* aPrevInFlow) {
600 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 600); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsQueryFrame::FrameIID(mClass) == GetFrameId()"
")"); do { *((volatile int*)__null) = 600; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
601 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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 601); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mContent" ") ("
"Double-initing a frame?" ")"); do { *((volatile int*)__null
) = 601; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
602
603 mContent = aContent;
604 mParent = aParent;
605 MOZ_DIAGNOSTIC_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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 605); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "!mParent || PresShell() == mParent->PresShell()"
")"); do { *((volatile int*)__null) = 605; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
606
607 if (aPrevInFlow) {
608 mWritingMode = aPrevInFlow->GetWritingMode();
609
610 // Copy some state bits from prev-in-flow (the bits that should apply
611 // throughout a continuation chain). The bits are sorted according to their
612 // order in nsFrameStateBits.h.
613
614 // clang-format off
615 AddStateBits(aPrevInFlow->GetStateBits() &
616 (NS_FRAME_GENERATED_CONTENT |
617 NS_FRAME_OUT_OF_FLOW |
618 NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN |
619 NS_FRAME_INDEPENDENT_SELECTION |
620 NS_FRAME_PART_OF_IBSPLIT |
621 NS_FRAME_MAY_BE_TRANSFORMED |
622 NS_FRAME_HAS_MULTI_COLUMN_ANCESTOR));
623 // clang-format on
624
625 // Copy other bits in nsIFrame from prev-in-flow.
626 mHasColumnSpanSiblings = aPrevInFlow->HasColumnSpanSiblings();
627 } else {
628 PresContext()->ConstructedFrame();
629 }
630
631 if (GetParent()) {
632 if (MOZ_UNLIKELY(mContent == PresContext()->Document()->GetRootElement() &&(__builtin_expect(!!(mContent == PresContext()->Document()
->GetRootElement() && mContent == GetParent()->
GetContent()), 0))
633 mContent == GetParent()->GetContent())(__builtin_expect(!!(mContent == PresContext()->Document()
->GetRootElement() && mContent == GetParent()->
GetContent()), 0))
) {
634 // Our content is the root element and we have the same content as our
635 // parent. That is, we are the internal anonymous frame of the root
636 // element. Copy the used mWritingMode from our parent because
637 // mDocElementContainingBlock gets its mWritingMode from <body>.
638 mWritingMode = GetParent()->GetWritingMode();
639 }
640
641 // Copy some state bits from our parent (the bits that should apply
642 // recursively throughout a subtree). The bits are sorted according to their
643 // order in nsFrameStateBits.h.
644
645 // clang-format off
646 AddStateBits(GetParent()->GetStateBits() &
647 (NS_FRAME_GENERATED_CONTENT |
648 NS_FRAME_INDEPENDENT_SELECTION |
649 NS_FRAME_IS_SVG_TEXT |
650 NS_FRAME_IN_POPUP |
651 NS_FRAME_IS_NONDISPLAY));
652 // clang-format on
653
654 if (HasAnyStateBits(NS_FRAME_IN_POPUP) && TrackingVisibility()) {
655 // Assume all frames in popups are visible.
656 IncApproximateVisibleCount();
657 }
658 }
659 if (aPrevInFlow) {
660 mMayHaveOpacityAnimation = aPrevInFlow->MayHaveOpacityAnimation();
661 mMayHaveTransformAnimation = aPrevInFlow->MayHaveTransformAnimation();
662 } else if (mContent) {
663 // It's fine to fetch the EffectSet for the style frame here because in the
664 // following code we take care of the case where animations may target
665 // a different frame.
666 EffectSet* effectSet = EffectSet::GetForStyleFrame(this);
667 if (effectSet) {
668 mMayHaveOpacityAnimation = effectSet->MayHaveOpacityAnimation();
669
670 if (effectSet->MayHaveTransformAnimation()) {
671 // If we are the inner table frame for display:table content, then
672 // transform animations should go on our parent frame (the table wrapper
673 // frame).
674 //
675 // We do this when initializing the child frame (table inner frame),
676 // because when initializng the table wrapper frame, we don't yet have
677 // access to its children so we can't tell if we have transform
678 // animations or not.
679 if (SupportsCSSTransforms()) {
680 mMayHaveTransformAnimation = true;
681 AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
682 } else if (aParent && nsLayoutUtils::GetStyleFrame(aParent) == this) {
683 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 686); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { *((volatile int*)__null) = 686; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
684 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 686); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { *((volatile int*)__null) = 686; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
685 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 686); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { *((volatile int*)__null) = 686; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
686 " 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 686); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->SupportsCSSTransforms()"
") (" "Style frames that don't support transforms should have parents"
" that do" ")"); do { *((volatile int*)__null) = 686; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
687 aParent->mMayHaveTransformAnimation = true;
688 aParent->AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
689 }
690 }
691 }
692 }
693
694 const nsStyleDisplay* disp = StyleDisplay();
695 if (disp->HasTransform(this)) {
696 // If 'transform' dynamically changes, RestyleManager takes care of
697 // updating this bit.
698 AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
699 }
700
701 if (nsLayoutUtils::FontSizeInflationEnabled(PresContext()) ||
702 !GetParent()
703#ifdef DEBUG1
704 // We have assertions that check inflation invariants even when
705 // font size inflation is not enabled.
706 || true
707#endif
708 ) {
709 if (IsFontSizeInflationContainer(this, disp)) {
710 AddStateBits(NS_FRAME_FONT_INFLATION_CONTAINER);
711 if (!GetParent() ||
712 // I'd use NS_FRAME_OUT_OF_FLOW, but it's not set yet.
713 disp->IsFloating(this) || disp->IsAbsolutelyPositioned(this) ||
714 GetParent()->IsFlexContainerFrame() ||
715 GetParent()->IsGridContainerFrame()) {
716 AddStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT);
717 }
718 }
719 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 721); MOZ_PretendNoReturn(); } } while (0)
720 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 721); MOZ_PretendNoReturn(); } } while (0)
721 "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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 721); MOZ_PretendNoReturn(); } } while (0)
;
722 }
723
724 if (TrackingVisibility() && PresShell()->AssumeAllFramesVisible()) {
725 IncApproximateVisibleCount();
726 }
727
728 DidSetComputedStyle(nullptr);
729
730 // For a newly created frame, we need to update this frame's visibility state.
731 // Usually we update the state when the frame is restyled and has a
732 // VisibilityChange change hint but we don't generate any change hints for
733 // newly created frames.
734 // Note: We don't need to do this for placeholders since placeholders have
735 // different styles so that the styles don't have visibility:hidden even if
736 // the parent has visibility:hidden style. We also don't need to update the
737 // state when creating continuations because its visibility is the same as its
738 // prev-in-flow, and the animation code cares only primary frames.
739 if (!IsPlaceholderFrame() && !aPrevInFlow) {
740 UpdateVisibleDescendantsState();
741 }
742
743 if (!aPrevInFlow && HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
744 // We aren't going to get a reflow, so nothing else will call
745 // InvalidateRenderingObservers, we have to do it here.
746 SVGObserverUtils::InvalidateRenderingObservers(this);
747 }
748}
749
750void nsIFrame::InitPrimaryFrame() {
751 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 751); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsPrimaryFrame()"
")"); do { *((volatile int*)__null) = 751; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
752 HandlePrimaryFrameStyleChange(nullptr);
753}
754
755void nsIFrame::HandlePrimaryFrameStyleChange(ComputedStyle* aOldStyle) {
756 const nsStyleDisplay* disp = StyleDisplay();
757 const nsStyleDisplay* oldDisp =
758 aOldStyle ? aOldStyle->StyleDisplay() : nullptr;
759
760 const bool wasQueryContainer = oldDisp && oldDisp->IsQueryContainer();
761 const bool isQueryContainer = disp->IsQueryContainer();
762 if (wasQueryContainer != isQueryContainer) {
763 auto* pc = PresContext();
764 if (isQueryContainer) {
765 pc->RegisterContainerQueryFrame(this);
766 } else {
767 pc->UnregisterContainerQueryFrame(this);
768 }
769 }
770
771 const auto cv = disp->ContentVisibility(*this);
772 if (!oldDisp || oldDisp->ContentVisibility(*this) != cv) {
773 if (cv == StyleContentVisibility::Auto) {
774 PresShell()->RegisterContentVisibilityAutoFrame(this);
775 } else {
776 if (auto* element = Element::FromNodeOrNull(GetContent())) {
777 element->ClearContentRelevancy();
778 }
779 PresShell()->UnregisterContentVisibilityAutoFrame(this);
780 }
781 PresContext()->SetNeedsToUpdateHiddenByContentVisibilityForAnimations();
782 }
783
784 HandleLastRememberedSize();
785}
786
787void nsIFrame::Destroy(DestroyContext& aContext) {
788 NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),do { if (!(!nsContentUtils::IsSafeToRunScript())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "destroy called on frame while scripts not blocked"
, "!nsContentUtils::IsSafeToRunScript()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 789); MOZ_PretendNoReturn(); } } while (0)
789 "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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 789); MOZ_PretendNoReturn(); } } while (0)
;
790 NS_ASSERTION(!GetNextSibling() && !GetPrevSibling(),do { if (!(!GetNextSibling() && !GetPrevSibling())) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Frames should be removed before destruction."
, "!GetNextSibling() && !GetPrevSibling()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 791); MOZ_PretendNoReturn(); } } while (0)
791 "Frames should be removed before destruction.")do { if (!(!GetNextSibling() && !GetPrevSibling())) {
NS_DebugBreak(NS_DEBUG_ASSERTION, "Frames should be removed before destruction."
, "!GetNextSibling() && !GetPrevSibling()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 791); MOZ_PretendNoReturn(); } } while (0)
;
792 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 792); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAbsolutelyPositionedChildren()"
")"); do { *((volatile int*)__null) = 792; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
793 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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 794); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
") (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")"); do { *((volatile int*)__null) = 794; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
794 "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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 794); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)"
") (" "NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?"
")"); do { *((volatile int*)__null) = 794; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
795
796 MaybeScheduleReflowSVGNonDisplayText(this);
797
798 SVGObserverUtils::InvalidateDirectRenderingObservers(this);
799
800 const auto* disp = StyleDisplay();
801 if (disp->mPosition == StylePositionProperty::Sticky) {
802 if (auto* ssc =
803 StickyScrollContainer::GetStickyScrollContainerForFrame(this)) {
804 ssc->RemoveFrame(this);
805 }
806 }
807
808 if (HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
809 if (nsPlaceholderFrame* placeholder = GetPlaceholderFrame()) {
810 placeholder->SetOutOfFlowFrame(nullptr);
811 }
812 }
813
814 nsPresContext* pc = PresContext();
815 mozilla::PresShell* ps = pc->GetPresShell();
816 if (IsPrimaryFrame()) {
817 if (disp->IsQueryContainer()) {
818 pc->UnregisterContainerQueryFrame(this);
819 }
820 if (disp->ContentVisibility(*this) == StyleContentVisibility::Auto) {
821 ps->UnregisterContentVisibilityAutoFrame(this);
822 }
823 // This needs to happen before we clear our Properties() table.
824 ActiveLayerTracker::TransferActivityToContent(this, mContent);
825 }
826
827 ScrollAnchorContainer* anchor = nullptr;
828 if (IsScrollAnchor(&anchor)) {
829 anchor->InvalidateAnchor();
830 }
831
832 if (HasCSSAnimations() || HasCSSTransitions() ||
833 // It's fine to look up the style frame here since if we're destroying the
834 // frames for display:table content we should be destroying both wrapper
835 // and inner frame.
836 EffectSet::GetForStyleFrame(this)) {
837 // If no new frame for this element is created by the end of the
838 // restyling process, stop animations and transitions for this frame
839 RestyleManager::AnimationsWithDestroyedFrame* adf =
840 pc->RestyleManager()->GetAnimationsWithDestroyedFrame();
841 // AnimationsWithDestroyedFrame only lives during the restyling process.
842 if (adf) {
843 adf->Put(mContent, mComputedStyle);
844 }
845 }
846
847 // Disable visibility tracking. Note that we have to do this before we clear
848 // frame properties and lose track of whether we were previously visible.
849 // XXX(seth): It'd be ideal to assert that we're already marked nonvisible
850 // here, but it's unfortunately tricky to guarantee in the face of things like
851 // frame reconstruction induced by style changes.
852 DisableVisibilityTracking();
853
854 // Ensure that we're not in the approximately visible list anymore.
855 ps->RemoveFrameFromApproximatelyVisibleList(this);
856
857 ps->NotifyDestroyingFrame(this);
858
859 if (HasAnyStateBits(NS_FRAME_EXTERNAL_REFERENCE)) {
860 ps->ClearFrameRefs(this);
861 }
862
863 nsView* view = GetView();
864 if (view) {
865 view->SetFrame(nullptr);
866 view->Destroy();
867 }
868
869 // Make sure that our deleted frame can't be returned from GetPrimaryFrame()
870 if (IsPrimaryFrame()) {
871 mContent->SetPrimaryFrame(nullptr);
872
873 // Pass the root of a generated content subtree (e.g. ::after/::before) to
874 // aPostDestroyData to unbind it after frame destruction is done.
875 if (HasAnyStateBits(NS_FRAME_GENERATED_CONTENT) &&
876 mContent->IsRootOfNativeAnonymousSubtree()) {
877 aContext.AddAnonymousContent(mContent.forget());
878 }
879 }
880
881 // Remove all properties attached to the frame, to ensure any property
882 // destructors that need the frame pointer are handled properly.
883 RemoveAllProperties();
884
885 // Must retrieve the object ID before calling destructors, so the
886 // vtable is still valid.
887 //
888 // Note to future tweakers: having the method that returns the
889 // object size call the destructor will not avoid an indirect call;
890 // the compiler cannot devirtualize the call to the destructor even
891 // if it's from a method defined in the same class.
892
893 nsQueryFrame::FrameIID id = GetFrameId();
894 this->~nsIFrame();
895
896#ifdef DEBUG1
897 {
898 nsIFrame* rootFrame = ps->GetRootFrame();
899 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 899); AnnotateMozCrashReason("MOZ_ASSERT" "(" "rootFrame" ")"
); do { *((volatile int*)__null) = 899; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
900 if (this != rootFrame) {
901 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(rootFrame);
902 auto* data = builder ? builder->Data() : nullptr;
903
904 const bool inData =
905 data && (data->IsModified(this) || data->HasProps(this));
906
907 if (inData) {
908 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)
;
909 }
910
911 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 911); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!inData" ") ("
"Deleted frame in retained data!" ")"); do { *((volatile int
*)__null) = 911; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
912 }
913 }
914#endif
915
916 // Now that we're totally cleaned out, we need to add ourselves to
917 // the presshell's recycler.
918 ps->FreeFrame(id, this);
919}
920
921std::pair<int32_t, int32_t> nsIFrame::GetOffsets() const {
922 return std::make_pair(0, 0);
923}
924
925static void CompareLayers(
926 const nsStyleImageLayers* aFirstLayers,
927 const nsStyleImageLayers* aSecondLayers,
928 const std::function<void(imgRequestProxy* aReq)>& aCallback) {
929 NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, (*aFirstLayers))for (uint32_t i = ((*aFirstLayers)).mImageCount; (i)-- != 0;) {
930 const auto& image = aFirstLayers->mLayers[i].mImage;
931 if (!image.IsImageRequestType() || !image.IsResolved()) {
932 continue;
933 }
934
935 // aCallback is called when the style image in aFirstLayers is thought to
936 // be different with the corresponded one in aSecondLayers
937 if (!aSecondLayers || i >= aSecondLayers->mImageCount ||
938 (!aSecondLayers->mLayers[i].mImage.IsResolved() ||
939 image.GetImageRequest() !=
940 aSecondLayers->mLayers[i].mImage.GetImageRequest())) {
941 if (imgRequestProxy* req = image.GetImageRequest()) {
942 aCallback(req);
943 }
944 }
945 }
946}
947
948static void AddAndRemoveImageAssociations(
949 ImageLoader& aImageLoader, nsIFrame* aFrame,
950 const nsStyleImageLayers* aOldLayers,
951 const nsStyleImageLayers* aNewLayers) {
952 // If the old context had a background-image image, or mask-image image,
953 // and new context does not have the same image, clear the image load
954 // notifier (which keeps the image loading, if it still is) for the frame.
955 // We want to do this conservatively because some frames paint their
956 // backgrounds from some other frame's style data, and we don't want
957 // to clear those notifiers unless we have to. (They'll be reset
958 // when we paint, although we could miss a notification in that
959 // interval.)
960 if (aOldLayers && aFrame->HasImageRequest()) {
961 CompareLayers(aOldLayers, aNewLayers, [&](imgRequestProxy* aReq) {
962 aImageLoader.DisassociateRequestFromFrame(aReq, aFrame);
963 });
964 }
965
966 CompareLayers(aNewLayers, aOldLayers, [&](imgRequestProxy* aReq) {
967 aImageLoader.AssociateRequestToFrame(aReq, aFrame);
968 });
969}
970
971void nsIFrame::AddDisplayItem(nsDisplayItem* aItem) {
972 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 972); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "!mDisplayItems.Contains(aItem)"
")"); do { *((volatile int*)__null) = 972; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
973 mDisplayItems.AppendElement(aItem);
974#ifdef ACCESSIBILITY1
975 if (nsAccessibilityService* accService = GetAccService()) {
976 accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
977 }
978#endif
979}
980
981bool nsIFrame::RemoveDisplayItem(nsDisplayItem* aItem) {
982 return mDisplayItems.RemoveElement(aItem);
983}
984
985bool nsIFrame::HasDisplayItems() { return !mDisplayItems.IsEmpty(); }
986
987bool nsIFrame::HasDisplayItem(nsDisplayItem* aItem) {
988 return mDisplayItems.Contains(aItem);
989}
990
991bool nsIFrame::HasDisplayItem(uint32_t aKey) {
992 for (nsDisplayItem* i : mDisplayItems) {
993 if (i->GetPerFrameKey() == aKey) {
994 return true;
995 }
996 }
997 return false;
998}
999
1000template <typename Condition>
1001static void DiscardDisplayItems(nsIFrame* aFrame, Condition aCondition) {
1002 for (nsDisplayItem* i : aFrame->DisplayItems()) {
1003 // Only discard items that are invalidated by this frame, as we're only
1004 // guaranteed to rebuild those items. Table background items are created by
1005 // the relevant table part, but have the cell frame as the primary frame,
1006 // and we don't want to remove them if this is the cell.
1007 if (aCondition(i) && i->FrameForInvalidation() == aFrame) {
1008 i->SetCantBeReused();
1009 }
1010 }
1011}
1012
1013static void DiscardOldItems(nsIFrame* aFrame) {
1014 DiscardDisplayItems(aFrame,
1015 [](nsDisplayItem* aItem) { return aItem->IsOldItem(); });
1016}
1017
1018void nsIFrame::RemoveDisplayItemDataForDeletion() {
1019 // Destroying a WebRenderUserDataTable can cause destruction of other objects
1020 // which can remove frame properties in their destructor. If we delete a frame
1021 // property it runs the destructor of the stored object in the middle of
1022 // updating the frame property table, so if the destruction of that object
1023 // causes another update to the frame property table it would leave the frame
1024 // property table in an inconsistent state. So we remove it from the table and
1025 // then destroy it. (bug 1530657)
1026 WebRenderUserDataTable* userDataTable =
1027 TakeProperty(WebRenderUserDataProperty::Key());
1028 if (userDataTable) {
1029 for (const auto& data : userDataTable->Values()) {
1030 data->RemoveFromTable();
1031 }
1032 delete userDataTable;
1033 }
1034
1035 if (!nsLayoutUtils::AreRetainedDisplayListsEnabled()) {
1036 // Retained display lists are disabled, no need to update
1037 // RetainedDisplayListData.
1038 return;
1039 }
1040
1041 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
1042 if (!builder) {
1043 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1043); AnnotateMozCrashReason("MOZ_ASSERT" "(" "DisplayItems().IsEmpty()"
")"); do { *((volatile int*)__null) = 1043; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1044 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1044); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsFrameModified()"
")"); do { *((volatile int*)__null) = 1044; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1045 return;
1046 }
1047
1048 for (nsDisplayItem* i : DisplayItems()) {
1049 if (i->GetDependentFrame() == this && !i->HasDeletedFrame()) {
1050 i->Frame()->MarkNeedsDisplayItemRebuild();
1051 }
1052 i->RemoveFrame(this);
1053 }
1054
1055 DisplayItems().Clear();
1056
1057 nsAutoString name;
1058#ifdef DEBUG_FRAME_DUMP1
1059 if (DL_LOG_TEST(LogLevel::Debug)(__builtin_expect(!!(mozilla::detail::log_test(GetLoggerByProcess
(), LogLevel::Debug)), 0))
) {
1060 GetFrameName(name);
1061 }
1062#endif
1063 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)
1064 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)
;
1065
1066 auto* data = builder->Data();
1067 if (MayHaveWillChangeBudget()) {
1068 // Keep the frame in list, so it can be removed from the will-change budget.
1069 data->Flags(this) = RetainedDisplayListData::FrameFlag::HadWillChange;
1070 } else {
1071 data->Remove(this);
1072 }
1073}
1074
1075void nsIFrame::MarkNeedsDisplayItemRebuild() {
1076 if (!nsLayoutUtils::AreRetainedDisplayListsEnabled() || IsFrameModified() ||
1077 HasAnyStateBits(NS_FRAME_IN_POPUP)) {
1078 // Skip frames that are already marked modified.
1079 return;
1080 }
1081
1082 if (Type() == LayoutFrameType::Placeholder) {
1083 nsIFrame* oof = static_cast<nsPlaceholderFrame*>(this)->GetOutOfFlowFrame();
1084 if (oof) {
1085 oof->MarkNeedsDisplayItemRebuild();
1086 }
1087 // Do not mark placeholder frames modified.
1088 return;
1089 }
1090
1091#ifdef ACCESSIBILITY1
1092 if (nsAccessibilityService* accService = GetAccService()) {
1093 accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
1094 }
1095#endif
1096
1097 nsIFrame* rootFrame = PresShell()->GetRootFrame();
1098
1099 if (rootFrame->IsFrameModified()) {
1100 // The whole frame tree is modified.
1101 return;
1102 }
1103
1104 auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
1105 if (!builder) {
1106 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1106); AnnotateMozCrashReason("MOZ_ASSERT" "(" "DisplayItems().IsEmpty()"
")"); do { *((volatile int*)__null) = 1106; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1107 return;
1108 }
1109
1110 RetainedDisplayListData* data = builder->Data();
1111 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1111); AnnotateMozCrashReason("MOZ_ASSERT" "(" "data" ")");
do { *((volatile int*)__null) = 1111; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1112
1113 if (data->AtModifiedFrameLimit()) {
1114 // This marks the whole frame tree modified.
1115 // See |RetainedDisplayListBuilder::ShouldBuildPartial()|.
1116 data->AddModifiedFrame(rootFrame);
1117 return;
1118 }
1119
1120 nsAutoString name;
1121#ifdef DEBUG_FRAME_DUMP1
1122 if (DL_LOG_TEST(LogLevel::Debug)(__builtin_expect(!!(mozilla::detail::log_test(GetLoggerByProcess
(), LogLevel::Debug)), 0))
) {
1123 GetFrameName(name);
1124 }
1125#endif
1126
1127 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)
1128 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)
;
1129
1130 data->AddModifiedFrame(this);
1131
1132 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1133); AnnotateMozCrashReason("MOZ_ASSERT" "(" "PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
")"); do { *((volatile int*)__null) = 1133; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1133 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1133); AnnotateMozCrashReason("MOZ_ASSERT" "(" "PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0"
")"); do { *((volatile int*)__null) = 1133; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1134
1135 // Hopefully this is cheap, but we could use a frame state bit to note
1136 // the presence of dependencies to speed it up.
1137 for (nsDisplayItem* i : DisplayItems()) {
1138 if (i->HasDeletedFrame() || i->Frame() == this) {
1139 // Ignore the items with deleted frames, and the items with |this| as
1140 // the primary frame.
1141 continue;
1142 }
1143
1144 if (i->GetDependentFrame() == this) {
1145 // For items with |this| as a dependent frame, mark the primary frame
1146 // for rebuild.
1147 i->Frame()->MarkNeedsDisplayItemRebuild();
1148 }
1149 }
1150}
1151
1152// Subclass hook for style post processing
1153/* virtual */
1154void nsIFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
1155#ifdef ACCESSIBILITY1
1156 // Don't notify for reconstructed frames here, since the frame is still being
1157 // constructed at this point and so LocalAccessible::GetFrame() will return
1158 // null. Style changes for reconstructed frames are handled in
1159 // DocAccessible::PruneOrInsertSubtree.
1160 if (aOldComputedStyle) {
1161 if (nsAccessibilityService* accService = GetAccService()) {
1162 accService->NotifyOfComputedStyleChange(PresShell(), mContent);
1163 }
1164 }
1165#endif
1166
1167 MaybeScheduleReflowSVGNonDisplayText(this);
1168
1169 Document* doc = PresContext()->Document();
1170 ImageLoader* loader = doc->StyleImageLoader();
1171 // Continuing text frame doesn't initialize its continuation pointer before
1172 // reaching here for the first time, so we have to exclude text frames. This
1173 // doesn't affect correctness because text can't match selectors.
1174 //
1175 // FIXME(emilio): We should consider fixing that.
1176 //
1177 // TODO(emilio): Can we avoid doing some / all of the image stuff when
1178 // isNonTextFirstContinuation is false? We should consider doing this just for
1179 // primary frames and pseudos, but the first-line reparenting code makes it
1180 // all bad, should get around to bug 1465474 eventually :(
1181 const bool isNonText = !IsTextFrame();
1182 if (isNonText) {
1183 mComputedStyle->StartImageLoads(*doc, aOldComputedStyle);
1184 }
1185
1186 const nsStyleImageLayers* oldLayers =
1187 aOldComputedStyle ? &aOldComputedStyle->StyleBackground()->mImage
1188 : nullptr;
1189 const nsStyleImageLayers* newLayers = &StyleBackground()->mImage;
1190 AddAndRemoveImageAssociations(*loader, this, oldLayers, newLayers);
1191
1192 oldLayers =
1193 aOldComputedStyle ? &aOldComputedStyle->StyleSVGReset()->mMask : nullptr;
1194 newLayers = &StyleSVGReset()->mMask;
1195 AddAndRemoveImageAssociations(*loader, this, oldLayers, newLayers);
1196
1197 const nsStyleDisplay* disp = StyleDisplay();
1198 bool handleStickyChange = false;
1199 if (aOldComputedStyle) {
1200 // Detect style changes that should trigger a scroll anchor adjustment
1201 // suppression.
1202 // https://drafts.csswg.org/css-scroll-anchoring/#suppression-triggers
1203 bool needAnchorSuppression = false;
1204
1205 const nsStyleMargin* oldMargin = aOldComputedStyle->StyleMargin();
1206 if (oldMargin->mMargin != StyleMargin()->mMargin) {
1207 needAnchorSuppression = true;
1208 }
1209
1210 const nsStylePadding* oldPadding = aOldComputedStyle->StylePadding();
1211 if (oldPadding->mPadding != StylePadding()->mPadding) {
1212 SetHasPaddingChange(true);
1213 needAnchorSuppression = true;
1214 }
1215
1216 const nsStyleDisplay* oldDisp = aOldComputedStyle->StyleDisplay();
1217 if (oldDisp->mOverflowAnchor != disp->mOverflowAnchor) {
1218 if (auto* container = ScrollAnchorContainer::FindFor(this)) {
1219 container->InvalidateAnchor();
1220 }
1221 if (ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(this)) {
1222 scrollContainerFrame->Anchor()->InvalidateAnchor();
1223 }
1224 }
1225
1226 if (mInScrollAnchorChain) {
1227 const nsStylePosition* pos = StylePosition();
1228 const nsStylePosition* oldPos = aOldComputedStyle->StylePosition();
1229 if (!needAnchorSuppression &&
1230 (oldPos->mOffset != pos->mOffset || oldPos->mWidth != pos->mWidth ||
1231 oldPos->mMinWidth != pos->mMinWidth ||
1232 oldPos->mMaxWidth != pos->mMaxWidth ||
1233 oldPos->mHeight != pos->mHeight ||
1234 oldPos->mMinHeight != pos->mMinHeight ||
1235 oldPos->mMaxHeight != pos->mMaxHeight ||
1236 oldDisp->mPosition != disp->mPosition ||
1237 oldDisp->mTransform != disp->mTransform)) {
1238 needAnchorSuppression = true;
1239 }
1240
1241 if (needAnchorSuppression &&
1242 StaticPrefs::layout_css_scroll_anchoring_suppressions_enabled()) {
1243 ScrollAnchorContainer::FindFor(this)->SuppressAdjustments();
1244 }
1245 }
1246
1247 if (disp->mPosition != oldDisp->mPosition) {
1248 if (!disp->IsRelativelyOrStickyPositionedStyle() &&
1249 oldDisp->IsRelativelyOrStickyPositionedStyle()) {
1250 RemoveProperty(NormalPositionProperty());
1251 }
1252
1253 handleStickyChange = disp->mPosition == StylePositionProperty::Sticky ||
1254 oldDisp->mPosition == StylePositionProperty::Sticky;
1255 }
1256 if (disp->mScrollSnapAlign != oldDisp->mScrollSnapAlign) {
1257 ScrollSnapUtils::PostPendingResnapFor(this);
1258 }
1259 if (aOldComputedStyle->IsRootElementStyle() &&
1260 disp->mScrollSnapType != oldDisp->mScrollSnapType) {
1261 if (ScrollContainerFrame* sf =
1262 PresShell()->GetRootScrollContainerFrame()) {
1263 sf->PostPendingResnap();
1264 }
1265 }
1266 if (StyleUIReset()->mMozSubtreeHiddenOnlyVisually &&
1267 !aOldComputedStyle->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
1268 PresShell::ClearMouseCapture(this);
1269 }
1270 } else { // !aOldComputedStyle
1271 handleStickyChange = disp->mPosition == StylePositionProperty::Sticky;
1272 }
1273
1274 if (handleStickyChange && !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) &&
1275 !GetPrevInFlow()) {
1276 // Note that we only add first continuations, but we really only
1277 // want to add first continuation-or-ib-split-siblings. But since we don't
1278 // yet know if we're a later part of a block-in-inline split, we'll just
1279 // add later members of a block-in-inline split here, and then
1280 // StickyScrollContainer will remove them later.
1281 if (auto* ssc =
1282 StickyScrollContainer::GetStickyScrollContainerForFrame(this)) {
1283 if (disp->mPosition == StylePositionProperty::Sticky) {
1284 ssc->AddFrame(this);
1285 } else {
1286 ssc->RemoveFrame(this);
1287 }
1288 }
1289 }
1290
1291 imgIRequest* oldBorderImage =
1292 aOldComputedStyle
1293 ? aOldComputedStyle->StyleBorder()->GetBorderImageRequest()
1294 : nullptr;
1295 imgIRequest* newBorderImage = StyleBorder()->GetBorderImageRequest();
1296 // FIXME (Bug 759996): The following is no longer true.
1297 // For border-images, we can't be as conservative (we need to set the
1298 // new loaders if there has been any change) since the CalcDifference
1299 // call depended on the result of GetComputedBorder() and that result
1300 // depends on whether the image has loaded, start the image load now
1301 // so that we'll get notified when it completes loading and can do a
1302 // restyle. Otherwise, the image might finish loading from the
1303 // network before we start listening to its notifications, and then
1304 // we'll never know that it's finished loading. Likewise, we want to
1305 // do this for freshly-created frames to prevent a similar race if the
1306 // image loads between reflow (which can depend on whether the image
1307 // is loaded) and paint. We also don't really care about any callers who try
1308 // to paint borders with a different style, because they won't have the
1309 // correct size for the border either.
1310 if (oldBorderImage != newBorderImage) {
1311 // stop and restart the image loading/notification
1312 if (oldBorderImage && HasImageRequest()) {
1313 loader->DisassociateRequestFromFrame(oldBorderImage, this);
1314 }
1315 if (newBorderImage) {
1316 loader->AssociateRequestToFrame(newBorderImage, this);
1317 }
1318 }
1319
1320 auto GetShapeImageRequest = [](const ComputedStyle* aStyle) -> imgIRequest* {
1321 if (!aStyle) {
1322 return nullptr;
1323 }
1324 auto& shape = aStyle->StyleDisplay()->mShapeOutside;
1325 if (!shape.IsImage()) {
1326 return nullptr;
1327 }
1328 return shape.AsImage().GetImageRequest();
1329 };
1330
1331 imgIRequest* oldShapeImage = GetShapeImageRequest(aOldComputedStyle);
1332 imgIRequest* newShapeImage = GetShapeImageRequest(Style());
1333 if (oldShapeImage != newShapeImage) {
1334 if (oldShapeImage && HasImageRequest()) {
1335 loader->DisassociateRequestFromFrame(oldShapeImage, this);
1336 }
1337 if (newShapeImage) {
1338 loader->AssociateRequestToFrame(
1339 newShapeImage, this,
1340 ImageLoader::Flags::
1341 RequiresReflowOnFirstFrameCompleteAndLoadEventBlocking);
1342 }
1343 }
1344
1345 // SVGObserverUtils::GetEffectProperties() asserts that we only invoke it with
1346 // the first continuation so we need to check that in advance.
1347 const bool isNonTextFirstContinuation = isNonText && !GetPrevContinuation();
1348 if (isNonTextFirstContinuation) {
1349 // Kick off loading of external SVG resources referenced from properties if
1350 // any. This currently includes filter, clip-path, and mask.
1351 SVGObserverUtils::InitiateResourceDocLoads(this);
1352 }
1353
1354 // If the page contains markup that overrides text direction, and
1355 // does not contain any characters that would activate the Unicode
1356 // bidi algorithm, we need to call |SetBidiEnabled| on the pres
1357 // context before reflow starts. See bug 115921.
1358 if (StyleVisibility()->mDirection == StyleDirection::Rtl) {
1359 PresContext()->SetBidiEnabled();
1360 }
1361
1362 // The following part is for caching offset-path:path(). We cache the
1363 // flatten gfx path, so we don't have to rebuild and re-flattern it at
1364 // each cycle if we have animations on offset-* with a fixed offset-path.
1365 const StyleOffsetPath* oldPath =
1366 aOldComputedStyle ? &aOldComputedStyle->StyleDisplay()->mOffsetPath
1367 : nullptr;
1368 const StyleOffsetPath& newPath = StyleDisplay()->mOffsetPath;
1369 if (!oldPath || *oldPath != newPath) {
1370 // FIXME: Bug 1837042. Cache all basic shapes.
1371 if (newPath.IsPath()) {
1372 RefPtr<gfx::PathBuilder> builder = MotionPathUtils::GetPathBuilder();
1373 RefPtr<gfx::Path> path =
1374 MotionPathUtils::BuildSVGPath(newPath.AsSVGPathData(), builder);
1375 if (path) {
1376 // The newPath could be path('') (i.e. empty path), so its gfx path
1377 // could be nullptr, and so we only set property for a non-empty path.
1378 SetProperty(nsIFrame::OffsetPathCache(), path.forget().take());
1379 } else {
1380 // May have an old cached path, so we have to delete it.
1381 RemoveProperty(nsIFrame::OffsetPathCache());
1382 }
1383 } else if (oldPath) {
1384 RemoveProperty(nsIFrame::OffsetPathCache());
1385 }
1386 }
1387
1388 if (IsPrimaryFrame()) {
1389 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1389); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aOldComputedStyle"
")"); do { *((volatile int*)__null) = 1389; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1390 HandlePrimaryFrameStyleChange(aOldComputedStyle);
1391 }
1392
1393 RemoveStateBits(NS_FRAME_SIMPLE_EVENT_REGIONS | NS_FRAME_SIMPLE_DISPLAYLIST);
1394
1395 mMayHaveRoundedCorners = true;
1396}
1397
1398void nsIFrame::HandleLastRememberedSize() {
1399 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1399); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsPrimaryFrame()"
")"); do { *((volatile int*)__null) = 1399; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1400 // Storing a last remembered size requires contain-intrinsic-size, and using
1401 // a previously stored last remembered size requires content-visibility.
1402 if (!StaticPrefs::layout_css_contain_intrinsic_size_enabled() ||
1403 !StaticPrefs::layout_css_content_visibility_enabled()) {
1404 return;
1405 }
1406 auto* element = Element::FromNodeOrNull(mContent);
1407 if (!element) {
1408 return;
1409 }
1410 const WritingMode wm = GetWritingMode();
1411 const nsStylePosition* stylePos = StylePosition();
1412 bool canRememberBSize = stylePos->ContainIntrinsicBSize(wm).HasAuto();
1413 bool canRememberISize = stylePos->ContainIntrinsicISize(wm).HasAuto();
1414 if (!canRememberBSize) {
1415 element->RemoveLastRememberedBSize();
1416 }
1417 if (!canRememberISize) {
1418 element->RemoveLastRememberedISize();
1419 }
1420 if ((canRememberBSize || canRememberISize) && !HidesContent()) {
1421 bool isNonReplacedInline = IsLineParticipant() && !IsReplaced();
1422 if (!isNonReplacedInline) {
1423 PresContext()->Document()->ObserveForLastRememberedSize(*element);
1424 return;
1425 }
1426 }
1427 PresContext()->Document()->UnobserveForLastRememberedSize(*element);
1428}
1429
1430#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED1
1431void nsIFrame::AssertNewStyleIsSane(ComputedStyle& aNewStyle) {
1432 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1433 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1434 // ::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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1435 // 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1436 (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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1437 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1438 // ::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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1439 // 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1440 // 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1441 (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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1442 aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) ||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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1443 (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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1444 PseudoStyleType::firstLetterContinuation &&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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1445 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
::firstLetterContinuation) || (mComputedStyle->GetPseudoType
() == PseudoStyleType::firstLetterContinuation && 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::firstLetterContinuation) || (mComputedStyle
->GetPseudoType() == PseudoStyleType::firstLetterContinuation
&& 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::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1445); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine && aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) || (mComputedStyle->GetPseudoType() == PseudoStyleType::mozText && aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) || (mComputedStyle->GetPseudoType() == PseudoStyleType::firstLetterContinuation && aNewStyle.GetPseudoType() == PseudoStyleType::mozText)"
")"); do { *((volatile int*)__null) = 1445; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1446}
1447#endif
1448
1449void nsIFrame::ReparentFrameViewTo(nsViewManager* aViewManager,
1450 nsView* aNewParentView) {
1451 if (HasView()) {
1452 if (IsMenuPopupFrame()) {
1453 // This view must be parented by the root view, don't reparent it.
1454 return;
1455 }
1456 nsView* view = GetView();
1457 aViewManager->RemoveChild(view);
1458
1459 // The view will remember the Z-order and other attributes that have been
1460 // set on it.
1461 nsView* insertBefore =
1462 nsLayoutUtils::FindSiblingViewFor(aNewParentView, this);
1463 aViewManager->InsertChild(aNewParentView, view, insertBefore,
1464 insertBefore != nullptr);
1465 } else if (HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW)) {
1466 for (const auto& childList : ChildLists()) {
1467 // Iterate the child frames, and check each child frame to see if it has
1468 // a view
1469 for (nsIFrame* child : childList.mList) {
1470 child->ReparentFrameViewTo(aViewManager, aNewParentView);
1471 }
1472 }
1473 }
1474}
1475
1476void nsIFrame::SyncFrameViewProperties(nsView* aView) {
1477 if (!aView) {
1478 aView = GetView();
1479 if (!aView) {
1480 return;
1481 }
1482 }
1483
1484 nsViewManager* vm = aView->GetViewManager();
1485
1486 // Make sure visibility is correct. This only affects nsSubDocumentFrame.
1487 if (!SupportsVisibilityHidden()) {
1488 // See if the view should be hidden or visible
1489 ComputedStyle* sc = Style();
1490 vm->SetViewVisibility(aView, sc->StyleVisibility()->IsVisible()
1491 ? ViewVisibility::Show
1492 : ViewVisibility::Hide);
1493 }
1494}
1495
1496void nsIFrame::CreateView() {
1497 MOZ_ASSERT(!HasView())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasView())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasView()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!HasView()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1497); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasView()"
")"); do { *((volatile int*)__null) = 1497; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1498
1499 nsView* parentView = GetParent()->GetClosestView();
1500 MOZ_ASSERT(parentView, "no parent with view")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parentView)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(parentView))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("parentView" " (" "no parent with view"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1500); AnnotateMozCrashReason("MOZ_ASSERT" "(" "parentView"
") (" "no parent with view" ")"); do { *((volatile int*)__null
) = 1500; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
1501
1502 nsViewManager* viewManager = parentView->GetViewManager();
1503 MOZ_ASSERT(viewManager, "null view manager")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(viewManager)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(viewManager))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("viewManager" " ("
"null view manager" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1503); AnnotateMozCrashReason("MOZ_ASSERT" "(" "viewManager"
") (" "null view manager" ")"); do { *((volatile int*)__null
) = 1503; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
1504
1505 nsView* view = viewManager->CreateView(GetRect(), parentView);
1506 SyncFrameViewProperties(view);
1507
1508 nsView* insertBefore = nsLayoutUtils::FindSiblingViewFor(parentView, this);
1509 // we insert this view 'above' the insertBefore view, unless insertBefore is
1510 // null, in which case we want to call with aAbove == false to insert at the
1511 // beginning in document order
1512 viewManager->InsertChild(parentView, view, insertBefore,
1513 insertBefore != nullptr);
1514
1515 // REVIEW: Don't create a widget for fixed-pos elements anymore.
1516 // ComputeRepaintRegionForCopy will calculate the right area to repaint
1517 // when we scroll.
1518 // Reparent views on any child frames (or their descendants) to this
1519 // view. We can just call ReparentFrameViewTo on this frame because
1520 // we know this frame has no view, so it will crawl the children. Also,
1521 // we know that any descendants with views must have 'parentView' as their
1522 // parent view.
1523 ReparentFrameViewTo(viewManager, view);
1524
1525 // Remember our view
1526 SetView(view);
1527
1528 NS_FRAME_LOG(NS_FRAME_TRACE_CALLS,do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsIFrame::CreateView: frame=%p view=%p"
, this, view); } } while (0)
1529 ("nsIFrame::CreateView: frame=%p view=%p", this, view))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { printf_stderr ("nsIFrame::CreateView: frame=%p view=%p"
, this, view); } } while (0)
;
1530}
1531
1532/* virtual */
1533nsMargin nsIFrame::GetUsedMargin() const {
1534 nsMargin margin;
1535 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1536 IsInSVGTextSubtree()) {
1537 return margin;
1538 }
1539
1540 if (nsMargin* m = GetProperty(UsedMarginProperty())) {
1541 margin = *m;
1542 } else if (!StyleMargin()->GetMargin(margin)) {
1543 // If we get here, our caller probably shouldn't be calling us...
1544 NS_ERROR(do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized margin, because this margin "
"depends on layout & isn't cached!", "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1546); MOZ_PretendNoReturn(); } while (0)
1545 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1546); MOZ_PretendNoReturn(); } while (0)
1546 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1546); MOZ_PretendNoReturn(); } while (0)
;
1547 }
1548 return margin;
1549}
1550
1551/* virtual */
1552nsMargin nsIFrame::GetUsedBorder() const {
1553 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1554 IsInSVGTextSubtree()) {
1555 return {};
1556 }
1557
1558 const nsStyleDisplay* disp = StyleDisplay();
1559 if (IsThemed(disp)) {
1560 // Theme methods don't use const-ness.
1561 auto* mutable_this = const_cast<nsIFrame*>(this);
1562 nsPresContext* pc = PresContext();
1563 LayoutDeviceIntMargin widgetBorder = pc->Theme()->GetWidgetBorder(
1564 pc->DeviceContext(), mutable_this, disp->EffectiveAppearance());
1565 return LayoutDevicePixel::ToAppUnits(widgetBorder,
1566 pc->AppUnitsPerDevPixel());
1567 }
1568
1569 return StyleBorder()->GetComputedBorder();
1570}
1571
1572/* virtual */
1573nsMargin nsIFrame::GetUsedPadding() const {
1574 nsMargin padding;
1575 if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
1576 IsInSVGTextSubtree()) {
1577 return padding;
1578 }
1579
1580 const nsStyleDisplay* disp = StyleDisplay();
1581 if (IsThemed(disp)) {
1582 // Theme methods don't use const-ness.
1583 nsIFrame* mutable_this = const_cast<nsIFrame*>(this);
1584 nsPresContext* pc = PresContext();
1585 LayoutDeviceIntMargin widgetPadding;
1586 if (pc->Theme()->GetWidgetPadding(pc->DeviceContext(), mutable_this,
1587 disp->EffectiveAppearance(),
1588 &widgetPadding)) {
1589 return LayoutDevicePixel::ToAppUnits(widgetPadding,
1590 pc->AppUnitsPerDevPixel());
1591 }
1592 }
1593
1594 if (nsMargin* p = GetProperty(UsedPaddingProperty())) {
1595 padding = *p;
1596 } else if (!StylePadding()->GetPadding(padding)) {
1597 // If we get here, our caller probably shouldn't be calling us...
1598 NS_ERROR(do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Returning bogus 0-sized padding, because this padding "
"depends on layout & isn't cached!", "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1600); MOZ_PretendNoReturn(); } while (0)
1599 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1600); MOZ_PretendNoReturn(); } while (0)
1600 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1600); MOZ_PretendNoReturn(); } while (0)
;
1601 }
1602 return padding;
1603}
1604
1605nsIFrame::Sides nsIFrame::GetSkipSides() const {
1606 if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
1607 StyleBoxDecorationBreak::Clone)(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
&&
1608 !HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
1609 return Sides();
1610 }
1611
1612 // Convert the logical skip sides to physical sides using the frame's
1613 // writing mode
1614 WritingMode writingMode = GetWritingMode();
1615 LogicalSides logicalSkip = GetLogicalSkipSides();
1616 Sides skip;
1617
1618 if (logicalSkip.BStart()) {
1619 if (writingMode.IsVertical()) {
1620 skip |= writingMode.IsVerticalLR() ? SideBits::eLeft : SideBits::eRight;
1621 } else {
1622 skip |= SideBits::eTop;
1623 }
1624 }
1625
1626 if (logicalSkip.BEnd()) {
1627 if (writingMode.IsVertical()) {
1628 skip |= writingMode.IsVerticalLR() ? SideBits::eRight : SideBits::eLeft;
1629 } else {
1630 skip |= SideBits::eBottom;
1631 }
1632 }
1633
1634 if (logicalSkip.IStart()) {
1635 if (writingMode.IsVertical()) {
1636 skip |= SideBits::eTop;
1637 } else {
1638 skip |= writingMode.IsBidiLTR() ? SideBits::eLeft : SideBits::eRight;
1639 }
1640 }
1641
1642 if (logicalSkip.IEnd()) {
1643 if (writingMode.IsVertical()) {
1644 skip |= SideBits::eBottom;
1645 } else {
1646 skip |= writingMode.IsBidiLTR() ? SideBits::eRight : SideBits::eLeft;
1647 }
1648 }
1649 return skip;
1650}
1651
1652nsRect nsIFrame::GetPaddingRectRelativeToSelf() const {
1653 nsMargin border = GetUsedBorder().ApplySkipSides(GetSkipSides());
1654 nsRect r(0, 0, mRect.width, mRect.height);
1655 r.Deflate(border);
1656 return r;
1657}
1658
1659nsRect nsIFrame::GetPaddingRect() const {
1660 return GetPaddingRectRelativeToSelf() + GetPosition();
1661}
1662
1663WritingMode nsIFrame::WritingModeForLine(WritingMode aSelfWM,
1664 nsIFrame* aSubFrame) const {
1665 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1665); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aSelfWM == GetWritingMode()"
")"); do { *((volatile int*)__null) = 1665; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1666 WritingMode writingMode = aSelfWM;
1667
1668 if (StyleTextReset()->mUnicodeBidi == StyleUnicodeBidi::Plaintext) {
1669 mozilla::intl::BidiEmbeddingLevel frameLevel =
1670 nsBidiPresUtils::GetFrameBaseLevel(aSubFrame);
1671 writingMode.SetDirectionFromBidiLevel(frameLevel);
1672 }
1673
1674 return writingMode;
1675}
1676
1677nsRect nsIFrame::GetMarginRect() const {
1678 return GetMarginRectRelativeToSelf() + GetPosition();
1679}
1680
1681nsRect nsIFrame::GetMarginRectRelativeToSelf() const {
1682 nsMargin m = GetUsedMargin().ApplySkipSides(GetSkipSides());
1683 nsRect r(0, 0, mRect.width, mRect.height);
1684 r.Inflate(m);
1685 return r;
1686}
1687
1688bool nsIFrame::IsTransformed() const {
1689 if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
1690 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1690); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsCSSTransformed()"
")"); do { *((volatile int*)__null) = 1690; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1691 MOZ_ASSERT(!IsSVGTransformed())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsSVGTransformed())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsSVGTransformed()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("!IsSVGTransformed()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1691); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsSVGTransformed()"
")"); do { *((volatile int*)__null) = 1691; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1692 return false;
1693 }
1694 return IsCSSTransformed() || IsSVGTransformed();
1695}
1696
1697bool nsIFrame::IsCSSTransformed() const {
1698 return HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED) &&
1699 (StyleDisplay()->HasTransform(this) || HasAnimationOfTransform());
1700}
1701
1702bool nsIFrame::HasAnimationOfTransform() const {
1703 return IsPrimaryFrame() &&
1704 nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this) &&
1705 SupportsCSSTransforms();
1706}
1707
1708bool nsIFrame::ChildrenHavePerspective(
1709 const nsStyleDisplay* aStyleDisplay) const {
1710 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1710); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStyleDisplay == StyleDisplay()"
")"); do { *((volatile int*)__null) = 1710; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1711 return aStyleDisplay->HasPerspective(this);
1712}
1713
1714bool nsIFrame::HasAnimationOfOpacity(EffectSet* aEffectSet) const {
1715 return ((nsLayoutUtils::IsPrimaryStyleFrame(this) ||
1716 nsLayoutUtils::FirstContinuationOrIBSplitSibling(this)
1717 ->IsPrimaryFrame()) &&
1718 nsLayoutUtils::HasAnimationOfPropertySet(
1719 this, nsCSSPropertyIDSet::OpacityProperties(), aEffectSet));
1720}
1721
1722bool nsIFrame::HasOpacityInternal(float aThreshold,
1723 const nsStyleDisplay* aStyleDisplay,
1724 const nsStyleEffects* aStyleEffects,
1725 EffectSet* aEffectSet) const {
1726 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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 1726); AnnotateMozCrashReason("MOZ_ASSERT" "(" "0.0 <= aThreshold && aThreshold <= 1.0"
") (" "Invalid argument" ")"); do { *((volatile int*)__null)
= 1726; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
1727 if (aStyleEffects->mOpacity < aThreshold ||
1728 aStyleDisplay->mWillChange.bits & StyleWillChangeBits::OPACITY) {
1729 return true;
1730 }
1731
1732 if (!mMayHaveOpacityAnimation) {
1733 return false;
1734 }
1735
1736 return HasAnimationOfOpacity(aEffectSet);
1737}
1738
1739bool nsIFrame::IsSVGTransformed(gfx::Matrix* aOwnTransforms,
1740 gfx::Matrix* aFromParentTransforms) const {
1741 return false;
1742}
1743
1744bool nsIFrame::Extend3DContext(const nsStyleDisplay* aStyleDisplay,
1745 const nsStyleEffects* aStyleEffects,
1746 mozilla::EffectSet* aEffectSetForOpacity) const {
1747 if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
1748 return false;
1749 }
1750 const nsStyleDisplay* disp = StyleDisplayWithOptionalParam(aStyleDisplay);
1751 if (disp->mTransformStyle != StyleTransformStyle::Preserve3d ||
1752 !SupportsCSSTransforms()) {
1753 return false;
1754 }
1755
1756 // If we're all scroll frame, then all descendants will be clipped, so we
1757 // can't preserve 3d.
1758 if (IsScrollContainerFrame()) {
1759 return false;
1760 }
1761
1762 const nsStyleEffects* effects = StyleEffectsWithOptionalParam(aStyleEffects);
1763 if (HasOpacity(disp, effects, aEffectSetForOpacity)) {
1764 return false;
1765 }
1766
1767 return ShouldApplyOverflowClipping(disp).isEmpty() &&
1768 !GetClipPropClipRect(disp, effects, GetSize()) &&
1769 !SVGIntegrationUtils::UsingEffectsForFrame(this) &&
1770 !effects->HasMixBlendMode() &&
1771 disp->mIsolation != StyleIsolation::Isolate;
1772}
1773
1774bool nsIFrame::Combines3DTransformWithAncestors() const {
1775 // Check these first as they are faster then both calls below and are we are
1776 // likely to hit the early return (backface hidden is uncommon and
1777 // GetReferenceFrame is a hot caller of this which only calls this if
1778 // IsCSSTransformed is false).
1779 if (!IsCSSTransformed() && !BackfaceIsHidden()) {
1780 return false;
1781 }
1782 nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
1783 return parent && parent->Extend3DContext();
1784}
1785
1786bool nsIFrame::In3DContextAndBackfaceIsHidden() const {
1787 // While both tests fail most of the time, test BackfaceIsHidden()
1788 // first since it's likely to fail faster.
1789 return BackfaceIsHidden() && Combines3DTransformWithAncestors();
1790}
1791
1792bool nsIFrame::HasPerspective() const {
1793 if (!IsCSSTransformed()) {
1794 return false;
1795 }
1796 nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
1797 if (!parent) {
1798 return false;
1799 }
1800 return parent->ChildrenHavePerspective();
1801}
1802
1803nsRect nsIFrame::GetContentRectRelativeToSelf() const {
1804 nsMargin bp = GetUsedBorderAndPadding().ApplySkipSides(GetSkipSides());
1805 nsRect r(0, 0, mRect.width, mRect.height);
1806 r.Deflate(bp);
1807 return r;
1808}
1809
1810nsRect nsIFrame::GetContentRect() const {
1811 return GetContentRectRelativeToSelf() + GetPosition();
1812}
1813
1814bool nsIFrame::ComputeBorderRadii(const BorderRadius& aBorderRadius,
1815 const nsSize& aFrameSize,
1816 const nsSize& aBorderArea, Sides aSkipSides,
1817 nscoord aRadii[8]) {
1818 // Percentages are relative to whichever side they're on.
1819 for (const auto i : mozilla::AllPhysicalHalfCorners()) {
1820 const LengthPercentage& c = aBorderRadius.Get(i);
1821 nscoord axis = HalfCornerIsX(i) ? aFrameSize.width : aFrameSize.height;
1822 aRadii[i] = std::max(0, c.Resolve(axis));
1823 }
1824
1825 if (aSkipSides.Top()) {
1826 aRadii[eCornerTopLeftX] = 0;
1827 aRadii[eCornerTopLeftY] = 0;
1828 aRadii[eCornerTopRightX] = 0;
1829 aRadii[eCornerTopRightY] = 0;
1830 }
1831
1832 if (aSkipSides.Right()) {
1833 aRadii[eCornerTopRightX] = 0;
1834 aRadii[eCornerTopRightY] = 0;
1835 aRadii[eCornerBottomRightX] = 0;
1836 aRadii[eCornerBottomRightY] = 0;
1837 }
1838
1839 if (aSkipSides.Bottom()) {
1840 aRadii[eCornerBottomRightX] = 0;
1841 aRadii[eCornerBottomRightY] = 0;
1842 aRadii[eCornerBottomLeftX] = 0;
1843 aRadii[eCornerBottomLeftY] = 0;
1844 }
1845
1846 if (aSkipSides.Left()) {
1847 aRadii[eCornerBottomLeftX] = 0;
1848 aRadii[eCornerBottomLeftY] = 0;
1849 aRadii[eCornerTopLeftX] = 0;
1850 aRadii[eCornerTopLeftY] = 0;
1851 }
1852
1853 // css3-background specifies this algorithm for reducing
1854 // corner radii when they are too big.
1855 bool haveRadius = false;
1856 double ratio = 1.0f;
1857 for (const auto side : mozilla::AllPhysicalSides()) {
1858 uint32_t hc1 = SideToHalfCorner(side, false, true);
1859 uint32_t hc2 = SideToHalfCorner(side, true, true);
1860 nscoord length =
1861 SideIsVertical(side) ? aBorderArea.height : aBorderArea.width;
1862 nscoord sum = aRadii[hc1] + aRadii[hc2];
1863 if (sum) {
1864 haveRadius = true;
1865 // avoid floating point division in the normal case
1866 if (length < sum) {
1867 ratio = std::min(ratio, double(length) / sum);
1868 }
1869 }
1870 }
1871 if (ratio < 1.0) {
1872 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1873 aRadii[corner] *= ratio;
1874 }
1875 }
1876
1877 return haveRadius;
1878}
1879
1880void nsIFrame::AdjustBorderRadii(nscoord aRadii[8], const nsMargin& aOffsets) {
1881 auto AdjustOffset = [](const uint32_t aRadius, const nscoord aOffset) {
1882 // Implement the cubic formula to adjust offset when aOffset > 0 and
1883 // aRadius / aOffset < 1.
1884 // https://drafts.csswg.org/css-shapes/#valdef-shape-box-margin-box
1885 if (aOffset > 0) {
1886 const double ratio = aRadius / double(aOffset);
1887 if (ratio < 1.0) {
1888 return nscoord(aOffset * (1.0 + std::pow(ratio - 1, 3)));
1889 }
1890 }
1891 return aOffset;
1892 };
1893
1894 for (const auto side : mozilla::AllPhysicalSides()) {
1895 const nscoord offset = aOffsets.Side(side);
1896 const uint32_t hc1 = SideToHalfCorner(side, false, false);
1897 const uint32_t hc2 = SideToHalfCorner(side, true, false);
1898 if (aRadii[hc1] > 0) {
1899 const nscoord offset1 = AdjustOffset(aRadii[hc1], offset);
1900 aRadii[hc1] = std::max(0, aRadii[hc1] + offset1);
1901 }
1902 if (aRadii[hc2] > 0) {
1903 const nscoord offset2 = AdjustOffset(aRadii[hc2], offset);
1904 aRadii[hc2] = std::max(0, aRadii[hc2] + offset2);
1905 }
1906 }
1907}
1908
1909static inline bool RadiiAreDefinitelyZero(const BorderRadius& aBorderRadius) {
1910 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1911 if (!aBorderRadius.Get(corner).IsDefinitelyZero()) {
1912 return false;
1913 }
1914 }
1915 return true;
1916}
1917
1918/* virtual */
1919bool nsIFrame::GetBorderRadii(const nsSize& aFrameSize,
1920 const nsSize& aBorderArea, Sides aSkipSides,
1921 nscoord aRadii[8]) const {
1922 if (!mMayHaveRoundedCorners) {
1923 memset(aRadii, 0, sizeof(nscoord) * 8);
1924 return false;
1925 }
1926
1927 if (IsThemed()) {
1928 // When we're themed, the native theme code draws the border and
1929 // background, and therefore it doesn't make sense to tell other
1930 // code that's interested in border-radius that we have any radii.
1931 //
1932 // In an ideal world, we might have a way for the them to tell us an
1933 // border radius, but since we don't, we're better off assuming
1934 // zero.
1935 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1936 aRadii[corner] = 0;
1937 }
1938 return false;
1939 }
1940
1941 const auto& radii = StyleBorder()->mBorderRadius;
1942 const bool hasRadii =
1943 ComputeBorderRadii(radii, aFrameSize, aBorderArea, aSkipSides, aRadii);
1944 if (!hasRadii) {
1945 // TODO(emilio): Maybe we can just remove this bit and do the
1946 // IsDefinitelyZero check unconditionally. That should still avoid most of
1947 // the work, though maybe not the cache miss of going through the style and
1948 // the border struct.
1949 const_cast<nsIFrame*>(this)->mMayHaveRoundedCorners =
1950 !RadiiAreDefinitelyZero(radii);
1951 }
1952 return hasRadii;
1953}
1954
1955bool nsIFrame::GetBorderRadii(nscoord aRadii[8]) const {
1956 nsSize sz = GetSize();
1957 return GetBorderRadii(sz, sz, GetSkipSides(), aRadii);
1958}
1959
1960bool nsIFrame::GetMarginBoxBorderRadii(nscoord aRadii[8]) const {
1961 return GetBoxBorderRadii(aRadii, GetUsedMargin());
1962}
1963
1964bool nsIFrame::GetPaddingBoxBorderRadii(nscoord aRadii[8]) const {
1965 return GetBoxBorderRadii(aRadii, -GetUsedBorder());
1966}
1967
1968bool nsIFrame::GetContentBoxBorderRadii(nscoord aRadii[8]) const {
1969 return GetBoxBorderRadii(aRadii, -GetUsedBorderAndPadding());
1970}
1971
1972bool nsIFrame::GetBoxBorderRadii(nscoord aRadii[8],
1973 const nsMargin& aOffsets) const {
1974 if (!GetBorderRadii(aRadii)) {
1975 return false;
1976 }
1977 AdjustBorderRadii(aRadii, aOffsets);
1978 for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
1979 if (aRadii[corner]) {
1980 return true;
1981 }
1982 }
1983 return false;
1984}
1985
1986bool nsIFrame::GetShapeBoxBorderRadii(nscoord aRadii[8]) const {
1987 using Tag = StyleShapeOutside::Tag;
1988 auto& shapeOutside = StyleDisplay()->mShapeOutside;
1989 auto box = StyleShapeBox::MarginBox;
1990 switch (shapeOutside.tag) {
1991 case Tag::Image:
1992 case Tag::None:
1993 return false;
1994 case Tag::Box:
1995 box = shapeOutside.AsBox();
1996 break;
1997 case Tag::Shape:
1998 box = shapeOutside.AsShape()._1;
1999 break;
2000 }
2001
2002 switch (box) {
2003 case StyleShapeBox::ContentBox:
2004 return GetContentBoxBorderRadii(aRadii);
2005 case StyleShapeBox::PaddingBox:
2006 return GetPaddingBoxBorderRadii(aRadii);
2007 case StyleShapeBox::BorderBox:
2008 return GetBorderRadii(aRadii);
2009 case StyleShapeBox::MarginBox:
2010 return GetMarginBoxBorderRadii(aRadii);
2011 default:
2012 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2012); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unexpected box value" ")"); do {
*((volatile int*)__null) = 2012; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
2013 return false;
2014 }
2015}
2016
2017nscoord nsIFrame::OneEmInAppUnits() const {
2018 return StyleFont()
2019 ->mFont.size.ScaledBy(nsLayoutUtils::FontSizeInflationFor(this))
2020 .ToAppUnits();
2021}
2022
2023ComputedStyle* nsIFrame::GetAdditionalComputedStyle(int32_t aIndex) const {
2024 MOZ_ASSERT(aIndex >= 0, "invalid index number")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aIndex >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aIndex >= 0))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("aIndex >= 0"
" (" "invalid index number" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2024); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aIndex >= 0"
") (" "invalid index number" ")"); do { *((volatile int*)__null
) = 2024; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
2025 return nullptr;
2026}
2027
2028void nsIFrame::SetAdditionalComputedStyle(int32_t aIndex,
2029 ComputedStyle* aComputedStyle) {
2030 MOZ_ASSERT(aIndex >= 0, "invalid index number")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aIndex >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aIndex >= 0))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("aIndex >= 0"
" (" "invalid index number" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2030); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aIndex >= 0"
") (" "invalid index number" ")"); do { *((volatile int*)__null
) = 2030; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
2031}
2032
2033nscoord nsIFrame::SynthesizeFallbackBaseline(
2034 WritingMode aWM, BaselineSharingGroup aBaselineGroup) const {
2035 const auto margin = GetLogicalUsedMargin(aWM);
2036 NS_ASSERTION(!IsSubtreeDirty(), "frame must not be dirty")do { if (!(!IsSubtreeDirty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "frame must not be dirty", "!IsSubtreeDirty()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2036); MOZ_PretendNoReturn(); } } while (0)
;
2037 if (aWM.IsCentralBaseline()) {
2038 return (BSize(aWM) + GetLogicalUsedMargin(aWM).BEnd(aWM)) / 2;
2039 }
2040 // Baseline for inverted line content is the top (block-start) margin edge,
2041 // as the frame is in effect "flipped" for alignment purposes.
2042 if (aWM.IsLineInverted()) {
2043 const auto marginStart = margin.BStart(aWM);
2044 return aBaselineGroup == BaselineSharingGroup::First
2045 ? -marginStart
2046 : BSize(aWM) + marginStart;
2047 }
2048 // Otherwise, the bottom margin edge, per CSS2.1's definition of the
2049 // 'baseline' value of 'vertical-align'.
2050 const auto marginEnd = margin.BEnd(aWM);
2051 return aBaselineGroup == BaselineSharingGroup::First ? BSize(aWM) + marginEnd
2052 : -marginEnd;
2053}
2054
2055nscoord nsIFrame::GetLogicalBaseline(WritingMode aWM) const {
2056 return GetLogicalBaseline(aWM, GetDefaultBaselineSharingGroup(),
2057 BaselineExportContext::LineLayout);
2058}
2059
2060nscoord nsIFrame::GetLogicalBaseline(
2061 WritingMode aWM, BaselineSharingGroup aBaselineGroup,
2062 BaselineExportContext aExportContext) const {
2063 const auto result =
2064 GetNaturalBaselineBOffset(aWM, aBaselineGroup, aExportContext)
2065 .valueOrFrom([this, aWM, aBaselineGroup]() {
2066 return SynthesizeFallbackBaseline(aWM, aBaselineGroup);
2067 });
2068 if (aBaselineGroup == BaselineSharingGroup::Last) {
2069 return BSize(aWM) - result;
2070 }
2071 return result;
2072}
2073
2074const nsFrameList& nsIFrame::GetChildList(ChildListID aListID) const {
2075 if (IsAbsoluteContainer() && aListID == GetAbsoluteListID()) {
2076 return GetAbsoluteContainingBlock()->GetChildList();
2077 } else {
2078 return nsFrameList::EmptyList();
2079 }
2080}
2081
2082void nsIFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
2083 if (IsAbsoluteContainer()) {
2084 const nsFrameList& absoluteList =
2085 GetAbsoluteContainingBlock()->GetChildList();
2086 absoluteList.AppendIfNonempty(aLists, GetAbsoluteListID());
2087 }
2088}
2089
2090AutoTArray<nsIFrame::ChildList, 4> nsIFrame::CrossDocChildLists() {
2091 AutoTArray<ChildList, 4> childLists;
2092 nsSubDocumentFrame* subdocumentFrame = do_QueryFrame(this);
2093 if (subdocumentFrame) {
2094 // Descend into the subdocument
2095 nsIFrame* root = subdocumentFrame->GetSubdocumentRootFrame();
2096 if (root) {
2097 childLists.EmplaceBack(
2098 nsFrameList(root, nsLayoutUtils::GetLastSibling(root)),
2099 FrameChildListID::Principal);
2100 }
2101 }
2102
2103 GetChildLists(&childLists);
2104 return childLists;
2105}
2106
2107nsIFrame::CaretBlockAxisMetrics nsIFrame::GetCaretBlockAxisMetrics(
2108 mozilla::WritingMode aWM, const nsFontMetrics& aFM) const {
2109 // Note(dshin): Ultimately, this does something highly similar (But still
2110 // different) to `nsLayoutUtils::GetFirstLinePosition`.
2111 const auto baseline = GetCaretBaseline();
2112 nscoord ascent = 0, descent = 0;
2113 ascent = aFM.MaxAscent();
2114 descent = aFM.MaxDescent();
2115 const nscoord height = ascent + descent;
2116 if (aWM.IsVertical() && aWM.IsLineInverted()) {
2117 return CaretBlockAxisMetrics{.mOffset = baseline - descent,
2118 .mExtent = height};
2119 }
2120 return CaretBlockAxisMetrics{.mOffset = baseline - ascent, .mExtent = height};
2121}
2122
2123const nsAtom* nsIFrame::ComputePageValue(const nsAtom* aAutoValue) const {
2124 const nsAtom* value = aAutoValue ? aAutoValue : nsGkAtoms::_empty;
2125 const nsIFrame* frame = this;
2126 // Find what CSS page name value this frame's subtree has, if any.
2127 // Starting with this frame, check if a page name other than auto is present,
2128 // and record it if so. Then, if the current frame is a container frame, find
2129 // the first non-placeholder child and repeat.
2130 // This will find the most deeply nested first in-flow child of this frame's
2131 // subtree, and return its page name (with auto resolved if applicable, and
2132 // subtrees with no page-names returning the empty atom rather than null).
2133 do {
2134 if (const nsAtom* maybePageName = frame->GetStylePageName()) {
2135 value = maybePageName;
2136 }
2137 // Get the next frame to read from.
2138 const nsIFrame* firstNonPlaceholderFrame = nullptr;
2139 // If this is a container frame, inspect its in-flow children.
2140 if (const nsContainerFrame* containerFrame = do_QueryFrame(frame)) {
2141 for (const nsIFrame* childFrame : containerFrame->PrincipalChildList()) {
2142 if (!childFrame->IsPlaceholderFrame()) {
2143 firstNonPlaceholderFrame = childFrame;
2144 break;
2145 }
2146 }
2147 }
2148 frame = firstNonPlaceholderFrame;
2149 } while (frame);
2150 return value;
2151}
2152
2153Visibility nsIFrame::GetVisibility() const {
2154 if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2155 return Visibility::Untracked;
2156 }
2157
2158 bool isSet = false;
2159 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2160
2161 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2163); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2163; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2162 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2163); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2163; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2163 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2163); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2163; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2164
2165 return visibleCount > 0 ? Visibility::ApproximatelyVisible
2166 : Visibility::ApproximatelyNonVisible;
2167}
2168
2169void nsIFrame::UpdateVisibilitySynchronously() {
2170 mozilla::PresShell* presShell = PresShell();
2171 if (!presShell) {
2172 return;
2173 }
2174
2175 if (presShell->AssumeAllFramesVisible()) {
2176 presShell->EnsureFrameInApproximatelyVisibleList(this);
2177 return;
2178 }
2179
2180 bool visible = StyleVisibility()->IsVisible();
2181 nsIFrame* f = GetParent();
2182 nsRect rect = GetRectRelativeToSelf();
2183 nsIFrame* rectFrame = this;
2184 while (f && visible) {
2185 if (ScrollContainerFrame* sf = do_QueryFrame(f)) {
2186 nsRect transformedRect =
2187 nsLayoutUtils::TransformFrameRectToAncestor(rectFrame, rect, f);
2188 if (!sf->IsRectNearlyVisible(transformedRect)) {
2189 visible = false;
2190 break;
2191 }
2192
2193 // In this code we're trying to synchronously update *approximate*
2194 // visibility. (In the future we may update precise visibility here as
2195 // well, which is why the method name does not contain 'approximate'.) The
2196 // IsRectNearlyVisible() check above tells us that the rect we're checking
2197 // is approximately visible within the scrollframe, but we still need to
2198 // ensure that, even if it was scrolled into view, it'd be visible when we
2199 // consider the rest of the document. To do that, we move transformedRect
2200 // to be contained in the scrollport as best we can (it might not fit) to
2201 // pretend that it was scrolled into view.
2202 rect = transformedRect.MoveInsideAndClamp(sf->GetScrollPortRect());
2203 rectFrame = f;
2204 }
2205 nsIFrame* parent = f->GetParent();
2206 if (!parent) {
2207 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(f);
2208 if (parent && parent->PresContext()->IsChrome()) {
2209 break;
2210 }
2211 }
2212 f = parent;
2213 }
2214
2215 if (visible) {
2216 presShell->EnsureFrameInApproximatelyVisibleList(this);
2217 } else {
2218 presShell->RemoveFrameFromApproximatelyVisibleList(this);
2219 }
2220}
2221
2222void nsIFrame::EnableVisibilityTracking() {
2223 if (HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2224 return; // Nothing to do.
2225 }
2226
2227 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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2229); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())"
") (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { *((volatile int*)__null) = 2229; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2228 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2229); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())"
") (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { *((volatile int*)__null) = 2229; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2229 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2229); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasProperty(VisibilityStateProperty())"
") (" "Shouldn't have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is not set"
")"); do { *((volatile int*)__null) = 2229; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2230
2231 // Add the state bit so we know to track visibility for this frame, and
2232 // initialize the frame property.
2233 AddStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
2234 SetProperty(VisibilityStateProperty(), 0);
2235
2236 mozilla::PresShell* presShell = PresShell();
2237 if (!presShell) {
2238 return;
2239 }
2240
2241 // Schedule a visibility update. This method will virtually always be called
2242 // when layout has changed anyway, so it's very unlikely that any additional
2243 // visibility updates will be triggered by this, but this way we guarantee
2244 // that if this frame is currently visible we'll eventually find out.
2245 presShell->ScheduleApproximateFrameVisibilityUpdateSoon();
2246}
2247
2248void nsIFrame::DisableVisibilityTracking() {
2249 if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
2250 return; // Nothing to do.
2251 }
2252
2253 bool isSet = false;
2254 uint32_t visibleCount = TakeProperty(VisibilityStateProperty(), &isSet);
2255
2256 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2258); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2258; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2257 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2258); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2258; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2258 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2258); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2258; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2259
2260 RemoveStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
2261
2262 if (visibleCount == 0) {
2263 return; // We were nonvisible.
2264 }
2265
2266 // We were visible, so send an OnVisibilityChange() notification.
2267 OnVisibilityChange(Visibility::ApproximatelyNonVisible);
2268}
2269
2270void nsIFrame::DecApproximateVisibleCount(
2271 const Maybe<OnNonvisible>& aNonvisibleAction
2272 /* = Nothing() */) {
2273 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2273); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
")"); do { *((volatile int*)__null) = 2273; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2274
2275 bool isSet = false;
2276 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2277
2278 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2280); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2280; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2279 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2280); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2280; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2280 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2280); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2280; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2281 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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2283); AnnotateMozCrashReason("MOZ_ASSERT" "(" "visibleCount > 0"
") (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")"); do { *((volatile int*)__null) = 2283; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2282 "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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2283); AnnotateMozCrashReason("MOZ_ASSERT" "(" "visibleCount > 0"
") (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")"); do { *((volatile int*)__null) = 2283; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2283 "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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2283); AnnotateMozCrashReason("MOZ_ASSERT" "(" "visibleCount > 0"
") (" "Frame is already nonvisible and we're " "decrementing its visible count?"
")"); do { *((volatile int*)__null) = 2283; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2284
2285 visibleCount--;
2286 SetProperty(VisibilityStateProperty(), visibleCount);
2287 if (visibleCount > 0) {
2288 return;
2289 }
2290
2291 // We just became nonvisible, so send an OnVisibilityChange() notification.
2292 OnVisibilityChange(Visibility::ApproximatelyNonVisible, aNonvisibleAction);
2293}
2294
2295void nsIFrame::IncApproximateVisibleCount() {
2296 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2296); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)"
")"); do { *((volatile int*)__null) = 2296; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2297
2298 bool isSet = false;
2299 uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
2300
2301 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2303); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2303; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2302 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2303); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2303; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2303 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2303); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isSet" ") ("
"Should have a VisibilityStateProperty value " "if NS_FRAME_VISIBILITY_IS_TRACKED is set"
")"); do { *((volatile int*)__null) = 2303; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2304
2305 visibleCount++;
2306 SetProperty(VisibilityStateProperty(), visibleCount);
2307 if (visibleCount > 1) {
2308 return;
2309 }
2310
2311 // We just became visible, so send an OnVisibilityChange() notification.
2312 OnVisibilityChange(Visibility::ApproximatelyVisible);
2313}
2314
2315void nsIFrame::OnVisibilityChange(Visibility aNewVisibility,
2316 const Maybe<OnNonvisible>& aNonvisibleAction
2317 /* = Nothing() */) {
2318 // XXX(seth): In bug 1218990 we'll implement visibility tracking for CSS
2319 // images here.
2320}
2321
2322static nsIFrame* GetActiveSelectionFrame(nsPresContext* aPresContext,
2323 nsIFrame* aFrame) {
2324 nsIContent* capturingContent = PresShell::GetCapturingContent();
2325 if (capturingContent) {
2326 nsIFrame* activeFrame = aPresContext->GetPrimaryFrameFor(capturingContent);
2327 return activeFrame ? activeFrame : aFrame;
2328 }
2329
2330 return aFrame;
2331}
2332
2333int16_t nsIFrame::DetermineDisplaySelection() {
2334 int16_t selType = nsISelectionController::SELECTION_OFF;
2335
2336 nsCOMPtr<nsISelectionController> selCon;
2337 nsresult result =
2338 GetSelectionController(PresContext(), getter_AddRefs(selCon));
2339 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) && selCon) {
2340 result = selCon->GetDisplaySelection(&selType);
2341 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) &&
2342 (selType != nsISelectionController::SELECTION_OFF)) {
2343 // Check whether style allows selection.
2344 if (!IsSelectable(nullptr)) {
2345 selType = nsISelectionController::SELECTION_OFF;
2346 }
2347 }
2348 }
2349 return selType;
2350}
2351
2352static Element* FindElementAncestorForMozSelection(nsIContent* aContent) {
2353 NS_ENSURE_TRUE(aContent, nullptr)do { if ((__builtin_expect(!!(!(aContent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aContent" ") failed", nullptr
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2353); return nullptr; } } while (false)
;
2354 while (aContent && aContent->IsInNativeAnonymousSubtree()) {
2355 aContent = aContent->GetClosestNativeAnonymousSubtreeRootParentOrHost();
2356 }
2357 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2357); MOZ_PretendNoReturn(); } } while (0)
;
2358 return aContent ? aContent->GetAsElementOrParentElement() : nullptr;
2359}
2360
2361already_AddRefed<ComputedStyle> nsIFrame::ComputeSelectionStyle(
2362 int16_t aSelectionStatus) const {
2363 // Just bail out if not a selection-status that ::selection applies to.
2364 if (aSelectionStatus != nsISelectionController::SELECTION_ON &&
2365 aSelectionStatus != nsISelectionController::SELECTION_DISABLED) {
2366 return nullptr;
2367 }
2368 Element* element = FindElementAncestorForMozSelection(GetContent());
2369 if (!element) {
2370 return nullptr;
2371 }
2372 RefPtr<ComputedStyle> pseudoStyle =
2373 PresContext()->StyleSet()->ProbePseudoElementStyle(
2374 *element, PseudoStyleType::selection, nullptr, Style());
2375 if (!pseudoStyle) {
2376 return nullptr;
2377 }
2378 // When in high-contrast mode, the style system ends up ignoring the color
2379 // declarations, which means that the ::selection style becomes the inherited
2380 // color, and default background. That's no good.
2381 // When force-color-adjust is set to none allow using the color styles,
2382 // as they will not be replaced.
2383 if (PresContext()->ForcingColors() &&
2384 pseudoStyle->StyleText()->mForcedColorAdjust !=
2385 StyleForcedColorAdjust::None) {
2386 return nullptr;
2387 }
2388 return do_AddRef(pseudoStyle);
2389}
2390
2391already_AddRefed<ComputedStyle> nsIFrame::ComputeHighlightSelectionStyle(
2392 nsAtom* aHighlightName) {
2393 Element* element = FindElementAncestorForMozSelection(GetContent());
2394 if (!element) {
2395 return nullptr;
2396 }
2397 return PresContext()->StyleSet()->ProbePseudoElementStyle(
2398 *element, PseudoStyleType::highlight, aHighlightName, Style());
2399}
2400
2401already_AddRefed<ComputedStyle> nsIFrame::ComputeTargetTextStyle() const {
2402 const Element* element = FindElementAncestorForMozSelection(GetContent());
2403 if (!element) {
2404 return nullptr;
2405 }
2406 return PresContext()->StyleSet()->ProbePseudoElementStyle(
2407 *element, PseudoStyleType::targetText, nullptr, Style());
2408}
2409
2410bool nsIFrame::CanBeDynamicReflowRoot() const {
2411 const auto& display = *StyleDisplay();
2412 if (IsLineParticipant() || display.mDisplay.IsRuby() ||
2413 display.IsInnerTableStyle() ||
2414 display.DisplayInside() == StyleDisplayInside::Table) {
2415 // We have a display type where 'width' and 'height' don't actually set the
2416 // width or height (i.e., the size depends on content).
2417 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2418); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
") (" "should not have dynamic reflow root bit" ")"); do { *
((volatile int*)__null) = 2418; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
2418 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2418); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT)"
") (" "should not have dynamic reflow root bit" ")"); do { *
((volatile int*)__null) = 2418; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
2419 return false;
2420 }
2421
2422 // In general, frames that have contain:layout+size can be reflow roots.
2423 // (One exception: table-wrapper frames don't work well as reflow roots,
2424 // because their inner-table ReflowInput init path tries to reuse & deref
2425 // the wrapper's containing block's reflow input, which may be null if we
2426 // initiate reflow from the table-wrapper itself.)
2427 //
2428 // Changes to `contain` force frame reconstructions, so we used to use
2429 // NS_FRAME_REFLOW_ROOT, this bit could be set for the whole lifetime of
2430 // this frame. But after the support of `content-visibility: auto` which
2431 // is with contain layout + size when it's not relevant to user, and only
2432 // with contain layout when it is relevant. The frame does not reconstruct
2433 // when the relevancy changes. So we use NS_FRAME_DYNAMIC_REFLOW_ROOT instead.
2434 //
2435 // We place it above the pref check on purpose, to make sure it works for
2436 // containment even with the pref disabled.
2437 if (display.IsContainLayout() && GetContainSizeAxes().IsBoth()) {
2438 return true;
2439 }
2440
2441 if (!StaticPrefs::layout_dynamic_reflow_roots_enabled()) {
2442 return false;
2443 }
2444
2445 // We can't serve as a dynamic reflow root if our used 'width' and 'height'
2446 // might be influenced by content.
2447 //
2448 // FIXME: For display:block, we should probably optimize inline-size: auto.
2449 // FIXME: Other flex and grid cases?
2450 const auto& pos = *StylePosition();
2451 const auto& width = pos.mWidth;
2452 const auto& height = pos.mHeight;
2453 if (!width.IsLengthPercentage() || width.HasPercent() ||
2454 !height.IsLengthPercentage() || height.HasPercent() ||
2455 IsIntrinsicKeyword(pos.mMinWidth) || IsIntrinsicKeyword(pos.mMaxWidth) ||
2456 IsIntrinsicKeyword(pos.mMinHeight) ||
2457 IsIntrinsicKeyword(pos.mMaxHeight) ||
2458 ((pos.mMinWidth.IsAuto() || pos.mMinHeight.IsAuto()) &&
2459 IsFlexOrGridItem())) {
2460 return false;
2461 }
2462
2463 // If our flex-basis is 'auto', it'll defer to 'width' (or 'height') which
2464 // we've already checked. Otherwise, it preempts them, so we need to
2465 // perform the same "could-this-value-be-influenced-by-content" checks that
2466 // we performed for 'width' and 'height' above.
2467 if (IsFlexItem()) {
2468 const auto& flexBasis = pos.mFlexBasis;
2469 if (!flexBasis.IsAuto()) {
2470 if (!flexBasis.IsSize() || !flexBasis.AsSize().IsLengthPercentage() ||
2471 flexBasis.AsSize().HasPercent()) {
2472 return false;
2473 }
2474 }
2475 }
2476
2477 if (!IsFixedPosContainingBlock()) {
2478 // We can't treat this frame as a reflow root, since dynamic changes
2479 // to absolutely-positioned frames inside of it require that we
2480 // reflow the placeholder before we reflow the absolutely positioned
2481 // frame.
2482 // FIXME: Alternatively, we could sort the reflow roots in
2483 // PresShell::ProcessReflowCommands by depth in the tree, from
2484 // deepest to least deep. However, for performance (FIXME) we
2485 // should really be sorting them in the opposite order!
2486 return false;
2487 }
2488
2489 // If we participate in a container's block reflow context, or margins
2490 // can collapse through us, we can't be a dynamic reflow root.
2491 if (IsBlockFrameOrSubclass() && !HasAnyStateBits(NS_BLOCK_BFC)) {
2492 return false;
2493 }
2494
2495 // Subgrids are never reflow roots, but 'contain:layout/paint' prevents
2496 // creating a subgrid in the first place.
2497 if (pos.mGridTemplateColumns.IsSubgrid() ||
2498 pos.mGridTemplateRows.IsSubgrid()) {
2499 // NOTE: we could check that 'display' of our parent's primary frame is
2500 // '[inline-]grid' here but that's probably not worth it in practice.
2501 if (!display.IsContainLayout() && !display.IsContainPaint()) {
2502 return false;
2503 }
2504 }
2505
2506 // If we are split, we can't be a dynamic reflow root. Our reflow status may
2507 // change after reflow, and our parent is responsible to create or delete our
2508 // next-in-flow.
2509 if (GetPrevContinuation() || GetNextContinuation()) {
2510 return false;
2511 }
2512
2513 return true;
2514}
2515
2516/********************************************************
2517 * Refreshes each content's frame
2518 *********************************************************/
2519
2520void nsIFrame::DisplayOutlineUnconditional(nsDisplayListBuilder* aBuilder,
2521 const nsDisplayListSet& aLists) {
2522 // Per https://drafts.csswg.org/css-tables-3/#global-style-overrides:
2523 // "All css properties of table-column and table-column-group boxes are
2524 // ignored, except when explicitly specified by this specification."
2525 // CSS outlines fall into this category, so we skip them on these boxes.
2526 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2526); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsTableColGroupFrame() && !IsTableColFrame()"
")"); do { *((volatile int*)__null) = 2526; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2527 const auto& outline = *StyleOutline();
2528
2529 if (!outline.ShouldPaintOutline()) {
2530 return;
2531 }
2532
2533 // Outlines are painted by the table wrapper frame.
2534 if (IsTableFrame()) {
2535 return;
2536 }
2537
2538 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT) &&
2539 ScrollableOverflowRect().IsEmpty()) {
2540 // Skip parts of IB-splits with an empty overflow rect, see bug 434301.
2541 // We may still want to fix some of the overflow area calculations over in
2542 // that bug.
2543 return;
2544 }
2545
2546 // We don't display outline-style: auto on themed frames that have their own
2547 // focus indicators.
2548 if (outline.mOutlineStyle.IsAuto()) {
2549 auto* disp = StyleDisplay();
2550 if (IsThemed(disp) && PresContext()->Theme()->ThemeDrawsFocusForWidget(
2551 this, disp->EffectiveAppearance())) {
2552 return;
2553 }
2554 }
2555
2556 aLists.Outlines()->AppendNewToTop<nsDisplayOutline>(aBuilder, this);
2557}
2558
2559void nsIFrame::DisplayOutline(nsDisplayListBuilder* aBuilder,
2560 const nsDisplayListSet& aLists) {
2561 if (!IsVisibleForPainting()) return;
2562
2563 DisplayOutlineUnconditional(aBuilder, aLists);
2564}
2565
2566void nsIFrame::DisplayInsetBoxShadowUnconditional(
2567 nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
2568 // XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
2569 // just because we're visible? Or should it depend on the cell visibility
2570 // when we're not the whole table?
2571 const auto* effects = StyleEffects();
2572 if (effects->HasBoxShadowWithInset(true)) {
2573 aList->AppendNewToTop<nsDisplayBoxShadowInner>(aBuilder, this);
2574 }
2575}
2576
2577void nsIFrame::DisplayInsetBoxShadow(nsDisplayListBuilder* aBuilder,
2578 nsDisplayList* aList) {
2579 if (!IsVisibleForPainting()) return;
2580
2581 DisplayInsetBoxShadowUnconditional(aBuilder, aList);
2582}
2583
2584void nsIFrame::DisplayOutsetBoxShadowUnconditional(
2585 nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
2586 // XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
2587 // just because we're visible? Or should it depend on the cell visibility
2588 // when we're not the whole table?
2589 const auto* effects = StyleEffects();
2590 if (effects->HasBoxShadowWithInset(false)) {
2591 aList->AppendNewToTop<nsDisplayBoxShadowOuter>(aBuilder, this);
2592 }
2593}
2594
2595void nsIFrame::DisplayOutsetBoxShadow(nsDisplayListBuilder* aBuilder,
2596 nsDisplayList* aList) {
2597 if (!IsVisibleForPainting()) return;
2598
2599 DisplayOutsetBoxShadowUnconditional(aBuilder, aList);
2600}
2601
2602void nsIFrame::DisplayCaret(nsDisplayListBuilder* aBuilder,
2603 nsDisplayList* aList) {
2604 if (!IsVisibleForPainting()) return;
2605
2606 aList->AppendNewToTop<nsDisplayCaret>(aBuilder, this);
2607}
2608
2609nscolor nsIFrame::GetCaretColorAt(int32_t aOffset) {
2610 return nsLayoutUtils::GetColor(this, &nsStyleUI::mCaretColor);
2611}
2612
2613auto nsIFrame::ComputeShouldPaintBackground() const -> ShouldPaintBackground {
2614 nsPresContext* pc = PresContext();
2615 ShouldPaintBackground settings{pc->GetBackgroundColorDraw(),
2616 pc->GetBackgroundImageDraw()};
2617 if (settings.mColor && settings.mImage) {
2618 return settings;
2619 }
2620
2621 if (StyleVisibility()->mPrintColorAdjust == StylePrintColorAdjust::Exact) {
2622 return {true, true};
2623 }
2624
2625 return settings;
2626}
2627
2628bool nsIFrame::DisplayBackgroundUnconditional(nsDisplayListBuilder* aBuilder,
2629 const nsDisplayListSet& aLists) {
2630 if (aBuilder->IsForEventDelivery() && !aBuilder->HitTestIsForVisibility()) {
2631 // For hit-testing, we generally just need a light-weight data structure
2632 // like nsDisplayEventReceiver. But if the hit-testing is for visibility,
2633 // then we need to know the opaque region in order to determine whether to
2634 // stop or not.
2635 aLists.BorderBackground()->AppendNewToTop<nsDisplayEventReceiver>(aBuilder,
2636 this);
2637 return false;
2638 }
2639
2640 const AppendedBackgroundType result =
2641 nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
2642 aBuilder, this,
2643 GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this),
2644 aLists.BorderBackground());
2645
2646 if (result == AppendedBackgroundType::None) {
2647 aBuilder->BuildCompositorHitTestInfoIfNeeded(this,
2648 aLists.BorderBackground());
2649 }
2650
2651 return result == AppendedBackgroundType::ThemedBackground;
2652}
2653
2654void nsIFrame::DisplayBorderBackgroundOutline(nsDisplayListBuilder* aBuilder,
2655 const nsDisplayListSet& aLists) {
2656 // The visibility check belongs here since child elements have the
2657 // opportunity to override the visibility property and display even if
2658 // their parent is hidden.
2659 if (!IsVisibleForPainting()) {
2660 return;
2661 }
2662
2663 DisplayOutsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
2664
2665 bool bgIsThemed = DisplayBackgroundUnconditional(aBuilder, aLists);
2666 DisplayInsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
2667
2668 // If there's a themed background, we should not create a border item.
2669 // It won't be rendered.
2670 // Don't paint borders for tables here, since they paint them in a different
2671 // order.
2672 if (!bgIsThemed && StyleBorder()->HasBorder() && !IsTableFrame()) {
2673 aLists.BorderBackground()->AppendNewToTop<nsDisplayBorder>(aBuilder, this);
2674 }
2675
2676 DisplayOutlineUnconditional(aBuilder, aLists);
2677}
2678
2679inline static bool IsSVGContentWithCSSClip(const nsIFrame* aFrame) {
2680 // The CSS spec says that the 'clip' property only applies to absolutely
2681 // positioned elements, whereas the SVG spec says that it applies to SVG
2682 // elements regardless of the value of the 'position' property. Here we obey
2683 // the CSS spec for outer-<svg> (since that's what we generally do), but
2684 // obey the SVG spec for other SVG elements to which 'clip' applies.
2685 return aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) &&
2686 aFrame->GetContent()->IsAnyOfSVGElements(nsGkAtoms::svg,
2687 nsGkAtoms::foreignObject);
2688}
2689
2690Maybe<nsRect> nsIFrame::GetClipPropClipRect(const nsStyleDisplay* aDisp,
2691 const nsStyleEffects* aEffects,
2692 const nsSize& aSize) const {
2693 if (aEffects->mClip.IsAuto() ||
2694 !(aDisp->IsAbsolutelyPositioned(this) || IsSVGContentWithCSSClip(this))) {
2695 return Nothing();
2696 }
2697
2698 auto& clipRect = aEffects->mClip.AsRect();
2699 nsRect rect = clipRect.ToLayoutRect();
2700 if (MOZ_LIKELY(StyleBorder()->mBoxDecorationBreak ==(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Slice), 1))
2701 StyleBoxDecorationBreak::Slice)(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Slice), 1))
) {
2702 // The clip applies to the joined boxes so it's relative the first
2703 // continuation.
2704 nscoord y = 0;
2705 for (nsIFrame* f = GetPrevContinuation(); f; f = f->GetPrevContinuation()) {
2706 y += f->GetRect().height;
2707 }
2708 rect.MoveBy(nsPoint(0, -y));
2709 }
2710
2711 if (clipRect.right.IsAuto()) {
2712 rect.width = aSize.width - rect.x;
2713 }
2714 if (clipRect.bottom.IsAuto()) {
2715 rect.height = aSize.height - rect.y;
2716 }
2717 return Some(rect);
2718}
2719
2720/**
2721 * If the CSS 'overflow' property applies to this frame, and is not
2722 * handled by constructing a dedicated nsHTML/XULScrollFrame, set up clipping
2723 * for that overflow in aBuilder->ClipState() to clip all containing-block
2724 * descendants.
2725 */
2726static void ApplyOverflowClipping(
2727 nsDisplayListBuilder* aBuilder, const nsIFrame* aFrame,
2728 PhysicalAxes aClipAxes,
2729 DisplayListClipState::AutoClipMultiple& aClipState) {
2730 // Only 'clip' is handled here (and 'hidden' for table frames, and any
2731 // non-'visible' value for blocks in a paginated context).
2732 // We allow 'clip' to apply to any kind of frame. This is required by
2733 // comboboxes which make their display text (an inline frame) have clipping.
2734 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2734); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aClipAxes.isEmpty()"
")"); do { *((volatile int*)__null) = 2734; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2735 MOZ_ASSERT(aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay
()) == aClipAxes)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aFrame->ShouldApplyOverflowClipping
(aFrame->StyleDisplay()) == aClipAxes))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) == aClipAxes"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2736); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) == aClipAxes"
")"); do { *((volatile int*)__null) = 2736; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2736 aClipAxes)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay
()) == aClipAxes)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aFrame->ShouldApplyOverflowClipping
(aFrame->StyleDisplay()) == aClipAxes))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) == aClipAxes"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2736); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) == aClipAxes"
")"); do { *((volatile int*)__null) = 2736; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2737
2738 nsRect clipRect;
2739 bool haveRadii = false;
2740 nscoord radii[8];
2741 auto* disp = aFrame->StyleDisplay();
2742 // Only deflate the padding if we clip to the content-box in that axis.
2743 auto wm = aFrame->GetWritingMode();
2744 bool cbH = (wm.IsVertical() ? disp->mOverflowClipBoxBlock
2745 : disp->mOverflowClipBoxInline) ==
2746 StyleOverflowClipBox::ContentBox;
2747 bool cbV = (wm.IsVertical() ? disp->mOverflowClipBoxInline
2748 : disp->mOverflowClipBoxBlock) ==
2749 StyleOverflowClipBox::ContentBox;
2750
2751 nsMargin boxMargin = -aFrame->GetUsedPadding();
2752 if (!cbH) {
2753 boxMargin.left = boxMargin.right = nscoord(0);
2754 }
2755 if (!cbV) {
2756 boxMargin.top = boxMargin.bottom = nscoord(0);
2757 }
2758
2759 auto clipMargin = aFrame->OverflowClipMargin(aClipAxes);
2760
2761 boxMargin -= aFrame->GetUsedBorder();
2762 boxMargin += nsMargin(clipMargin.height, clipMargin.width, clipMargin.height,
2763 clipMargin.width);
2764 boxMargin.ApplySkipSides(aFrame->GetSkipSides());
2765
2766 nsRect rect(nsPoint(0, 0), aFrame->GetSize());
2767 rect.Inflate(boxMargin);
2768 if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Horizontal))(__builtin_expect(!!(!aClipAxes.contains(PhysicalAxis::Horizontal
)), 0))
) {
2769 // NOTE(mats) We shouldn't be clipping at all in this dimension really,
2770 // but clipping in just one axis isn't supported by our GFX APIs so we
2771 // clip to our visual overflow rect instead.
2772 nsRect o = aFrame->InkOverflowRect();
2773 rect.x = o.x;
2774 rect.width = o.width;
2775 }
2776 if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Vertical))(__builtin_expect(!!(!aClipAxes.contains(PhysicalAxis::Vertical
)), 0))
) {
2777 // See the note above.
2778 nsRect o = aFrame->InkOverflowRect();
2779 rect.y = o.y;
2780 rect.height = o.height;
2781 }
2782 clipRect = rect + aBuilder->ToReferenceFrame(aFrame);
2783 haveRadii = aFrame->GetBoxBorderRadii(radii, boxMargin);
2784 aClipState.ClipContainingBlockDescendantsExtra(clipRect,
2785 haveRadii ? radii : nullptr);
2786}
2787
2788nsSize nsIFrame::OverflowClipMargin(PhysicalAxes aClipAxes) const {
2789 nsSize result;
2790 if (aClipAxes.isEmpty()) {
2791 return result;
2792 }
2793 const auto& margin = StyleMargin()->mOverflowClipMargin;
2794 if (margin.IsZero()) {
2795 return result;
2796 }
2797 nscoord marginAu = margin.ToAppUnits();
2798 if (aClipAxes.contains(PhysicalAxis::Horizontal)) {
2799 result.width = marginAu;
2800 }
2801 if (aClipAxes.contains(PhysicalAxis::Vertical)) {
2802 result.height = marginAu;
2803 }
2804 return result;
2805}
2806
2807/**
2808 * Returns whether a display item that gets created with the builder's current
2809 * state will have a scrolled clip, i.e. a clip that is scrolled by a scroll
2810 * frame which does not move the item itself.
2811 */
2812static bool BuilderHasScrolledClip(nsDisplayListBuilder* aBuilder) {
2813 const DisplayItemClipChain* currentClip =
2814 aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
2815 if (!currentClip) {
2816 return false;
2817 }
2818
2819 const ActiveScrolledRoot* currentClipASR = currentClip->mASR;
2820 const ActiveScrolledRoot* currentASR = aBuilder->CurrentActiveScrolledRoot();
2821 return ActiveScrolledRoot::PickDescendant(currentClipASR, currentASR) !=
2822 currentASR;
2823}
2824
2825class AutoSaveRestoreContainsBlendMode {
2826 nsDisplayListBuilder& mBuilder;
2827 bool mSavedContainsBlendMode;
2828
2829 public:
2830 explicit AutoSaveRestoreContainsBlendMode(nsDisplayListBuilder& aBuilder)
2831 : mBuilder(aBuilder),
2832 mSavedContainsBlendMode(aBuilder.ContainsBlendMode()) {}
2833
2834 ~AutoSaveRestoreContainsBlendMode() {
2835 mBuilder.SetContainsBlendMode(mSavedContainsBlendMode);
2836 }
2837};
2838
2839static bool IsFrameOrAncestorApzAware(nsIFrame* aFrame) {
2840 nsIContent* node = aFrame->GetContent();
2841 if (!node) {
2842 return false;
2843 }
2844
2845 do {
2846 if (node->IsNodeApzAware()) {
2847 return true;
2848 }
2849 nsIContent* shadowRoot = node->GetShadowRoot();
2850 if (shadowRoot && shadowRoot->IsNodeApzAware()) {
2851 return true;
2852 }
2853
2854 // Even if the node owning aFrame doesn't have apz-aware event listeners
2855 // itself, its shadow root or display: contents ancestors (which have no
2856 // frames) might, so we need to account for them too.
2857 } while ((node = node->GetFlattenedTreeParent()) && node->IsElement() &&
2858 node->AsElement()->IsDisplayContents());
2859
2860 return false;
2861}
2862
2863static void CheckForApzAwareEventHandlers(nsDisplayListBuilder* aBuilder,
2864 nsIFrame* aFrame) {
2865 if (aBuilder->GetAncestorHasApzAwareEventHandler()) {
2866 return;
2867 }
2868
2869 if (IsFrameOrAncestorApzAware(aFrame)) {
2870 aBuilder->SetAncestorHasApzAwareEventHandler(true);
2871 }
2872}
2873
2874static void UpdateCurrentHitTestInfo(nsDisplayListBuilder* aBuilder,
2875 nsIFrame* aFrame) {
2876 if (!aBuilder->BuildCompositorHitTestInfo()) {
2877 // Compositor hit test info is not used.
2878 return;
2879 }
2880
2881 CheckForApzAwareEventHandlers(aBuilder, aFrame);
2882
2883 const CompositorHitTestInfo info = aFrame->GetCompositorHitTestInfo(aBuilder);
2884 aBuilder->SetCompositorHitTestInfo(info);
2885}
2886
2887/**
2888 * True if aDescendant participates the context aAncestor participating.
2889 */
2890static bool FrameParticipatesIn3DContext(nsIFrame* aAncestor,
2891 nsIFrame* aDescendant) {
2892 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2892); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAncestor != aDescendant"
")"); do { *((volatile int*)__null) = 2892; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2893 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2893); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAncestor->GetContent() != aDescendant->GetContent()"
")"); do { *((volatile int*)__null) = 2893; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2894 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2894); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAncestor->Extend3DContext()"
")"); do { *((volatile int*)__null) = 2894; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2895
2896 nsIFrame* ancestor = aAncestor->FirstContinuation();
2897 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2897); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ancestor->IsPrimaryFrame()"
")"); do { *((volatile int*)__null) = 2897; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2898
2899 nsIFrame* frame;
2900 for (frame = aDescendant->GetClosestFlattenedTreeAncestorPrimaryFrame();
2901 frame && ancestor != frame;
2902 frame = frame->GetClosestFlattenedTreeAncestorPrimaryFrame()) {
2903 if (!frame->Extend3DContext()) {
2904 return false;
2905 }
2906 }
2907
2908 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 2908); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame == ancestor"
")"); do { *((volatile int*)__null) = 2908; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2909 return true;
2910}
2911
2912static bool ItemParticipatesIn3DContext(nsIFrame* aAncestor,
2913 nsDisplayItem* aItem) {
2914 auto type = aItem->GetType();
2915 const bool isContainer = type == DisplayItemType::TYPE_WRAP_LIST ||
2916 type == DisplayItemType::TYPE_CONTAINER;
2917
2918 if (isContainer && aItem->GetChildren()->Length() == 1) {
2919 // If the wraplist has only one child item, use the type of that item.
2920 type = aItem->GetChildren()->GetBottom()->GetType();
2921 }
2922
2923 if (type != DisplayItemType::TYPE_TRANSFORM &&
2924 type != DisplayItemType::TYPE_PERSPECTIVE) {
2925 return false;
2926 }
2927 nsIFrame* transformFrame = aItem->Frame();
2928 if (aAncestor->GetContent() == transformFrame->GetContent()) {
2929 return true;
2930 }
2931 return FrameParticipatesIn3DContext(aAncestor, transformFrame);
2932}
2933
2934static void WrapSeparatorTransform(nsDisplayListBuilder* aBuilder,
2935 nsIFrame* aFrame,
2936 nsDisplayList* aNonParticipants,
2937 nsDisplayList* aParticipants, int aIndex,
2938 nsDisplayItem** aSeparator) {
2939 if (aNonParticipants->IsEmpty()) {
2940 return;
2941 }
2942
2943 nsDisplayTransform* item = MakeDisplayItemWithIndex<nsDisplayTransform>(
2944 aBuilder, aFrame, aIndex, aNonParticipants, aBuilder->GetVisibleRect());
2945
2946 if (*aSeparator == nullptr && item) {
2947 *aSeparator = item;
2948 }
2949
2950 aParticipants->AppendToTop(item);
2951}
2952
2953// Try to compute a clip rect to bound the contents of the mask item
2954// that will be built for |aMaskedFrame|. If we're not able to compute
2955// one, return an empty Maybe.
2956// The returned clip rect, if there is one, is relative to |aMaskedFrame|.
2957static Maybe<nsRect> ComputeClipForMaskItem(
2958 nsDisplayListBuilder* aBuilder, nsIFrame* aMaskedFrame,
2959 const SVGUtils::MaskUsage& aMaskUsage) {
2960 const nsStyleSVGReset* svgReset = aMaskedFrame->StyleSVGReset();
2961
2962 nsPoint offsetToUserSpace =
2963 nsLayoutUtils::ComputeOffsetToUserSpace(aBuilder, aMaskedFrame);
2964 int32_t devPixelRatio = aMaskedFrame->PresContext()->AppUnitsPerDevPixel();
2965 gfxPoint devPixelOffsetToUserSpace =
2966 nsLayoutUtils::PointToGfxPoint(offsetToUserSpace, devPixelRatio);
2967 CSSToLayoutDeviceScale cssToDevScale =
2968 aMaskedFrame->PresContext()->CSSToDevPixelScale();
2969
2970 nsPoint toReferenceFrame;
2971 aBuilder->FindReferenceFrameFor(aMaskedFrame, &toReferenceFrame);
2972
2973 Maybe<gfxRect> combinedClip;
2974 if (aMaskUsage.ShouldApplyBasicShapeOrPath()) {
2975 Maybe<Rect> result =
2976 CSSClipPathInstance::GetBoundingRectForBasicShapeOrPathClip(
2977 aMaskedFrame, svgReset->mClipPath);
2978 if (result) {
2979 combinedClip = Some(ThebesRect(*result));
2980 }
2981 } else if (aMaskUsage.ShouldApplyClipPath()) {
2982 gfxRect result = SVGUtils::GetBBox(
2983 aMaskedFrame,
2984 SVGUtils::eBBoxIncludeClipped | SVGUtils::eBBoxIncludeFill |
2985 SVGUtils::eBBoxIncludeMarkers | SVGUtils::eBBoxIncludeStroke |
2986 SVGUtils::eDoNotClipToBBoxOfContentInsideClipPath);
2987 combinedClip = Some(
2988 ThebesRect((CSSRect::FromUnknownRect(ToRect(result)) * cssToDevScale)
2989 .ToUnknownRect()));
2990 } else {
2991 // The code for this case is adapted from ComputeMaskGeometry().
2992
2993 nsRect borderArea(toReferenceFrame, aMaskedFrame->GetSize());
2994 borderArea -= offsetToUserSpace;
2995
2996 // Use an infinite dirty rect to pass into nsCSSRendering::
2997 // GetImageLayerClip() because we don't have an actual dirty rect to
2998 // pass in. This is fine because the only time GetImageLayerClip() will
2999 // not intersect the incoming dirty rect with something is in the "NoClip"
3000 // case, and we handle that specially.
3001 nsRect dirtyRect(nscoord_MIN / 2, nscoord_MIN / 2, nscoord_MAX,
3002 nscoord_MAX);
3003
3004 nsIFrame* firstFrame =
3005 nsLayoutUtils::FirstContinuationOrIBSplitSibling(aMaskedFrame);
3006 nsTArray<SVGMaskFrame*> maskFrames;
3007 // XXX check return value?
3008 SVGObserverUtils::GetAndObserveMasks(firstFrame, &maskFrames);
3009
3010 for (uint32_t i = 0; i < maskFrames.Length(); ++i) {
3011 gfxRect clipArea;
3012 if (maskFrames[i]) {
3013 clipArea = maskFrames[i]->GetMaskArea(aMaskedFrame);
3014 clipArea = ThebesRect(
3015 (CSSRect::FromUnknownRect(ToRect(clipArea)) * cssToDevScale)
3016 .ToUnknownRect());
3017 } else {
3018 const auto& layer = svgReset->mMask.mLayers[i];
3019 if (layer.mClip == StyleGeometryBox::NoClip) {
3020 return Nothing();
3021 }
3022
3023 nsCSSRendering::ImageLayerClipState clipState;
3024 nsCSSRendering::GetImageLayerClip(
3025 layer, aMaskedFrame, *aMaskedFrame->StyleBorder(), borderArea,
3026 dirtyRect, false /* aWillPaintBorder */, devPixelRatio, &clipState);
3027 clipArea = clipState.mDirtyRectInDevPx;
3028 }
3029 combinedClip = UnionMaybeRects(combinedClip, Some(clipArea));
3030 }
3031 }
3032 if (combinedClip) {
3033 if (combinedClip->IsEmpty()) {
3034 // *clipForMask might be empty if all mask references are not resolvable
3035 // or the size of them are empty. We still need to create a transparent
3036 // mask before bug 1276834 fixed, so don't clip ctx by an empty rectangle
3037 // for for now.
3038 return Nothing();
3039 }
3040
3041 // Convert to user space.
3042 *combinedClip += devPixelOffsetToUserSpace;
3043
3044 // Round the clip out. In FrameLayerBuilder we round clips to nearest
3045 // pixels, and if we have a really thin clip here, that can cause the
3046 // clip to become empty if we didn't round out here.
3047 // The rounding happens in coordinates that are relative to the reference
3048 // frame, which matches what FrameLayerBuilder does.
3049 combinedClip->RoundOut();
3050
3051 // Convert to app units.
3052 nsRect result =
3053 nsLayoutUtils::RoundGfxRectToAppRect(*combinedClip, devPixelRatio);
3054
3055 // The resulting clip is relative to the reference frame, but the caller
3056 // expects it to be relative to the masked frame, so adjust it.
3057 result -= toReferenceFrame;
3058 return Some(result);
3059 }
3060 return Nothing();
3061}
3062
3063struct AutoCheckBuilder {
3064 explicit AutoCheckBuilder(nsDisplayListBuilder* aBuilder)
3065 : mBuilder(aBuilder) {
3066 aBuilder->Check();
3067 }
3068
3069 ~AutoCheckBuilder() { mBuilder->Check(); }
3070
3071 nsDisplayListBuilder* mBuilder;
3072};
3073
3074/**
3075 * Tries to reuse a top-level stacking context item from the previous paint.
3076 * Returns true if an item was reused, otherwise false.
3077 */
3078bool TryToReuseStackingContextItem(nsDisplayListBuilder* aBuilder,
3079 nsDisplayList* aList, nsIFrame* aFrame) {
3080 if (!aBuilder->IsForPainting() || !aBuilder->IsPartialUpdate() ||
3081 aBuilder->InInvalidSubtree()) {
3082 return false;
3083 }
3084
3085 if (aFrame->IsFrameModified() || aFrame->HasModifiedDescendants()) {
3086 return false;
3087 }
3088
3089 auto& items = aFrame->DisplayItems();
3090 auto* res = std::find_if(
3091 items.begin(), items.end(),
3092 [](nsDisplayItem* aItem) { return aItem->IsPreProcessed(); });
3093
3094 if (res == items.end()) {
3095 return false;
3096 }
3097
3098 nsDisplayItem* container = *res;
3099 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3099); AnnotateMozCrashReason("MOZ_ASSERT" "(" "container->Frame() == aFrame"
")"); do { *((volatile int*)__null) = 3099; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3100 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)
3101 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)
;
3102
3103 aList->AppendToTop(container);
3104 aBuilder->ReuseDisplayItem(container);
3105 return true;
3106}
3107
3108void nsIFrame::BuildDisplayListForStackingContext(
3109 nsDisplayListBuilder* aBuilder, nsDisplayList* aList,
3110 bool* aCreatedContainerItem) {
3111#ifdef DEBUG1
3112 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)
;
3113 ScopeExit e(
3114 [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)
; });
3115#endif
3116
3117 AutoCheckBuilder check(aBuilder);
3118
3119 if (aBuilder->IsReusingStackingContextItems() &&
3120 TryToReuseStackingContextItem(aBuilder, aList, this)) {
3121 if (aCreatedContainerItem) {
3122 *aCreatedContainerItem = true;
3123 }
3124 return;
3125 }
3126
3127 if (HasAnyStateBits(NS_FRAME_TOO_DEEP_IN_FRAME_TREE)) {
3128 return;
3129 }
3130
3131 const auto& style = *Style();
3132 const nsStyleDisplay* disp = style.StyleDisplay();
3133 const nsStyleEffects* effects = style.StyleEffects();
3134 EffectSet* effectSetForOpacity =
3135 EffectSet::GetForFrame(this, nsCSSPropertyIDSet::OpacityProperties());
3136 // We can stop right away if this is a zero-opacity stacking context and
3137 // we're painting, and we're not animating opacity.
3138 bool needHitTestInfo = aBuilder->BuildCompositorHitTestInfo() &&
3139 Style()->PointerEvents() != StylePointerEvents::None;
3140 bool opacityItemForEventsOnly = false;
3141 if (effects->IsTransparent() && aBuilder->IsForPainting() &&
3142 !(disp->mWillChange.bits & StyleWillChangeBits::OPACITY) &&
3143 !nsLayoutUtils::HasAnimationOfPropertySet(
3144 this, nsCSSPropertyIDSet::OpacityProperties(), effectSetForOpacity)) {
3145 if (needHitTestInfo) {
3146 opacityItemForEventsOnly = true;
3147 } else {
3148 return;
3149 }
3150 }
3151
3152 if (aBuilder->IsForPainting() && disp->mWillChange.bits) {
3153 aBuilder->AddToWillChangeBudget(this, GetSize());
3154 }
3155
3156 // For preserves3d, use the dirty rect already installed on the
3157 // builder, since aDirtyRect maybe distorted for transforms along
3158 // the chain.
3159 nsRect visibleRect = aBuilder->GetVisibleRect();
3160 nsRect dirtyRect = aBuilder->GetDirtyRect();
3161
3162 // We build an opacity item if it's not going to be drawn by SVG content.
3163 // We could in principle skip creating an nsDisplayOpacity item if
3164 // nsDisplayOpacity::NeedsActiveLayer returns false and usingSVGEffects is
3165 // true (the nsDisplayFilter/nsDisplayMasksAndClipPaths could handle the
3166 // opacity). Since SVG has perf issues where we sometimes spend a lot of
3167 // time creating display list items that might be helpful. We'd need to
3168 // restore our mechanism to do that (changed in bug 1482403), and we'd
3169 // need to invalidate the frame if the value that would be return from
3170 // NeedsActiveLayer was to change, which we don't currently do.
3171 const bool useOpacity =
3172 HasVisualOpacity(disp, effects, effectSetForOpacity) &&
3173 !SVGUtils::CanOptimizeOpacity(this);
3174
3175 const bool isTransformed = IsTransformed();
3176 const bool hasPerspective = isTransformed && HasPerspective();
3177 const bool extend3DContext =
3178 Extend3DContext(disp, effects, effectSetForOpacity);
3179 const bool combines3DTransformWithAncestors =
3180 (extend3DContext || isTransformed) && Combines3DTransformWithAncestors();
3181
3182 Maybe<nsDisplayListBuilder::AutoPreserves3DContext> autoPreserves3DContext;
3183 if (extend3DContext && !combines3DTransformWithAncestors) {
3184 // Start a new preserves3d context to keep informations on
3185 // nsDisplayListBuilder.
3186 autoPreserves3DContext.emplace(aBuilder);
3187 // Save dirty rect on the builder to avoid being distorted for
3188 // multiple transforms along the chain.
3189 aBuilder->SavePreserves3DRect();
3190
3191 // We rebuild everything within preserve-3d and don't try
3192 // to retain, so override the dirty rect now.
3193 if (aBuilder->IsRetainingDisplayList()) {
3194 dirtyRect = visibleRect;
3195 aBuilder->SetDisablePartialUpdates(true);
3196 }
3197 }
3198
3199 const bool useBlendMode = effects->mMixBlendMode != StyleBlend::Normal;
3200 if (useBlendMode) {
3201 aBuilder->SetContainsBlendMode(true);
3202 }
3203
3204 // reset blend mode so we can keep track if this stacking context needs have
3205 // a nsDisplayBlendContainer. Set the blend mode back when the routine exits
3206 // so we keep track if the parent stacking context needs a container too.
3207 AutoSaveRestoreContainsBlendMode autoRestoreBlendMode(*aBuilder);
3208 aBuilder->SetContainsBlendMode(false);
3209
3210 // NOTE: When changing this condition make sure to tweak ScrollContainerFrame
3211 // as well.
3212 bool usingBackdropFilter = effects->HasBackdropFilters() &&
3213 IsVisibleForPainting() &&
3214 !style.IsRootElementStyle();
3215
3216 nsRect visibleRectOutsideTransform = visibleRect;
3217 nsDisplayTransform::PrerenderInfo prerenderInfo;
3218 bool inTransform = aBuilder->IsInTransform();
3219 if (isTransformed) {
3220 prerenderInfo = nsDisplayTransform::ShouldPrerenderTransformedContent(
3221 aBuilder, this, &visibleRect);
3222
3223 switch (prerenderInfo.mDecision) {
3224 case nsDisplayTransform::PrerenderDecision::Full:
3225 case nsDisplayTransform::PrerenderDecision::Partial:
3226 dirtyRect = visibleRect;
3227 break;
3228 case nsDisplayTransform::PrerenderDecision::No: {
3229 // If we didn't prerender an animated frame in a preserve-3d context,
3230 // then we want disable async animations for the rest of the preserve-3d
3231 // (especially ancestors).
3232 if ((extend3DContext || combines3DTransformWithAncestors) &&
3233 prerenderInfo.mHasAnimations) {
3234 aBuilder->SavePreserves3DAllowAsyncAnimation(false);
3235 }
3236
3237 const nsRect overflow = InkOverflowRectRelativeToSelf();
3238 if (overflow.IsEmpty() && !extend3DContext) {
3239 return;
3240 }
3241
3242 // If we're in preserve-3d then grab the dirty rect that was given to
3243 // the root and transform using the combined transform.
3244 if (combines3DTransformWithAncestors) {
3245 visibleRect = dirtyRect = aBuilder->GetPreserves3DRect();
3246 }
3247
3248 float appPerDev = PresContext()->AppUnitsPerDevPixel();
3249 auto transform = nsDisplayTransform::GetResultingTransformMatrix(
3250 this, nsPoint(), appPerDev,
3251 nsDisplayTransform::kTransformRectFlags);
3252 nsRect untransformedDirtyRect;
3253 if (nsDisplayTransform::UntransformRect(dirtyRect, overflow, transform,
3254 appPerDev,
3255 &untransformedDirtyRect)) {
3256 dirtyRect = untransformedDirtyRect;
3257 nsDisplayTransform::UntransformRect(visibleRect, overflow, transform,
3258 appPerDev, &visibleRect);
3259 } else {
3260 // This should only happen if the transform is singular, in which case
3261 // nothing is visible anyway
3262 dirtyRect.SetEmpty();
3263 visibleRect.SetEmpty();
3264 }
3265 }
3266 }
3267 inTransform = true;
3268 } else if (IsFixedPosContainingBlock()) {
3269 // Restict the building area to the overflow rect for these frames, since
3270 // RetainedDisplayListBuilder uses it to know if the size of the stacking
3271 // context changed.
3272 visibleRect.IntersectRect(visibleRect, InkOverflowRect());
3273 dirtyRect.IntersectRect(dirtyRect, InkOverflowRect());
3274 }
3275
3276 bool hasOverrideDirtyRect = false;
3277 // If we're doing a partial build, we're not invalid and we're capable
3278 // of having an override building rect (stacking context and fixed pos
3279 // containing block), then we should assume we have one.
3280 // Either we have an explicit one, or nothing in our subtree changed and
3281 // we have an implicit empty rect.
3282 //
3283 // These conditions should match |CanStoreDisplayListBuildingRect()| in
3284 // RetainedDisplayListBuilder.cpp
3285 if (!aBuilder->IsReusingStackingContextItems() &&
3286 aBuilder->IsPartialUpdate() && !aBuilder->InInvalidSubtree() &&
3287 !IsFrameModified() && IsFixedPosContainingBlock() &&
3288 !GetPrevContinuation() && !GetNextContinuation()) {
3289 dirtyRect = nsRect();
3290 if (HasOverrideDirtyRegion()) {
3291 nsDisplayListBuilder::DisplayListBuildingData* data =
3292 GetProperty(nsDisplayListBuilder::DisplayListBuildingRect());
3293 if (data) {
3294 dirtyRect = data->mDirtyRect.Intersect(visibleRect);
3295 hasOverrideDirtyRect = true;
3296 }
3297 }
3298 }
3299
3300 bool usingFilter = effects->HasFilters() && !style.IsRootElementStyle();
3301 SVGUtils::MaskUsage maskUsage = SVGUtils::DetermineMaskUsage(this, false);
3302 bool usingMask = maskUsage.UsingMaskOrClipPath();
3303 bool usingSVGEffects = usingFilter || usingMask;
3304
3305 nsRect visibleRectOutsideSVGEffects = visibleRect;
3306 nsDisplayList hoistedScrollInfoItemsStorage(aBuilder);
3307 if (usingSVGEffects) {
3308 dirtyRect =
3309 SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, dirtyRect);
3310 visibleRect =
3311 SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, visibleRect);
3312 aBuilder->EnterSVGEffectsContents(this, &hoistedScrollInfoItemsStorage);
3313 }
3314
3315 bool useStickyPosition = disp->mPosition == StylePositionProperty::Sticky;
3316
3317 bool useFixedPosition =
3318 disp->mPosition == StylePositionProperty::Fixed &&
3319 (DisplayPortUtils::IsFixedPosFrameInDisplayPort(this) ||
3320 BuilderHasScrolledClip(aBuilder));
3321
3322 nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
3323 aBuilder, this, visibleRect, dirtyRect, isTransformed);
3324
3325 UpdateCurrentHitTestInfo(aBuilder, this);
3326
3327 // Depending on the effects that are applied to this frame, we can create
3328 // multiple container display items and wrap them around our contents.
3329 // This enum lists all the potential container display items, in the order
3330 // outside to inside.
3331 enum class ContainerItemType : uint8_t {
3332 None = 0,
3333 OwnLayerIfNeeded,
3334 BlendMode,
3335 FixedPosition,
3336 OwnLayerForTransformWithRoundedClip,
3337 Perspective,
3338 Transform,
3339 SeparatorTransforms,
3340 Opacity,
3341 Filter,
3342 BlendContainer
3343 };
3344
3345 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
3346
3347 auto cssClip = GetClipPropClipRect(disp, effects, GetSize());
3348 auto ApplyClipProp = [&](DisplayListClipState::AutoSaveRestore& aClipState) {
3349 if (!cssClip) {
3350 return;
3351 }
3352 nsPoint offset = aBuilder->GetCurrentFrameOffsetToReferenceFrame();
3353 aBuilder->IntersectDirtyRect(*cssClip);
3354 aBuilder->IntersectVisibleRect(*cssClip);
3355 aClipState.ClipContentDescendants(*cssClip + offset);
3356 };
3357
3358 // The CSS clip property is effectively inside the transform, but outside the
3359 // filters. So if we're not transformed we can apply it just here for
3360 // simplicity, instead of on each of the places that handle clipCapturedBy.
3361 DisplayListClipState::AutoSaveRestore untransformedCssClip(aBuilder);
3362 if (!isTransformed) {
3363 ApplyClipProp(untransformedCssClip);
3364 }
3365
3366 // If there is a current clip, then depending on the container items we
3367 // create, different things can happen to it. Some container items simply
3368 // propagate the clip to their children and aren't clipped themselves.
3369 // But other container items, especially those that establish a different
3370 // geometry for their contents (e.g. transforms), capture the clip on
3371 // themselves and unset the clip for their contents. If we create more than
3372 // one of those container items, the clip will be captured on the outermost
3373 // one and the inner container items will be unclipped.
3374 ContainerItemType clipCapturedBy = ContainerItemType::None;
3375 if (useFixedPosition) {
3376 clipCapturedBy = ContainerItemType::FixedPosition;
3377 } else if (isTransformed) {
3378 const DisplayItemClipChain* currentClip =
3379 aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
3380 if ((hasPerspective || extend3DContext) &&
3381 (currentClip && currentClip->HasRoundedCorners())) {
3382 // If we're creating an nsDisplayTransform item that is going to combine
3383 // its transform with its children (preserve-3d or perspective), then we
3384 // can't have an intermediate surface. Mask layers force an intermediate
3385 // surface, so if we're going to need both then create a separate
3386 // wrapping layer for the mask.
3387 clipCapturedBy = ContainerItemType::OwnLayerForTransformWithRoundedClip;
3388 } else if (hasPerspective) {
3389 clipCapturedBy = ContainerItemType::Perspective;
3390 } else {
3391 clipCapturedBy = ContainerItemType::Transform;
3392 }
3393 } else if (usingFilter) {
3394 clipCapturedBy = ContainerItemType::Filter;
3395 }
3396
3397 DisplayListClipState::AutoSaveRestore clipState(aBuilder);
3398 if (clipCapturedBy != ContainerItemType::None) {
3399 clipState.Clear();
3400 }
3401
3402 DisplayListClipState::AutoSaveRestore transformedCssClip(aBuilder);
3403 if (isTransformed) {
3404 // FIXME(emilio, bug 1525159): In the case we have a both a transform _and_
3405 // filters, this clips the input to the filters as well, which is not
3406 // correct (clipping by the `clip` property is supposed to happen after
3407 // applying the filter effects, per [1].
3408 //
3409 // This is not a regression though, since we used to do that anyway before
3410 // bug 1514384, and even without the transform we get it wrong.
3411 //
3412 // [1]: https://drafts.fxtf.org/css-masking/#placement
3413 ApplyClipProp(transformedCssClip);
3414 }
3415
3416 uint32_t numActiveScrollframesEncounteredBefore =
3417 aBuilder->GetNumActiveScrollframesEncountered();
3418
3419 nsDisplayListCollection set(aBuilder);
3420 Maybe<nsRect> clipForMask;
3421 {
3422 DisplayListClipState::AutoSaveRestore nestedClipState(aBuilder);
3423 nsDisplayListBuilder::AutoInTransformSetter inTransformSetter(aBuilder,
3424 inTransform);
3425 nsDisplayListBuilder::AutoEnterFilter filterASRSetter(aBuilder,
3426 usingFilter);
3427 nsDisplayListBuilder::AutoInEventsOnly inEventsSetter(
3428 aBuilder, opacityItemForEventsOnly);
3429
3430 // If we have a mask, compute a clip to bound the masked content.
3431 // This is necessary in case the content moves with an ancestor
3432 // ASR of the mask.
3433 // Don't do this if we also have a filter, because then the clip
3434 // would be applied before the filter, violating
3435 // https://www.w3.org/TR/filter-effects-1/#placement.
3436 // Filters are a containing block for fixed and absolute descendants,
3437 // so the masked content cannot move with an ancestor ASR.
3438 if (usingMask && !usingFilter) {
3439 clipForMask = ComputeClipForMaskItem(aBuilder, this, maskUsage);
3440 if (clipForMask) {
3441 aBuilder->IntersectDirtyRect(*clipForMask);
3442 aBuilder->IntersectVisibleRect(*clipForMask);
3443 nestedClipState.ClipContentDescendants(
3444 *clipForMask + aBuilder->GetCurrentFrameOffsetToReferenceFrame());
3445 }
3446 }
3447
3448 // extend3DContext also guarantees that applyAbsPosClipping and
3449 // usingSVGEffects are false We only modify the preserve-3d rect if we are
3450 // the top of a preserve-3d heirarchy
3451 if (extend3DContext) {
3452 // Mark these first so MarkAbsoluteFramesForDisplayList knows if we are
3453 // going to be forced to descend into frames.
3454 aBuilder->MarkPreserve3DFramesForDisplayList(this);
3455 }
3456
3457 aBuilder->AdjustWindowDraggingRegion(this);
3458
3459 MarkAbsoluteFramesForDisplayList(aBuilder);
3460 aBuilder->Check();
3461 BuildDisplayList(aBuilder, set);
3462 SetBuiltDisplayList(true);
3463 aBuilder->Check();
3464 aBuilder->DisplayCaret(this, set.Outlines());
3465
3466 // Blend modes are a real pain for retained display lists. We build a blend
3467 // container item if the built list contains any blend mode items within
3468 // the current stacking context. This can change without an invalidation
3469 // to the stacking context frame, or the blend mode frame (e.g. by moving
3470 // an intermediate frame).
3471 // When we gain/remove a blend container item, we need to mark this frame
3472 // as invalid and have the full display list for merging to track
3473 // the change correctly.
3474 // It seems really hard to track this in advance, as the bookkeeping
3475 // required to note which stacking contexts have blend descendants
3476 // is complex and likely to be buggy.
3477 // Instead we're doing the sad thing, detecting it afterwards, and just
3478 // repeating display list building if it changed.
3479 // We have to repeat building for the entire display list (or at least
3480 // the outer stacking context), since we need to mark this frame as invalid
3481 // to remove any existing content that isn't wrapped in the blend container,
3482 // and then we need to build content infront/behind the blend container
3483 // to get correct positioning during merging.
3484 if (aBuilder->ContainsBlendMode() && aBuilder->IsRetainingDisplayList()) {
3485 if (aBuilder->IsPartialUpdate()) {
3486 aBuilder->SetPartialBuildFailed(true);
3487 } else {
3488 aBuilder->SetDisablePartialUpdates(true);
3489 }
3490 }
3491 }
3492
3493 if (aBuilder->IsBackgroundOnly()) {
3494 set.BlockBorderBackgrounds()->DeleteAll(aBuilder);
3495 set.Floats()->DeleteAll(aBuilder);
3496 set.Content()->DeleteAll(aBuilder);
3497 set.PositionedDescendants()->DeleteAll(aBuilder);
3498 set.Outlines()->DeleteAll(aBuilder);
3499 }
3500
3501 if (hasOverrideDirtyRect &&
3502 StaticPrefs::layout_display_list_show_rebuild_area()) {
3503 nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
3504 aBuilder, this,
3505 dirtyRect + aBuilder->GetCurrentFrameOffsetToReferenceFrame(),
3506 NS_RGBA(255, 0, 0, 64)((nscolor)(((64) << 24) | ((0) << 16) | ((0) <<
8) | (255)))
, false);
3507 if (color) {
3508 color->SetOverrideZIndex(INT32_MAX(2147483647));
3509 set.PositionedDescendants()->AppendToTop(color);
3510 }
3511 }
3512
3513 nsIContent* content = GetContent();
3514 if (!content) {
3515 content = PresContext()->Document()->GetRootElement();
3516 }
3517
3518 nsDisplayList resultList(aBuilder);
3519 set.SerializeWithCorrectZOrder(&resultList, content);
3520
3521 // Get the ASR to use for the container items that we create here.
3522 const ActiveScrolledRoot* containerItemASR = contASRTracker.GetContainerASR();
3523
3524 bool createdContainer = false;
3525
3526 // If adding both a nsDisplayBlendContainer and a nsDisplayBlendMode to the
3527 // same list, the nsDisplayBlendContainer should be added first. This only
3528 // happens when the element creating this stacking context has mix-blend-mode
3529 // and also contains a child which has mix-blend-mode.
3530 // The nsDisplayBlendContainer must be added to the list first, so it does not
3531 // isolate the containing element blending as well.
3532 if (aBuilder->ContainsBlendMode()) {
3533 resultList.AppendToTop(nsDisplayBlendContainer::CreateForMixBlendMode(
3534 aBuilder, this, &resultList, containerItemASR));
3535 createdContainer = true;
3536 }
3537
3538 if (usingBackdropFilter) {
3539 nsRect backdropRect =
3540 GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
3541 resultList.AppendNewToTop<nsDisplayBackdropFilters>(
3542 aBuilder, this, &resultList, backdropRect, this);
3543 createdContainer = true;
3544 }
3545
3546 // If there are any SVG effects, wrap the list up in an SVG effects item
3547 // (which also handles CSS group opacity). Note that we create an SVG effects
3548 // item even if resultList is empty, since a filter can produce graphical
3549 // output even if the element being filtered wouldn't otherwise do so.
3550 if (usingSVGEffects) {
3551 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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3552); AnnotateMozCrashReason("MOZ_ASSERT" "(" "usingFilter || usingMask"
") (" "Beside filter & mask/clip-path, what else effect do we have?"
")"); do { *((volatile int*)__null) = 3552; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
3552 "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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3552); AnnotateMozCrashReason("MOZ_ASSERT" "(" "usingFilter || usingMask"
") (" "Beside filter & mask/clip-path, what else effect do we have?"
")"); do { *((volatile int*)__null) = 3552; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3553
3554 if (clipCapturedBy == ContainerItemType::Filter) {
3555 clipState.Restore();
3556 }
3557 // Revert to the post-filter dirty rect.
3558 aBuilder->SetVisibleRect(visibleRectOutsideSVGEffects);
3559
3560 // Skip all filter effects while generating glyph mask.
3561 if (usingFilter && !aBuilder->IsForGenerateGlyphMask()) {
3562 /* List now emptied, so add the new list to the top. */
3563 resultList.AppendNewToTop<nsDisplayFilters>(aBuilder, this, &resultList,
3564 this, usingBackdropFilter);
3565 createdContainer = true;
Value stored to 'createdContainer' is never read
3566 }
3567
3568 if (usingMask) {
3569 // The mask should move with aBuilder->CurrentActiveScrolledRoot(), so
3570 // that's the ASR we prefer to use for the mask item. However, we can
3571 // only do this if the mask if clipped with respect to that ASR, because
3572 // an item always needs to have finite bounds with respect to its ASR.
3573 // If we weren't able to compute a clip for the mask, we fall back to
3574 // using containerItemASR, which is the lowest common ancestor clip of
3575 // the mask's contents. That's not entirely correct, but it satisfies
3576 // the base requirement of the ASR system (that items have finite bounds
3577 // wrt. their ASR).
3578 const ActiveScrolledRoot* maskASR =
3579 clipForMask.isSome() ? aBuilder->CurrentActiveScrolledRoot()
3580 : containerItemASR;
3581 /* List now emptied, so add the new list to the top. */
3582 resultList.AppendNewToTop<nsDisplayMasksAndClipPaths>(
3583 aBuilder, this, &resultList, maskASR, usingBackdropFilter);
3584 createdContainer = true;
3585 }
3586
3587 // TODO(miko): We could probably create a wraplist here and avoid creating
3588 // it later in |BuildDisplayListForChild()|.
3589 createdContainer = false;
3590
3591 // Also add the hoisted scroll info items. We need those for APZ scrolling
3592 // because nsDisplayMasksAndClipPaths items can't build active layers.
3593 aBuilder->ExitSVGEffectsContents();
3594 resultList.AppendToTop(&hoistedScrollInfoItemsStorage);
3595 }
3596
3597 // If the list is non-empty and there is CSS group opacity without SVG
3598 // effects, wrap it up in an opacity item.
3599 if (useOpacity) {
3600 const bool needsActiveOpacityLayer =
3601 nsDisplayOpacity::NeedsActiveLayer(aBuilder, this);
3602 resultList.AppendNewToTop<nsDisplayOpacity>(
3603 aBuilder, this, &resultList, containerItemASR, opacityItemForEventsOnly,
3604 needsActiveOpacityLayer, usingBackdropFilter);
3605 createdContainer = true;
3606 }
3607
3608 // If we're going to apply a transformation and don't have preserve-3d set,
3609 // wrap everything in an nsDisplayTransform. If there's nothing in the list,
3610 // don't add anything.
3611 //
3612 // For the preserve-3d case we want to individually wrap every child in the
3613 // list with a separate nsDisplayTransform instead. When the child is already
3614 // an nsDisplayTransform, we can skip this step, as the computed transform
3615 // will already include our own.
3616 //
3617 // We also traverse into sublists created by nsDisplayWrapList, so that we
3618 // find all the correct children.
3619 if (isTransformed && extend3DContext) {
3620 // Install dummy nsDisplayTransform as a leaf containing
3621 // descendants not participating this 3D rendering context.
3622 nsDisplayList nonparticipants(aBuilder);
3623 nsDisplayList participants(aBuilder);
3624 int index = 1;
3625
3626 nsDisplayItem* separator = nullptr;
3627
3628 // TODO: This can be simplified: |participants| is just |resultList|.
3629 for (nsDisplayItem* item : resultList.TakeItems()) {
3630 if (ItemParticipatesIn3DContext(this, item) &&
3631 !item->GetClip().HasClip()) {
3632 // The frame of this item participates the same 3D context.
3633 WrapSeparatorTransform(aBuilder, this, &nonparticipants, &participants,
3634 index++, &separator);
3635
3636 participants.AppendToTop(item);
3637 } else {
3638 // The frame of the item doesn't participate the current
3639 // context, or has no transform.
3640 //
3641 // For items participating but not transformed, they are add
3642 // to nonparticipants to get a separator layer for handling
3643 // clips, if there is, on an intermediate surface.
3644 // \see ContainerLayer::DefaultComputeEffectiveTransforms().
3645 nonparticipants.AppendToTop(item);
3646 }
3647 }
3648 WrapSeparatorTransform(aBuilder, this, &nonparticipants, &participants,
3649 index++, &separator);
3650
3651 if (separator) {
3652 createdContainer = true;
3653 }
3654
3655 resultList.AppendToTop(&participants);
3656 }
3657
3658 if (isTransformed) {
3659 transformedCssClip.Restore();
3660 if (clipCapturedBy == ContainerItemType::Transform) {
3661 // Restore clip state now so nsDisplayTransform is clipped properly.
3662 clipState.Restore();
3663 }
3664 // Revert to the dirtyrect coming in from the parent, without our transform
3665 // taken into account.
3666 aBuilder->SetVisibleRect(visibleRectOutsideTransform);
3667
3668 if (this != aBuilder->RootReferenceFrame()) {
3669 // Revert to the outer reference frame and offset because all display
3670 // items we create from now on are outside the transform.
3671 nsPoint toOuterReferenceFrame;
3672 const nsIFrame* outerReferenceFrame =
3673 aBuilder->FindReferenceFrameFor(GetParent(), &toOuterReferenceFrame);
3674 toOuterReferenceFrame += GetPosition();
3675
3676 buildingDisplayList.SetReferenceFrameAndCurrentOffset(
3677 outerReferenceFrame, toOuterReferenceFrame);
3678 }
3679
3680 // We would like to block async animations for ancestors of ones not
3681 // prerendered in the preserve-3d tree. Now that we've finished processing
3682 // all descendants, update allowAsyncAnimation to take their prerender
3683 // state into account
3684 // FIXME: We don't block async animations for previous siblings because
3685 // their prerender decisions have been made. We may have to figure out a
3686 // better way to rollback their prerender decisions.
3687 // Alternatively we could not block animations for later siblings, and only
3688 // block them for ancestors of a blocked one.
3689 if ((extend3DContext || combines3DTransformWithAncestors) &&
3690 prerenderInfo.CanUseAsyncAnimations() &&
3691 !aBuilder->GetPreserves3DAllowAsyncAnimation()) {
3692 // aBuilder->GetPreserves3DAllowAsyncAnimation() means the inner or
3693 // previous silbing frames are allowed/disallowed for async animations.
3694 prerenderInfo.mDecision = nsDisplayTransform::PrerenderDecision::No;
3695 }
3696
3697 nsDisplayTransform* transformItem = MakeDisplayItem<nsDisplayTransform>(
3698 aBuilder, this, &resultList, visibleRect, prerenderInfo.mDecision);
3699 if (transformItem) {
3700 resultList.AppendToTop(transformItem);
3701 createdContainer = true;
3702
3703 if (numActiveScrollframesEncounteredBefore !=
3704 aBuilder->GetNumActiveScrollframesEncountered()) {
3705 transformItem->SetContainsASRs(true);
3706 }
3707
3708 if (hasPerspective) {
3709 transformItem->MarkWithAssociatedPerspective();
3710
3711 if (clipCapturedBy == ContainerItemType::Perspective) {
3712 clipState.Restore();
3713 }
3714 resultList.AppendNewToTop<nsDisplayPerspective>(aBuilder, this,
3715 &resultList);
3716 createdContainer = true;
3717 }
3718 }
3719 }
3720
3721 if (clipCapturedBy ==
3722 ContainerItemType::OwnLayerForTransformWithRoundedClip) {
3723 clipState.Restore();
3724 resultList.AppendNewToTopWithIndex<nsDisplayOwnLayer>(
3725 aBuilder, this,
3726 /* aIndex = */ nsDisplayOwnLayer::OwnLayerForTransformWithRoundedClip,
3727 &resultList, aBuilder->CurrentActiveScrolledRoot(),
3728 nsDisplayOwnLayerFlags::None, ScrollbarData{},
3729 /* aForceActive = */ false, false);
3730 createdContainer = true;
3731 }
3732
3733 // If we have sticky positioning, wrap it in a sticky position item.
3734 if (useFixedPosition) {
3735 if (clipCapturedBy == ContainerItemType::FixedPosition) {
3736 clipState.Restore();
3737 }
3738 // The ASR for the fixed item should be the ASR of our containing block,
3739 // which has been set as the builder's current ASR, unless this frame is
3740 // invisible and we hadn't saved display item data for it. In that case,
3741 // we need to take the containerItemASR since we might have fixed children.
3742 // For WebRender, we want to the know what |containerItemASR| is for the
3743 // case where the fixed-pos item is not a "real" fixed-pos item (e.g. it's
3744 // nested inside a scrolling transform), so we stash that on the display
3745 // item as well.
3746 const ActiveScrolledRoot* fixedASR = ActiveScrolledRoot::PickAncestor(
3747 containerItemASR, aBuilder->CurrentActiveScrolledRoot());
3748 resultList.AppendNewToTop<nsDisplayFixedPosition>(
3749 aBuilder, this, &resultList, fixedASR, containerItemASR);
3750 createdContainer = true;
3751 } else if (useStickyPosition) {
3752 // For position:sticky, the clip needs to be applied both to the sticky
3753 // container item and to the contents. The container item needs the clip
3754 // because a scrolled clip needs to move independently from the sticky
3755 // contents, and the contents need the clip so that they have finite
3756 // clipped bounds with respect to the container item's ASR. The latter is
3757 // a little tricky in the case where the sticky item has both fixed and
3758 // non-fixed descendants, because that means that the sticky container
3759 // item's ASR is the ASR of the fixed descendant.
3760 // For WebRender display list building, though, we still want to know the
3761 // the ASR that the sticky container item would normally have, so we stash
3762 // that on the display item as the "container ASR" (i.e. the normal ASR of
3763 // the container item, excluding the special behaviour induced by fixed
3764 // descendants).
3765 const ActiveScrolledRoot* stickyASR = ActiveScrolledRoot::PickAncestor(
3766 containerItemASR, aBuilder->CurrentActiveScrolledRoot());
3767
3768 auto* stickyItem = MakeDisplayItem<nsDisplayStickyPosition>(
3769 aBuilder, this, &resultList, stickyASR,
3770 aBuilder->CurrentActiveScrolledRoot(),
3771 clipState.IsClippedToDisplayPort());
3772
3773 bool shouldFlatten = true;
3774
3775 StickyScrollContainer* stickyScrollContainer =
3776 StickyScrollContainer::GetStickyScrollContainerForFrame(this);
3777 if (stickyScrollContainer && stickyScrollContainer->ScrollContainer()
3778 ->IsMaybeAsynchronouslyScrolled()) {
3779 shouldFlatten = false;
3780 }
3781
3782 stickyItem->SetShouldFlatten(shouldFlatten);
3783
3784 resultList.AppendToTop(stickyItem);
3785 createdContainer = true;
3786
3787 // If the sticky element is inside a filter, annotate the scroll frame that
3788 // scrolls the filter as having out-of-flow content inside a filter (this
3789 // inhibits paint skipping).
3790 if (aBuilder->GetFilterASR() && aBuilder->GetFilterASR() == stickyASR) {
3791 aBuilder->GetFilterASR()
3792 ->mScrollContainerFrame->SetHasOutOfFlowContentInsideFilter();
3793 }
3794 }
3795
3796 // If there's blending, wrap up the list in a blend-mode item. Note that
3797 // opacity can be applied before blending as the blend color is not affected
3798 // by foreground opacity (only background alpha).
3799 if (useBlendMode) {
3800 DisplayListClipState::AutoSaveRestore blendModeClipState(aBuilder);
3801 resultList.AppendNewToTop<nsDisplayBlendMode>(aBuilder, this, &resultList,
3802 effects->mMixBlendMode,
3803 containerItemASR, false);
3804 createdContainer = true;
3805 }
3806
3807 if (aBuilder->IsReusingStackingContextItems()) {
3808 if (resultList.IsEmpty()) {
3809 return;
3810 }
3811
3812 nsDisplayItem* container = resultList.GetBottom();
3813 if (resultList.Length() > 1 || container->Frame() != this) {
3814 container = MakeDisplayItem<nsDisplayContainer>(
3815 aBuilder, this, containerItemASR, &resultList);
3816 } else {
3817 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3817); AnnotateMozCrashReason("MOZ_ASSERT" "(" "resultList.Length() == 1"
")"); do { *((volatile int*)__null) = 3817; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3818 resultList.Clear();
3819 }
3820
3821 // Mark the outermost display item as reusable. These display items and
3822 // their chidren can be reused during the next paint if no ancestor or
3823 // descendant frames have been modified.
3824 if (!container->IsReusedItem()) {
3825 container->SetReusable();
3826 }
3827 aList->AppendToTop(container);
3828 createdContainer = true;
3829 } else {
3830 aList->AppendToTop(&resultList);
3831 }
3832
3833 if (aCreatedContainerItem) {
3834 *aCreatedContainerItem = createdContainer;
3835 }
3836}
3837
3838static nsDisplayItem* WrapInWrapList(nsDisplayListBuilder* aBuilder,
3839 nsIFrame* aFrame, nsDisplayList* aList,
3840 const ActiveScrolledRoot* aContainerASR,
3841 bool aBuiltContainerItem = false) {
3842 nsDisplayItem* item = aList->GetBottom();
3843 if (!item) {
3844 return nullptr;
3845 }
3846
3847 // We need a wrap list if there are multiple items, or if the single
3848 // item has a different frame. This can change in a partial build depending
3849 // on which items we build, so we need to ensure that we don't transition
3850 // to/from a wrap list without invalidating correctly.
3851 bool needsWrapList =
3852 aList->Length() > 1 || item->Frame() != aFrame || item->GetChildren();
3853
3854 // If we have an explicit container item (that can't change without an
3855 // invalidation) or we're doing a full build and don't need a wrap list, then
3856 // we can skip adding one.
3857 if (aBuiltContainerItem || (!aBuilder->IsPartialUpdate() && !needsWrapList)) {
3858 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3858); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aList->Length() == 1"
")"); do { *((volatile int*)__null) = 3858; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3859 aList->Clear();
3860 return item;
3861 }
3862
3863 // If we're doing a partial build and we didn't need a wrap list
3864 // previously then we can try to work from there.
3865 if (aBuilder->IsPartialUpdate() &&
3866 !aFrame->HasDisplayItem(uint32_t(DisplayItemType::TYPE_CONTAINER))) {
3867 // If we now need a wrap list, we must previously have had no display items
3868 // or a single one belonging to this frame. Mark the item itself as
3869 // discarded so that RetainedDisplayListBuilder uses the ones we just built.
3870 // We don't want to mark the frame as modified as that would invalidate
3871 // positioned descendants that might be outside of this list, and might not
3872 // have been rebuilt this time.
3873 if (needsWrapList) {
3874 DiscardOldItems(aFrame);
3875 } else {
3876 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3876); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aList->Length() == 1"
")"); do { *((volatile int*)__null) = 3876; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3877 aList->Clear();
3878 return item;
3879 }
3880 }
3881
3882 // The last case we could try to handle is when we previously had a wrap list,
3883 // but no longer need it. Unfortunately we can't differentiate this case from
3884 // a partial build where other children exist but we just didn't build them
3885 // this time.
3886 // TODO:RetainedDisplayListBuilder's merge phase has the full list and
3887 // could strip them out.
3888
3889 return MakeDisplayItem<nsDisplayContainer>(aBuilder, aFrame, aContainerASR,
3890 aList);
3891}
3892
3893/**
3894 * Check if a frame should be visited for building display list.
3895 */
3896static bool DescendIntoChild(nsDisplayListBuilder* aBuilder,
3897 const nsIFrame* aChild, const nsRect& aVisible,
3898 const nsRect& aDirty) {
3899 if (aChild->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
3900 return true;
3901 }
3902
3903 // If the child is a scrollframe that we want to ignore, then we need
3904 // to descend into it because its scrolled child may intersect the dirty
3905 // area even if the scrollframe itself doesn't.
3906 if (aChild == aBuilder->GetIgnoreScrollFrame()) {
3907 return true;
3908 }
3909
3910 // There are cases where the "ignore scroll frame" on the builder is not set
3911 // correctly, and so we additionally want to catch cases where the child is
3912 // a root scrollframe and we are ignoring scrolling on the viewport.
3913 if (aChild == aBuilder->GetPresShellIgnoreScrollFrame()) {
3914 return true;
3915 }
3916
3917 nsRect overflow = aChild->InkOverflowRect();
3918
3919 // On mobile, there may be a dynamic toolbar. The root content document's
3920 // root scroll frame's ink overflow rect does not include the toolbar
3921 // height, but if the toolbar is hidden, we still want to be able to target
3922 // content underneath the toolbar, so expand the overflow rect here to
3923 // allow display list building to descend into the scroll frame.
3924 if (aBuilder->IsForEventDelivery() &&
3925 aChild == aChild->PresShell()->GetRootScrollContainerFrame() &&
3926 aChild->PresContext()->IsRootContentDocumentCrossProcess() &&
3927 aChild->PresContext()->HasDynamicToolbar()) {
3928 overflow.SizeTo(nsLayoutUtils::ExpandHeightForDynamicToolbar(
3929 aChild->PresContext(), overflow.Size()));
3930 }
3931
3932 if (aDirty.Intersects(overflow)) {
3933 return true;
3934 }
3935
3936 if (aChild->ForceDescendIntoIfVisible() && aVisible.Intersects(overflow)) {
3937 return true;
3938 }
3939
3940 if (aChild->IsTablePart()) {
3941 // Relative positioning and transforms can cause table parts to move, but we
3942 // will still paint the backgrounds for their ancestor parts under them at
3943 // their 'normal' position. That means that we must consider the overflow
3944 // rects at both positions.
3945
3946 // We convert the overflow rect into the nsTableFrame's coordinate
3947 // space, applying the normal position offset at each step. Then we
3948 // compare that against the builder's cached dirty rect in table
3949 // coordinate space.
3950 const nsIFrame* f = aChild;
3951 nsRect normalPositionOverflowRelativeToTable = overflow;
3952
3953 while (f->IsTablePart()) {
3954 normalPositionOverflowRelativeToTable += f->GetNormalPosition();
3955 f = f->GetParent();
3956 }
3957
3958 nsDisplayTableBackgroundSet* tableBGs = aBuilder->GetTableBackgroundSet();
3959 if (tableBGs && tableBGs->GetDirtyRect().Intersects(
3960 normalPositionOverflowRelativeToTable)) {
3961 return true;
3962 }
3963 }
3964
3965 return false;
3966}
3967
3968void nsIFrame::BuildDisplayListForSimpleChild(nsDisplayListBuilder* aBuilder,
3969 nsIFrame* aChild,
3970 const nsDisplayListSet& aLists) {
3971 // This is the shortcut for frames been handled along the common
3972 // path, the most common one of THE COMMON CASE mentioned later.
3973 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3973); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aChild->Type() != LayoutFrameType::Placeholder"
")"); do { *((volatile int*)__null) = 3973; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3974 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3976); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { *
((volatile int*)__null) = 3976; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
3975 !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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3976); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { *
((volatile int*)__null) = 3976; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
3976 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3976); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aBuilder->GetSelectedFramesOnly() && !aBuilder->GetIncludeAllOutOfFlows()"
") (" "It should be held for painting to window" ")"); do { *
((volatile int*)__null) = 3976; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
3977 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 3977); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST)"
")"); do { *((volatile int*)__null) = 3977; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3978
3979 const nsPoint offset = aChild->GetOffsetTo(this);
3980 const nsRect visible = aBuilder->GetVisibleRect() - offset;
3981 const nsRect dirty = aBuilder->GetDirtyRect() - offset;
3982
3983 if (!DescendIntoChild(aBuilder, aChild, visible, dirty)) {
3984 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)
;
3985 return;
3986 }
3987
3988 // Child cannot be transformed since it is not a stacking context.
3989 nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
3990 aBuilder, aChild, visible, dirty, false);
3991
3992 UpdateCurrentHitTestInfo(aBuilder, aChild);
3993
3994 aChild->MarkAbsoluteFramesForDisplayList(aBuilder);
3995 aBuilder->AdjustWindowDraggingRegion(aChild);
3996 aBuilder->Check();
3997 aChild->BuildDisplayList(aBuilder, aLists);
3998 aChild->SetBuiltDisplayList(true);
3999 aBuilder->Check();
4000 aBuilder->DisplayCaret(aChild, aLists.Outlines());
4001}
4002
4003static bool ShouldSkipFrame(nsDisplayListBuilder* aBuilder,
4004 const nsIFrame* aFrame) {
4005 // If painting is restricted to just the background of the top level frame,
4006 // then we have nothing to do here.
4007 if (aBuilder->IsBackgroundOnly()) {
4008 return true;
4009 }
4010 if (aBuilder->IsForGenerateGlyphMask() &&
4011 (!aFrame->IsTextFrame() && aFrame->IsLeaf())) {
4012 return true;
4013 }
4014 // The placeholder frame should have the same content as the OOF frame.
4015 if (aBuilder->GetSelectedFramesOnly() &&
4016 (aFrame->IsLeaf() && !aFrame->IsSelected())) {
4017 return true;
4018 }
4019 static const nsFrameState skipFlags =
4020 (NS_FRAME_TOO_DEEP_IN_FRAME_TREE | NS_FRAME_IS_NONDISPLAY);
4021 if (aFrame->HasAnyStateBits(skipFlags)) {
4022 return true;
4023 }
4024 return aFrame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually;
4025}
4026
4027void nsIFrame::BuildDisplayListForChild(nsDisplayListBuilder* aBuilder,
4028 nsIFrame* aChild,
4029 const nsDisplayListSet& aLists,
4030 DisplayChildFlags aFlags) {
4031 AutoCheckBuilder check(aBuilder);
4032#ifdef DEBUG1
4033 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)
;
4034 ScopeExit e(
4035 [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)
; });
4036#endif
4037
4038 if (ShouldSkipFrame(aBuilder, aChild)) {
4039 return;
4040 }
4041
4042 if (HidesContent()) {
4043 return;
4044 }
4045
4046 nsIFrame* child = aChild;
4047 auto* placeholder = child->IsPlaceholderFrame()
4048 ? static_cast<nsPlaceholderFrame*>(child)
4049 : nullptr;
4050 nsIFrame* childOrOutOfFlow =
4051 placeholder ? placeholder->GetOutOfFlowFrame() : child;
4052
4053 // If we're generating a display list for printing, include Link items for
4054 // frames that correspond to HTML link elements so that we can have active
4055 // links in saved PDF output. Note that the state of "within a link" is
4056 // set on the display-list builder, such that all descendants of the link
4057 // element will generate display-list links.
4058 // TODO: we should be able to optimize this so as to avoid creating links
4059 // for the same destination that entirely overlap each other, which adds
4060 // nothing useful to the final PDF.
4061 Maybe<nsDisplayListBuilder::Linkifier> linkifier;
4062 if (StaticPrefs::print_save_as_pdf_links_enabled() &&
4063 aBuilder->IsForPrinting()) {
4064 linkifier.emplace(aBuilder, childOrOutOfFlow, aLists.Content());
4065 linkifier->MaybeAppendLink(aBuilder, childOrOutOfFlow);
4066 }
4067
4068 nsIFrame* parent = childOrOutOfFlow->GetParent();
4069 const auto* parentDisplay = parent->StyleDisplay();
4070 const auto overflowClipAxes =
4071 parent->ShouldApplyOverflowClipping(parentDisplay);
4072
4073 const bool isPaintingToWindow = aBuilder->IsPaintingToWindow();
4074 const bool doingShortcut =
4075 isPaintingToWindow &&
4076 child->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST) &&
4077 // Animations may change the stacking context state.
4078 // ShouldApplyOverflowClipping is affected by the parent style, which does
4079 // not invalidate the NS_FRAME_SIMPLE_DISPLAYLIST bit.
4080 !(!overflowClipAxes.isEmpty() || child->MayHaveTransformAnimation() ||
4081 child->MayHaveOpacityAnimation());
4082
4083 if (aBuilder->IsForPainting()) {
4084 aBuilder->ClearWillChangeBudgetStatus(child);
4085 }
4086
4087 if (StaticPrefs::layout_css_scroll_anchoring_highlight()) {
4088 if (child->FirstContinuation()->IsScrollAnchor()) {
4089 nsRect bounds = child->GetContentRectRelativeToSelf() +
4090 aBuilder->ToReferenceFrame(child);
4091 nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
4092 aBuilder, child, bounds, NS_RGBA(255, 0, 255, 64)((nscolor)(((64) << 24) | ((255) << 16) | ((0) <<
8) | (255)))
);
4093 if (color) {
4094 color->SetOverrideZIndex(INT32_MAX(2147483647));
4095 aLists.PositionedDescendants()->AppendToTop(color);
4096 }
4097 }
4098 }
4099
4100 if (doingShortcut) {
4101 BuildDisplayListForSimpleChild(aBuilder, child, aLists);
4102 return;
4103 }
4104
4105 // dirty rect in child-relative coordinates
4106 NS_ASSERTION(aBuilder->GetCurrentFrame() == this, "Wrong coord space!")do { if (!(aBuilder->GetCurrentFrame() == this)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Wrong coord space!", "aBuilder->GetCurrentFrame() == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4106); MOZ_PretendNoReturn(); } } while (0)
;
4107 const nsPoint offset = child->GetOffsetTo(this);
4108 nsRect visible = aBuilder->GetVisibleRect() - offset;
4109 nsRect dirty = aBuilder->GetDirtyRect() - offset;
4110
4111 nsDisplayListBuilder::OutOfFlowDisplayData* savedOutOfFlowData = nullptr;
4112 if (placeholder) {
4113 if (placeholder->HasAnyStateBits(PLACEHOLDER_FOR_TOPLAYER)) {
4114 // If the out-of-flow frame is in the top layer, the viewport frame
4115 // will paint it. Skip it here. Note that, only out-of-flow frames
4116 // with this property should be skipped, because non-HTML elements
4117 // may stop their children from being out-of-flow. Those frames
4118 // should still be handled in the normal in-flow path.
4119 return;
4120 }
4121
4122 child = childOrOutOfFlow;
4123 if (aBuilder->IsForPainting()) {
4124 aBuilder->ClearWillChangeBudgetStatus(child);
4125 }
4126
4127 // If 'child' is a pushed float then it's owned by a block that's not an
4128 // ancestor of the placeholder, and it will be painted by that block and
4129 // should not be painted through the placeholder. Also recheck
4130 // NS_FRAME_TOO_DEEP_IN_FRAME_TREE and NS_FRAME_IS_NONDISPLAY.
4131 static const nsFrameState skipFlags =
4132 (NS_FRAME_IS_PUSHED_FLOAT | NS_FRAME_TOO_DEEP_IN_FRAME_TREE |
4133 NS_FRAME_IS_NONDISPLAY);
4134 if (child->HasAnyStateBits(skipFlags) || nsLayoutUtils::IsPopup(child)) {
4135 return;
4136 }
4137
4138 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4138); AnnotateMozCrashReason("MOZ_ASSERT" "(" "child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)"
")"); do { *((volatile int*)__null) = 4138; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4139 savedOutOfFlowData = nsDisplayListBuilder::GetOutOfFlowData(child);
4140
4141 if (aBuilder->GetIncludeAllOutOfFlows()) {
4142 visible = child->InkOverflowRect();
4143 dirty = child->InkOverflowRect();
4144 } else if (savedOutOfFlowData) {
4145 visible =
4146 savedOutOfFlowData->GetVisibleRectForFrame(aBuilder, child, &dirty);
4147 } else {
4148 // The out-of-flow frame did not intersect the dirty area. We may still
4149 // need to traverse into it, since it may contain placeholders we need
4150 // to enter to reach other out-of-flow frames that are visible.
4151 visible.SetEmpty();
4152 dirty.SetEmpty();
4153 }
4154 }
4155
4156 NS_ASSERTION(!child->IsPlaceholderFrame(),do { if (!(!child->IsPlaceholderFrame())) { NS_DebugBreak(
NS_DEBUG_ASSERTION, "Should have dealt with placeholders already"
, "!child->IsPlaceholderFrame()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4157); MOZ_PretendNoReturn(); } } while (0)
4157 "Should have dealt with placeholders already")do { if (!(!child->IsPlaceholderFrame())) { NS_DebugBreak(
NS_DEBUG_ASSERTION, "Should have dealt with placeholders already"
, "!child->IsPlaceholderFrame()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4157); MOZ_PretendNoReturn(); } } while (0)
;
4158
4159 if (!DescendIntoChild(aBuilder, child, visible, dirty)) {
4160 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
)
;
4161 return;
4162 }
4163
4164 const bool isSVG = child->HasAnyStateBits(NS_FRAME_SVG_LAYOUT);
4165
4166 // This flag is raised if the control flow strays off the common path.
4167 // The common path is the most common one of THE COMMON CASE mentioned later.
4168 bool awayFromCommonPath = !isPaintingToWindow;
4169
4170 // true if this is a real or pseudo stacking context
4171 bool pseudoStackingContext =
4172 aFlags.contains(DisplayChildFlag::ForcePseudoStackingContext);
4173
4174 if (!pseudoStackingContext && !isSVG &&
4175 aFlags.contains(DisplayChildFlag::Inline) &&
4176 !child->IsLineParticipant()) {
4177 // child is a non-inline frame in an inline context, i.e.,
4178 // it acts like inline-block or inline-table. Therefore it is a
4179 // pseudo-stacking-context.
4180 pseudoStackingContext = true;
4181 }
4182
4183 const nsStyleDisplay* ourDisp = StyleDisplay();
4184 // Don't paint our children if the theme object is a leaf.
4185 if (IsThemed(ourDisp) && !PresContext()->Theme()->WidgetIsContainer(
4186 ourDisp->EffectiveAppearance())) {
4187 return;
4188 }
4189
4190 // Since we're now sure that we're adding this frame to the display list
4191 // (which means we're painting it, modulo occlusion), mark it as visible
4192 // within the displayport.
4193 if (isPaintingToWindow && child->TrackingVisibility() &&
4194 child->IsVisibleForPainting()) {
4195 child->PresShell()->EnsureFrameInApproximatelyVisibleList(child);
4196 awayFromCommonPath = true;
4197 }
4198
4199 // Child is composited if it's transformed, partially transparent, or has
4200 // SVG effects or a blend mode..
4201 const nsStyleDisplay* disp = child->StyleDisplay();
4202 const nsStyleEffects* effects = child->StyleEffects();
4203
4204 const bool isPositioned = disp->IsPositionedStyle();
4205 const bool isStackingContext =
4206 aFlags.contains(DisplayChildFlag::ForceStackingContext) ||
4207 child->IsStackingContext(disp, effects);
4208
4209 if (pseudoStackingContext || isStackingContext || isPositioned ||
4210 placeholder || (!isSVG && disp->IsFloating(child)) ||
4211 (isSVG && effects->mClip.IsRect() && IsSVGContentWithCSSClip(child))) {
4212 pseudoStackingContext = true;
4213 awayFromCommonPath = true;
4214 }
4215
4216 NS_ASSERTION(!isStackingContext || pseudoStackingContext,do { if (!(!isStackingContext || pseudoStackingContext)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Stacking contexts must also be pseudo-stacking-contexts"
, "!isStackingContext || pseudoStackingContext", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4217); MOZ_PretendNoReturn(); } } while (0)
4217 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4217); MOZ_PretendNoReturn(); } } while (0)
;
4218
4219 nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
4220 aBuilder, child, visible, dirty);
4221
4222 UpdateCurrentHitTestInfo(aBuilder, child);
4223
4224 DisplayListClipState::AutoClipMultiple clipState(aBuilder);
4225 nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(aBuilder);
4226
4227 if (savedOutOfFlowData) {
4228 aBuilder->SetBuildingInvisibleItems(false);
4229
4230 clipState.SetClipChainForContainingBlockDescendants(
4231 savedOutOfFlowData->mContainingBlockClipChain);
4232 asrSetter.SetCurrentActiveScrolledRoot(
4233 savedOutOfFlowData->mContainingBlockActiveScrolledRoot);
4234 asrSetter.SetCurrentScrollParentId(savedOutOfFlowData->mScrollParentId);
4235 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" ")",
"/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4236); AnnotateMozCrashReason("MOZ_ASSERT" "(" "awayFromCommonPath"
") (" "It is impossible when savedOutOfFlowData is true" ")"
); do { *((volatile int*)__null) = 4236; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
4236 "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" ")",
"/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4236); AnnotateMozCrashReason("MOZ_ASSERT" "(" "awayFromCommonPath"
") (" "It is impossible when savedOutOfFlowData is true" ")"
); do { *((volatile int*)__null) = 4236; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4237 } else if (HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) &&
4238 placeholder) {
4239 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4239); MOZ_PretendNoReturn(); } } while (0)
;
4240 // Every item we build from now until we descent into an out of flow that
4241 // does have saved out of flow data should be invisible. This state gets
4242 // restored when AutoBuildingDisplayList gets out of scope.
4243 aBuilder->SetBuildingInvisibleItems(true);
4244
4245 // If we have nested out-of-flow frames and the outer one isn't visible
4246 // then we won't have stored clip data for it. We can just clear the clip
4247 // instead since we know we won't render anything, and the inner out-of-flow
4248 // frame will setup the correct clip for itself.
4249 clipState.SetClipChainForContainingBlockDescendants(nullptr);
4250 }
4251
4252 // Setup clipping for the parent's overflow:clip,
4253 // or overflow:hidden on elements that don't support scrolling (and therefore
4254 // don't create nsHTML/XULScrollFrame). This clipping needs to not clip
4255 // anything directly rendered by the parent, only the rendering of its
4256 // children.
4257 // Don't use overflowClip to restrict the dirty rect, since some of the
4258 // descendants may not be clipped by it. Even if we end up with unnecessary
4259 // display items, they'll be pruned during ComputeVisibility.
4260 //
4261 // FIXME(emilio): Why can't we handle this more similarly to `clip` (on the
4262 // parent, rather than on the children)? Would ClipContentDescendants do what
4263 // we want?
4264 if (!overflowClipAxes.isEmpty()) {
4265 ApplyOverflowClipping(aBuilder, parent, overflowClipAxes, clipState);
4266 awayFromCommonPath = true;
4267 }
4268
4269 nsDisplayList list(aBuilder);
4270 nsDisplayList extraPositionedDescendants(aBuilder);
4271 const ActiveScrolledRoot* wrapListASR;
4272 bool builtContainerItem = false;
4273 if (isStackingContext) {
4274 // True stacking context.
4275 // For stacking contexts, BuildDisplayListForStackingContext handles
4276 // clipping and MarkAbsoluteFramesForDisplayList.
4277 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
4278 child->BuildDisplayListForStackingContext(aBuilder, &list,
4279 &builtContainerItem);
4280 wrapListASR = contASRTracker.GetContainerASR();
4281 if (!aBuilder->IsReusingStackingContextItems() &&
4282 aBuilder->GetCaretFrame() == child) {
4283 builtContainerItem = false;
4284 }
4285 } else {
4286 Maybe<nsRect> clipPropClip =
4287 child->GetClipPropClipRect(disp, effects, child->GetSize());
4288 if (clipPropClip) {
4289 aBuilder->IntersectVisibleRect(*clipPropClip);
4290 aBuilder->IntersectDirtyRect(*clipPropClip);
4291 clipState.ClipContentDescendants(*clipPropClip +
4292 aBuilder->ToReferenceFrame(child));
4293 awayFromCommonPath = true;
4294 }
4295
4296 child->MarkAbsoluteFramesForDisplayList(aBuilder);
4297 child->SetBuiltDisplayList(true);
4298
4299 // Some SVG frames might change opacity without invalidating the frame, so
4300 // exclude them from the fast-path.
4301 if (!awayFromCommonPath && !child->IsSVGFrame()) {
4302 // The shortcut is available for the child for next time.
4303 child->AddStateBits(NS_FRAME_SIMPLE_DISPLAYLIST);
4304 }
4305
4306 if (!pseudoStackingContext) {
4307 // THIS IS THE COMMON CASE.
4308 // Not a pseudo or real stacking context. Do the simple thing and
4309 // return early.
4310 aBuilder->AdjustWindowDraggingRegion(child);
4311 aBuilder->Check();
4312 child->BuildDisplayList(aBuilder, aLists);
4313 aBuilder->Check();
4314 aBuilder->DisplayCaret(child, aLists.Outlines());
4315 return;
4316 }
4317
4318 // A pseudo-stacking context (e.g., a positioned element with z-index auto).
4319 // We allow positioned descendants of the child to escape to our parent
4320 // stacking context's positioned descendant list, because they might be
4321 // z-index:non-auto
4322 nsDisplayListCollection pseudoStack(aBuilder);
4323
4324 aBuilder->AdjustWindowDraggingRegion(child);
4325 nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
4326 aBuilder->Check();
4327 child->BuildDisplayList(aBuilder, pseudoStack);
4328 aBuilder->Check();
4329 if (aBuilder->DisplayCaret(child, pseudoStack.Outlines())) {
4330 builtContainerItem = false;
4331 }
4332 wrapListASR = contASRTracker.GetContainerASR();
4333
4334 list.AppendToTop(pseudoStack.BorderBackground());
4335 list.AppendToTop(pseudoStack.BlockBorderBackgrounds());
4336 list.AppendToTop(pseudoStack.Floats());
4337 list.AppendToTop(pseudoStack.Content());
4338 list.AppendToTop(pseudoStack.Outlines());
4339 extraPositionedDescendants.AppendToTop(pseudoStack.PositionedDescendants());
4340 }
4341
4342 buildingForChild.RestoreBuildingInvisibleItemsValue();
4343
4344 if (!list.IsEmpty()) {
4345 if (isPositioned || isStackingContext) {
4346 // Genuine stacking contexts, and positioned pseudo-stacking-contexts,
4347 // go in this level.
4348 nsDisplayItem* item = WrapInWrapList(aBuilder, child, &list, wrapListASR,
4349 builtContainerItem);
4350 if (isSVG) {
4351 aLists.Content()->AppendToTop(item);
4352 } else {
4353 aLists.PositionedDescendants()->AppendToTop(item);
4354 }
4355 } else if (!isSVG && disp->IsFloating(child)) {
4356 aLists.Floats()->AppendToTop(
4357 WrapInWrapList(aBuilder, child, &list, wrapListASR));
4358 } else {
4359 aLists.Content()->AppendToTop(&list);
4360 }
4361 }
4362 // We delay placing the positioned descendants of positioned frames to here,
4363 // because in the absence of z-index this is the correct order for them.
4364 // This doesn't affect correctness because the positioned descendants list
4365 // is sorted by z-order and content in BuildDisplayListForStackingContext,
4366 // but it means that sort routine needs to do less work.
4367 aLists.PositionedDescendants()->AppendToTop(&extraPositionedDescendants);
4368}
4369
4370void nsIFrame::MarkAbsoluteFramesForDisplayList(
4371 nsDisplayListBuilder* aBuilder) {
4372 if (IsAbsoluteContainer()) {
4373 aBuilder->MarkFramesForDisplayList(
4374 this, GetAbsoluteContainingBlock()->GetChildList());
4375 }
4376}
4377
4378nsresult nsIFrame::GetContentForEvent(const WidgetEvent* aEvent,
4379 nsIContent** aContent) {
4380 nsIFrame* f = nsLayoutUtils::GetNonGeneratedAncestor(this);
4381 *aContent = f->GetContent();
4382 NS_IF_ADDREF(*aContent)ns_if_addref(*aContent);
4383 return NS_OK;
4384}
4385
4386void nsIFrame::FireDOMEvent(const nsAString& aDOMEventName,
4387 nsIContent* aContent) {
4388 nsIContent* target = aContent ? aContent : GetContent();
4389
4390 if (target) {
4391 RefPtr<AsyncEventDispatcher> asyncDispatcher = new AsyncEventDispatcher(
4392 target, aDOMEventName, CanBubble::eYes, ChromeOnlyDispatch::eNo);
4393 DebugOnly<nsresult> rv = asyncDispatcher->PostDOMEvent();
4394 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4394); MOZ_PretendNoReturn(); } } while (0)
;
4395 }
4396}
4397
4398nsresult nsIFrame::HandleEvent(nsPresContext* aPresContext,
4399 WidgetGUIEvent* aEvent,
4400 nsEventStatus* aEventStatus) {
4401 if (aEvent->mMessage == eMouseMove) {
4402 // XXX If the second argument of HandleDrag() is WidgetMouseEvent,
4403 // the implementation becomes simpler.
4404 return HandleDrag(aPresContext, aEvent, aEventStatus);
4405 }
4406
4407 if ((aEvent->mClass == eMouseEventClass &&
4408 aEvent->AsMouseEvent()->mButton == MouseButton::ePrimary) ||
4409 aEvent->mClass == eTouchEventClass) {
4410 if (aEvent->mMessage == eMouseDown || aEvent->mMessage == eTouchStart) {
4411 HandlePress(aPresContext, aEvent, aEventStatus);
4412 } else if (aEvent->mMessage == eMouseUp || aEvent->mMessage == eTouchEnd) {
4413 HandleRelease(aPresContext, aEvent, aEventStatus);
4414 }
4415 return NS_OK;
4416 }
4417
4418 // When secondary buttion is down, we need to move selection to make users
4419 // possible to paste something at click point quickly.
4420 // When middle button is down, we need to just move selection and focus at
4421 // the clicked point. Note that even if middle click paste is not enabled,
4422 // Chrome moves selection at middle mouse button down. So, we should follow
4423 // the behavior for the compatibility.
4424 if (aEvent->mMessage == eMouseDown) {
4425 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
4426 if (mouseEvent && (mouseEvent->mButton == MouseButton::eSecondary ||
4427 mouseEvent->mButton == MouseButton::eMiddle)) {
4428 if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
4429 return NS_OK;
4430 }
4431 return MoveCaretToEventPoint(aPresContext, mouseEvent, aEventStatus);
4432 }
4433 }
4434
4435 return NS_OK;
4436}
4437
4438nsresult nsIFrame::GetDataForTableSelection(
4439 const nsFrameSelection* aFrameSelection, mozilla::PresShell* aPresShell,
4440 WidgetMouseEvent* aMouseEvent, nsIContent** aParentContent,
4441 int32_t* aContentOffset, TableSelectionMode* aTarget) {
4442 if (!aFrameSelection || !aPresShell || !aMouseEvent || !aParentContent ||
4443 !aContentOffset || !aTarget)
4444 return NS_ERROR_NULL_POINTER;
4445
4446 *aParentContent = nullptr;
4447 *aContentOffset = 0;
4448 *aTarget = TableSelectionMode::None;
4449
4450 int16_t displaySelection = aPresShell->GetSelectionFlags();
4451
4452 bool selectingTableCells = aFrameSelection->IsInTableSelectionMode();
4453
4454 // DISPLAY_ALL means we're in an editor.
4455 // If already in cell selection mode,
4456 // continue selecting with mouse drag or end on mouse up,
4457 // or when using shift key to extend block of cells
4458 // (Mouse down does normal selection unless Ctrl/Cmd is pressed)
4459 bool doTableSelection =
4460 displaySelection == nsISelectionDisplay::DISPLAY_ALL &&
4461 selectingTableCells &&
4462 (aMouseEvent->mMessage == eMouseMove ||
4463 (aMouseEvent->mMessage == eMouseUp &&
4464 aMouseEvent->mButton == MouseButton::ePrimary) ||
4465 aMouseEvent->IsShift());
4466
4467 if (!doTableSelection) {
4468 // In Browser, special 'table selection' key must be pressed for table
4469 // selection or when just Shift is pressed and we're already in table/cell
4470 // selection mode
4471#ifdef XP_MACOSX
4472 doTableSelection = aMouseEvent->IsMeta() ||
4473 (aMouseEvent->IsShift() && selectingTableCells);
4474#else
4475 doTableSelection = aMouseEvent->IsControl() ||
4476 (aMouseEvent->IsShift() && selectingTableCells);
4477#endif
4478 }
4479 if (!doTableSelection) return NS_OK;
4480
4481 // Get the cell frame or table frame (or parent) of the current content node
4482 nsIFrame* frame = this;
4483 bool foundCell = false;
4484 bool foundTable = false;
4485
4486 // Get the limiting node to stop parent frame search
4487 nsIContent* limiter = aFrameSelection->GetLimiter();
4488
4489 // If our content node is an ancestor of the limiting node,
4490 // we should stop the search right now.
4491 if (limiter && limiter->IsInclusiveDescendantOf(GetContent())) return NS_OK;
4492
4493 // We don't initiate row/col selection from here now,
4494 // but we may in future
4495 // bool selectColumn = false;
4496 // bool selectRow = false;
4497
4498 while (frame) {
4499 // Check for a table cell by querying to a known CellFrame interface
4500 nsITableCellLayout* cellElement = do_QueryFrame(frame);
4501 if (cellElement) {
4502 foundCell = true;
4503 // TODO: If we want to use proximity to top or left border
4504 // for row and column selection, this is the place to do it
4505 break;
4506 } else {
4507 // If not a cell, check for table
4508 // This will happen when starting frame is the table or child of a table,
4509 // such as a row (we were inbetween cells or in table border)
4510 nsTableWrapperFrame* tableFrame = do_QueryFrame(frame);
4511 if (tableFrame) {
4512 foundTable = true;
4513 // TODO: How can we select row when along left table edge
4514 // or select column when along top edge?
4515 break;
4516 } else {
4517 frame = frame->GetParent();
4518 // Stop if we have hit the selection's limiting content node
4519 if (frame && frame->GetContent() == limiter) break;
4520 }
4521 }
4522 }
4523 // We aren't in a cell or table
4524 if (!foundCell && !foundTable) return NS_OK;
4525
4526 nsIContent* tableOrCellContent = frame->GetContent();
4527 if (!tableOrCellContent) return NS_ERROR_FAILURE;
4528
4529 nsCOMPtr<nsIContent> parentContent = tableOrCellContent->GetParent();
4530 if (!parentContent) return NS_ERROR_FAILURE;
4531
4532 const int32_t offset =
4533 parentContent->ComputeIndexOf_Deprecated(tableOrCellContent);
4534 // Not likely?
4535 if (offset < 0) {
4536 return NS_ERROR_FAILURE;
4537 }
4538
4539 // Everything is OK -- set the return values
4540 parentContent.forget(aParentContent);
4541
4542 *aContentOffset = offset;
4543
4544#if 0
4545 if (selectRow)
4546 *aTarget = TableSelectionMode::Row;
4547 else if (selectColumn)
4548 *aTarget = TableSelectionMode::Column;
4549 else
4550#endif
4551 if (foundCell) {
4552 *aTarget = TableSelectionMode::Cell;
4553 } else if (foundTable) {
4554 *aTarget = TableSelectionMode::Table;
4555 }
4556
4557 return NS_OK;
4558}
4559
4560static bool IsEditingHost(const nsIFrame* aFrame) {
4561 nsIContent* content = aFrame->GetContent();
4562 return content && content->IsEditingHost();
4563}
4564
4565static StyleUserSelect UsedUserSelect(const nsIFrame* aFrame) {
4566 if (aFrame->IsGeneratedContentFrame()) {
4567 return StyleUserSelect::None;
4568 }
4569
4570 // Per https://drafts.csswg.org/css-ui-4/#content-selection:
4571 //
4572 // The used value is the same as the computed value, except:
4573 //
4574 // 1 - on editable elements where the used value is always 'contain'
4575 // regardless of the computed value
4576 // 2 - when the computed value is auto, in which case the used value is one
4577 // of the other values...
4578 //
4579 // See https://github.com/w3c/csswg-drafts/issues/3344 to see why we do this
4580 // at used-value time instead of at computed-value time.
4581
4582 if (aFrame->IsTextInputFrame() || IsEditingHost(aFrame)) {
4583 // We don't implement 'contain' itself, but we make 'text' behave as
4584 // 'contain' for contenteditable and <input> / <textarea> elements anyway so
4585 // this is ok.
4586 return StyleUserSelect::Text;
4587 }
4588
4589 auto style = aFrame->Style()->UserSelect();
4590 if (style != StyleUserSelect::Auto) {
4591 return style;
4592 }
4593
4594 auto* parent = nsLayoutUtils::GetParentOrPlaceholderFor(aFrame);
4595 return parent ? UsedUserSelect(parent) : StyleUserSelect::Text;
4596}
4597
4598bool nsIFrame::IsSelectable(StyleUserSelect* aSelectStyle) const {
4599 auto style = UsedUserSelect(this);
4600 if (aSelectStyle) {
4601 *aSelectStyle = style;
4602 }
4603 return style != StyleUserSelect::None;
4604}
4605
4606bool nsIFrame::ShouldHaveLineIfEmpty() const {
4607 if (Style()->IsPseudoOrAnonBox() &&
4608 Style()->GetPseudoType() != PseudoStyleType::scrolledContent) {
4609 return false;
4610 }
4611 return IsEditingHost(this);
4612}
4613
4614/**
4615 * Handles the Mouse Press Event for the frame
4616 */
4617NS_IMETHODIMPnsresult
4618nsIFrame::HandlePress(nsPresContext* aPresContext, WidgetGUIEvent* aEvent,
4619 nsEventStatus* aEventStatus) {
4620 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4620); return NS_ERROR_INVALID_POINTER; } } while (false)
;
4621 if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
4622 return NS_OK;
4623 }
4624
4625 NS_ENSURE_ARG_POINTER(aEvent)do { if ((__builtin_expect(!!(!(aEvent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEvent" ") failed", nullptr
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4625); return NS_ERROR_INVALID_POINTER; } } while (false)
;
4626 if (aEvent->mClass == eTouchEventClass) {
4627 return NS_OK;
4628 }
4629
4630 return MoveCaretToEventPoint(aPresContext, aEvent->AsMouseEvent(),
4631 aEventStatus);
4632}
4633
4634nsresult nsIFrame::MoveCaretToEventPoint(nsPresContext* aPresContext,
4635 WidgetMouseEvent* aMouseEvent,
4636 nsEventStatus* aEventStatus) {
4637 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4637); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPresContext"
")"); do { *((volatile int*)__null) = 4637; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4638 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4638); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aMouseEvent"
")"); do { *((volatile int*)__null) = 4638; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4639 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4639); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aMouseEvent->mMessage == eMouseDown"
")"); do { *((volatile int*)__null) = 4639; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4640 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4640); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEventStatus"
")"); do { *((volatile int*)__null) = 4640; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4641 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4641); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsEventStatus_eConsumeNoDefault != *aEventStatus"
")"); do { *((volatile int*)__null) = 4641; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4642
4643 mozilla::PresShell* presShell = aPresContext->GetPresShell();
4644 if (!presShell) {
4645 return NS_ERROR_FAILURE;
4646 }
4647
4648 // We often get out of sync state issues with mousedown events that
4649 // get interrupted by alerts/dialogs.
4650 // Check with the ESM to see if we should process this one
4651 if (!aPresContext->EventStateManager()->EventStatusOK(aMouseEvent)) {
4652 return NS_OK;
4653 }
4654
4655 const nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
4656 aMouseEvent, RelativeTo{this});
4657
4658 // When not using `alt`, and clicking on a draggable, but non-editable
4659 // element, don't do anything, and let d&d handle the event.
4660 //
4661 // See bug 48876, bug 388659 and bug 55921 for context here.
4662 //
4663 // FIXME(emilio): The .Contains(pt) check looks a bit fishy. When would it be
4664 // false given we're the event target? If it is needed, why not checking the
4665 // actual draggable node rect instead?
4666 if (!aMouseEvent->IsAlt() && GetRectRelativeToSelf().Contains(pt)) {
4667 for (nsIContent* content = mContent; content;
4668 content = content->GetFlattenedTreeParent()) {
4669 if (nsContentUtils::ContentIsDraggable(content) &&
4670 !content->IsEditable()) {
4671 return NS_OK;
4672 }
4673 }
4674 }
4675
4676 // If we are in Navigator and the click is in a draggable node, we don't want
4677 // to start selection because we don't want to interfere with a potential
4678 // drag of said node and steal all its glory.
4679 const bool isEditor =
4680 presShell->GetSelectionFlags() == nsISelectionDisplay::DISPLAY_ALL;
4681
4682 // Don't do something if it's middle button down event.
4683 const bool isPrimaryButtonDown =
4684 aMouseEvent->mButton == MouseButton::ePrimary;
4685
4686 // check whether style allows selection
4687 // if not, don't tell selection the mouse event even occurred.
4688 StyleUserSelect selectStyle;
4689 // check for select: none
4690 if (!IsSelectable(&selectStyle)) {
4691 return NS_OK;
4692 }
4693
4694 if (isPrimaryButtonDown) {
4695 // If the mouse is dragged outside the nearest enclosing scrollable area
4696 // while making a selection, the area will be scrolled. To do this, capture
4697 // the mouse on the nearest scroll container frame. If there isn't a scroll
4698 // container frame, or something else is already capturing the mouse,
4699 // there's no reason to capture.
4700 if (!PresShell::GetCapturingContent()) {
4701 ScrollContainerFrame* scrollContainerFrame =
4702 nsLayoutUtils::GetNearestScrollContainerFrame(
4703 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
4704 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
4705 if (scrollContainerFrame) {
4706 nsIFrame* capturingFrame = scrollContainerFrame;
4707 PresShell::SetCapturingContent(capturingFrame->GetContent(),
4708 CaptureFlags::IgnoreAllowedState);
4709 }
4710 }
4711 }
4712
4713 // XXX This is screwy; it really should use the selection frame, not the
4714 // event frame
4715 const nsFrameSelection* frameselection =
4716 selectStyle == StyleUserSelect::Text ? GetConstFrameSelection()
4717 : presShell->ConstFrameSelection();
4718
4719 if (!frameselection || frameselection->GetDisplaySelection() ==
4720 nsISelectionController::SELECTION_OFF) {
4721 return NS_OK; // nothing to do we cannot affect selection from here
4722 }
4723
4724#ifdef XP_MACOSX
4725 // If Control key is pressed on macOS, it should be treated as right click.
4726 // So, don't change selection.
4727 if (aMouseEvent->IsControl()) {
4728 return NS_OK;
4729 }
4730 const bool control = aMouseEvent->IsMeta();
4731#else
4732 const bool control = aMouseEvent->IsControl();
4733#endif
4734
4735 RefPtr<nsFrameSelection> fc = const_cast<nsFrameSelection*>(frameselection);
4736 if (isPrimaryButtonDown && aMouseEvent->mClickCount > 1) {
4737 // These methods aren't const but can't actually delete anything,
4738 // so no need for AutoWeakFrame.
4739 fc->SetDragState(true);
4740 return HandleMultiplePress(aPresContext, aMouseEvent, aEventStatus,
4741 control);
4742 }
4743
4744 ContentOffsets offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
4745
4746 if (!offsets.content) {
4747 return NS_ERROR_FAILURE;
4748 }
4749
4750 const bool isSecondaryButton =
4751 aMouseEvent->mButton == MouseButton::eSecondary;
4752 if (isSecondaryButton &&
4753 !MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
4754 *frameselection, *aMouseEvent, *offsets.content,
4755 // When we collapse selection in nsFrameSelection::TakeFocus,
4756 // we always collapse selection to the start offset. Therefore,
4757 // we can ignore the end offset here. E.g., when an <img> is clicked,
4758 // set the primary offset to after it, but the the secondary offset
4759 // may be before it, see OffsetsForSingleFrame for the detail.
4760 offsets.StartOffset())) {
4761 return NS_OK;
4762 }
4763
4764 if (aMouseEvent->mMessage == eMouseDown &&
4765 aMouseEvent->mButton == MouseButton::eMiddle &&
4766 !offsets.content->IsEditable()) {
4767 // However, some users don't like the Chrome compatible behavior of
4768 // middle mouse click. They want to keep selection after starting
4769 // autoscroll. However, the selection change is important for middle
4770 // mouse past. Therefore, we should allow users to take the traditional
4771 // behavior back by themselves unless middle click paste is enabled or
4772 // autoscrolling is disabled.
4773 if (!Preferences::GetBool("middlemouse.paste", false) &&
4774 Preferences::GetBool("general.autoScroll", false) &&
4775 Preferences::GetBool("general.autoscroll.prevent_to_collapse_selection_"
4776 "by_middle_mouse_down",
4777 false)) {
4778 return NS_OK;
4779 }
4780 }
4781
4782 if (isPrimaryButtonDown) {
4783 // Let Ctrl/Cmd + left mouse down do table selection instead of drag
4784 // initiation.
4785 nsCOMPtr<nsIContent> parentContent;
4786 int32_t contentOffset;
4787 TableSelectionMode target;
4788 nsresult rv = GetDataForTableSelection(
4789 frameselection, presShell, aMouseEvent, getter_AddRefs(parentContent),
4790 &contentOffset, &target);
4791 if (NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1))) && parentContent) {
4792 fc->SetDragState(true);
4793 return fc->HandleTableSelection(parentContent, contentOffset, target,
4794 aMouseEvent);
4795 }
4796 }
4797
4798 fc->SetDelayedCaretData(0);
4799
4800 if (isPrimaryButtonDown) {
4801 // Check if any part of this frame is selected, and if the user clicked
4802 // inside the selected region, and if it's the left button. If so, we delay
4803 // starting a new selection since the user may be trying to drag the
4804 // selected region to some other app.
4805
4806 if (GetContent() && GetContent()->IsMaybeSelected()) {
4807 bool inSelection = false;
4808 UniquePtr<SelectionDetails> details = frameselection->LookUpSelection(
4809 offsets.content, 0, offsets.EndOffset(), false);
4810
4811 //
4812 // If there are any details, check to see if the user clicked
4813 // within any selected region of the frame.
4814 //
4815
4816 for (SelectionDetails* curDetail = details.get(); curDetail;
4817 curDetail = curDetail->mNext.get()) {
4818 //
4819 // If the user clicked inside a selection, then just
4820 // return without doing anything. We will handle placing
4821 // the caret later on when the mouse is released. We ignore
4822 // the spellcheck, find and url formatting selections.
4823 //
4824 if (curDetail->mSelectionType != SelectionType::eSpellCheck &&
4825 curDetail->mSelectionType != SelectionType::eFind &&
4826 curDetail->mSelectionType != SelectionType::eURLSecondary &&
4827 curDetail->mSelectionType != SelectionType::eURLStrikeout &&
4828 curDetail->mSelectionType != SelectionType::eHighlight &&
4829 curDetail->mStart <= offsets.StartOffset() &&
4830 offsets.EndOffset() <= curDetail->mEnd) {
4831 inSelection = true;
4832 }
4833 }
4834
4835 if (inSelection) {
4836 fc->SetDragState(false);
4837 fc->SetDelayedCaretData(aMouseEvent);
4838 return NS_OK;
4839 }
4840 }
4841
4842 fc->SetDragState(true);
4843 }
4844
4845 // Do not touch any nsFrame members after this point without adding
4846 // weakFrame checks.
4847 const nsFrameSelection::FocusMode focusMode = [&]() {
4848 // If "Shift" and "Ctrl" are both pressed, "Shift" is given precedence. This
4849 // mimics the old behaviour.
4850 const bool isShift =
4851 aMouseEvent->IsShift() &&
4852 // If Shift + secondary button press shoud open context menu without a
4853 // contextmenu event, user wants to open context menu like as a
4854 // secondary button press without Shift key.
4855 !(isSecondaryButton &&
4856 StaticPrefs::dom_event_contextmenu_shift_suppresses_event());
4857 if (isShift) {
4858 // If clicked in a link when focused content is editable, we should
4859 // collapse selection in the link for compatibility with Blink.
4860 if (isEditor) {
4861 for (Element* element : mContent->InclusiveAncestorsOfType<Element>()) {
4862 if (element->IsLink()) {
4863 return nsFrameSelection::FocusMode::kCollapseToNewPoint;
4864 }
4865 }
4866 }
4867 return nsFrameSelection::FocusMode::kExtendSelection;
4868 }
4869
4870 if (isPrimaryButtonDown && control) {
4871 return nsFrameSelection::FocusMode::kMultiRangeSelection;
4872 }
4873
4874 return nsFrameSelection::FocusMode::kCollapseToNewPoint;
4875 }();
4876
4877 nsresult rv = fc->HandleClick(
4878 MOZ_KnownLive(offsets.content)(offsets.content) /* bug 1636889 */, offsets.StartOffset(),
4879 offsets.EndOffset(), focusMode, offsets.associate);
4880 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
4881 return rv;
4882 }
4883
4884 // We don't handle mouse button up if it's middle button.
4885 if (isPrimaryButtonDown && offsets.offset != offsets.secondaryOffset) {
4886 fc->MaintainSelection();
4887 }
4888
4889 if (isPrimaryButtonDown && isEditor && !aMouseEvent->IsShift() &&
4890 (offsets.EndOffset() - offsets.StartOffset()) == 1) {
4891 // A single node is selected and we aren't extending an existing selection,
4892 // which means the user clicked directly on an object (either
4893 // `user-select: all` or a non-text node without children). Therefore,
4894 // disable selection extension during mouse moves.
4895 // XXX This is a bit hacky; shouldn't editor be able to deal with this?
4896 fc->SetDragState(false);
4897 }
4898
4899 return NS_OK;
4900}
4901
4902bool nsIFrame::MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
4903 const nsFrameSelection& aFrameSelection,
4904 WidgetMouseEvent& aSecondaryButtonEvent,
4905 const nsIContent& aContentAtEventPoint, int32_t aOffsetAtEventPoint) const {
4906 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4906); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aSecondaryButtonEvent.mButton == MouseButton::eSecondary"
")"); do { *((volatile int*)__null) = 4906; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4907
4908 if (NS_WARN_IF(aOffsetAtEventPoint < 0)NS_warn_if_impl(aOffsetAtEventPoint < 0, "aOffsetAtEventPoint < 0"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4908)
) {
4909 return false;
4910 }
4911
4912 const bool contentIsEditable = aContentAtEventPoint.IsEditable();
4913 const TextControlElement* const contentAsTextControl =
4914 TextControlElement::FromNodeOrNull(
4915 aContentAtEventPoint.IsTextControlElement()
4916 ? &aContentAtEventPoint
4917 : aContentAtEventPoint.GetClosestNativeAnonymousSubtreeRoot());
4918 if (Selection* selection =
4919 aFrameSelection.GetSelection(SelectionType::eNormal)) {
4920 const bool selectionIsCollapsed =
4921 selection->AreNormalAndCrossShadowBoundaryRangesCollapsed();
4922 // If right click in a selection range, we should not collapse
4923 // selection.
4924 if (!selectionIsCollapsed && nsContentUtils::IsPointInSelection(
4925 *selection, aContentAtEventPoint,
4926 static_cast<uint32_t>(aOffsetAtEventPoint),
4927 true /* aAllowCrossShadowBoundary */)) {
4928 return false;
4929 }
4930 const bool wantToPreventMoveCaret =
4931 StaticPrefs::
4932 ui_mouse_right_click_move_caret_stop_if_in_focused_editable_node() &&
4933 selectionIsCollapsed && (contentIsEditable || contentAsTextControl);
4934 const bool wantToPreventCollapseSelection =
4935 StaticPrefs::
4936 ui_mouse_right_click_collapse_selection_stop_if_non_collapsed_selection() &&
4937 !selectionIsCollapsed;
4938 if (wantToPreventMoveCaret || wantToPreventCollapseSelection) {
4939 // If currently selection is limited in an editing host, we should not
4940 // collapse selection nor move caret if the clicked point is in the
4941 // ancestor limiter. Otherwise, this mouse click moves focus from the
4942 // editing host to different one or blur the editing host. In this case,
4943 // we need to update selection because keeping current selection in the
4944 // editing host looks like it's not blurred.
4945 // FIXME: If the active editing host is the document element, editor
4946 // does not set ancestor limiter properly. Fix it in the editor side.
4947 if (nsIContent* ancestorLimiter = selection->GetAncestorLimiter()) {
4948 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4948); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ancestorLimiter->IsEditable()"
")"); do { *((volatile int*)__null) = 4948; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4949 return !aContentAtEventPoint.IsInclusiveDescendantOf(ancestorLimiter);
4950 }
4951 }
4952 // If selection is editable and `stop_if_in_focused_editable_node` pref is
4953 // set to true, user does not want to move caret to right click place if
4954 // clicked in the focused text control element.
4955 if (wantToPreventMoveCaret && contentAsTextControl &&
4956 contentAsTextControl == nsFocusManager::GetFocusedElementStatic()) {
4957 return false;
4958 }
4959 // If currently selection is not limited in an editing host, we should
4960 // collapse selection only when this click moves focus to an editing
4961 // host because we need to update selection in this case.
4962 if (wantToPreventCollapseSelection && !contentIsEditable) {
4963 return false;
4964 }
4965 }
4966
4967 return !StaticPrefs::
4968 ui_mouse_right_click_collapse_selection_stop_if_non_editable_node() ||
4969 // The user does not want to collapse selection into non-editable
4970 // content by a right button click.
4971 contentIsEditable ||
4972 // Treat clicking in a text control as always clicked on editable
4973 // content because we want a hack only for clicking in normal text
4974 // nodes which is outside any editing hosts.
4975 contentAsTextControl;
4976}
4977
4978nsresult nsIFrame::SelectByTypeAtPoint(nsPresContext* aPresContext,
4979 const nsPoint& aPoint,
4980 nsSelectionAmount aBeginAmountType,
4981 nsSelectionAmount aEndAmountType,
4982 uint32_t aSelectFlags) {
4983 NS_ENSURE_ARG_POINTER(aPresContext)do { if ((__builtin_expect(!!(!(aPresContext)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aPresContext" ") failed"
, nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 4983); return NS_ERROR_INVALID_POINTER; } } while (false)
;
4984
4985 // No point in selecting if selection is turned off
4986 if (DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
4987 return NS_OK;
4988 }
4989
4990 ContentOffsets offsets = GetContentOffsetsFromPoint(
4991 aPoint, SKIP_HIDDEN | IGNORE_NATIVE_ANONYMOUS_SUBTREE);
4992 if (!offsets.content) {
4993 return NS_ERROR_FAILURE;
4994 }
4995
4996 uint32_t offset;
4997 nsIFrame* frame = SelectionMovementUtils::GetFrameForNodeOffset(
4998 offsets.content, offsets.offset, offsets.associate, &offset);
4999 if (!frame) {
5000 return NS_ERROR_FAILURE;
5001 }
5002 return frame->PeekBackwardAndForward(
5003 aBeginAmountType, aEndAmountType, static_cast<int32_t>(offset),
5004 aBeginAmountType != eSelectWord, aSelectFlags);
5005}
5006
5007/**
5008 * Multiple Mouse Press -- line or paragraph selection -- for the frame.
5009 * Wouldn't it be nice if this didn't have to be hardwired into Frame code?
5010 */
5011NS_IMETHODIMPnsresult
5012nsIFrame::HandleMultiplePress(nsPresContext* aPresContext,
5013 WidgetGUIEvent* aEvent,
5014 nsEventStatus* aEventStatus, bool aControlHeld) {
5015 NS_ENSURE_ARG_POINTER(aEvent)do { if ((__builtin_expect(!!(!(aEvent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEvent" ") failed", nullptr
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5015); return NS_ERROR_INVALID_POINTER; } } while (false)
;
5016 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5016); return NS_ERROR_INVALID_POINTER; } } while (false)
;
5017
5018 if (nsEventStatus_eConsumeNoDefault == *aEventStatus ||
5019 DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
5020 return NS_OK;
5021 }
5022
5023 // Find out whether we're doing line or paragraph selection.
5024 // If browser.triple_click_selects_paragraph is true, triple-click selects
5025 // paragraph. Otherwise, triple-click selects line, and quadruple-click
5026 // selects paragraph (on platforms that support quadruple-click).
5027 nsSelectionAmount beginAmount, endAmount;
5028 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
5029 if (!mouseEvent) {
5030 return NS_OK;
5031 }
5032
5033 if (mouseEvent->mClickCount == 4) {
5034 beginAmount = endAmount = eSelectParagraph;
5035 } else if (mouseEvent->mClickCount == 3) {
5036 if (Preferences::GetBool("browser.triple_click_selects_paragraph")) {
5037 beginAmount = endAmount = eSelectParagraph;
5038 } else {
5039 beginAmount = eSelectBeginLine;
5040 endAmount = eSelectEndLine;
5041 }
5042 } else if (mouseEvent->mClickCount == 2) {
5043 // We only want inline frames; PeekBackwardAndForward dislikes blocks
5044 beginAmount = endAmount = eSelectWord;
5045 } else {
5046 return NS_OK;
5047 }
5048
5049 nsPoint relPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5050 mouseEvent, RelativeTo{this});
5051 return SelectByTypeAtPoint(aPresContext, relPoint, beginAmount, endAmount,
5052 (aControlHeld ? SELECT_ACCUMULATE : 0));
5053}
5054
5055nsresult nsIFrame::PeekBackwardAndForward(nsSelectionAmount aAmountBack,
5056 nsSelectionAmount aAmountForward,
5057 int32_t aStartPos, bool aJumpLines,
5058 uint32_t aSelectFlags) {
5059 nsIFrame* baseFrame = this;
5060 int32_t baseOffset = aStartPos;
5061 nsresult rv;
5062
5063 PeekOffsetOptions peekOffsetOptions{PeekOffsetOption::StopAtScroller};
5064 if (aJumpLines) {
5065 peekOffsetOptions += PeekOffsetOption::JumpLines;
5066 }
5067
5068 if (aAmountBack == eSelectWord) {
5069 // To avoid selecting the previous word when at start of word,
5070 // first move one character forward.
5071 PeekOffsetStruct pos(eSelectCharacter, eDirNext, aStartPos, nsPoint(0, 0),
5072 peekOffsetOptions);
5073 rv = PeekOffset(&pos);
5074 if (NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1)))) {
5075 baseFrame = pos.mResultFrame;
5076 baseOffset = pos.mContentOffset;
5077 }
5078 }
5079
5080 // Search backward for a boundary.
5081 PeekOffsetStruct startpos(aAmountBack, eDirPrevious, baseOffset,
5082 nsPoint(0, 0), peekOffsetOptions);
5083 rv = baseFrame->PeekOffset(&startpos);
5084 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5085 return rv;
5086 }
5087
5088 // If the backward search stayed within the same frame, search forward from
5089 // that position for the end boundary; but if it crossed out to a sibling or
5090 // ancestor, start from the original position.
5091 if (startpos.mResultFrame == baseFrame) {
5092 baseOffset = startpos.mContentOffset;
5093 } else {
5094 baseFrame = this;
5095 baseOffset = aStartPos;
5096 }
5097
5098 PeekOffsetStruct endpos(aAmountForward, eDirNext, baseOffset, nsPoint(0, 0),
5099 peekOffsetOptions);
5100 rv = baseFrame->PeekOffset(&endpos);
5101 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5102 return rv;
5103 }
5104
5105 // Keep frameSelection alive.
5106 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
5107
5108 const nsFrameSelection::FocusMode focusMode =
5109 (aSelectFlags & SELECT_ACCUMULATE)
5110 ? nsFrameSelection::FocusMode::kMultiRangeSelection
5111 : nsFrameSelection::FocusMode::kCollapseToNewPoint;
5112 rv = frameSelection->HandleClick(
5113 MOZ_KnownLive(startpos.mResultContent)(startpos.mResultContent) /* bug 1636889 */,
5114 startpos.mContentOffset, startpos.mContentOffset, focusMode,
5115 CaretAssociationHint::After);
5116 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5117 return rv;
5118 }
5119
5120 rv = frameSelection->HandleClick(
5121 MOZ_KnownLive(endpos.mResultContent)(endpos.mResultContent) /* bug 1636889 */,
5122 endpos.mContentOffset, endpos.mContentOffset,
5123 nsFrameSelection::FocusMode::kExtendSelection,
5124 CaretAssociationHint::Before);
5125 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5126 return rv;
5127 }
5128 if (aAmountBack == eSelectWord) {
5129 frameSelection->SetClickSelectionType(ClickSelectionType::Double);
5130 } else if (aAmountBack == eSelectParagraph) {
5131 frameSelection->SetClickSelectionType(ClickSelectionType::Triple);
5132 }
5133
5134 // maintain selection
5135 return frameSelection->MaintainSelection(aAmountBack);
5136}
5137
5138NS_IMETHODIMPnsresult nsIFrame::HandleDrag(nsPresContext* aPresContext,
5139 WidgetGUIEvent* aEvent,
5140 nsEventStatus* aEventStatus) {
5141 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5142); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEvent->mClass == eMouseEventClass"
") (" "HandleDrag can only handle mouse event" ")"); do { *(
(volatile int*)__null) = 5142; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
5142 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5142); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aEvent->mClass == eMouseEventClass"
") (" "HandleDrag can only handle mouse event" ")"); do { *(
(volatile int*)__null) = 5142; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
5143
5144 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5144); return NS_ERROR_INVALID_POINTER; } } while (false)
;
5145
5146 RefPtr<nsFrameSelection> frameselection = GetFrameSelection();
5147 if (!frameselection) {
5148 return NS_OK;
5149 }
5150
5151 bool mouseDown = frameselection->GetDragState();
5152 if (!mouseDown) {
5153 return NS_OK;
5154 }
5155
5156 nsIFrame* scrollbar =
5157 nsLayoutUtils::GetClosestFrameOfType(this, LayoutFrameType::Scrollbar);
5158 if (!scrollbar) {
5159 // XXX Do we really need to exclude non-selectable content here?
5160 // GetContentOffsetsFromPoint can handle it just fine, although some
5161 // other stuff might not like it.
5162 // NOTE: DetermineDisplaySelection() returns SELECTION_OFF for
5163 // non-selectable frames.
5164 if (DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
5165 return NS_OK;
5166 }
5167 }
5168
5169 frameselection->StopAutoScrollTimer();
5170
5171 // Check if we are dragging in a table cell
5172 nsCOMPtr<nsIContent> parentContent;
5173 int32_t contentOffset;
5174 TableSelectionMode target;
5175 WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
5176 mozilla::PresShell* presShell = aPresContext->PresShell();
5177 nsresult result;
5178 result = GetDataForTableSelection(frameselection, presShell, mouseEvent,
5179 getter_AddRefs(parentContent),
5180 &contentOffset, &target);
5181
5182 AutoWeakFrame weakThis = this;
5183 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) && parentContent) {
5184 result = frameselection->HandleTableSelection(parentContent, contentOffset,
5185 target, mouseEvent);
5186 if (NS_WARN_IF(NS_FAILED(result))NS_warn_if_impl(((bool)(__builtin_expect(!!(NS_FAILED_impl(result
)), 0))), "NS_FAILED(result)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5186)
) {
5187 return result;
5188 }
5189 } else {
5190 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mouseEvent,
5191 RelativeTo{this});
5192 frameselection->HandleDrag(this, pt);
5193 }
5194
5195 // The frameselection object notifies selection listeners synchronously above
5196 // which might have killed us.
5197 if (!weakThis.IsAlive()) {
5198 return NS_OK;
5199 }
5200
5201 // Get the nearest scroll container frame.
5202 ScrollContainerFrame* scrollContainerFrame =
5203 nsLayoutUtils::GetNearestScrollContainerFrame(
5204 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
5205 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
5206
5207 if (scrollContainerFrame) {
5208 nsIFrame* capturingFrame = scrollContainerFrame->GetScrolledFrame();
5209 if (capturingFrame) {
5210 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5211 mouseEvent, RelativeTo{capturingFrame});
5212 frameselection->StartAutoScrollTimer(capturingFrame, pt, 30);
5213 }
5214 }
5215
5216 return NS_OK;
5217}
5218
5219/**
5220 * This static method handles part of the nsIFrame::HandleRelease in a way
5221 * which doesn't rely on the nsFrame object to stay alive.
5222 */
5223MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult HandleFrameSelection(
5224 nsFrameSelection* aFrameSelection, nsIFrame::ContentOffsets& aOffsets,
5225 bool aHandleTableSel, int32_t aContentOffsetForTableSel,
5226 TableSelectionMode aTargetForTableSel,
5227 nsIContent* aParentContentForTableSel, WidgetGUIEvent* aEvent,
5228 const nsEventStatus* aEventStatus) {
5229 if (!aFrameSelection) {
5230 return NS_OK;
5231 }
5232
5233 nsresult rv = NS_OK;
5234
5235 if (nsEventStatus_eConsumeNoDefault != *aEventStatus) {
5236 if (!aHandleTableSel) {
5237 if (!aOffsets.content || !aFrameSelection->HasDelayedCaretData()) {
5238 return NS_ERROR_FAILURE;
5239 }
5240
5241 // We are doing this to simulate what we would have done on HandlePress.
5242 // We didn't do it there to give the user an opportunity to drag
5243 // the text, but since they didn't drag, we want to place the
5244 // caret.
5245 // However, we'll use the mouse position from the release, since:
5246 // * it's easier
5247 // * that's the normal click position to use (although really, in
5248 // the normal case, small movements that don't count as a drag
5249 // can do selection)
5250 aFrameSelection->SetDragState(true);
5251
5252 const nsFrameSelection::FocusMode focusMode =
5253 aFrameSelection->IsShiftDownInDelayedCaretData()
5254 ? nsFrameSelection::FocusMode::kExtendSelection
5255 : nsFrameSelection::FocusMode::kCollapseToNewPoint;
5256 rv = aFrameSelection->HandleClick(
5257 MOZ_KnownLive(aOffsets.content)(aOffsets.content) /* bug 1636889 */,
5258 aOffsets.StartOffset(), aOffsets.EndOffset(), focusMode,
5259 aOffsets.associate);
5260 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5261 return rv;
5262 }
5263 } else if (aParentContentForTableSel) {
5264 aFrameSelection->SetDragState(false);
5265 rv = aFrameSelection->HandleTableSelection(
5266 aParentContentForTableSel, aContentOffsetForTableSel,
5267 aTargetForTableSel, aEvent->AsMouseEvent());
5268 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
5269 return rv;
5270 }
5271 }
5272 aFrameSelection->SetDelayedCaretData(0);
5273 }
5274
5275 aFrameSelection->SetDragState(false);
5276 aFrameSelection->StopAutoScrollTimer();
5277
5278 return NS_OK;
5279}
5280
5281NS_IMETHODIMPnsresult nsIFrame::HandleRelease(nsPresContext* aPresContext,
5282 WidgetGUIEvent* aEvent,
5283 nsEventStatus* aEventStatus) {
5284 if (aEvent->mClass != eMouseEventClass) {
5285 return NS_OK;
5286 }
5287
5288 nsIFrame* activeFrame = GetActiveSelectionFrame(aPresContext, this);
5289
5290 nsCOMPtr<nsIContent> captureContent = PresShell::GetCapturingContent();
5291
5292 bool selectionOff =
5293 (DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF);
5294
5295 RefPtr<nsFrameSelection> frameselection;
5296 ContentOffsets offsets;
5297 nsCOMPtr<nsIContent> parentContent;
5298 int32_t contentOffsetForTableSel = 0;
5299 TableSelectionMode targetForTableSel = TableSelectionMode::None;
5300 bool handleTableSelection = true;
5301
5302 if (!selectionOff) {
5303 frameselection = GetFrameSelection();
5304 if (nsEventStatus_eConsumeNoDefault != *aEventStatus && frameselection) {
5305 // Check if the frameselection recorded the mouse going down.
5306 // If not, the user must have clicked in a part of the selection.
5307 // Place the caret before continuing!
5308
5309 if (frameselection->MouseDownRecorded()) {
5310 nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
5311 aEvent, RelativeTo{this});
5312 offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
5313 handleTableSelection = false;
5314 } else {
5315 GetDataForTableSelection(frameselection, PresShell(),
5316 aEvent->AsMouseEvent(),
5317 getter_AddRefs(parentContent),
5318 &contentOffsetForTableSel, &targetForTableSel);
5319 }
5320 }
5321 }
5322
5323 // We might be capturing in some other document and the event just happened to
5324 // trickle down here. Make sure that document's frame selection is notified.
5325 // Note, this may cause the current nsFrame object to be deleted, bug 336592.
5326 RefPtr<nsFrameSelection> frameSelection;
5327 if (activeFrame != this && activeFrame->DetermineDisplaySelection() !=
5328 nsISelectionController::SELECTION_OFF) {
5329 frameSelection = activeFrame->GetFrameSelection();
5330 }
5331
5332 // Also check the selection of the capturing content which might be in a
5333 // different document.
5334 if (!frameSelection && captureContent) {
5335 if (Document* doc = captureContent->GetComposedDoc()) {
5336 mozilla::PresShell* capturingPresShell = doc->GetPresShell();
5337 if (capturingPresShell &&
5338 capturingPresShell != PresContext()->GetPresShell()) {
5339 frameSelection = capturingPresShell->FrameSelection();
5340 }
5341 }
5342 }
5343
5344 if (frameSelection) {
5345 AutoWeakFrame wf(this);
5346 frameSelection->SetDragState(false);
5347 frameSelection->StopAutoScrollTimer();
5348 if (wf.IsAlive()) {
5349 ScrollContainerFrame* scrollContainerFrame =
5350 nsLayoutUtils::GetNearestScrollContainerFrame(
5351 this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
5352 nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
5353 if (scrollContainerFrame) {
5354 // Perform any additional scrolling needed to maintain CSS snap point
5355 // requirements when autoscrolling is over.
5356 scrollContainerFrame->ScrollSnap();
5357 }
5358 }
5359 }
5360
5361 // Do not call any methods of the current object after this point!!!
5362 // The object is perhaps dead!
5363
5364 return selectionOff ? NS_OK
5365 : HandleFrameSelection(
5366 frameselection, offsets, handleTableSelection,
5367 contentOffsetForTableSel, targetForTableSel,
5368 parentContent, aEvent, aEventStatus);
5369}
5370
5371struct MOZ_STACK_CLASS FrameContentRange {
5372 FrameContentRange(nsIContent* aContent, int32_t aStart, int32_t aEnd)
5373 : content(aContent), start(aStart), end(aEnd) {}
5374 nsCOMPtr<nsIContent> content;
5375 int32_t start;
5376 int32_t end;
5377};
5378
5379// Retrieve the content offsets of a frame
5380static FrameContentRange GetRangeForFrame(const nsIFrame* aFrame) {
5381 nsIContent* content = aFrame->GetContent();
5382 if (!content) {
5383 NS_WARNING("Frame has no content")NS_DebugBreak(NS_DEBUG_WARNING, "Frame has no content", nullptr
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5383)
;
5384 return FrameContentRange(nullptr, -1, -1);
5385 }
5386
5387 LayoutFrameType type = aFrame->Type();
5388 if (type == LayoutFrameType::Text) {
5389 auto [offset, offsetEnd] = aFrame->GetOffsets();
5390 return FrameContentRange(content, offset, offsetEnd);
5391 }
5392
5393 if (type == LayoutFrameType::Br) {
5394 nsIContent* parent = content->GetParent();
5395 const int32_t beginOffset = parent->ComputeIndexOf_Deprecated(content);
5396 return FrameContentRange(parent, beginOffset, beginOffset);
5397 }
5398
5399 while (content->IsRootOfNativeAnonymousSubtree()) {
5400 content = content->GetParent();
5401 }
5402
5403 nsIContent* parent = content->GetParent();
5404 if (aFrame->IsBlockOutside() || !parent) {
5405 return FrameContentRange(content, 0, content->GetChildCount());
5406 }
5407
5408 // TODO(emilio): Revise this in presence of Shadow DOM / display: contents,
5409 // it's likely that we don't want to just walk the light tree, and we need to
5410 // change the representation of FrameContentRange.
5411 const int32_t index = parent->ComputeIndexOf_Deprecated(content);
5412 MOZ_ASSERT(index >= 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(index >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(index >= 0))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("index >= 0",
"/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5412); AnnotateMozCrashReason("MOZ_ASSERT" "(" "index >= 0"
")"); do { *((volatile int*)__null) = 5412; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5413 return FrameContentRange(parent, index, index + 1);
5414}
5415
5416// The FrameTarget represents the closest frame to a point that can be selected
5417// The frame is the frame represented, frameEdge says whether one end of the
5418// frame is the result (in which case different handling is needed), and
5419// afterFrame says which end is represented if frameEdge is true
5420struct FrameTarget {
5421 explicit operator bool() const { return !!frame; }
5422
5423 nsIFrame* frame = nullptr;
5424 bool frameEdge = false;
5425 bool afterFrame = false;
5426};
5427
5428// See function implementation for information
5429static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
5430 const nsPoint& aPoint,
5431 uint32_t aFlags);
5432
5433static bool SelfIsSelectable(nsIFrame* aFrame, nsIFrame* aParentFrame,
5434 uint32_t aFlags) {
5435 // We should not move selection into a native anonymous subtree when handling
5436 // selection outside it.
5437 if ((aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE) &&
5438 aParentFrame->GetClosestNativeAnonymousSubtreeRoot() !=
5439 aFrame->GetClosestNativeAnonymousSubtreeRoot()) {
5440 return false;
5441 }
5442 if ((aFlags & nsIFrame::SKIP_HIDDEN) &&
5443 !aFrame->StyleVisibility()->IsVisible()) {
5444 return false;
5445 }
5446 return !aFrame->IsGeneratedContentFrame() &&
5447 aFrame->Style()->UserSelect() != StyleUserSelect::None;
5448}
5449
5450static bool FrameContentCanHaveParentSelectionRange(nsIFrame* aFrame) {
5451 // If we are only near (not directly over) then don't traverse
5452 // frames with independent selection (e.g. text and list controls, see bug
5453 // 268497). Note that this prevents any of the users of this method from
5454 // entering form controls.
5455 // XXX We might want some way to allow using the up-arrow to go into a form
5456 // control, but the focus didn't work right anyway; it'd probably be enough
5457 // if the left and right arrows could enter textboxes (which I don't believe
5458 // they can at the moment)
5459 if (aFrame->IsTextInputFrame() || aFrame->IsListControlFrame()) {
5460 MOZ_ASSERT(aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5460); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
")"); do { *((volatile int*)__null) = 5460; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5461 return false;
5462 }
5463
5464 // Failure in this assertion means a new type of frame forms the root of an
5465 // NS_FRAME_INDEPENDENT_SELECTION subtree. In such case, the condition above
5466 // should be changed to handle it.
5467 MOZ_ASSERT_IF(do { if (aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5469); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
")"); do { *((volatile int*)__null) = 5469; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
5468 aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION),do { if (aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5469); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
")"); do { *((volatile int*)__null) = 5469; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
5469 aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION))do { if (aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 5469); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)"
")"); do { *((volatile int*)__null) = 5469; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
5470
5471 return !aFrame->IsGeneratedContentFrame();
5472}
5473
5474static bool SelectionDescendToKids(nsIFrame* aFrame) {
5475 if (!FrameContentCanHaveParentSelectionRange(aFrame)) {
5476 return false;
5477 }
5478 auto style = aFrame->Style()->UserSelect();
5479 return style != StyleUserSelect::All && style != StyleUserSelect::None;
5480}
5481
5482static FrameTarget GetSelectionClosestFrameForChild(nsIFrame* aChild,
5483 const nsPoint& aPoint,
5484 uint32_t aFlags) {
5485 nsIFrame* parent = aChild->GetParent();
5486 if (SelectionDescendToKids(aChild)) {
5487 nsPoint pt = aPoint - aChild->GetOffsetTo(parent);
5488 return GetSelectionClosestFrame(aChild, pt, aFlags);
5489 }
5490 return FrameTarget{aChild, false, false};
5491}
5492
5493// When the cursor needs to be at the beginning of a block, it shouldn't be
5494// before the first child. A click on a block whose first child is a block
5495// should put the cursor in the child. The cursor shouldn't be between the
5496// blocks, because that's not where it's expected.
5497// Note that this method is guaranteed to succeed.
5498static FrameTarget DrillDownToSelectionFrame(nsIFrame* aFrame, bool aEndFrame,
5499 uint32_t aFlags) {
5500 if (SelectionDescendToKids(aFrame)) {
5501 nsIFrame* result = nullptr;
5502 nsIFrame* frame = aFrame->PrincipalChildList().FirstChild();
5503 if (!aEndFrame) {
5504 while (frame &&
5505 (!SelfIsSelectable(frame, aFrame, aFlags) || frame->IsEmpty())) {
5506 frame = frame->GetNextSibling();
5507 }
5508 if (frame) {
5509 result = frame;
5510 }
5511 } else {
5512 // Because the frame tree is singly linked, to find the last frame,
5513 // we have to iterate through all the frames
5514 // XXX I have a feeling this could be slow for long blocks, although
5515 // I can't find any slowdowns
5516 while (frame) {
5517 if (!frame->IsEmpty() && SelfIsSelectable(frame, aFrame, aFlags)) {
5518 result = frame;
5519 }
5520 frame = frame->GetNextSibling();
5521 }
5522 }
5523 if (result) {
5524 return DrillDownToSelectionFrame(result, aEndFrame, aFlags);
5525 }
5526 }
5527 // If the current frame has no targetable children, target the current frame
5528 return FrameTarget{aFrame, true, aEndFrame};
5529}
5530
5531// This method finds the closest valid FrameTarget on a given line; if there is
5532// no valid FrameTarget on the line, it returns a null FrameTarget
5533static FrameTarget GetSelectionClosestFrameForLine(
5534 nsBlockFrame* aParent, nsBlockFrame::LineIterator aLine,
5535 const nsPoint& aPoint, uint32_t aFlags) {
5536 // Account for end of lines (any iterator from the block is valid)
5537 if (aLine == aParent->LinesEnd()) {
5538 return DrillDownToSelectionFrame(aParent, true, aFlags);
5539 }
5540 nsIFrame* frame = aLine->mFirstChild;
5541 nsIFrame* closestFromIStart = nullptr;
5542 nsIFrame* closestFromIEnd = nullptr;
5543 nscoord closestIStart = aLine->IStart(), closestIEnd = aLine->IEnd();
5544 WritingMode wm = aLine->mWritingMode;
5545 LogicalPoint pt(wm, aPoint, aLine->mContainerSize);
5546 bool canSkipBr = false;
5547 bool lastFrameWasEditable = false;
5548 for (int32_t n = aLine->GetChildCount(); n;
5549 --n, frame = frame->GetNextSibling()) {
5550 // Skip brFrames. Can only skip if the line contains at least
5551 // one selectable and non-empty frame before. Also, avoid skipping brs if
5552 // the previous thing had a different editableness than us, since then we
5553 // may end up not being able to select after it if the br is the last thing
5554 // on the line.
5555 if (!SelfIsSelectable(frame, aParent, aFlags) || frame->IsEmpty() ||
5556 (canSkipBr && frame->IsBrFrame() &&
5557 lastFrameWasEditable == frame->GetContent()->IsEditable())) {
5558 continue;
5559 }
5560 canSkipBr = true;
5561 lastFrameWasEditable =
5562 frame->GetContent() && frame->GetContent()->IsEditable();
5563 LogicalRect frameRect =
5564 LogicalRect(wm, frame->GetRect(), aLine->mContainerSize);
5565 if (pt.I(wm) >= frameRect.IStart(wm)) {
5566 if (pt.I(wm) < frameRect.IEnd(wm)) {
5567 return GetSelectionClosestFrameForChild(frame, aPoint, aFlags);
5568 }
5569 if (frameRect.IEnd(wm) >= closestIStart) {
5570 closestFromIStart = frame;
5571 closestIStart = frameRect.IEnd(wm);
5572 }
5573 } else {
5574 if (frameRect.IStart(wm) <= closestIEnd) {
5575 closestFromIEnd = frame;
5576 closestIEnd = frameRect.IStart(wm);
5577 }
5578 }
5579 }
5580 if (!closestFromIStart && !closestFromIEnd) {
5581 // We should only get here if there are no selectable frames on a line
5582 // XXX Do we need more elaborate handling here?
5583 return FrameTarget();
5584 }
5585 if (closestFromIStart &&
5586 (!closestFromIEnd ||
5587 (abs(pt.I(wm) - closestIStart) <= abs(pt.I(wm) - closestIEnd)))) {
5588 return GetSelectionClosestFrameForChild(closestFromIStart, aPoint, aFlags);
5589 }
5590 return GetSelectionClosestFrameForChild(closestFromIEnd, aPoint, aFlags);
5591}
5592
5593// This method is for the special handling we do for block frames; they're
5594// special because they represent paragraphs and because they are organized
5595// into lines, which have bounds that are not stored elsewhere in the
5596// frame tree. Returns a null FrameTarget for frames which are not
5597// blocks or blocks with no lines except editable one.
5598static FrameTarget GetSelectionClosestFrameForBlock(nsIFrame* aFrame,
5599 const nsPoint& aPoint,
5600 uint32_t aFlags) {
5601 nsBlockFrame* bf = do_QueryFrame(aFrame);
5602 if (!bf) {
5603 return FrameTarget();
5604 }
5605
5606 // This code searches for the correct line
5607 nsBlockFrame::LineIterator end = bf->LinesEnd();
5608 nsBlockFrame::LineIterator curLine = bf->LinesBegin();
5609 nsBlockFrame::LineIterator closestLine = end;
5610
5611 if (curLine != end) {
5612 // Convert aPoint into a LogicalPoint in the writing-mode of this block
5613 WritingMode wm = curLine->mWritingMode;
5614 LogicalPoint pt(wm, aPoint, curLine->mContainerSize);
5615 do {
5616 // Check to see if our point lies within the line's block-direction bounds
5617 nscoord BCoord = pt.B(wm) - curLine->BStart();
5618 nscoord BSize = curLine->BSize();
5619 if (BCoord >= 0 && BCoord < BSize) {
5620 closestLine = curLine;
5621 break; // We found the line; stop looking
5622 }
5623 if (BCoord < 0) break;
5624 ++curLine;
5625 } while (curLine != end);
5626
5627 if (closestLine == end) {
5628 nsBlockFrame::LineIterator prevLine = curLine.prev();
5629 nsBlockFrame::LineIterator nextLine = curLine;
5630 // Avoid empty lines
5631 while (nextLine != end && nextLine->IsEmpty()) ++nextLine;
5632 while (prevLine != end && prevLine->IsEmpty()) --prevLine;
5633
5634 // This hidden pref dictates whether a point above or below all lines
5635 // comes up with a line or the beginning or end of the frame; 0 on
5636 // Windows, 1 on other platforms by default at the writing of this code
5637 int32_t dragOutOfFrame =
5638 Preferences::GetInt("browser.drag_out_of_frame_style");
5639
5640 if (prevLine == end) {
5641 if (dragOutOfFrame == 1 || nextLine == end)
5642 return DrillDownToSelectionFrame(aFrame, false, aFlags);
5643 closestLine = nextLine;
5644 } else if (nextLine == end) {
5645 if (dragOutOfFrame == 1)
5646 return DrillDownToSelectionFrame(aFrame, true, aFlags);
5647 closestLine = prevLine;
5648 } else { // Figure out which line is closer
5649 if (pt.B(wm) - prevLine->BEnd() < nextLine->BStart() - pt.B(wm))
5650 closestLine = prevLine;
5651 else
5652 closestLine = nextLine;
5653 }
5654 }
5655 }
5656
5657 do {
5658 if (auto target =
5659 GetSelectionClosestFrameForLine(bf, closestLine, aPoint, aFlags)) {
5660 return target;
5661 }
5662 ++closestLine;
5663 } while (closestLine != end);
5664
5665 // Fall back to just targeting the last targetable place
5666 return DrillDownToSelectionFrame(aFrame, true, aFlags);
5667}
5668
5669// Use frame edge for grid, flex, table, and non-editable images. Choose the
5670// edge based on the point position past the frame rect. If past the middle,
5671// caret should be at end, otherwise at start. This behavior matches Blink.
5672//
5673// TODO(emilio): Can we use this code path for other replaced elements other
5674// than images? Or even all other frames? We only get there when we didn't find
5675// selectable children... At least one XUL test fails if we make this apply to
5676// XUL labels. Also, editable images need _not_ to use the frame edge, see
5677// below.
5678static bool UseFrameEdge(nsIFrame* aFrame) {
5679 if (aFrame->IsFlexOrGridContainer() || aFrame->IsTableFrame()) {
5680 return true;
5681 }
5682 const nsImageFrame* image = do_QueryFrame(aFrame);
5683 if (image && !aFrame->GetContent()->IsEditable()) {
5684 // Editable images are a special-case because editing relies on clicking on
5685 // an editable image selecting it, for it to show resizers.
5686 return true;
5687 }
5688 return false;
5689}
5690
5691static FrameTarget LastResortFrameTargetForFrame(nsIFrame* aFrame,
5692 const nsPoint& aPoint) {
5693 if (!UseFrameEdge(aFrame)) {
5694 return {aFrame, false, false};
5695 }
5696 const auto& rect = aFrame->GetRectRelativeToSelf();
5697 nscoord reference;
5698 nscoord middle;
5699 if (aFrame->GetWritingMode().IsVertical()) {
5700 reference = aPoint.y;
5701 middle = rect.Height() / 2;
5702 } else {
5703 reference = aPoint.x;
5704 middle = rect.Width() / 2;
5705 }
5706 const bool afterFrame = reference > middle;
5707 return {aFrame, true, afterFrame};
5708}
5709
5710// GetSelectionClosestFrame is the helper function that calculates the closest
5711// frame to the given point.
5712// It doesn't completely account for offset styles, so needs to be used in
5713// restricted environments.
5714// Cannot handle overlapping frames correctly, so it should receive the output
5715// of GetFrameForPoint
5716// Guaranteed to return a valid FrameTarget.
5717// aPoint is relative to aFrame.
5718static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
5719 const nsPoint& aPoint,
5720 uint32_t aFlags) {
5721 // Handle blocks; if the frame isn't a block, the method fails
5722 if (auto target = GetSelectionClosestFrameForBlock(aFrame, aPoint, aFlags)) {
5723 return target;
5724 }
5725
5726 if (aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE &&
5727 !FrameContentCanHaveParentSelectionRange(aFrame)) {
5728 return LastResortFrameTargetForFrame(aFrame, aPoint);
5729 }
5730
5731 if (nsIFrame* kid = aFrame->PrincipalChildList().FirstChild()) {
5732 // Go through all the child frames to find the closest one
5733 nsIFrame::FrameWithDistance closest = {nullptr, nscoord_MAX, nscoord_MAX};
5734 for (; kid; kid = kid->GetNextSibling()) {
5735 if (!SelfIsSelectable(kid, aFrame, aFlags) || kid->IsEmpty()) {
5736 continue;
5737 }
5738
5739 kid->FindCloserFrameForSelection(aPoint, &closest);
5740 }
5741 if (closest.mFrame) {
5742 if (closest.mFrame->IsInSVGTextSubtree())
5743 return FrameTarget{closest.mFrame, false, false};
5744 return GetSelectionClosestFrameForChild(closest.mFrame, aPoint, aFlags);
5745 }
5746 }
5747
5748 return LastResortFrameTargetForFrame(aFrame, aPoint);
5749}
5750
5751static nsIFrame::ContentOffsets OffsetsForSingleFrame(nsIFrame* aFrame,
5752 const nsPoint& aPoint) {
5753 nsIFrame::ContentOffsets offsets;
5754 FrameContentRange range = GetRangeForFrame(aFrame);
5755 offsets.content = range.content;
5756 // If there are continuations (meaning it's not one rectangle), this is the
5757 // best this function can do
5758 if (aFrame->GetNextContinuation() || aFrame->GetPrevContinuation()) {
5759 offsets.offset = range.start;
5760 offsets.secondaryOffset = range.end;
5761 offsets.associate = CaretAssociationHint::After;
5762 return offsets;
5763 }
5764
5765 // Figure out whether the offsets should be over, after, or before the frame
5766 nsRect rect(nsPoint(0, 0), aFrame->GetSize());
5767
5768 bool isBlock = !aFrame->StyleDisplay()->IsInlineFlow();
5769 bool isRtl = (aFrame->StyleVisibility()->mDirection == StyleDirection::Rtl);
5770 if ((isBlock && rect.y < aPoint.y) ||
5771 (!isBlock && ((isRtl && rect.x + rect.width / 2 > aPoint.x) ||
5772 (!isRtl && rect.x + rect.width / 2 < aPoint.x)))) {
5773 offsets.offset = range.end;
5774 if (rect.Contains(aPoint))
5775 offsets.secondaryOffset = range.start;
5776 else
5777 offsets.secondaryOffset = range.end;
5778 } else {
5779 offsets.offset = range.start;
5780 if (rect.Contains(aPoint))
5781 offsets.secondaryOffset = range.end;
5782 else
5783 offsets.secondaryOffset = range.start;
5784 }
5785 offsets.associate = offsets.offset == range.start
5786 ? CaretAssociationHint::After
5787 : CaretAssociationHint::Before;
5788 return offsets;
5789}
5790
5791static nsIFrame* AdjustFrameForSelectionStyles(nsIFrame* aFrame) {
5792 nsIFrame* adjustedFrame = aFrame;
5793 for (nsIFrame* frame = aFrame; frame; frame = frame->GetParent()) {
5794 // These are the conditions that make all children not able to handle
5795 // a cursor.
5796 auto userSelect = frame->Style()->UserSelect();
5797 if (userSelect != StyleUserSelect::Auto &&
5798 userSelect != StyleUserSelect::All) {
5799 break;
5800 }
5801 if (userSelect == StyleUserSelect::All ||
5802 frame->IsGeneratedContentFrame()) {
5803 adjustedFrame = frame;
5804 }
5805 }
5806 return adjustedFrame;
5807}
5808
5809nsIFrame::ContentOffsets nsIFrame::GetContentOffsetsFromPoint(
5810 const nsPoint& aPoint, uint32_t aFlags) {
5811 nsIFrame* adjustedFrame;
5812 if (aFlags & IGNORE_SELECTION_STYLE) {
5813 adjustedFrame = this;
5814 } else {
5815 // This section of code deals with special selection styles. Note that
5816 // -moz-all exists, even though it doesn't need to be explicitly handled.
5817 //
5818 // The offset is forced not to end up in generated content; content offsets
5819 // cannot represent content outside of the document's content tree.
5820
5821 adjustedFrame = AdjustFrameForSelectionStyles(this);
5822
5823 // `user-select: all` needs special handling, because clicking on it should
5824 // lead to the whole frame being selected.
5825 if (adjustedFrame->Style()->UserSelect() == StyleUserSelect::All) {
5826 nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
5827 return OffsetsForSingleFrame(adjustedFrame, adjustedPoint);
5828 }
5829
5830 // For other cases, try to find a closest frame starting from the parent of
5831 // the unselectable frame
5832 if (adjustedFrame != this) {
5833 adjustedFrame = adjustedFrame->GetParent();
5834 }
5835 }
5836
5837 nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
5838
5839 FrameTarget closest =
5840 GetSelectionClosestFrame(adjustedFrame, adjustedPoint, aFlags);
5841
5842 // If the correct offset is at one end of a frame, use offset-based
5843 // calculation method
5844 if (closest.frameEdge) {
5845 ContentOffsets offsets;
5846 FrameContentRange range = GetRangeForFrame(closest.frame);
5847 offsets.content = range.content;
5848 if (closest.afterFrame)
5849 offsets.offset = range.end;
5850 else
5851 offsets.offset = range.start;
5852 offsets.secondaryOffset = offsets.offset;
5853 offsets.associate = offsets.offset == range.start
5854 ? CaretAssociationHint::After
5855 : CaretAssociationHint::Before;
5856 return offsets;
5857 }
5858
5859 nsPoint pt;
5860 if (closest.frame != this) {
5861 if (closest.frame->IsInSVGTextSubtree()) {
5862 pt = nsLayoutUtils::TransformAncestorPointToFrame(
5863 RelativeTo{closest.frame}, aPoint, RelativeTo{this});
5864 } else {
5865 pt = aPoint - closest.frame->GetOffsetTo(this);
5866 }
5867 } else {
5868 pt = aPoint;
5869 }
5870 return closest.frame->CalcContentOffsetsFromFramePoint(pt);
5871
5872 // XXX should I add some kind of offset standardization?
5873 // consider <b>xxxxx</b><i>zzzzz</i>; should any click between the last
5874 // x and first z put the cursor in the same logical position in addition
5875 // to the same visual position?
5876}
5877
5878nsIFrame::ContentOffsets nsIFrame::CalcContentOffsetsFromFramePoint(
5879 const nsPoint& aPoint) {
5880 return OffsetsForSingleFrame(this, aPoint);
5881}
5882
5883bool nsIFrame::AssociateImage(const StyleImage& aImage) {
5884 imgRequestProxy* req = aImage.GetImageRequest();
5885 if (!req) {
5886 return false;
5887 }
5888
5889 mozilla::css::ImageLoader* loader =
5890 PresContext()->Document()->StyleImageLoader();
5891
5892 loader->AssociateRequestToFrame(req, this);
5893 return true;
5894}
5895
5896void nsIFrame::DisassociateImage(const StyleImage& aImage) {
5897 imgRequestProxy* req = aImage.GetImageRequest();
5898 if (!req) {
5899 return;
5900 }
5901
5902 mozilla::css::ImageLoader* loader =
5903 PresContext()->Document()->StyleImageLoader();
5904
5905 loader->DisassociateRequestFromFrame(req, this);
5906}
5907
5908StyleImageRendering nsIFrame::UsedImageRendering() const {
5909 ComputedStyle* style;
5910 if (IsCanvasFrame()) {
5911 // XXXdholbert Maybe we should use FindCanvasBackground here (instead of
5912 // FindBackground), since we're inside an IsCanvasFrame check? Though then
5913 // we'd also have to copypaste or abstract-away the multi-part root-frame
5914 // lookup that the canvas-flavored API requires.
5915 style = nsCSSRendering::FindBackground(this);
5916 } else {
5917 style = Style();
5918 }
5919 return style->StyleVisibility()->mImageRendering;
5920}
5921
5922// The touch-action CSS property applies to: all elements except: non-replaced
5923// inline elements, table rows, row groups, table columns, and column groups.
5924StyleTouchAction nsIFrame::UsedTouchAction() const {
5925 if (IsLineParticipant()) {
5926 return StyleTouchAction::AUTO;
5927 }
5928 auto& disp = *StyleDisplay();
5929 if (disp.IsInternalTableStyleExceptCell()) {
5930 return StyleTouchAction::AUTO;
5931 }
5932 return disp.mTouchAction;
5933}
5934
5935nsIFrame::Cursor nsIFrame::GetCursor(const nsPoint&) {
5936 StyleCursorKind kind = StyleUI()->Cursor().keyword;
5937 if (kind == StyleCursorKind::Auto) {
5938 // If this is editable, I-beam cursor is better for most elements.
5939 kind = (mContent && mContent->IsEditable()) ? StyleCursorKind::Text
5940 : StyleCursorKind::Default;
5941 }
5942 if (kind == StyleCursorKind::Text && GetWritingMode().IsVertical()) {
5943 // Per CSS UI spec, UA may treat value 'text' as
5944 // 'vertical-text' for vertical text.
5945 kind = StyleCursorKind::VerticalText;
5946 }
5947
5948 return Cursor{kind, AllowCustomCursorImage::Yes};
5949}
5950
5951// Resize and incremental reflow
5952
5953/* virtual */
5954void nsIFrame::MarkIntrinsicISizesDirty() {
5955 // If we're a flex item, clear our flex-item-specific cached measurements
5956 // (which likely depended on our now-stale intrinsic isize).
5957 if (IsFlexItem()) {
5958 nsFlexContainerFrame::MarkCachedFlexMeasurementsDirty(this);
5959 }
5960
5961 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT)) {
5962 nsFontInflationData::MarkFontInflationDataTextDirty(this);
5963 }
5964
5965 RemoveProperty(nsGridContainerFrame::CachedBAxisMeasurement::Prop());
5966}
5967
5968void nsIFrame::MarkSubtreeDirty() {
5969 if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
5970 return;
5971 }
5972 // Unconditionally mark given frame dirty.
5973 AddStateBits(NS_FRAME_IS_DIRTY);
5974
5975 // Mark all descendants dirty, unless:
5976 // - Already dirty.
5977 // - TableColGroup
5978 AutoTArray<nsIFrame*, 32> stack;
5979 for (const auto& childLists : ChildLists()) {
5980 for (nsIFrame* kid : childLists.mList) {
5981 stack.AppendElement(kid);
5982 }
5983 }
5984 while (!stack.IsEmpty()) {
5985 nsIFrame* f = stack.PopLastElement();
5986 if (f->HasAnyStateBits(NS_FRAME_IS_DIRTY) || f->IsTableColGroupFrame()) {
5987 continue;
5988 }
5989
5990 f->AddStateBits(NS_FRAME_IS_DIRTY);
5991
5992 for (const auto& childLists : f->ChildLists()) {
5993 for (nsIFrame* kid : childLists.mList) {
5994 stack.AppendElement(kid);
5995 }
5996 }
5997 }
5998}
5999
6000/* virtual */
6001nscoord nsIFrame::GetMinISize(gfxContext* aRenderingContext) { return 0; }
6002
6003/* virtual */
6004nscoord nsIFrame::GetPrefISize(gfxContext* aRenderingContext) { return 0; }
6005
6006/* virtual */
6007void nsIFrame::AddInlineMinISize(gfxContext* aRenderingContext,
6008 nsIFrame::InlineMinISizeData* aData) {
6009 nscoord isize = nsLayoutUtils::IntrinsicForContainer(
6010 aRenderingContext, this, IntrinsicISizeType::MinISize);
6011 aData->DefaultAddInlineMinISize(this, isize);
6012}
6013
6014/* virtual */
6015void nsIFrame::AddInlinePrefISize(gfxContext* aRenderingContext,
6016 nsIFrame::InlinePrefISizeData* aData) {
6017 nscoord isize = nsLayoutUtils::IntrinsicForContainer(
6018 aRenderingContext, this, IntrinsicISizeType::PrefISize);
6019 aData->DefaultAddInlinePrefISize(isize);
6020}
6021
6022void nsIFrame::InlineMinISizeData::DefaultAddInlineMinISize(nsIFrame* aFrame,
6023 nscoord aISize,
6024 bool aAllowBreak) {
6025 auto parent = aFrame->GetParent();
6026 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6026); AnnotateMozCrashReason("MOZ_ASSERT" "(" "parent" ") ("
"Must have a parent if we get here!" ")"); do { *((volatile int
*)__null) = 6026; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
6027 const bool mayBreak = aAllowBreak && !aFrame->CanContinueTextRun() &&
6028 !parent->Style()->ShouldSuppressLineBreak() &&
6029 parent->StyleText()->WhiteSpaceCanWrap(parent);
6030 if (mayBreak) {
6031 OptionallyBreak();
6032 }
6033 mTrailingWhitespace = 0;
6034 mSkipWhitespace = false;
6035 mCurrentLine += aISize;
6036 mAtStartOfLine = false;
6037 if (mayBreak) {
6038 OptionallyBreak();
6039 }
6040}
6041
6042void nsIFrame::InlinePrefISizeData::DefaultAddInlinePrefISize(nscoord aISize) {
6043 mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, aISize);
6044 mTrailingWhitespace = 0;
6045 mSkipWhitespace = false;
6046 mLineIsEmpty = false;
6047}
6048
6049void nsIFrame::InlineMinISizeData::ForceBreak() {
6050 mCurrentLine -= mTrailingWhitespace;
6051 mPrevLines = std::max(mPrevLines, mCurrentLine);
6052 mCurrentLine = mTrailingWhitespace = 0;
6053
6054 for (uint32_t i = 0, i_end = mFloats.Length(); i != i_end; ++i) {
6055 nscoord float_min = mFloats[i].Width();
6056 if (float_min > mPrevLines) mPrevLines = float_min;
6057 }
6058 mFloats.Clear();
6059 mSkipWhitespace = true;
6060}
6061
6062void nsIFrame::InlineMinISizeData::OptionallyBreak(nscoord aHyphenWidth) {
6063 // If we can fit more content into a smaller width by staying on this
6064 // line (because we're still at a negative offset due to negative
6065 // text-indent or negative margin), don't break. Otherwise, do the
6066 // same as ForceBreak. it doesn't really matter when we accumulate
6067 // floats.
6068 if (mCurrentLine + aHyphenWidth < 0 || mAtStartOfLine) return;
6069 mCurrentLine += aHyphenWidth;
6070 ForceBreak();
6071}
6072
6073void nsIFrame::InlinePrefISizeData::ForceBreak(StyleClear aClearType) {
6074 // If this force break is not clearing any float, we can leave all the
6075 // floats to the next force break.
6076 if (!mFloats.IsEmpty() && aClearType != StyleClear::None) {
6077 // preferred widths accumulated for floats that have already
6078 // been cleared past
6079 nscoord floats_done = 0,
6080 // preferred widths accumulated for floats that have not yet
6081 // been cleared past
6082 floats_cur_left = 0, floats_cur_right = 0;
6083
6084 for (const FloatInfo& floatInfo : mFloats) {
6085 const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
6086 StyleClear clearType = floatDisp->mClear;
6087 if (clearType == StyleClear::Left || clearType == StyleClear::Right ||
6088 clearType == StyleClear::Both) {
6089 nscoord floats_cur =
6090 NSCoordSaturatingAdd(floats_cur_left, floats_cur_right);
6091 if (floats_cur > floats_done) {
6092 floats_done = floats_cur;
6093 }
6094 if (clearType != StyleClear::Right) {
6095 floats_cur_left = 0;
6096 }
6097 if (clearType != StyleClear::Left) {
6098 floats_cur_right = 0;
6099 }
6100 }
6101
6102 StyleFloat floatStyle = floatDisp->mFloat;
6103 nscoord& floats_cur =
6104 floatStyle == StyleFloat::Left ? floats_cur_left : floats_cur_right;
6105 nscoord floatWidth = floatInfo.Width();
6106 // Negative-width floats don't change the available space so they
6107 // shouldn't change our intrinsic line width either.
6108 floats_cur = NSCoordSaturatingAdd(floats_cur, std::max(0, floatWidth));
6109 }
6110
6111 nscoord floats_cur =
6112 NSCoordSaturatingAdd(floats_cur_left, floats_cur_right);
6113 if (floats_cur > floats_done) floats_done = floats_cur;
6114
6115 mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, floats_done);
6116
6117 if (aClearType == StyleClear::Both) {
6118 mFloats.Clear();
6119 } else {
6120 // If the break type does not clear all floats, it means there may
6121 // be some floats whose isize should contribute to the intrinsic
6122 // isize of the next line. The code here scans the current mFloats
6123 // and keeps floats which are not cleared by this break. Note that
6124 // floats may be cleared directly or indirectly. See below.
6125 nsTArray<FloatInfo> newFloats;
6126 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == StyleClear::Left || aClearType == StyleClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == StyleClear::Left || aClearType == StyleClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == StyleClear::Left || aClearType == StyleClear::Right"
" (" "Other values should have been handled in other branches"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6128); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aClearType == StyleClear::Left || aClearType == StyleClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { *((volatile int*)__null) = 6128; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6127 aClearType == StyleClear::Left || aClearType == StyleClear::Right,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == StyleClear::Left || aClearType == StyleClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == StyleClear::Left || aClearType == StyleClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == StyleClear::Left || aClearType == StyleClear::Right"
" (" "Other values should have been handled in other branches"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6128); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aClearType == StyleClear::Left || aClearType == StyleClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { *((volatile int*)__null) = 6128; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6128 "Other values should have been handled in other branches")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aClearType == StyleClear::Left || aClearType == StyleClear
::Right)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aClearType == StyleClear::Left || aClearType == StyleClear
::Right))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aClearType == StyleClear::Left || aClearType == StyleClear::Right"
" (" "Other values should have been handled in other branches"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6128); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aClearType == StyleClear::Left || aClearType == StyleClear::Right"
") (" "Other values should have been handled in other branches"
")"); do { *((volatile int*)__null) = 6128; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6129 StyleFloat clearFloatType =
6130 aClearType == StyleClear::Left ? StyleFloat::Left : StyleFloat::Right;
6131 // Iterate the array in reverse so that we can stop when there are
6132 // no longer any floats we need to keep. See below.
6133 for (FloatInfo& floatInfo : Reversed(mFloats)) {
6134 const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
6135 if (floatDisp->mFloat != clearFloatType) {
6136 newFloats.AppendElement(floatInfo);
6137 } else {
6138 // This is a float on the side that this break directly clears
6139 // which means we're not keeping it in mFloats. However, if
6140 // this float clears floats on the opposite side (via a value
6141 // of either 'both' or one of 'left'/'right'), any remaining
6142 // (earlier) floats on that side would be indirectly cleared
6143 // as well. Thus, we should break out of this loop and stop
6144 // considering earlier floats to be kept in mFloats.
6145 StyleClear clearType = floatDisp->mClear;
6146 if (clearType != aClearType && clearType != StyleClear::None) {
6147 break;
6148 }
6149 }
6150 }
6151 newFloats.Reverse();
6152 mFloats = std::move(newFloats);
6153 }
6154 }
6155
6156 mCurrentLine =
6157 NSCoordSaturatingSubtract(mCurrentLine, mTrailingWhitespace, nscoord_MAX);
6158 mPrevLines = std::max(mPrevLines, mCurrentLine);
6159 mCurrentLine = mTrailingWhitespace = 0;
6160 mSkipWhitespace = true;
6161 mLineIsEmpty = true;
6162}
6163
6164static nscoord ResolveMargin(const LengthPercentageOrAuto& aStyle,
6165 nscoord aPercentageBasis) {
6166 if (aStyle.IsAuto()) {
6167 return nscoord(0);
6168 }
6169 return nsLayoutUtils::ResolveToLength<false>(aStyle.AsLengthPercentage(),
6170 aPercentageBasis);
6171}
6172
6173static nscoord ResolvePadding(const LengthPercentage& aStyle,
6174 nscoord aPercentageBasis) {
6175 return nsLayoutUtils::ResolveToLength<true>(aStyle, aPercentageBasis);
6176}
6177
6178static nsIFrame::IntrinsicSizeOffsetData IntrinsicSizeOffsets(
6179 nsIFrame* aFrame, nscoord aPercentageBasis, bool aForISize) {
6180 nsIFrame::IntrinsicSizeOffsetData result;
6181 WritingMode wm = aFrame->GetWritingMode();
6182 const auto& margin = aFrame->StyleMargin()->mMargin;
6183 bool verticalAxis = aForISize == wm.IsVertical();
6184 if (verticalAxis) {
6185 result.margin += ResolveMargin(margin.Get(eSideTop), aPercentageBasis);
6186 result.margin += ResolveMargin(margin.Get(eSideBottom), aPercentageBasis);
6187 } else {
6188 result.margin += ResolveMargin(margin.Get(eSideLeft), aPercentageBasis);
6189 result.margin += ResolveMargin(margin.Get(eSideRight), aPercentageBasis);
6190 }
6191
6192 const auto& padding = aFrame->StylePadding()->mPadding;
6193 if (verticalAxis) {
6194 result.padding += ResolvePadding(padding.Get(eSideTop), aPercentageBasis);
6195 result.padding +=
6196 ResolvePadding(padding.Get(eSideBottom), aPercentageBasis);
6197 } else {
6198 result.padding += ResolvePadding(padding.Get(eSideLeft), aPercentageBasis);
6199 result.padding += ResolvePadding(padding.Get(eSideRight), aPercentageBasis);
6200 }
6201
6202 const nsStyleBorder* styleBorder = aFrame->StyleBorder();
6203 if (verticalAxis) {
6204 result.border += styleBorder->GetComputedBorderWidth(eSideTop);
6205 result.border += styleBorder->GetComputedBorderWidth(eSideBottom);
6206 } else {
6207 result.border += styleBorder->GetComputedBorderWidth(eSideLeft);
6208 result.border += styleBorder->GetComputedBorderWidth(eSideRight);
6209 }
6210
6211 const nsStyleDisplay* disp = aFrame->StyleDisplay();
6212 if (aFrame->IsThemed(disp)) {
6213 nsPresContext* presContext = aFrame->PresContext();
6214
6215 LayoutDeviceIntMargin border = presContext->Theme()->GetWidgetBorder(
6216 presContext->DeviceContext(), aFrame, disp->EffectiveAppearance());
6217 result.border = presContext->DevPixelsToAppUnits(
6218 verticalAxis ? border.TopBottom() : border.LeftRight());
6219
6220 LayoutDeviceIntMargin padding;
6221 if (presContext->Theme()->GetWidgetPadding(
6222 presContext->DeviceContext(), aFrame, disp->EffectiveAppearance(),
6223 &padding)) {
6224 result.padding = presContext->DevPixelsToAppUnits(
6225 verticalAxis ? padding.TopBottom() : padding.LeftRight());
6226 }
6227 }
6228 return result;
6229}
6230
6231/* virtual */ nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicISizeOffsets(
6232 nscoord aPercentageBasis) {
6233 return IntrinsicSizeOffsets(this, aPercentageBasis, true);
6234}
6235
6236nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicBSizeOffsets(
6237 nscoord aPercentageBasis) {
6238 return IntrinsicSizeOffsets(this, aPercentageBasis, false);
6239}
6240
6241/* virtual */
6242IntrinsicSize nsIFrame::GetIntrinsicSize() {
6243 // Defaults to no intrinsic size.
6244 return IntrinsicSize();
6245}
6246
6247AspectRatio nsIFrame::GetAspectRatio() const {
6248 // Per spec, 'aspect-ratio' property applies to all elements except inline
6249 // boxes and internal ruby or table boxes.
6250 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio
6251 // For those frame types that don't support aspect-ratio, they must not have
6252 // the natural ratio, so this early return is fine.
6253 if (!SupportsAspectRatio()) {
6254 return AspectRatio();
6255 }
6256
6257 const StyleAspectRatio& aspectRatio = StylePosition()->mAspectRatio;
6258 // If aspect-ratio is zero or infinite, it's a degenerate ratio and behaves
6259 // as auto.
6260 // https://drafts.csswg.org/css-sizing-4/#valdef-aspect-ratio-ratio
6261 if (!aspectRatio.BehavesAsAuto()) {
6262 // Non-auto. Return the preferred aspect ratio from the aspect-ratio style.
6263 return aspectRatio.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::Yes);
6264 }
6265
6266 // The rest of the cases are when aspect-ratio has 'auto'.
6267 if (auto intrinsicRatio = GetIntrinsicRatio()) {
6268 return intrinsicRatio;
6269 }
6270
6271 if (aspectRatio.HasRatio()) {
6272 // If it's a degenerate ratio, this returns 0. Just the same as the auto
6273 // case.
6274 return aspectRatio.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::No);
6275 }
6276
6277 return AspectRatio();
6278}
6279
6280/* virtual */
6281AspectRatio nsIFrame::GetIntrinsicRatio() const { return AspectRatio(); }
6282
6283static bool ShouldApplyAutomaticMinimumOnInlineAxis(
6284 WritingMode aWM, const nsStyleDisplay* aDisplay,
6285 const nsStylePosition* aPosition) {
6286 // Apply the automatic minimum size for aspect ratio:
6287 // Note: The replaced elements shouldn't be here, so we only check the scroll
6288 // container.
6289 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-minimum
6290 return !aDisplay->IsScrollableOverflow() && aPosition->MinISize(aWM).IsAuto();
6291}
6292
6293/* virtual */
6294nsIFrame::SizeComputationResult nsIFrame::ComputeSize(
6295 gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
6296 nscoord aAvailableISize, const LogicalSize& aMargin,
6297 const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
6298 ComputeSizeFlags aFlags) {
6299 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."
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6301); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetIntrinsicRatio()"
") (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { *((volatile int*)__null) = 6301; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6300 "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."
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6301); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetIntrinsicRatio()"
") (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { *((volatile int*)__null) = 6301; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6301 "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."
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6301); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetIntrinsicRatio()"
") (" "Please override this method and call " "nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead."
")"); do { *((volatile int*)__null) = 6301; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6302 LogicalSize result =
6303 ComputeAutoSize(aRenderingContext, aWM, aCBSize, aAvailableISize, aMargin,
6304 aBorderPadding, aSizeOverrides, aFlags);
6305 const nsStylePosition* stylePos = StylePosition();
6306 const nsStyleDisplay* disp = StyleDisplay();
6307 auto aspectRatioUsage = AspectRatioUsage::None;
6308
6309 const auto boxSizingAdjust = stylePos->mBoxSizing == StyleBoxSizing::Border
6310 ? aBorderPadding
6311 : LogicalSize(aWM);
6312 nscoord boxSizingToMarginEdgeISize = aMargin.ISize(aWM) +
6313 aBorderPadding.ISize(aWM) -
6314 boxSizingAdjust.ISize(aWM);
6315
6316 const auto& styleISize = aSizeOverrides.mStyleISize
6317 ? *aSizeOverrides.mStyleISize
6318 : stylePos->ISize(aWM);
6319 const auto& styleBSize = aSizeOverrides.mStyleBSize
6320 ? *aSizeOverrides.mStyleBSize
6321 : stylePos->BSize(aWM);
6322 const auto& aspectRatio = aSizeOverrides.mAspectRatio
6323 ? *aSizeOverrides.mAspectRatio
6324 : GetAspectRatio();
6325
6326 auto parentFrame = GetParent();
6327 auto alignCB = parentFrame;
6328 bool isGridItem = IsGridItem();
6329 const bool isSubgrid = IsSubgrid();
6330 if (parentFrame && parentFrame->IsTableWrapperFrame() && IsTableFrame()) {
6331 // An inner table frame is sized as a grid item if its table wrapper is,
6332 // because they actually have the same CB (the wrapper's CB).
6333 // @see ReflowInput::InitCBReflowInput
6334 auto tableWrapper = GetParent();
6335 auto grandParent = tableWrapper->GetParent();
6336 isGridItem = grandParent->IsGridContainerFrame() &&
6337 !tableWrapper->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
6338 if (isGridItem) {
6339 // When resolving justify/align-self below, we want to use the grid
6340 // container's justify/align-items value and WritingMode.
6341 alignCB = grandParent;
6342 }
6343 }
6344 const bool isFlexItem =
6345 IsFlexItem() && !parentFrame->HasAnyStateBits(
6346 NS_STATE_FLEX_IS_EMULATING_LEGACY_WEBKIT_BOX);
6347 // This variable only gets set (and used) if isFlexItem is true. It
6348 // indicates which axis (in this frame's own WM) corresponds to its
6349 // flex container's main axis.
6350 LogicalAxis flexMainAxis =
6351 LogicalAxis::Inline; // (init to make valgrind happy)
6352 if (isFlexItem) {
6353 flexMainAxis = nsFlexContainerFrame::IsItemInlineAxisMainAxis(this)
6354 ? LogicalAxis::Inline
6355 : LogicalAxis::Block;
6356 }
6357
6358 const bool isOrthogonal = aWM.IsOrthogonalTo(alignCB->GetWritingMode());
6359 const bool isAutoISize = styleISize.IsAuto();
6360 const bool isAutoBSize =
6361 nsLayoutUtils::IsAutoBSize(styleBSize, aCBSize.BSize(aWM));
6362
6363 // Compute inline-axis size
6364 const bool isSubgriddedInInlineAxis =
6365 isSubgrid && static_cast<nsGridContainerFrame*>(this)->IsColSubgrid();
6366
6367 // Per https://drafts.csswg.org/css-grid/#subgrid-box-alignment, if we are
6368 // subgridded in the inline-axis, ignore our style inline-size, and stretch to
6369 // fill the CB.
6370 const bool shouldComputeISize = !isAutoISize && !isSubgriddedInInlineAxis;
6371 if (shouldComputeISize) {
6372 auto iSizeResult =
6373 ComputeISizeValue(aRenderingContext, aWM, aCBSize, boxSizingAdjust,
6374 boxSizingToMarginEdgeISize, styleISize, styleBSize,
6375 aspectRatio, aFlags);
6376 result.ISize(aWM) = iSizeResult.mISize;
6377 aspectRatioUsage = iSizeResult.mAspectRatioUsage;
6378 } else if (MOZ_UNLIKELY(isGridItem)(__builtin_expect(!!(isGridItem), 0)) && !IsTrueOverflowContainer()) {
6379 // 'auto' inline-size for grid-level box - fill the CB for 'stretch' /
6380 // 'normal' and clamp it to the CB if requested:
6381 bool stretch = false;
6382 bool mayUseAspectRatio = aspectRatio && !isAutoBSize;
6383 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap) &&
6384 !StyleMargin()->HasInlineAxisAuto(aWM) &&
6385 !alignCB->IsMasonry(isOrthogonal ? LogicalAxis::Block
6386 : LogicalAxis::Inline)) {
6387 auto inlineAxisAlignment =
6388 isOrthogonal ? StylePosition()->UsedAlignSelf(alignCB->Style())._0
6389 : StylePosition()->UsedJustifySelf(alignCB->Style())._0;
6390 stretch = inlineAxisAlignment == StyleAlignFlags::STRETCH ||
6391 (inlineAxisAlignment == StyleAlignFlags::NORMAL &&
6392 !mayUseAspectRatio);
6393 }
6394
6395 // Apply the preferred aspect ratio for alignments other than *stretch* and
6396 // *normal without aspect ratio*.
6397 // The spec says all other values should size the items as fit-content, and
6398 // the intrinsic size should respect the preferred aspect ratio, so we also
6399 // apply aspect ratio for all other values.
6400 // https://drafts.csswg.org/css-grid/#grid-item-sizing
6401 if (!stretch && mayUseAspectRatio) {
6402 result.ISize(aWM) = ComputeISizeValueFromAspectRatio(
6403 aWM, aCBSize, boxSizingAdjust, styleBSize.AsLengthPercentage(),
6404 aspectRatio);
6405 aspectRatioUsage = AspectRatioUsage::ToComputeISize;
6406 }
6407
6408 if (stretch || aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize)) {
6409 auto iSizeToFillCB =
6410 std::max(nscoord(0), aCBSize.ISize(aWM) - aBorderPadding.ISize(aWM) -
6411 aMargin.ISize(aWM));
6412 if (stretch || result.ISize(aWM) > iSizeToFillCB) {
6413 result.ISize(aWM) = iSizeToFillCB;
6414 }
6415 }
6416 } else if (aspectRatio && !isAutoBSize) {
6417 // Note: if both the inline size and the block size are auto, the block axis
6418 // is the ratio-dependent axis by default. That means we only need to
6419 // transfer the resolved inline size via aspect-ratio to block axis later in
6420 // this method, but not the other way around.
6421 //
6422 // In this branch, we transfer the non-auto block size via aspect-ration to
6423 // inline axis.
6424 result.ISize(aWM) = ComputeISizeValueFromAspectRatio(
6425 aWM, aCBSize, boxSizingAdjust, styleBSize.AsLengthPercentage(),
6426 aspectRatio);
6427 aspectRatioUsage = AspectRatioUsage::ToComputeISize;
6428 }
6429
6430 // Calculate and apply transferred min & max size contraints.
6431 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-size-transfers
6432 //
6433 // Note: The basic principle is that sizing constraints transfer through the
6434 // aspect-ratio to the other side to preserve the aspect ratio to the extent
6435 // that they can without violating any sizes specified explicitly on that
6436 // affected axis.
6437 //
6438 // FIXME: The spec words may not be correct, so we may have to update this
6439 // tentative solution once this spec issue gets resolved. Here, we clamp the
6440 // flex base size by the transferred min and max sizes, and don't include
6441 // the transferred min & max sizes into its used min & max sizes. So this
6442 // lets us match other browsers' current behaviors.
6443 // https://github.com/w3c/csswg-drafts/issues/6071
6444 //
6445 // Note: This may make more sense if we clamp the flex base size in
6446 // FlexItem::ResolveFlexBaseSizeFromAspectRatio(). However, the result should
6447 // be identical. FlexItem::ResolveFlexBaseSizeFromAspectRatio() only handles
6448 // the case of the definite cross size, and the definite cross size is clamped
6449 // by the min & max cross sizes below in this function. This means its flex
6450 // base size has been clamped by the transferred min & max size already after
6451 // generating the flex items. So here we make the code more general for both
6452 // definite cross size and indefinite cross size.
6453 const bool isDefiniteISize = styleISize.IsLengthPercentage();
6454 const auto& minBSizeCoord = stylePos->MinBSize(aWM);
6455 const auto& maxBSizeCoord = stylePos->MaxBSize(aWM);
6456 const bool isAutoMinBSize =
6457 nsLayoutUtils::IsAutoBSize(minBSizeCoord, aCBSize.BSize(aWM));
6458 const bool isAutoMaxBSize =
6459 nsLayoutUtils::IsAutoBSize(maxBSizeCoord, aCBSize.BSize(aWM));
6460 if (aspectRatio && !isDefiniteISize) {
6461 // Note: the spec mentions that
6462 // 1. This transferred minimum is capped by any definite preferred or
6463 // maximum size in the destination axis.
6464 // 2. This transferred maximum is floored by any definite preferred or
6465 // minimum size in the destination axis.
6466 //
6467 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-size-transfers
6468 //
6469 // The spec requires us to clamp these by the specified size (it calls it
6470 // the preferred size). However, we actually don't need to worry about that,
6471 // because we are here only if the inline size is indefinite.
6472 //
6473 // We do not need to clamp the transferred minimum and maximum as long as we
6474 // always apply the transferred min/max size before the explicit min/max
6475 // size; the result will be identical.
6476 const nscoord transferredMinISize =
6477 isAutoMinBSize ? 0
6478 : ComputeISizeValueFromAspectRatio(
6479 aWM, aCBSize, boxSizingAdjust,
6480 minBSizeCoord.AsLengthPercentage(), aspectRatio);
6481 const nscoord transferredMaxISize =
6482 isAutoMaxBSize ? nscoord_MAX
6483 : ComputeISizeValueFromAspectRatio(
6484 aWM, aCBSize, boxSizingAdjust,
6485 maxBSizeCoord.AsLengthPercentage(), aspectRatio);
6486
6487 result.ISize(aWM) = NS_CSS_MINMAX(result.ISize(aWM), transferredMinISize,
6488 transferredMaxISize);
6489 }
6490
6491 // Flex items ignore their min & max sizing properties in their
6492 // flex container's main-axis. (Those properties get applied later in
6493 // the flexbox algorithm.)
6494 const bool isFlexItemInlineAxisMainAxis =
6495 isFlexItem && flexMainAxis == LogicalAxis::Inline;
6496 // Grid items that are subgridded in inline-axis also ignore their min & max
6497 // sizing properties in that axis.
6498 const bool shouldIgnoreMinMaxISize =
6499 isFlexItemInlineAxisMainAxis || isSubgriddedInInlineAxis;
6500 const auto& maxISizeCoord = stylePos->MaxISize(aWM);
6501 nscoord maxISize = NS_UNCONSTRAINEDSIZE;
6502 if (!maxISizeCoord.IsNone() && !shouldIgnoreMinMaxISize) {
6503 maxISize = ComputeISizeValue(aRenderingContext, aWM, aCBSize,
6504 boxSizingAdjust, boxSizingToMarginEdgeISize,
6505 maxISizeCoord, styleBSize, aspectRatio, aFlags)
6506 .mISize;
6507 result.ISize(aWM) = std::min(maxISize, result.ISize(aWM));
6508 }
6509
6510 const auto& minISizeCoord = stylePos->MinISize(aWM);
6511 nscoord minISize;
6512 if (!minISizeCoord.IsAuto() && !shouldIgnoreMinMaxISize) {
6513 minISize = ComputeISizeValue(aRenderingContext, aWM, aCBSize,
6514 boxSizingAdjust, boxSizingToMarginEdgeISize,
6515 minISizeCoord, styleBSize, aspectRatio, aFlags)
6516 .mISize;
6517 } else if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize
)), 0))
6518 aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IApplyAutoMinSize
)), 0))
) {
6519 // This implements "Implied Minimum Size of Grid Items".
6520 // https://drafts.csswg.org/css-grid/#min-size-auto
6521 minISize = std::min(maxISize, GetMinISize(aRenderingContext));
6522 if (styleISize.IsLengthPercentage()) {
6523 minISize = std::min(minISize, result.ISize(aWM));
6524 } else if (aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize)) {
6525 // "if the grid item spans only grid tracks that have a fixed max track
6526 // sizing function, its automatic minimum size in that dimension is
6527 // further clamped to less than or equal to the size necessary to fit
6528 // its margin box within the resulting grid area (flooring at zero)"
6529 // https://drafts.csswg.org/css-grid/#min-size-auto
6530 auto maxMinISize =
6531 std::max(nscoord(0), aCBSize.ISize(aWM) - aBorderPadding.ISize(aWM) -
6532 aMargin.ISize(aWM));
6533 minISize = std::min(minISize, maxMinISize);
6534 }
6535 } else if (aspectRatioUsage == AspectRatioUsage::ToComputeISize &&
6536 ShouldApplyAutomaticMinimumOnInlineAxis(aWM, disp, stylePos)) {
6537 // This means we successfully applied aspect-ratio and now need to check
6538 // if we need to apply the automatic content-based minimum size:
6539 // https://drafts.csswg.org/css-sizing-4/#aspect-ratio-minimum
6540 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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6541); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasReplacedSizing()"
") (" "aspect-ratio minimums should not apply to replaced elements"
")"); do { *((volatile int*)__null) = 6541; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6541 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6541); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasReplacedSizing()"
") (" "aspect-ratio minimums should not apply to replaced elements"
")"); do { *((volatile int*)__null) = 6541; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6542 // The inline size computed by aspect-ratio shouldn't less than the
6543 // min-content size, which should be capped by its maximum inline size.
6544 minISize = std::min(GetMinISize(aRenderingContext), maxISize);
6545 } else {
6546 // Treat "min-width: auto" as 0.
6547 // NOTE: Technically, "auto" is supposed to behave like "min-content" on
6548 // flex items. However, we don't need to worry about that here, because
6549 // flex items' min-sizes are intentionally ignored until the flex
6550 // container explicitly considers them during space distribution.
6551 minISize = 0;
6552 }
6553 result.ISize(aWM) = std::max(minISize, result.ISize(aWM));
6554
6555 // Compute block-axis size
6556 // (but not if we have auto bsize -- then, we'll just stick with the bsize
6557 // that we already calculated in the initial ComputeAutoSize() call. However,
6558 // if we have a valid preferred aspect ratio, we still have to compute the
6559 // block size because aspect ratio affects the intrinsic content size.)
6560 const bool isSubgriddedInBlockAxis =
6561 isSubgrid && static_cast<nsGridContainerFrame*>(this)->IsRowSubgrid();
6562
6563 // Per https://drafts.csswg.org/css-grid/#subgrid-box-alignment, if we are
6564 // subgridded in the block-axis, ignore our style block-size, and stretch to
6565 // fill the CB.
6566 const bool shouldComputeBSize = !isAutoBSize && !isSubgriddedInBlockAxis;
6567 if (shouldComputeBSize) {
6568 result.BSize(aWM) = nsLayoutUtils::ComputeBSizeValue(
6569 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
6570 styleBSize.AsLengthPercentage());
6571 } else if (MOZ_UNLIKELY(isGridItem)(__builtin_expect(!!(isGridItem), 0)) && styleBSize.IsAuto() &&
6572 !aFlags.contains(ComputeSizeFlag::IsGridMeasuringReflow) &&
6573 !IsTrueOverflowContainer() &&
6574 !alignCB->IsMasonry(isOrthogonal ? LogicalAxis::Inline
6575 : LogicalAxis::Block)) {
6576 auto cbSize = aCBSize.BSize(aWM);
6577 if (cbSize != NS_UNCONSTRAINEDSIZE) {
6578 // 'auto' block-size for grid-level box - fill the CB for 'stretch' /
6579 // 'normal' and clamp it to the CB if requested:
6580 bool stretch = false;
6581 bool mayUseAspectRatio =
6582 aspectRatio && result.ISize(aWM) != NS_UNCONSTRAINEDSIZE;
6583 if (!StyleMargin()->HasBlockAxisAuto(aWM)) {
6584 auto blockAxisAlignment =
6585 isOrthogonal ? StylePosition()->UsedJustifySelf(alignCB->Style())._0
6586 : StylePosition()->UsedAlignSelf(alignCB->Style())._0;
6587 stretch = blockAxisAlignment == StyleAlignFlags::STRETCH ||
6588 (blockAxisAlignment == StyleAlignFlags::NORMAL &&
6589 !mayUseAspectRatio);
6590 }
6591
6592 // Apply the preferred aspect ratio for alignments other than *stretch*
6593 // and *normal without aspect ratio*.
6594 // The spec says all other values should size the items as fit-content,
6595 // and the intrinsic size should respect the preferred aspect ratio, so
6596 // we also apply aspect ratio for all other values.
6597 // https://drafts.csswg.org/css-grid/#grid-item-sizing
6598 if (!stretch && mayUseAspectRatio) {
6599 result.BSize(aWM) = aspectRatio.ComputeRatioDependentSize(
6600 LogicalAxis::Block, aWM, result.ISize(aWM), boxSizingAdjust);
6601 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6601); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aspectRatioUsage == AspectRatioUsage::None"
")"); do { *((volatile int*)__null) = 6601; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6602 aspectRatioUsage = AspectRatioUsage::ToComputeBSize;
6603 }
6604
6605 if (stretch || aFlags.contains(ComputeSizeFlag::BClampMarginBoxMinSize)) {
6606 auto bSizeToFillCB =
6607 std::max(nscoord(0),
6608 cbSize - aBorderPadding.BSize(aWM) - aMargin.BSize(aWM));
6609 if (stretch || (result.BSize(aWM) != NS_UNCONSTRAINEDSIZE &&
6610 result.BSize(aWM) > bSizeToFillCB)) {
6611 result.BSize(aWM) = bSizeToFillCB;
6612 }
6613 }
6614 }
6615 } else if (aspectRatio) {
6616 // If both inline and block dimensions are auto, the block axis is the
6617 // ratio-dependent axis by default.
6618 // If we have a super large inline size, aspect-ratio should still be
6619 // applied (so aspectRatioUsage flag is set as expected). That's why we
6620 // apply aspect-ratio unconditionally for auto block size here.
6621 result.BSize(aWM) = aspectRatio.ComputeRatioDependentSize(
6622 LogicalAxis::Block, aWM, result.ISize(aWM), boxSizingAdjust);
6623 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6623); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aspectRatioUsage == AspectRatioUsage::None"
")"); do { *((volatile int*)__null) = 6623; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6624 aspectRatioUsage = AspectRatioUsage::ToComputeBSize;
6625 }
6626
6627 if (result.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
6628 // Flex items ignore their min & max sizing properties in their flex
6629 // container's main-axis. (Those properties get applied later in the flexbox
6630 // algorithm.)
6631 const bool isFlexItemBlockAxisMainAxis =
6632 isFlexItem && flexMainAxis == LogicalAxis::Block;
6633 // Grid items that are subgridded in block-axis also ignore their min & max
6634 // sizing properties in that axis.
6635 const bool shouldIgnoreMinMaxBSize =
6636 isFlexItemBlockAxisMainAxis || isSubgriddedInBlockAxis;
6637 if (!isAutoMaxBSize && !shouldIgnoreMinMaxBSize) {
6638 nscoord maxBSize = nsLayoutUtils::ComputeBSizeValue(
6639 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
6640 maxBSizeCoord.AsLengthPercentage());
6641 result.BSize(aWM) = std::min(maxBSize, result.BSize(aWM));
6642 }
6643
6644 if (!isAutoMinBSize && !shouldIgnoreMinMaxBSize) {
6645 nscoord minBSize = nsLayoutUtils::ComputeBSizeValue(
6646 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
6647 minBSizeCoord.AsLengthPercentage());
6648 result.BSize(aWM) = std::max(minBSize, result.BSize(aWM));
6649 }
6650 }
6651
6652 if (IsThemed(disp)) {
6653 nsPresContext* pc = PresContext();
6654 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
6655 pc, this, disp->EffectiveAppearance());
6656
6657 // Convert themed widget's physical dimensions to logical coords
6658 LogicalSize size(aWM, LayoutDeviceIntSize::ToAppUnits(
6659 widget, pc->AppUnitsPerDevPixel()));
6660
6661 // GetMinimumWidgetSize() returns border-box; we need content-box.
6662 size -= aBorderPadding;
6663
6664 if (size.BSize(aWM) > result.BSize(aWM)) {
6665 result.BSize(aWM) = size.BSize(aWM);
6666 }
6667 if (size.ISize(aWM) > result.ISize(aWM)) {
6668 result.ISize(aWM) = size.ISize(aWM);
6669 }
6670 }
6671
6672 result.ISize(aWM) = std::max(0, result.ISize(aWM));
6673 result.BSize(aWM) = std::max(0, result.BSize(aWM));
6674
6675 return {result, aspectRatioUsage};
6676}
6677
6678nsRect nsIFrame::ComputeTightBounds(DrawTarget* aDrawTarget) const {
6679 return InkOverflowRect();
6680}
6681
6682/* virtual */
6683nsresult nsIFrame::GetPrefWidthTightBounds(gfxContext* aContext, nscoord* aX,
6684 nscoord* aXMost) {
6685 return NS_ERROR_NOT_IMPLEMENTED;
6686}
6687
6688/* virtual */
6689LogicalSize nsIFrame::ComputeAutoSize(
6690 gfxContext* aRenderingContext, WritingMode aWM,
6691 const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
6692 const mozilla::LogicalSize& aMargin,
6693 const mozilla::LogicalSize& aBorderPadding,
6694 const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) {
6695 // Use basic shrink-wrapping as a default implementation.
6696 LogicalSize result(aWM, 0xdeadbeef, NS_UNCONSTRAINEDSIZE);
6697
6698 // don't bother setting it if the result won't be used
6699 const auto& styleISize = aSizeOverrides.mStyleISize
6700 ? *aSizeOverrides.mStyleISize
6701 : StylePosition()->ISize(aWM);
6702 if (styleISize.IsAuto()) {
6703 nscoord availBased =
6704 aAvailableISize - aMargin.ISize(aWM) - aBorderPadding.ISize(aWM);
6705 result.ISize(aWM) = ShrinkISizeToFit(aRenderingContext, availBased, aFlags);
6706 }
6707 return result;
6708}
6709
6710nscoord nsIFrame::ShrinkISizeToFit(gfxContext* aRenderingContext,
6711 nscoord aISizeInCB,
6712 ComputeSizeFlags aFlags) {
6713 // If we're a container for font size inflation, then shrink
6714 // wrapping inside of us should not apply font size inflation.
6715 AutoMaybeDisableFontInflation an(this);
6716
6717 nscoord result;
6718 nscoord minISize = GetMinISize(aRenderingContext);
6719 if (minISize > aISizeInCB) {
6720 const bool clamp = aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize);
6721 result = MOZ_UNLIKELY(clamp)(__builtin_expect(!!(clamp), 0)) ? aISizeInCB : minISize;
6722 } else {
6723 nscoord prefISize = GetPrefISize(aRenderingContext);
6724 if (prefISize > aISizeInCB) {
6725 result = aISizeInCB;
6726 } else {
6727 result = prefISize;
6728 }
6729 }
6730 return result;
6731}
6732
6733nscoord nsIFrame::ComputeISizeValueFromAspectRatio(
6734 WritingMode aWM, const LogicalSize& aCBSize,
6735 const LogicalSize& aContentEdgeToBoxSizing, const LengthPercentage& aBSize,
6736 const AspectRatio& aAspectRatio) const {
6737 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6737); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aAspectRatio"
") (" "Must have a valid AspectRatio!" ")"); do { *((volatile
int*)__null) = 6737; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
6738 const nscoord bSize = nsLayoutUtils::ComputeBSizeValue(
6739 aCBSize.BSize(aWM), aContentEdgeToBoxSizing.BSize(aWM), aBSize);
6740 return aAspectRatio.ComputeRatioDependentSize(LogicalAxis::Inline, aWM, bSize,
6741 aContentEdgeToBoxSizing);
6742}
6743
6744nsIFrame::ISizeComputationResult nsIFrame::ComputeISizeValue(
6745 gfxContext* aRenderingContext, const WritingMode aWM,
6746 const LogicalSize& aCBSize, const LogicalSize& aContentEdgeToBoxSizing,
6747 nscoord aBoxSizingToMarginEdge, ExtremumLength aSize,
6748 Maybe<nscoord> aAvailableISizeOverride, const StyleSize& aStyleBSize,
6749 const AspectRatio& aAspectRatio, ComputeSizeFlags aFlags) {
6750 auto GetAvailableISize = [&]() {
6751 return aCBSize.ISize(aWM) - aBoxSizingToMarginEdge -
6752 aContentEdgeToBoxSizing.ISize(aWM);
6753 };
6754
6755 // If 'this' is a container for font size inflation, then shrink
6756 // wrapping inside of it should not apply font size inflation.
6757 AutoMaybeDisableFontInflation an(this);
6758 // If we have an aspect-ratio and a definite block size, we should use them to
6759 // resolve the sizes with intrinsic keywords.
6760 // https://github.com/w3c/csswg-drafts/issues/5032
6761 Maybe<nscoord> iSizeFromAspectRatio = [&]() -> Maybe<nscoord> {
6762 if (aSize == ExtremumLength::MozAvailable) {
6763 return Nothing();
6764 }
6765 if (!aAspectRatio) {
6766 return Nothing();
6767 }
6768 if (nsLayoutUtils::IsAutoBSize(aStyleBSize, aCBSize.BSize(aWM))) {
6769 return Nothing();
6770 }
6771 return Some(ComputeISizeValueFromAspectRatio(
6772 aWM, aCBSize, aContentEdgeToBoxSizing, aStyleBSize.AsLengthPercentage(),
6773 aAspectRatio));
6774 }();
6775
6776 nscoord result;
6777 switch (aSize) {
6778 case ExtremumLength::MaxContent:
6779 result = iSizeFromAspectRatio ? *iSizeFromAspectRatio
6780 : GetPrefISize(aRenderingContext);
6781 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6781); MOZ_PretendNoReturn(); } } while (0)
;
6782 return {result, iSizeFromAspectRatio ? AspectRatioUsage::ToComputeISize
6783 : AspectRatioUsage::None};
6784 case ExtremumLength::MinContent:
6785 result = iSizeFromAspectRatio ? *iSizeFromAspectRatio
6786 : GetMinISize(aRenderingContext);
6787 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6787); MOZ_PretendNoReturn(); } } while (0)
;
6788 if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
6789 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
) {
6790 result = std::min(GetAvailableISize(), result);
6791 }
6792 return {result, iSizeFromAspectRatio ? AspectRatioUsage::ToComputeISize
6793 : AspectRatioUsage::None};
6794 case ExtremumLength::FitContentFunction:
6795 case ExtremumLength::FitContent: {
6796 nscoord pref = NS_UNCONSTRAINEDSIZE;
6797 nscoord min = 0;
6798 if (iSizeFromAspectRatio) {
6799 // The min-content and max-content size are identical and equal to the
6800 // size computed from the block size and the aspect ratio.
6801 pref = min = *iSizeFromAspectRatio;
6802 } else {
6803 pref = GetPrefISize(aRenderingContext);
6804 min = GetMinISize(aRenderingContext);
6805 }
6806
6807 const nscoord fill = aAvailableISizeOverride ? *aAvailableISizeOverride
6808 : GetAvailableISize();
6809 if (MOZ_UNLIKELY((__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
6810 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize))(__builtin_expect(!!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize
)), 0))
) {
6811 min = std::min(min, fill);
6812 }
6813 result = std::max(min, std::min(pref, fill));
6814 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6814); MOZ_PretendNoReturn(); } } while (0)
;
6815 return {result};
6816 }
6817 case ExtremumLength::MozAvailable:
6818 return {GetAvailableISize()};
6819 }
6820 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6820); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown extremum length?" ")"); do
{ *((volatile int*)__null) = 6820; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
6821 return {};
6822}
6823
6824nscoord nsIFrame::ComputeISizeValue(const WritingMode aWM,
6825 const LogicalSize& aCBSize,
6826 const LogicalSize& aContentEdgeToBoxSizing,
6827 const LengthPercentage& aSize) const {
6828 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6832); } } while (0)
6829 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6832); } } while (0)
6830 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6832); } } while (0)
6831 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6832); } } while (0)
6832 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6832); } } while (0)
;
6833 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",
"/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6833); MOZ_PretendNoReturn(); } } while (0)
;
6834
6835 nscoord result = aSize.Resolve(aCBSize.ISize(aWM));
6836 // The result of a calc() expression might be less than 0; we
6837 // should clamp at runtime (below). (Percentages and coords that
6838 // are less than 0 have already been dropped by the parser.)
6839 result -= aContentEdgeToBoxSizing.ISize(aWM);
6840 return std::max(0, result);
6841}
6842
6843void nsIFrame::DidReflow(nsPresContext* aPresContext,
6844 const ReflowInput* aReflowInput) {
6845 NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("nsIFrame::DidReflow"))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("nsIFrame::DidReflow"
); } } while (0)
;
6846
6847 if (IsHiddenByContentVisibilityOfInFlowParentForLayout()) {
6848 RemoveStateBits(NS_FRAME_IN_REFLOW);
6849 return;
6850 }
6851
6852 SVGObserverUtils::InvalidateDirectRenderingObservers(
6853 this, SVGObserverUtils::INVALIDATE_REFLOW);
6854
6855 RemoveStateBits(NS_FRAME_IN_REFLOW | NS_FRAME_FIRST_REFLOW |
6856 NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
6857
6858 // Clear bits that were used in ReflowInput::InitResizeFlags (see
6859 // comment there for why we can't clear it there).
6860 SetHasBSizeChange(false);
6861 SetHasPaddingChange(false);
6862
6863 // Notify the percent bsize observer if there is a percent bsize.
6864 // The observer may be able to initiate another reflow with a computed
6865 // bsize. This happens in the case where a table cell has no computed
6866 // bsize but can fabricate one when the cell bsize is known.
6867 if (aReflowInput && aReflowInput->mPercentBSizeObserver && !GetPrevInFlow()) {
6868 const auto& bsize =
6869 aReflowInput->mStylePosition->BSize(aReflowInput->GetWritingMode());
6870 if (bsize.HasPercent()) {
6871 aReflowInput->mPercentBSizeObserver->NotifyPercentBSize(*aReflowInput);
6872 }
6873 }
6874
6875 aPresContext->ReflowedFrame();
6876}
6877
6878void nsIFrame::FinishReflowWithAbsoluteFrames(nsPresContext* aPresContext,
6879 ReflowOutput& aDesiredSize,
6880 const ReflowInput& aReflowInput,
6881 nsReflowStatus& aStatus,
6882 bool aConstrainBSize) {
6883 ReflowAbsoluteFrames(aPresContext, aDesiredSize, aReflowInput, aStatus,
6884 aConstrainBSize);
6885
6886 FinishAndStoreOverflow(&aDesiredSize, aReflowInput.mStyleDisplay);
6887}
6888
6889void nsIFrame::ReflowAbsoluteFrames(nsPresContext* aPresContext,
6890 ReflowOutput& aDesiredSize,
6891 const ReflowInput& aReflowInput,
6892 nsReflowStatus& aStatus,
6893 bool aConstrainBSize) {
6894 if (HasAbsolutelyPositionedChildren()) {
6895 nsAbsoluteContainingBlock* absoluteContainer = GetAbsoluteContainingBlock();
6896
6897 // Let the absolutely positioned container reflow any absolutely positioned
6898 // child frames that need to be reflowed
6899
6900 // The containing block for the abs pos kids is formed by our padding edge.
6901 nsMargin usedBorder = GetUsedBorder();
6902 nscoord containingBlockWidth =
6903 std::max(0, aDesiredSize.Width() - usedBorder.LeftRight());
6904 nscoord containingBlockHeight =
6905 std::max(0, aDesiredSize.Height() - usedBorder.TopBottom());
6906 nsContainerFrame* container = do_QueryFrame(this);
6907 NS_ASSERTION(container,do { if (!(container)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Abs-pos children only supported on container frames for now"
, "container", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6908); MOZ_PretendNoReturn(); } } while (0)
6908 "Abs-pos children only supported on container frames for now")do { if (!(container)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Abs-pos children only supported on container frames for now"
, "container", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6908); MOZ_PretendNoReturn(); } } while (0)
;
6909
6910 nsRect containingBlock(0, 0, containingBlockWidth, containingBlockHeight);
6911 AbsPosReflowFlags flags =
6912 AbsPosReflowFlags::CBWidthAndHeightChanged; // XXX could be optimized
6913 if (aConstrainBSize) {
6914 flags |= AbsPosReflowFlags::ConstrainHeight;
6915 }
6916 absoluteContainer->Reflow(container, aPresContext, aReflowInput, aStatus,
6917 containingBlock, flags,
6918 &aDesiredSize.mOverflowAreas);
6919 }
6920}
6921
6922/* virtual */
6923bool nsIFrame::CanContinueTextRun() const {
6924 // By default, a frame will *not* allow a text run to be continued
6925 // through it.
6926 return false;
6927}
6928
6929void nsIFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize,
6930 const ReflowInput& aReflowInput,
6931 nsReflowStatus& aStatus) {
6932 MarkInReflow();
6933 DO_GLOBAL_REFLOW_COUNT("nsFrame")aPresContext->CountReflows(("nsFrame"), (nsIFrame*)this);;
6934 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStatus.IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStatus.IsEmpty()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aStatus.IsEmpty()"
" (" "Caller should pass a fresh reflow status!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6934); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 6934; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
6935 aDesiredSize.ClearSize();
6936}
6937
6938bool nsIFrame::IsContentDisabled() const {
6939 // FIXME(emilio): Doing this via CSS means callers must ensure the style is up
6940 // to date, and they don't!
6941 if (StyleUI()->UserInput() == StyleUserInput::None) {
6942 return true;
6943 }
6944
6945 auto* element = nsGenericHTMLElement::FromNodeOrNull(GetContent());
6946 return element && element->IsDisabled();
6947}
6948
6949bool nsIFrame::IsContentRelevant() const {
6950 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6951); AnnotateMozCrashReason("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { *((volatile int*)__null) = 6951; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
6951 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6951); AnnotateMozCrashReason("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { *((volatile int*)__null) = 6951; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6952
6953 auto* element = Element::FromNodeOrNull(GetContent());
6954 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 6954); AnnotateMozCrashReason("MOZ_ASSERT" "(" "element" ")"
); do { *((volatile int*)__null) = 6954; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
6955
6956 Maybe<ContentRelevancy> relevancy = element->GetContentRelevancy();
6957 return relevancy.isSome() && !relevancy->isEmpty();
6958}
6959
6960bool nsIFrame::HidesContent(
6961 const EnumSet<IncludeContentVisibility>& aInclude) const {
6962 auto effectiveContentVisibility = StyleDisplay()->ContentVisibility(*this);
6963 if (aInclude.contains(IncludeContentVisibility::Hidden) &&
6964 effectiveContentVisibility == StyleContentVisibility::Hidden) {
6965 return true;
6966 }
6967
6968 if (aInclude.contains(IncludeContentVisibility::Auto) &&
6969 effectiveContentVisibility == StyleContentVisibility::Auto) {
6970 return !IsContentRelevant();
6971 }
6972
6973 return false;
6974}
6975
6976bool nsIFrame::HidesContentForLayout() const {
6977 return HidesContent() && !PresShell()->IsForcingLayoutForHiddenContent(this);
6978}
6979
6980bool nsIFrame::IsHiddenByContentVisibilityOfInFlowParentForLayout() const {
6981 const auto* parent = GetInFlowParent();
6982 // The anonymous children owned by parent are important for properly sizing
6983 // their parents.
6984 return parent && parent->HidesContentForLayout() &&
6985 !(parent->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES) &&
6986 Style()->IsAnonBox());
6987}
6988
6989nsIFrame* nsIFrame::GetClosestContentVisibilityAncestor(
6990 const EnumSet<IncludeContentVisibility>& aInclude) const {
6991 if (!StaticPrefs::layout_css_content_visibility_enabled()) {
6992 return nullptr;
6993 }
6994
6995 auto* parent = GetInFlowParent();
6996 bool isAnonymousBlock = Style()->IsAnonBox() && parent &&
6997 parent->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES);
6998 for (nsIFrame* cur = parent; cur; cur = cur->GetInFlowParent()) {
6999 if (!isAnonymousBlock && cur->HidesContent(aInclude)) {
7000 return cur;
7001 }
7002
7003 // Anonymous boxes are not hidden by the content-visibility of their first
7004 // non-anonymous ancestor, but can be hidden by ancestors further up the
7005 // tree.
7006 isAnonymousBlock = false;
7007 }
7008
7009 return nullptr;
7010}
7011
7012bool nsIFrame::IsHiddenByContentVisibilityOnAnyAncestor(
7013 const EnumSet<IncludeContentVisibility>& aInclude) const {
7014 return !!GetClosestContentVisibilityAncestor(aInclude);
7015}
7016
7017bool nsIFrame::HasSelectionInSubtree() {
7018 if (IsSelected()) {
7019 return true;
7020 }
7021
7022 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
7023 if (!frameSelection) {
7024 return false;
7025 }
7026
7027 const Selection* selection =
7028 frameSelection->GetSelection(SelectionType::eNormal);
7029 if (!selection) {
7030 return false;
7031 }
7032
7033 for (uint32_t i = 0; i < selection->RangeCount(); i++) {
7034 auto* range = selection->GetRangeAt(i);
7035 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7035); AnnotateMozCrashReason("MOZ_ASSERT" "(" "range" ")")
; do { *((volatile int*)__null) = 7035; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7036
7037 const auto* commonAncestorNode =
7038 range->GetRegisteredClosestCommonInclusiveAncestor();
7039 if (commonAncestorNode &&
7040 commonAncestorNode->IsInclusiveDescendantOf(GetContent())) {
7041 return true;
7042 }
7043 }
7044
7045 return false;
7046}
7047
7048bool nsIFrame::UpdateIsRelevantContent(
7049 const ContentRelevancy& aRelevancyToUpdate) {
7050 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7051); AnnotateMozCrashReason("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { *((volatile int*)__null) = 7051; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7051 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7051); AnnotateMozCrashReason("MOZ_ASSERT" "(" "StyleDisplay()->ContentVisibility(*this) == StyleContentVisibility::Auto"
")"); do { *((volatile int*)__null) = 7051; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7052
7053 auto* element = Element::FromNodeOrNull(GetContent());
7054 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7054); AnnotateMozCrashReason("MOZ_ASSERT" "(" "element" ")"
); do { *((volatile int*)__null) = 7054; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7055
7056 ContentRelevancy newRelevancy;
7057 Maybe<ContentRelevancy> oldRelevancy = element->GetContentRelevancy();
7058 if (oldRelevancy.isSome()) {
7059 newRelevancy = *oldRelevancy;
7060 }
7061
7062 auto setRelevancyValue = [&](ContentRelevancyReason reason, bool value) {
7063 if (value) {
7064 newRelevancy += reason;
7065 } else {
7066 newRelevancy -= reason;
7067 }
7068 };
7069
7070 if (!oldRelevancy ||
7071 aRelevancyToUpdate.contains(ContentRelevancyReason::Visible)) {
7072 Maybe<bool> visible = element->GetVisibleForContentVisibility();
7073 if (visible.isSome()) {
7074 setRelevancyValue(ContentRelevancyReason::Visible, *visible);
7075 }
7076 }
7077
7078 if (!oldRelevancy ||
7079 aRelevancyToUpdate.contains(ContentRelevancyReason::FocusInSubtree)) {
7080 setRelevancyValue(ContentRelevancyReason::FocusInSubtree,
7081 element->State().HasAtLeastOneOfStates(
7082 ElementState::FOCUS_WITHIN | ElementState::FOCUS));
7083 }
7084
7085 if (!oldRelevancy ||
7086 aRelevancyToUpdate.contains(ContentRelevancyReason::Selected)) {
7087 setRelevancyValue(ContentRelevancyReason::Selected,
7088 HasSelectionInSubtree());
7089 }
7090
7091 // If the proximity to the viewport has not been determined yet,
7092 // and neither the element nor its contents are focused or selected,
7093 // we should wait for the determination of the proximity. Otherwise,
7094 // there might be a redundant contentvisibilityautostatechange event.
7095 // See https://github.com/w3c/csswg-drafts/issues/9803
7096 bool isProximityToViewportDetermined =
7097 oldRelevancy ? true : element->GetVisibleForContentVisibility().isSome();
7098 if (!isProximityToViewportDetermined && newRelevancy.isEmpty()) {
7099 return false;
7100 }
7101
7102 bool overallRelevancyChanged =
7103 !oldRelevancy || oldRelevancy->isEmpty() != newRelevancy.isEmpty();
7104 if (!oldRelevancy || *oldRelevancy != newRelevancy) {
7105 element->SetContentRelevancy(newRelevancy);
7106 }
7107
7108 if (!overallRelevancyChanged) {
7109 return false;
7110 }
7111
7112 HandleLastRememberedSize();
7113 PresContext()->SetNeedsToUpdateHiddenByContentVisibilityForAnimations();
7114 PresShell()->FrameNeedsReflow(
7115 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
7116 InvalidateFrame();
7117
7118 ContentVisibilityAutoStateChangeEventInit init;
7119 init.mSkipped = newRelevancy.isEmpty();
7120 RefPtr<ContentVisibilityAutoStateChangeEvent> event =
7121 ContentVisibilityAutoStateChangeEvent::Constructor(
7122 element, u"contentvisibilityautostatechange"_ns, init);
7123
7124 // Per
7125 // https://drafts.csswg.org/css-contain/#content-visibility-auto-state-changed
7126 // "This event is dispatched by posting a task at the time when the state
7127 // change occurs."
7128 RefPtr<AsyncEventDispatcher> asyncDispatcher =
7129 new AsyncEventDispatcher(element, event.forget());
7130 DebugOnly<nsresult> rv = asyncDispatcher->PostDOMEvent();
7131 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7131); MOZ_PretendNoReturn(); } } while (0)
;
7132 return true;
7133}
7134
7135nsresult nsIFrame::CharacterDataChanged(const CharacterDataChangeInfo&) {
7136 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7136); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "should only be called for text frames"
")"); do { *((volatile int*)__null) = 7136; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7137 return NS_OK;
7138}
7139
7140nsresult nsIFrame::AttributeChanged(int32_t aNameSpaceID, nsAtom* aAttribute,
7141 int32_t aModType) {
7142 return NS_OK;
7143}
7144
7145nsIFrame* nsIFrame::GetPrevContinuation() const { return nullptr; }
7146
7147void nsIFrame::SetPrevContinuation(nsIFrame*) {
7148 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7148); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { *((volatile
int*)__null) = 7148; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7149}
7150
7151nsIFrame* nsIFrame::GetNextContinuation() const { return nullptr; }
7152
7153void nsIFrame::SetNextContinuation(nsIFrame*) {
7154 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7154); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { *((volatile
int*)__null) = 7154; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7155}
7156
7157nsIFrame* nsIFrame::GetPrevInFlow() const { return nullptr; }
7158
7159void nsIFrame::SetPrevInFlow(nsIFrame*) {
7160 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7160); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { *((volatile
int*)__null) = 7160; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7161}
7162
7163nsIFrame* nsIFrame::GetNextInFlow() const { return nullptr; }
7164
7165void nsIFrame::SetNextInFlow(nsIFrame*) {
7166 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7166); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Not splittable!" ")"); do { *((volatile
int*)__null) = 7166; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7167}
7168
7169nsIFrame* nsIFrame::GetTailContinuation() {
7170 nsIFrame* frame = this;
7171 while (frame->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
7172 frame = frame->GetPrevContinuation();
7173 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7173); MOZ_PretendNoReturn(); } } while (0)
;
7174 }
7175 for (nsIFrame* next = frame->GetNextContinuation();
7176 next && !next->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
7177 next = frame->GetNextContinuation()) {
7178 frame = next;
7179 }
7180
7181 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."
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7181); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame" ") ("
"illegal state in continuation chain." ")"); do { *((volatile
int*)__null) = 7181; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7182 return frame;
7183}
7184
7185// Associated view object
7186void nsIFrame::SetView(nsView* aView) {
7187 if (aView) {
7188 aView->SetFrame(this);
7189
7190#ifdef DEBUG1
7191 LayoutFrameType frameType = Type();
7192 NS_ASSERTION(frameType == LayoutFrameType::SubDocument ||do { if (!(frameType == LayoutFrameType::SubDocument || frameType
== LayoutFrameType::ListControl || frameType == LayoutFrameType
::Viewport || frameType == LayoutFrameType::MenuPopup)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Only specific frame types can have an nsView"
, "frameType == LayoutFrameType::SubDocument || frameType == LayoutFrameType::ListControl || frameType == LayoutFrameType::Viewport || frameType == LayoutFrameType::MenuPopup"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7196); MOZ_PretendNoReturn(); } } while (0)
7193 frameType == LayoutFrameType::ListControl ||do { if (!(frameType == LayoutFrameType::SubDocument || frameType
== LayoutFrameType::ListControl || frameType == LayoutFrameType
::Viewport || frameType == LayoutFrameType::MenuPopup)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Only specific frame types can have an nsView"
, "frameType == LayoutFrameType::SubDocument || frameType == LayoutFrameType::ListControl || frameType == LayoutFrameType::Viewport || frameType == LayoutFrameType::MenuPopup"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7196); MOZ_PretendNoReturn(); } } while (0)
7194 frameType == LayoutFrameType::Viewport ||do { if (!(frameType == LayoutFrameType::SubDocument || frameType
== LayoutFrameType::ListControl || frameType == LayoutFrameType
::Viewport || frameType == LayoutFrameType::MenuPopup)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Only specific frame types can have an nsView"
, "frameType == LayoutFrameType::SubDocument || frameType == LayoutFrameType::ListControl || frameType == LayoutFrameType::Viewport || frameType == LayoutFrameType::MenuPopup"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7196); MOZ_PretendNoReturn(); } } while (0)
7195 frameType == LayoutFrameType::MenuPopup,do { if (!(frameType == LayoutFrameType::SubDocument || frameType
== LayoutFrameType::ListControl || frameType == LayoutFrameType
::Viewport || frameType == LayoutFrameType::MenuPopup)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Only specific frame types can have an nsView"
, "frameType == LayoutFrameType::SubDocument || frameType == LayoutFrameType::ListControl || frameType == LayoutFrameType::Viewport || frameType == LayoutFrameType::MenuPopup"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7196); MOZ_PretendNoReturn(); } } while (0)
7196 "Only specific frame types can have an nsView")do { if (!(frameType == LayoutFrameType::SubDocument || frameType
== LayoutFrameType::ListControl || frameType == LayoutFrameType
::Viewport || frameType == LayoutFrameType::MenuPopup)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Only specific frame types can have an nsView"
, "frameType == LayoutFrameType::SubDocument || frameType == LayoutFrameType::ListControl || frameType == LayoutFrameType::Viewport || frameType == LayoutFrameType::MenuPopup"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7196); MOZ_PretendNoReturn(); } } while (0)
;
7197#endif
7198
7199 // Store the view on the frame.
7200 SetViewInternal(aView);
7201
7202 // Set the frame state bit that says the frame has a view
7203 AddStateBits(NS_FRAME_HAS_VIEW);
7204
7205 // Let all of the ancestors know they have a descendant with a view.
7206 for (nsIFrame* f = GetParent();
7207 f && !f->HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW);
7208 f = f->GetParent())
7209 f->AddStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW);
7210 } else {
7211 MOZ_ASSERT_UNREACHABLE("Destroying a view while the frame is alive?")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: "
"Destroying a view while the frame is alive?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7211); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Destroying a view while the frame is alive?"
")"); do { *((volatile int*)__null) = 7211; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7212 RemoveStateBits(NS_FRAME_HAS_VIEW);
7213 SetViewInternal(nullptr);
7214 }
7215}
7216
7217// Find the first geometric parent that has a view
7218nsIFrame* nsIFrame::GetAncestorWithView() const {
7219 for (nsIFrame* f = GetParent(); nullptr != f; f = f->GetParent()) {
7220 if (f->HasView()) {
7221 return f;
7222 }
7223 }
7224 return nullptr;
7225}
7226
7227template <nsPoint (nsIFrame::*PositionGetter)() const>
7228static nsPoint OffsetCalculator(const nsIFrame* aThis, const nsIFrame* aOther) {
7229 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7229); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aOther" ") ("
"Must have frame for destination coordinate system!" ")"); do
{ *((volatile int*)__null) = 7229; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
7230
7231 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7232); MOZ_PretendNoReturn(); } } while (0)
7232 "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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7232); MOZ_PretendNoReturn(); } } while (0)
;
7233
7234 nsPoint offset(0, 0);
7235 const nsIFrame* f;
7236 for (f = aThis; f != aOther && f; f = f->GetParent()) {
7237 offset += (f->*PositionGetter)();
7238 }
7239
7240 if (f != aOther) {
7241 // Looks like aOther wasn't an ancestor of |this|. So now we have
7242 // the root-frame-relative position of |this| in |offset|. Convert back
7243 // to the coordinates of aOther
7244 while (aOther) {
7245 offset -= (aOther->*PositionGetter)();
7246 aOther = aOther->GetParent();
7247 }
7248 }
7249
7250 return offset;
7251}
7252
7253nsPoint nsIFrame::GetOffsetTo(const nsIFrame* aOther) const {
7254 return OffsetCalculator<&nsIFrame::GetPosition>(this, aOther);
7255}
7256
7257nsPoint nsIFrame::GetOffsetToIgnoringScrolling(const nsIFrame* aOther) const {
7258 return OffsetCalculator<&nsIFrame::GetPositionIgnoringScrolling>(this,
7259 aOther);
7260}
7261
7262nsPoint nsIFrame::GetOffsetToCrossDoc(const nsIFrame* aOther) const {
7263 return GetOffsetToCrossDoc(aOther, PresContext()->AppUnitsPerDevPixel());
7264}
7265
7266nsPoint nsIFrame::GetOffsetToCrossDoc(const nsIFrame* aOther,
7267 const int32_t aAPD) const {
7268 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7268); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aOther" ") ("
"Must have frame for destination coordinate system!" ")"); do
{ *((volatile int*)__null) = 7268; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
7269 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7273); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { *((volatile int*)__null) = 7273; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
7270 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7273); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { *((volatile int*)__null) = 7273; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
7271 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7273); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { *((volatile int*)__null) = 7273; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
7272 "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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7273); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { *((volatile int*)__null) = 7273; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
7273 "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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7273); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "PresContext()->GetRootPresContext() == aOther->PresContext()->GetRootPresContext()"
") (" "trying to get the offset between frames in different document "
"hierarchies?" ")"); do { *((volatile int*)__null) = 7273; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
7274
7275 const nsIFrame* root = nullptr;
7276 // offset will hold the final offset
7277 // docOffset holds the currently accumulated offset at the current APD, it
7278 // will be converted and added to offset when the current APD changes.
7279 nsPoint offset(0, 0), docOffset(0, 0);
7280 const nsIFrame* f = this;
7281 int32_t currAPD = PresContext()->AppUnitsPerDevPixel();
7282 while (f && f != aOther) {
7283 docOffset += f->GetPosition();
7284 nsIFrame* parent = f->GetParent();
7285 if (parent) {
7286 f = parent;
7287 } else {
7288 nsPoint newOffset(0, 0);
7289 root = f;
7290 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f, &newOffset);
7291 int32_t newAPD = f ? f->PresContext()->AppUnitsPerDevPixel() : 0;
7292 if (!f || newAPD != currAPD) {
7293 // Convert docOffset to the right APD and add it to offset.
7294 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
7295 docOffset.x = docOffset.y = 0;
7296 }
7297 currAPD = newAPD;
7298 docOffset += newOffset;
7299 }
7300 }
7301 if (f == aOther) {
7302 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
7303 } else {
7304 // Looks like aOther wasn't an ancestor of |this|. So now we have
7305 // the root-document-relative position of |this| in |offset|. Subtract the
7306 // root-document-relative position of |aOther| from |offset|.
7307 // This call won't try to recurse again because root is an ancestor of
7308 // aOther.
7309 nsPoint negOffset = aOther->GetOffsetToCrossDoc(root, aAPD);
7310 offset -= negOffset;
7311 }
7312
7313 return offset;
7314}
7315
7316CSSIntRect nsIFrame::GetScreenRect() const {
7317 return CSSIntRect::FromAppUnitsToNearest(GetScreenRectInAppUnits());
7318}
7319
7320nsRect nsIFrame::GetScreenRectInAppUnits() const {
7321 nsPresContext* presContext = PresContext();
7322 nsIFrame* rootFrame = presContext->PresShell()->GetRootFrame();
7323 nsPoint rootScreenPos(0, 0);
7324 nsPoint rootFrameOffsetInParent(0, 0);
7325 nsIFrame* rootFrameParent = nsLayoutUtils::GetCrossDocParentFrameInProcess(
7326 rootFrame, &rootFrameOffsetInParent);
7327 if (rootFrameParent) {
7328 nsRect parentScreenRectAppUnits =
7329 rootFrameParent->GetScreenRectInAppUnits();
7330 nsPresContext* parentPresContext = rootFrameParent->PresContext();
7331 double parentScale = double(presContext->AppUnitsPerDevPixel()) /
7332 parentPresContext->AppUnitsPerDevPixel();
7333 nsPoint rootPt =
7334 parentScreenRectAppUnits.TopLeft() + rootFrameOffsetInParent;
7335 rootScreenPos.x = NS_round(parentScale * rootPt.x);
7336 rootScreenPos.y = NS_round(parentScale * rootPt.y);
7337 } else {
7338 nsCOMPtr<nsIWidget> rootWidget =
7339 presContext->PresShell()->GetViewManager()->GetRootWidget();
7340 if (rootWidget) {
7341 LayoutDeviceIntPoint rootDevPx = rootWidget->WidgetToScreenOffset();
7342 rootScreenPos.x = presContext->DevPixelsToAppUnits(rootDevPx.x);
7343 rootScreenPos.y = presContext->DevPixelsToAppUnits(rootDevPx.y);
7344 }
7345 }
7346
7347 return nsRect(rootScreenPos + GetOffsetTo(rootFrame), GetSize());
7348}
7349
7350// Returns the offset from this frame to the closest geometric parent that
7351// has a view. Also returns the containing view or null in case of error
7352void nsIFrame::GetOffsetFromView(nsPoint& aOffset, nsView** aView) const {
7353 MOZ_ASSERT(nullptr != aView, "null OUT parameter pointer")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(nullptr != aView)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(nullptr != aView))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("nullptr != aView"
" (" "null OUT parameter pointer" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7353); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nullptr != aView"
") (" "null OUT parameter pointer" ")"); do { *((volatile int
*)__null) = 7353; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7354 nsIFrame* frame = const_cast<nsIFrame*>(this);
7355
7356 *aView = nullptr;
7357 aOffset.MoveTo(0, 0);
7358 do {
7359 aOffset += frame->GetPosition();
7360 frame = frame->GetParent();
7361 } while (frame && !frame->HasView());
7362
7363 if (frame) {
7364 *aView = frame->GetView();
7365 }
7366}
7367
7368nsIWidget* nsIFrame::GetNearestWidget() const {
7369 return GetClosestView()->GetNearestWidget(nullptr);
7370}
7371
7372nsIWidget* nsIFrame::GetNearestWidget(nsPoint& aOffset) const {
7373 nsPoint offsetToView;
7374 nsPoint offsetToWidget;
7375 nsIWidget* widget =
7376 GetClosestView(&offsetToView)->GetNearestWidget(&offsetToWidget);
7377 aOffset = offsetToView + offsetToWidget;
7378 return widget;
7379}
7380
7381Matrix4x4Flagged nsIFrame::GetTransformMatrix(ViewportType aViewportType,
7382 RelativeTo aStopAtAncestor,
7383 nsIFrame** aOutAncestor,
7384 uint32_t aFlags) const {
7385 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7385); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aOutAncestor"
") (" "Need a place to put the ancestor!" ")"); do { *((volatile
int*)__null) = 7385; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
7386
7387 /* If we're transformed, we want to hand back the combination
7388 * transform/translate matrix that will apply our current transform, then
7389 * shift us to our parent.
7390 */
7391 const bool isTransformed = IsTransformed();
7392 const nsIFrame* zoomedContentRoot = nullptr;
7393 if (aStopAtAncestor.mViewportType == ViewportType::Visual) {
7394 zoomedContentRoot = ViewportUtils::IsZoomedContentRoot(this);
7395 if (zoomedContentRoot) {
7396 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7396); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aViewportType != ViewportType::Visual"
")"); do { *((volatile int*)__null) = 7396; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7397 }
7398 }
7399
7400 if (isTransformed || zoomedContentRoot) {
7401 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7401); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetParent()"
")"); do { *((volatile int*)__null) = 7401; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7402 Matrix4x4 result;
7403 int32_t scaleFactor =
7404 ((aFlags & IN_CSS_UNITS) ? AppUnitsPerCSSPixel()
7405 : PresContext()->AppUnitsPerDevPixel());
7406
7407 /* Compute the delta to the parent, which we need because we are converting
7408 * coordinates to our parent.
7409 */
7410 if (isTransformed) {
7411 result = result * nsDisplayTransform::GetResultingTransformMatrix(
7412 this, nsPoint(0, 0), scaleFactor,
7413 nsDisplayTransform::INCLUDE_PERSPECTIVE |
7414 nsDisplayTransform::OFFSET_BY_ORIGIN);
7415 }
7416
7417 // The offset from a zoomed content root to its parent (e.g. from
7418 // a canvas frame to a scroll frame) is in layout coordinates, so
7419 // apply it before applying any layout-to-visual transform.
7420 *aOutAncestor = GetParent();
7421 nsPoint delta = GetPosition();
7422 /* Combine the raw transform with a translation to our parent. */
7423 result.PostTranslate(NSAppUnitsToFloatPixels(delta.x, scaleFactor),
7424 NSAppUnitsToFloatPixels(delta.y, scaleFactor), 0.0f);
7425
7426 if (zoomedContentRoot) {
7427 Matrix4x4 layoutToVisual;
7428 ScrollableLayerGuid::ViewID targetScrollId =
7429 nsLayoutUtils::FindOrCreateIDFor(zoomedContentRoot->GetContent());
7430 if (aFlags & nsIFrame::IN_CSS_UNITS) {
7431 layoutToVisual =
7432 ViewportUtils::GetVisualToLayoutTransform(targetScrollId)
7433 .Inverse()
7434 .ToUnknownMatrix();
7435 } else {
7436 layoutToVisual =
7437 ViewportUtils::GetVisualToLayoutTransform<LayoutDevicePixel>(
7438 targetScrollId)
7439 .Inverse()
7440 .ToUnknownMatrix();
7441 }
7442 result = result * layoutToVisual;
7443 }
7444
7445 return result;
7446 }
7447
7448 // We are not transformed, so the returned transform is just going to be a
7449 // translation up to whatever ancestor we decide to stop at.
7450
7451 nsPoint crossdocOffset;
7452 *aOutAncestor =
7453 nsLayoutUtils::GetCrossDocParentFrameInProcess(this, &crossdocOffset);
7454
7455 /* Otherwise, we're not transformed. In that case, we'll walk up the frame
7456 * tree until we either hit the root frame or something that may be
7457 * transformed. We'll then change coordinates into that frame, since we're
7458 * guaranteed that nothing in-between can be transformed. First, however,
7459 * we have to check to see if we have a parent. If not, we'll set the
7460 * outparam to null (indicating that there's nothing left) and will hand back
7461 * the identity matrix.
7462 */
7463 if (!*aOutAncestor) return Matrix4x4Flagged();
7464
7465 /* Keep iterating while the frame can't possibly be transformed. */
7466 const nsIFrame* current = this;
7467 auto shouldStopAt = [](const nsIFrame* aCurrent, RelativeTo& aStopAtAncestor,
7468 nsIFrame* aOutAncestor, uint32_t aFlags) {
7469 return aOutAncestor->IsTransformed() ||
7470 ((aStopAtAncestor.mViewportType == ViewportType::Visual) &&
7471 ViewportUtils::IsZoomedContentRoot(aOutAncestor)) ||
7472 ((aFlags & STOP_AT_STACKING_CONTEXT_AND_DISPLAY_PORT) &&
7473 (aOutAncestor->IsStackingContext() ||
7474 DisplayPortUtils::FrameHasDisplayPort(aOutAncestor, aCurrent)));
7475 };
7476
7477 // We run the GetOffsetToCrossDoc code here as an optimization, instead of
7478 // walking the parent chain here and then asking GetOffsetToCrossDoc to walk
7479 // the same parent chain and compute the offset.
7480 const int32_t finalAPD = PresContext()->AppUnitsPerDevPixel();
7481 // offset accumulates the offset at finalAPD.
7482 nsPoint offset = GetPosition();
7483
7484 int32_t currAPD = (*aOutAncestor)->PresContext()->AppUnitsPerDevPixel();
7485 // docOffset accumulates the current offset at currAPD, and then flushes to
7486 // offset at finalAPD when the APD changes or we finish.
7487 nsPoint docOffset = crossdocOffset;
7488 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7488); AnnotateMozCrashReason("MOZ_ASSERT" "(" "crossdocOffset == nsPoint(0, 0) || !GetParent()"
")"); do { *((volatile int*)__null) = 7488; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7489
7490 while (*aOutAncestor != aStopAtAncestor.mFrame &&
7491 !shouldStopAt(current, aStopAtAncestor, *aOutAncestor, aFlags)) {
7492 docOffset += (*aOutAncestor)->GetPosition();
7493
7494 nsIFrame* parent = (*aOutAncestor)->GetParent();
7495 if (!parent) {
7496 crossdocOffset.x = crossdocOffset.y = 0;
7497 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(*aOutAncestor,
7498 &crossdocOffset);
7499
7500 int32_t newAPD =
7501 parent ? parent->PresContext()->AppUnitsPerDevPixel() : currAPD;
7502 if (!parent || newAPD != currAPD) {
7503 // Convert docOffset to finalAPD and add it to offset.
7504 offset += docOffset.ScaleToOtherAppUnits(currAPD, finalAPD);
7505 docOffset.x = docOffset.y = 0;
7506 }
7507 currAPD = newAPD;
7508 docOffset += crossdocOffset;
7509
7510 if (!parent) break;
7511 }
7512
7513 current = *aOutAncestor;
7514 *aOutAncestor = parent;
7515 }
7516 offset += docOffset.ScaleToOtherAppUnits(currAPD, finalAPD);
7517
7518 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7518); MOZ_PretendNoReturn(); } } while (0)
;
7519
7520 int32_t scaleFactor =
7521 ((aFlags & IN_CSS_UNITS) ? AppUnitsPerCSSPixel()
7522 : PresContext()->AppUnitsPerDevPixel());
7523 return Matrix4x4Flagged::Translation2d(
7524 NSAppUnitsToFloatPixels(offset.x, scaleFactor),
7525 NSAppUnitsToFloatPixels(offset.y, scaleFactor));
7526}
7527
7528static void InvalidateRenderingObservers(nsIFrame* aDisplayRoot,
7529 nsIFrame* aFrame,
7530 bool aFrameChanged = true) {
7531 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7531); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
")"); do { *((volatile int*)__null) = 7531; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7532 SVGObserverUtils::InvalidateDirectRenderingObservers(aFrame);
7533 nsIFrame* parent = aFrame;
7534 while (parent != aDisplayRoot &&
7535 (parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(parent)) &&
7536 !parent->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
7537 SVGObserverUtils::InvalidateDirectRenderingObservers(parent);
7538 }
7539
7540 if (!aFrameChanged) {
7541 return;
7542 }
7543
7544 aFrame->MarkNeedsDisplayItemRebuild();
7545}
7546
7547static void SchedulePaintInternal(
7548 nsIFrame* aDisplayRoot, nsIFrame* aFrame,
7549 nsIFrame::PaintType aType = nsIFrame::PAINT_DEFAULT) {
7550 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7550); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aDisplayRoot == nsLayoutUtils::GetDisplayRootFrame(aFrame)"
")"); do { *((volatile int*)__null) = 7550; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7551 nsPresContext* pres = aDisplayRoot->PresContext()->GetRootPresContext();
7552
7553 // No need to schedule a paint for an external document since they aren't
7554 // painted directly.
7555 if (!pres || (pres->Document() && pres->Document()->IsResourceDoc())) {
7556 return;
7557 }
7558 if (!pres->GetContainerWeak()) {
7559 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, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7559)
;
7560 return;
7561 }
7562
7563 pres->PresShell()->ScheduleViewManagerFlush();
7564
7565 if (aType == nsIFrame::PAINT_DEFAULT) {
7566 aDisplayRoot->AddStateBits(NS_FRAME_UPDATE_LAYER_TREE);
7567 }
7568}
7569
7570static void InvalidateFrameInternal(nsIFrame* aFrame, bool aHasDisplayItem,
7571 bool aRebuildDisplayItems) {
7572 if (aHasDisplayItem) {
7573 aFrame->AddStateBits(NS_FRAME_NEEDS_PAINT);
7574 }
7575
7576 if (aRebuildDisplayItems) {
7577 aFrame->MarkNeedsDisplayItemRebuild();
7578 }
7579 SVGObserverUtils::InvalidateDirectRenderingObservers(aFrame);
7580 bool needsSchedulePaint = false;
7581 if (nsLayoutUtils::IsPopup(aFrame)) {
7582 needsSchedulePaint = true;
7583 } else {
7584 nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(aFrame);
7585 while (parent &&
7586 !parent->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
7587 if (aHasDisplayItem && !parent->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
7588 parent->AddStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT);
7589 }
7590 SVGObserverUtils::InvalidateDirectRenderingObservers(parent);
7591
7592 // If we're inside a popup, then we need to make sure that we
7593 // call schedule paint so that the NS_FRAME_UPDATE_LAYER_TREE
7594 // flag gets added to the popup display root frame.
7595 if (nsLayoutUtils::IsPopup(parent)) {
7596 needsSchedulePaint = true;
7597 break;
7598 }
7599 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(parent);
7600 }
7601 if (!parent) {
7602 needsSchedulePaint = true;
7603 }
7604 }
7605 if (!aHasDisplayItem) {
7606 return;
7607 }
7608 if (needsSchedulePaint) {
7609 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(aFrame);
7610 SchedulePaintInternal(displayRoot, aFrame);
7611 }
7612 if (aFrame->HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
7613 aFrame->RemoveProperty(nsIFrame::InvalidationRect());
7614 aFrame->RemoveStateBits(NS_FRAME_HAS_INVALID_RECT);
7615 }
7616}
7617
7618void nsIFrame::InvalidateFrameSubtree(bool aRebuildDisplayItems /* = true */) {
7619 InvalidateFrame(0, aRebuildDisplayItems);
7620
7621 if (HasAnyStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT)) {
7622 return;
7623 }
7624
7625 AddStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT);
7626
7627 for (const auto& childList : CrossDocChildLists()) {
7628 for (nsIFrame* child : childList.mList) {
7629 // Don't explicitly rebuild display items for our descendants,
7630 // since we should be marked and it implicitly includes all
7631 // descendants.
7632 child->InvalidateFrameSubtree(false);
7633 }
7634 }
7635}
7636
7637void nsIFrame::ClearInvalidationStateBits() {
7638 if (HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT)) {
7639 for (const auto& childList : CrossDocChildLists()) {
7640 for (nsIFrame* child : childList.mList) {
7641 child->ClearInvalidationStateBits();
7642 }
7643 }
7644 }
7645
7646 RemoveStateBits(NS_FRAME_NEEDS_PAINT | NS_FRAME_DESCENDANT_NEEDS_PAINT |
7647 NS_FRAME_ALL_DESCENDANTS_NEED_PAINT);
7648}
7649
7650bool HasRetainedDataFor(const nsIFrame* aFrame, uint32_t aDisplayItemKey) {
7651 if (RefPtr<WebRenderUserData> data =
7652 GetWebRenderUserData<WebRenderFallbackData>(aFrame,
7653 aDisplayItemKey)) {
7654 return true;
7655 }
7656
7657 return false;
7658}
7659
7660void nsIFrame::InvalidateFrame(uint32_t aDisplayItemKey,
7661 bool aRebuildDisplayItems /* = true */) {
7662 bool hasDisplayItem =
7663 !aDisplayItemKey || HasRetainedDataFor(this, aDisplayItemKey);
7664 InvalidateFrameInternal(this, hasDisplayItem, aRebuildDisplayItems);
7665}
7666
7667void nsIFrame::InvalidateFrameWithRect(const nsRect& aRect,
7668 uint32_t aDisplayItemKey,
7669 bool aRebuildDisplayItems /* = true */) {
7670 if (aRect.IsEmpty()) {
7671 return;
7672 }
7673 bool hasDisplayItem =
7674 !aDisplayItemKey || HasRetainedDataFor(this, aDisplayItemKey);
7675 bool alreadyInvalid = false;
7676 if (!HasAnyStateBits(NS_FRAME_NEEDS_PAINT)) {
7677 InvalidateFrameInternal(this, hasDisplayItem, aRebuildDisplayItems);
7678 } else {
7679 alreadyInvalid = true;
7680 }
7681
7682 if (!hasDisplayItem) {
7683 return;
7684 }
7685
7686 nsRect* rect;
7687 if (HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
7688 rect = GetProperty(InvalidationRect());
7689 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7689); AnnotateMozCrashReason("MOZ_ASSERT" "(" "rect" ")");
do { *((volatile int*)__null) = 7689; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7690 } else {
7691 if (alreadyInvalid) {
7692 return;
7693 }
7694 rect = new nsRect();
7695 AddProperty(InvalidationRect(), rect);
7696 AddStateBits(NS_FRAME_HAS_INVALID_RECT);
7697 }
7698
7699 *rect = rect->Union(aRect);
7700}
7701
7702/*static*/
7703uint8_t nsIFrame::sLayerIsPrerenderedDataKey;
7704
7705bool nsIFrame::IsInvalid(nsRect& aRect) {
7706 if (!HasAnyStateBits(NS_FRAME_NEEDS_PAINT)) {
7707 return false;
7708 }
7709
7710 if (HasAnyStateBits(NS_FRAME_HAS_INVALID_RECT)) {
7711 nsRect* rect = GetProperty(InvalidationRect());
7712 NS_ASSERTION(do { if (!(rect)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must have an invalid rect if NS_FRAME_HAS_INVALID_RECT is set!"
, "rect", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7713); MOZ_PretendNoReturn(); } } while (0)
7713 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7713); MOZ_PretendNoReturn(); } } while (0)
;
7714 aRect = *rect;
7715 } else {
7716 aRect.SetEmpty();
7717 }
7718 return true;
7719}
7720
7721void nsIFrame::SchedulePaint(PaintType aType, bool aFrameChanged) {
7722 if (PresShell()->IsPaintingSuppressed()) {
7723 // We can't have any display items yet, and when we unsuppress we will
7724 // invalidate the root frame.
7725 return;
7726 }
7727 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
7728 InvalidateRenderingObservers(displayRoot, this, aFrameChanged);
7729 SchedulePaintInternal(displayRoot, this, aType);
7730}
7731
7732void nsIFrame::SchedulePaintWithoutInvalidatingObservers(PaintType aType) {
7733 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
7734 SchedulePaintInternal(displayRoot, this, aType);
7735}
7736
7737void nsIFrame::InvalidateLayer(DisplayItemType aDisplayItemKey,
7738 const nsIntRect* aDamageRect,
7739 const nsRect* aFrameDamageRect,
7740 uint32_t aFlags /* = 0 */) {
7741 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7741); MOZ_PretendNoReturn(); } } while (0)
;
7742
7743 nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(this);
7744 InvalidateRenderingObservers(displayRoot, this, false);
7745
7746 // Check if frame supports WebRender's async update
7747 if ((aFlags & UPDATE_IS_ASYNC) &&
7748 WebRenderUserData::SupportsAsyncUpdate(this)) {
7749 // WebRender does not use layer, then return nullptr.
7750 return;
7751 }
7752
7753 if (aFrameDamageRect && aFrameDamageRect->IsEmpty()) {
7754 return;
7755 }
7756
7757 // In the bug 930056, dialer app startup but not shown on the
7758 // screen because sometimes we don't have any retainned data
7759 // for remote type displayitem and thus Repaint event is not
7760 // triggered. So, always invalidate in this case.
7761 DisplayItemType displayItemKey = aDisplayItemKey;
7762 if (aDisplayItemKey == DisplayItemType::TYPE_REMOTE) {
7763 displayItemKey = DisplayItemType::TYPE_ZERO;
7764 }
7765
7766 if (aFrameDamageRect) {
7767 InvalidateFrameWithRect(*aFrameDamageRect,
7768 static_cast<uint32_t>(displayItemKey));
7769 } else {
7770 InvalidateFrame(static_cast<uint32_t>(displayItemKey));
7771 }
7772}
7773
7774static nsRect ComputeEffectsRect(nsIFrame* aFrame, const nsRect& aOverflowRect,
7775 const nsSize& aNewSize) {
7776 nsRect r = aOverflowRect;
7777
7778 if (aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
7779 // For SVG frames, we only need to account for filters.
7780 // TODO: We could also take account of clipPath and mask to reduce the
7781 // ink overflow, but that's not essential.
7782 if (aFrame->StyleEffects()->HasFilters()) {
7783 SetOrUpdateRectValuedProperty(aFrame, nsIFrame::PreEffectsBBoxProperty(),
7784 r);
7785 r = SVGUtils::GetPostFilterInkOverflowRect(aFrame, aOverflowRect);
7786 }
7787 return r;
7788 }
7789
7790 // box-shadow
7791 r.UnionRect(r, nsLayoutUtils::GetBoxShadowRectForFrame(aFrame, aNewSize));
7792
7793 // border-image-outset.
7794 // We need to include border-image-outset because it can cause the
7795 // border image to be drawn beyond the border box.
7796
7797 // (1) It's important we not check whether there's a border-image
7798 // since the style hint for a change in border image doesn't cause
7799 // reflow, and that's probably more important than optimizing the
7800 // overflow areas for the silly case of border-image-outset without
7801 // border-image
7802 // (2) It's important that we not check whether the border-image
7803 // is actually loaded, since that would require us to reflow when
7804 // the image loads.
7805 const nsStyleBorder* styleBorder = aFrame->StyleBorder();
7806 nsMargin outsetMargin = styleBorder->GetImageOutset();
7807
7808 if (outsetMargin != nsMargin(0, 0, 0, 0)) {
7809 nsRect outsetRect(nsPoint(0, 0), aNewSize);
7810 outsetRect.Inflate(outsetMargin);
7811 r.UnionRect(r, outsetRect);
7812 }
7813
7814 // Note that we don't remove the outlineInnerRect if a frame loses outline
7815 // style. That would require an extra property lookup for every frame,
7816 // or a new frame state bit to track whether a property had been stored,
7817 // or something like that. It's not worth doing that here. At most it's
7818 // only one heap-allocated rect per frame and it will be cleaned up when
7819 // the frame dies.
7820
7821 if (SVGIntegrationUtils::UsingOverflowAffectingEffects(aFrame)) {
7822 SetOrUpdateRectValuedProperty(aFrame, nsIFrame::PreEffectsBBoxProperty(),
7823 r);
7824 r = SVGIntegrationUtils::ComputePostEffectsInkOverflowRect(aFrame, r);
7825 }
7826
7827 return r;
7828}
7829
7830void nsIFrame::SetPosition(const nsPoint& aPt) {
7831 if (mRect.TopLeft() == aPt) {
7832 return;
7833 }
7834 mRect.MoveTo(aPt);
7835 MarkNeedsDisplayItemRebuild();
7836}
7837
7838void nsIFrame::MovePositionBy(const nsPoint& aTranslation) {
7839 nsPoint position = GetNormalPosition() + aTranslation;
7840
7841 const nsMargin* computedOffsets = nullptr;
7842 if (IsRelativelyOrStickyPositioned()) {
7843 computedOffsets = GetProperty(nsIFrame::ComputedOffsetProperty());
7844 }
7845 ReflowInput::ApplyRelativePositioning(
7846 this, computedOffsets ? *computedOffsets : nsMargin(), &position);
7847 SetPosition(position);
7848}
7849
7850nsRect nsIFrame::GetNormalRect() const {
7851 // It might be faster to first check
7852 // StyleDisplay()->IsRelativelyPositionedStyle().
7853 bool hasProperty;
7854 nsPoint normalPosition = GetProperty(NormalPositionProperty(), &hasProperty);
7855 if (hasProperty) {
7856 return nsRect(normalPosition, GetSize());
7857 }
7858 return GetRect();
7859}
7860
7861nsRect nsIFrame::GetBoundingClientRect() {
7862 return nsLayoutUtils::GetAllInFlowRectsUnion(
7863 this, nsLayoutUtils::GetContainingBlockForClientRect(this),
7864 nsLayoutUtils::GetAllInFlowRectsFlag::AccountForTransforms);
7865}
7866
7867nsPoint nsIFrame::GetPositionIgnoringScrolling() const {
7868 return GetParent() ? GetParent()->GetPositionOfChildIgnoringScrolling(this)
7869 : GetPosition();
7870}
7871
7872nsRect nsIFrame::GetOverflowRect(OverflowType aType) const {
7873 // Note that in some cases the overflow area might not have been
7874 // updated (yet) to reflect any outline set on the frame or the area
7875 // of child frames. That's OK because any reflow that updates these
7876 // areas will invalidate the appropriate area, so any (mis)uses of
7877 // this method will be fixed up.
7878
7879 if (mOverflow.mType == OverflowStorageType::Large) {
7880 // there is an overflow rect, and it's not stored as deltas but as
7881 // a separately-allocated rect
7882 return GetOverflowAreasProperty()->Overflow(aType);
7883 }
7884
7885 if (aType == OverflowType::Ink &&
7886 mOverflow.mType != OverflowStorageType::None) {
7887 return InkOverflowFromDeltas();
7888 }
7889
7890 return GetRectRelativeToSelf();
7891}
7892
7893OverflowAreas nsIFrame::GetOverflowAreas() const {
7894 if (mOverflow.mType == OverflowStorageType::Large) {
7895 // there is an overflow rect, and it's not stored as deltas but as
7896 // a separately-allocated rect
7897 return *GetOverflowAreasProperty();
7898 }
7899
7900 return OverflowAreas(InkOverflowFromDeltas(),
7901 nsRect(nsPoint(0, 0), GetSize()));
7902}
7903
7904OverflowAreas nsIFrame::GetOverflowAreasRelativeToSelf() const {
7905 if (IsTransformed()) {
7906 if (OverflowAreas* preTransformOverflows =
7907 GetProperty(PreTransformOverflowAreasProperty())) {
7908 return *preTransformOverflows;
7909 }
7910 }
7911 return GetOverflowAreas();
7912}
7913
7914OverflowAreas nsIFrame::GetOverflowAreasRelativeToParent() const {
7915 return GetOverflowAreas() + GetPosition();
7916}
7917
7918OverflowAreas nsIFrame::GetActualAndNormalOverflowAreasRelativeToParent()
7919 const {
7920 if (MOZ_LIKELY(!IsRelativelyOrStickyPositioned())(__builtin_expect(!!(!IsRelativelyOrStickyPositioned()), 1))) {
7921 return GetOverflowAreasRelativeToParent();
7922 }
7923
7924 const OverflowAreas overflows = GetOverflowAreas();
7925 OverflowAreas actualAndNormalOverflows = overflows + GetNormalPosition();
7926 if (IsRelativelyPositioned()) {
7927 actualAndNormalOverflows.UnionWith(overflows + GetPosition());
7928 } else {
7929 // For sticky positioned elements, we only use the normal position for the
7930 // scrollable overflow. This avoids circular dependencies between sticky
7931 // positioned elements and their scroll container. (The scroll position and
7932 // the scroll container's size impact the sticky position, so we don't want
7933 // the sticky position to impact them.)
7934 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7934); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsStickyPositioned()"
")"); do { *((volatile int*)__null) = 7934; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7935 actualAndNormalOverflows.UnionWith(
7936 OverflowAreas(overflows.InkOverflow() + GetPosition(), nsRect()));
7937 }
7938 return actualAndNormalOverflows;
7939}
7940
7941nsRect nsIFrame::ScrollableOverflowRectRelativeToParent() const {
7942 return ScrollableOverflowRect() + GetPosition();
7943}
7944
7945nsRect nsIFrame::InkOverflowRectRelativeToParent() const {
7946 return InkOverflowRect() + GetPosition();
7947}
7948
7949nsRect nsIFrame::ScrollableOverflowRectRelativeToSelf() const {
7950 if (IsTransformed()) {
7951 if (OverflowAreas* preTransformOverflows =
7952 GetProperty(PreTransformOverflowAreasProperty())) {
7953 return preTransformOverflows->ScrollableOverflow();
7954 }
7955 }
7956 return ScrollableOverflowRect();
7957}
7958
7959nsRect nsIFrame::InkOverflowRectRelativeToSelf() const {
7960 if (IsTransformed()) {
7961 if (OverflowAreas* preTransformOverflows =
7962 GetProperty(PreTransformOverflowAreasProperty())) {
7963 return preTransformOverflows->InkOverflow();
7964 }
7965 }
7966 return InkOverflowRect();
7967}
7968
7969nsRect nsIFrame::PreEffectsInkOverflowRect() const {
7970 nsRect* r = GetProperty(nsIFrame::PreEffectsBBoxProperty());
7971 return r ? *r : InkOverflowRectRelativeToSelf();
7972}
7973
7974bool nsIFrame::UpdateOverflow() {
7975 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" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7976); AnnotateMozCrashReason("MOZ_ASSERT" "(" "FrameMaintainsOverflow()"
") (" "Non-display SVG do not maintain ink overflow rects" ")"
); do { *((volatile int*)__null) = 7976; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
7976 "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" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 7976); AnnotateMozCrashReason("MOZ_ASSERT" "(" "FrameMaintainsOverflow()"
") (" "Non-display SVG do not maintain ink overflow rects" ")"
); do { *((volatile int*)__null) = 7976; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
7977
7978 nsRect rect(nsPoint(0, 0), GetSize());
7979 OverflowAreas overflowAreas(rect, rect);
7980
7981 if (!ComputeCustomOverflow(overflowAreas)) {
7982 // If updating overflow wasn't supported by this frame, then it should
7983 // have scheduled any necessary reflows. We can return false to say nothing
7984 // changed, and wait for reflow to correct it.
7985 return false;
7986 }
7987
7988 UnionChildOverflow(overflowAreas);
7989
7990 if (FinishAndStoreOverflow(overflowAreas, GetSize())) {
7991 if (nsView* view = GetView()) {
7992 // Make sure the frame's view is properly sized.
7993 nsViewManager* vm = view->GetViewManager();
7994 vm->ResizeView(view, overflowAreas.InkOverflow());
7995 }
7996
7997 return true;
7998 }
7999
8000 // Frames that combine their 3d transform with their ancestors
8001 // only compute a pre-transform overflow rect, and then contribute
8002 // to the normal overflow rect of the preserve-3d root. Always return
8003 // true here so that we propagate changes up to the root for final
8004 // calculation.
8005 return Combines3DTransformWithAncestors();
8006}
8007
8008/* virtual */
8009bool nsIFrame::ComputeCustomOverflow(OverflowAreas& aOverflowAreas) {
8010 return true;
8011}
8012
8013bool nsIFrame::DoesClipChildrenInBothAxes() const {
8014 if (IsScrollContainerOrSubclass()) {
8015 return true;
8016 }
8017 const nsStyleDisplay* display = StyleDisplay();
8018 if (display->IsContainPaint() && SupportsContainLayoutAndPaint()) {
8019 return true;
8020 }
8021 return display->mOverflowX == StyleOverflow::Clip &&
8022 display->mOverflowY == StyleOverflow::Clip;
8023}
8024
8025/* virtual */
8026void nsIFrame::UnionChildOverflow(OverflowAreas& aOverflowAreas) {
8027 if (!DoesClipChildrenInBothAxes()) {
8028 nsLayoutUtils::UnionChildOverflow(this, aOverflowAreas);
8029 }
8030}
8031
8032// Return true if this form control element's preferred size property (but not
8033// percentage max size property) contains a percentage value that should be
8034// resolved against zero when calculating its min-content contribution in the
8035// corresponding axis.
8036//
8037// For proper replaced elements, the percentage value in both their max size
8038// property or preferred size property should be resolved against zero. This is
8039// handled in IsPercentageResolvedAgainstZero().
8040inline static bool FormControlShrinksForPercentSize(const nsIFrame* aFrame) {
8041 if (!aFrame->IsReplaced()) {
8042 // Quick test to reject most frames.
8043 return false;
8044 }
8045
8046 LayoutFrameType fType = aFrame->Type();
8047 if (fType == LayoutFrameType::Meter || fType == LayoutFrameType::Progress ||
8048 fType == LayoutFrameType::Range) {
8049 // progress, meter and range do have this shrinking behavior
8050 // FIXME: Maybe these should be nsIFormControlFrame?
8051 return true;
8052 }
8053
8054 if (!static_cast<nsIFormControlFrame*>(do_QueryFrame(aFrame))) {
8055 // Not a form control. This includes fieldsets, which do not
8056 // shrink.
8057 return false;
8058 }
8059
8060 if (fType == LayoutFrameType::GfxButtonControl ||
8061 fType == LayoutFrameType::HTMLButtonControl) {
8062 // Buttons don't have this shrinking behavior. (Note that color
8063 // inputs do, even though they inherit from button, so we can't use
8064 // do_QueryFrame here.)
8065 return false;
8066 }
8067
8068 return true;
8069}
8070
8071bool nsIFrame::IsPercentageResolvedAgainstZero(
8072 const StyleSize& aStyleSize, const StyleMaxSize& aStyleMaxSize) const {
8073 const bool sizeHasPercent = aStyleSize.HasPercent();
8074 return ((sizeHasPercent || aStyleMaxSize.HasPercent()) &&
8075 HasReplacedSizing()) ||
8076 (sizeHasPercent && FormControlShrinksForPercentSize(this));
8077}
8078
8079// Summary of the Cyclic-Percentage Intrinsic Size Contribution Rules:
8080//
8081// Element Type | Replaced | Non-replaced
8082// Contribution Type | min-content max-content | min-content max-content
8083// ---------------------------------------------------------------------------
8084// min size | zero zero | zero zero
8085// max & preferred size | zero initial | initial initial
8086//
8087// https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution
8088bool nsIFrame::IsPercentageResolvedAgainstZero(const LengthPercentage& aSize,
8089 SizeProperty aProperty) const {
8090 // Early return to avoid calling the virtual function, IsFrameOfType().
8091 if (aProperty == SizeProperty::MinSize) {
8092 return true;
8093 }
8094
8095 const bool hasPercentOnReplaced = aSize.HasPercent() && HasReplacedSizing();
8096 if (aProperty == SizeProperty::MaxSize) {
8097 return hasPercentOnReplaced;
8098 }
8099
8100 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8100); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aProperty == SizeProperty::Size"
")"); do { *((volatile int*)__null) = 8100; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8101 return hasPercentOnReplaced ||
8102 (aSize.HasPercent() && FormControlShrinksForPercentSize(this));
8103}
8104
8105bool nsIFrame::IsBlockWrapper() const {
8106 auto pseudoType = Style()->GetPseudoType();
8107 return pseudoType == PseudoStyleType::mozBlockInsideInlineWrapper ||
8108 pseudoType == PseudoStyleType::buttonContent ||
8109 pseudoType == PseudoStyleType::cellContent ||
8110 pseudoType == PseudoStyleType::columnSpanWrapper;
8111}
8112
8113bool nsIFrame::IsBlockFrameOrSubclass() const {
8114 const nsBlockFrame* thisAsBlock = do_QueryFrame(this);
8115 return !!thisAsBlock;
8116}
8117
8118bool nsIFrame::IsImageFrameOrSubclass() const {
8119 const nsImageFrame* asImage = do_QueryFrame(this);
8120 return !!asImage;
8121}
8122
8123bool nsIFrame::IsScrollContainerOrSubclass() const {
8124 const bool result = IsScrollContainerFrame() || IsListControlFrame();
8125 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8125); AnnotateMozCrashReason("MOZ_ASSERT" "(" "result == !!QueryFrame(ScrollContainerFrame::kFrameIID)"
")"); do { *((volatile int*)__null) = 8125; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8126 return result;
8127}
8128
8129bool nsIFrame::IsSubgrid() const {
8130 return IsGridContainerFrame() &&
8131 static_cast<const nsGridContainerFrame*>(this)->IsSubgrid();
8132}
8133
8134static nsIFrame* GetNearestBlockContainer(nsIFrame* frame) {
8135 while (!frame->IsBlockContainer()) {
8136 frame = frame->GetParent();
8137 NS_ASSERTION(do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "How come we got to the root frame without seeing a containing block?"
, "frame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8139); MOZ_PretendNoReturn(); } } while (0)
8138 frame,do { if (!(frame)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "How come we got to the root frame without seeing a containing block?"
, "frame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8139); MOZ_PretendNoReturn(); } } while (0)
8139 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8139); MOZ_PretendNoReturn(); } } while (0)
;
8140 }
8141 return frame;
8142}
8143
8144bool nsIFrame::IsBlockContainer() const {
8145 // The block wrappers we use to wrap blocks inside inlines aren't
8146 // described in the CSS spec. We need to make them not be containing
8147 // blocks.
8148 // Since the parent of such a block is either a normal block or
8149 // another such pseudo, this shouldn't cause anything bad to happen.
8150 // Also the anonymous blocks inside table cells are not containing blocks.
8151 //
8152 // If we ever start skipping table row groups from being containing blocks,
8153 // you need to remove the StickyScrollContainer hack referencing bug 1421660.
8154 return !IsLineParticipant() && !IsBlockWrapper() && !IsSubgrid() &&
8155 // Table rows are not containing blocks either
8156 !IsTableRowFrame();
8157}
8158
8159nsIFrame* nsIFrame::GetContainingBlock(
8160 uint32_t aFlags, const nsStyleDisplay* aStyleDisplay) const {
8161 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8161); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStyleDisplay == StyleDisplay()"
")"); do { *((volatile int*)__null) = 8161; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8162
8163 // Keep this in sync with MightBeContainingBlockFor in ReflowInput.cpp.
8164
8165 if (!GetParent()) {
8166 return nullptr;
8167 }
8168 // MathML frames might have absolute positioning style, but they would
8169 // still be in-flow. So we have to check to make sure that the frame
8170 // is really out-of-flow too.
8171 nsIFrame* f;
8172 if (IsAbsolutelyPositioned(aStyleDisplay)) {
8173 f = GetParent(); // the parent is always the containing block
8174 } else {
8175 f = GetNearestBlockContainer(GetParent());
8176 }
8177
8178 if (aFlags & SKIP_SCROLLED_FRAME && f &&
8179 f->Style()->GetPseudoType() == PseudoStyleType::scrolledContent) {
8180 f = f->GetParent();
8181 }
8182 return f;
8183}
8184
8185#ifdef DEBUG_FRAME_DUMP1
8186
8187Maybe<uint32_t> nsIFrame::ContentIndexInContainer(const nsIFrame* aFrame) {
8188 if (nsIContent* content = aFrame->GetContent()) {
8189 return content->ComputeIndexInParentContent();
8190 }
8191 return Nothing();
8192}
8193
8194nsAutoCString nsIFrame::ListTag() const {
8195 nsAutoString tmp;
8196 GetFrameName(tmp);
8197
8198 nsAutoCString tag;
8199 tag += NS_ConvertUTF16toUTF8(tmp);
8200 tag += nsPrintfCString("@%p", static_cast<const void*>(this));
8201 return tag;
8202}
8203
8204std::string nsIFrame::ConvertToString(const LogicalRect& aRect,
8205 const WritingMode aWM, ListFlags aFlags) {
8206 if (aFlags.contains(ListFlag::DisplayInCSSPixels)) {
8207 // Abuse CSSRect to store all LogicalRect's dimensions in CSS pixels.
8208 return ToString(mozilla::CSSRect(CSSPixel::FromAppUnits(aRect.IStart(aWM)),
8209 CSSPixel::FromAppUnits(aRect.BStart(aWM)),
8210 CSSPixel::FromAppUnits(aRect.ISize(aWM)),
8211 CSSPixel::FromAppUnits(aRect.BSize(aWM))));
8212 }
8213 return ToString(aRect);
8214}
8215
8216std::string nsIFrame::ConvertToString(const LogicalSize& aSize,
8217 const WritingMode aWM, ListFlags aFlags) {
8218 if (aFlags.contains(ListFlag::DisplayInCSSPixels)) {
8219 // Abuse CSSSize to store all LogicalSize's dimensions in CSS pixels.
8220 return ToString(CSSSize(CSSPixel::FromAppUnits(aSize.ISize(aWM)),
8221 CSSPixel::FromAppUnits(aSize.BSize(aWM))));
8222 }
8223 return ToString(aSize);
8224}
8225
8226// Debugging
8227void nsIFrame::ListGeneric(nsACString& aTo, const char* aPrefix,
8228 ListFlags aFlags) const {
8229 aTo += aPrefix;
8230 aTo += ListTag();
8231 if (HasView()) {
8232 aTo += nsPrintfCString(" [view=%p]", static_cast<void*>(GetView()));
8233 }
8234 if (GetParent()) {
8235 aTo += nsPrintfCString(" parent=%p", static_cast<void*>(GetParent()));
8236 }
8237 if (GetNextSibling()) {
8238 aTo += nsPrintfCString(" next=%p", static_cast<void*>(GetNextSibling()));
8239 }
8240 if (GetPrevContinuation()) {
8241 bool fluid = GetPrevInFlow() == GetPrevContinuation();
8242 aTo += nsPrintfCString(" prev-%s=%p", fluid ? "in-flow" : "continuation",
8243 static_cast<void*>(GetPrevContinuation()));
8244 }
8245 if (GetNextContinuation()) {
8246 bool fluid = GetNextInFlow() == GetNextContinuation();
8247 aTo += nsPrintfCString(" next-%s=%p", fluid ? "in-flow" : "continuation",
8248 static_cast<void*>(GetNextContinuation()));
8249 }
8250 if (const nsAtom* const autoPageValue =
8251 GetProperty(AutoPageValueProperty())) {
8252 aTo += " AutoPage=";
8253 aTo += nsAtomCString(autoPageValue);
8254 }
8255 if (const nsIFrame::PageValues* const pageValues =
8256 GetProperty(PageValuesProperty())) {
8257 aTo += " PageValues={";
8258 if (pageValues->mStartPageValue) {
8259 aTo += nsAtomCString(pageValues->mStartPageValue);
8260 } else {
8261 aTo += "<null>";
8262 }
8263 aTo += ", ";
8264 if (pageValues->mEndPageValue) {
8265 aTo += nsAtomCString(pageValues->mEndPageValue);
8266 } else {
8267 aTo += "<null>";
8268 }
8269 aTo += "}";
8270 }
8271 void* IBsibling = GetProperty(IBSplitSibling());
8272 if (IBsibling) {
8273 aTo += nsPrintfCString(" IBSplitSibling=%p", IBsibling);
8274 }
8275 void* IBprevsibling = GetProperty(IBSplitPrevSibling());
8276 if (IBprevsibling) {
8277 aTo += nsPrintfCString(" IBSplitPrevSibling=%p", IBprevsibling);
8278 }
8279 if (nsLayoutUtils::FontSizeInflationEnabled(PresContext())) {
8280 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT)) {
8281 aTo += nsPrintfCString(" FFR");
8282 if (nsFontInflationData* data =
8283 nsFontInflationData::FindFontInflationDataFor(this)) {
8284 aTo += nsPrintfCString(
8285 ",enabled=%s,UIS=%s", data->InflationEnabled() ? "yes" : "no",
8286 ConvertToString(data->UsableISize(), aFlags).c_str());
8287 }
8288 }
8289 if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)) {
8290 aTo += nsPrintfCString(" FIC");
8291 }
8292 aTo += nsPrintfCString(" FI=%f", nsLayoutUtils::FontSizeInflationFor(this));
8293 }
8294 aTo += nsPrintfCString(" %s", ConvertToString(mRect, aFlags).c_str());
8295
8296 mozilla::WritingMode wm = GetWritingMode();
8297 if (wm.IsVertical() || wm.IsBidiRTL()) {
8298 aTo +=
8299 nsPrintfCString(" wm=%s logical-size=(%s)", ToString(wm).c_str(),
8300 ConvertToString(GetLogicalSize(), wm, aFlags).c_str());
8301 }
8302
8303 nsIFrame* parent = GetParent();
8304 if (parent) {
8305 WritingMode pWM = parent->GetWritingMode();
8306 if (pWM.IsVertical() || pWM.IsBidiRTL()) {
8307 nsSize containerSize = parent->mRect.Size();
8308 LogicalRect lr(pWM, mRect, containerSize);
8309 aTo += nsPrintfCString(" parent-wm=%s cs=(%s) logical-rect=%s",
8310 ToString(pWM).c_str(),
8311 ConvertToString(containerSize, aFlags).c_str(),
8312 ConvertToString(lr, pWM, aFlags).c_str());
8313 }
8314 }
8315 nsIFrame* f = const_cast<nsIFrame*>(this);
8316 if (f->HasOverflowAreas()) {
8317 nsRect io = f->InkOverflowRect();
8318 if (!io.IsEqualEdges(mRect)) {
8319 aTo += nsPrintfCString(" ink-overflow=%s",
8320 ConvertToString(io, aFlags).c_str());
8321 }
8322 nsRect so = f->ScrollableOverflowRect();
8323 if (!so.IsEqualEdges(mRect)) {
8324 aTo += nsPrintfCString(" scr-overflow=%s",
8325 ConvertToString(so, aFlags).c_str());
8326 }
8327 }
8328 if (OverflowAreas* preTransformOverflows =
8329 f->GetProperty(PreTransformOverflowAreasProperty())) {
8330 nsRect io = preTransformOverflows->InkOverflow();
8331 if (!io.IsEqualEdges(mRect) &&
8332 (!f->HasOverflowAreas() || !io.IsEqualEdges(f->InkOverflowRect()))) {
8333 aTo += nsPrintfCString(" pre-transform-ink-overflow=%s",
8334 ConvertToString(io, aFlags).c_str());
8335 }
8336 nsRect so = preTransformOverflows->ScrollableOverflow();
8337 if (!so.IsEqualEdges(mRect) &&
8338 (!f->HasOverflowAreas() ||
8339 !so.IsEqualEdges(f->ScrollableOverflowRect()))) {
8340 aTo += nsPrintfCString(" pre-transform-scr-overflow=%s",
8341 ConvertToString(so, aFlags).c_str());
8342 }
8343 }
8344 bool hasNormalPosition;
8345 nsPoint normalPosition = GetNormalPosition(&hasNormalPosition);
8346 if (hasNormalPosition) {
8347 aTo += nsPrintfCString(" normal-position=%s",
8348 ConvertToString(normalPosition, aFlags).c_str());
8349 }
8350 if (HasProperty(BidiDataProperty())) {
8351 FrameBidiData bidi = GetBidiData();
8352 aTo += nsPrintfCString(" bidi(%d,%d,%d)", bidi.baseLevel.Value(),
8353 bidi.embeddingLevel.Value(),
8354 bidi.precedingControl.Value());
8355 }
8356 if (IsTransformed()) {
8357 aTo += nsPrintfCString(" transformed");
8358 }
8359 if (ChildrenHavePerspective()) {
8360 aTo += nsPrintfCString(" perspective");
8361 }
8362 if (Extend3DContext()) {
8363 aTo += nsPrintfCString(" extend-3d");
8364 }
8365 if (Combines3DTransformWithAncestors()) {
8366 aTo += nsPrintfCString(" combines-3d-transform-with-ancestors");
8367 }
8368 if (mContent) {
8369 aTo += nsPrintfCString(" [content=%p]", static_cast<void*>(mContent));
8370 }
8371 aTo += nsPrintfCString(" [cs=%p", static_cast<void*>(mComputedStyle));
8372 if (mComputedStyle) {
8373 auto pseudoType = mComputedStyle->GetPseudoType();
8374 aTo += ToString(pseudoType).c_str();
8375 }
8376 aTo += "]";
8377
8378 auto contentVisibility = StyleDisplay()->ContentVisibility(*this);
8379 if (contentVisibility != StyleContentVisibility::Visible) {
8380 aTo += nsPrintfCString(" [content-visibility=");
8381 if (contentVisibility == StyleContentVisibility::Auto) {
8382 aTo += "auto, "_ns;
8383 } else if (contentVisibility == StyleContentVisibility::Hidden) {
8384 aTo += "hiden, "_ns;
8385 }
8386
8387 if (HidesContent()) {
8388 aTo += "HidesContent=hidden"_ns;
8389 } else {
8390 aTo += "HidesContent=visibile"_ns;
8391 }
8392 aTo += "]";
8393 }
8394
8395 if (IsFrameModified()) {
8396 aTo += nsPrintfCString(" modified");
8397 }
8398
8399 if (HasModifiedDescendants()) {
8400 aTo += nsPrintfCString(" has-modified-descendants");
8401 }
8402}
8403
8404void nsIFrame::List(FILE* out, const char* aPrefix, ListFlags aFlags) const {
8405 nsCString str;
8406 ListGeneric(str, aPrefix, aFlags);
8407 fprintf_stderr(out, "%s\n", str.get());
8408}
8409
8410void nsIFrame::ListTextRuns(FILE* out) const {
8411 nsTHashSet<const void*> seen;
8412 ListTextRuns(out, seen);
8413}
8414
8415void nsIFrame::ListTextRuns(FILE* out, nsTHashSet<const void*>& aSeen) const {
8416 for (const auto& childList : ChildLists()) {
8417 for (const nsIFrame* kid : childList.mList) {
8418 kid->ListTextRuns(out, aSeen);
8419 }
8420 }
8421}
8422
8423void nsIFrame::ListMatchedRules(FILE* out, const char* aPrefix) const {
8424 nsTArray<const StyleLockedStyleRule*> rawRuleList;
8425 Servo_ComputedValues_GetStyleRuleList(mComputedStyle, &rawRuleList);
8426 for (const StyleLockedStyleRule* rawRule : rawRuleList) {
8427 nsAutoCString ruleText;
8428 Servo_StyleRule_GetCssText(rawRule, &ruleText);
8429 fprintf_stderr(out, "%s%s\n", aPrefix, ruleText.get());
8430 }
8431}
8432
8433void nsIFrame::ListWithMatchedRules(FILE* out, const char* aPrefix) const {
8434 fprintf_stderr(out, "%s%s\n", aPrefix, ListTag().get());
8435
8436 nsCString rulePrefix;
8437 rulePrefix += aPrefix;
8438 rulePrefix += " ";
8439 ListMatchedRules(out, rulePrefix.get());
8440}
8441
8442nsresult nsIFrame::GetFrameName(nsAString& aResult) const {
8443 return MakeFrameName(u"Frame"_ns, aResult);
8444}
8445
8446nsresult nsIFrame::MakeFrameName(const nsAString& aType,
8447 nsAString& aResult) const {
8448 aResult = aType;
8449 if (mContent && !mContent->IsText()) {
8450 nsAutoString buf;
8451 mContent->NodeInfo()->NameAtom()->ToString(buf);
8452 if (nsAtom* id = mContent->GetID()) {
8453 buf.AppendLiteral(" id=");
8454 buf.Append(nsDependentAtomString(id));
8455 }
8456 if (IsSubDocumentFrame()) {
8457 nsAutoString src;
8458 mContent->AsElement()->GetAttr(nsGkAtoms::src, src);
8459 buf.AppendLiteral(" src=");
8460 buf.Append(src);
8461 }
8462 aResult.Append('(');
8463 aResult.Append(buf);
8464 aResult.Append(')');
8465 }
8466 aResult.Append('(');
8467 Maybe<uint32_t> index = ContentIndexInContainer(this);
8468 if (index.isSome()) {
8469 aResult.AppendInt(*index);
8470 } else {
8471 aResult.AppendInt(-1);
8472 }
8473 aResult.Append(')');
8474 return NS_OK;
8475}
8476
8477void nsIFrame::DumpFrameTree() const {
8478 PresShell()->GetRootFrame()->List(stderrstderr);
8479}
8480
8481void nsIFrame::DumpFrameTreeInCSSPixels() const {
8482 PresShell()->GetRootFrame()->List(stderrstderr, "", ListFlag::DisplayInCSSPixels);
8483}
8484
8485void nsIFrame::DumpFrameTreeLimited() const { List(stderrstderr); }
8486void nsIFrame::DumpFrameTreeLimitedInCSSPixels() const {
8487 List(stderrstderr, "", ListFlag::DisplayInCSSPixels);
8488}
8489
8490#endif
8491
8492bool nsIFrame::IsVisibleForPainting() const {
8493 return StyleVisibility()->IsVisible();
8494}
8495
8496bool nsIFrame::IsVisibleOrCollapsedForPainting() const {
8497 return StyleVisibility()->IsVisibleOrCollapsed();
8498}
8499
8500/* virtual */
8501bool nsIFrame::IsEmpty() {
8502 return IsHiddenByContentVisibilityOfInFlowParentForLayout();
8503}
8504
8505bool nsIFrame::CachedIsEmpty() {
8506 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IS_DIRTY) ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
" (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8509); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
") (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")"); do { *((volatile int*)__null) = 8509
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
8507 IsHiddenByContentVisibilityOfInFlowParentForLayout(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
" (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8509); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
") (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")"); do { *((volatile int*)__null) = 8509
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
8508 "Must only be called on reflowed lines or those hidden by "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
" (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8509); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
") (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")"); do { *((volatile int*)__null) = 8509
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
8509 "content-visibility.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
" (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8509); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsHiddenByContentVisibilityOfInFlowParentForLayout()"
") (" "Must only be called on reflowed lines or those hidden by "
"content-visibility." ")"); do { *((volatile int*)__null) = 8509
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
8510 return IsEmpty();
8511}
8512
8513/* virtual */
8514bool nsIFrame::IsSelfEmpty() {
8515 return IsHiddenByContentVisibilityOfInFlowParentForLayout();
8516}
8517
8518nsresult nsIFrame::GetSelectionController(nsPresContext* aPresContext,
8519 nsISelectionController** aSelCon) {
8520 if (!aPresContext || !aSelCon) return NS_ERROR_INVALID_ARG;
8521
8522 nsIFrame* frame = this;
8523 while (frame && frame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)) {
8524 nsITextControlFrame* tcf = do_QueryFrame(frame);
8525 if (tcf) {
8526 return tcf->GetOwnedSelectionController(aSelCon);
8527 }
8528 frame = frame->GetParent();
8529 }
8530
8531 *aSelCon = do_AddRef(aPresContext->PresShell()).take();
8532 return NS_OK;
8533}
8534
8535already_AddRefed<nsFrameSelection> nsIFrame::GetFrameSelection() {
8536 RefPtr<nsFrameSelection> fs =
8537 const_cast<nsFrameSelection*>(GetConstFrameSelection());
8538 return fs.forget();
8539}
8540
8541const nsFrameSelection* nsIFrame::GetConstFrameSelection() const {
8542 nsIFrame* frame = const_cast<nsIFrame*>(this);
8543 while (frame && frame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION)) {
8544 nsITextControlFrame* tcf = do_QueryFrame(frame);
8545 if (tcf) {
8546 return tcf->GetOwnedFrameSelection();
8547 }
8548 frame = frame->GetParent();
8549 }
8550
8551 return PresShell()->ConstFrameSelection();
8552}
8553
8554bool nsIFrame::IsFrameSelected() const {
8555 NS_ASSERTION(!GetContent() || GetContent()->IsMaybeSelected(),do { if (!(!GetContent() || GetContent()->IsMaybeSelected(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "use the public IsSelected() instead"
, "!GetContent() || GetContent()->IsMaybeSelected()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8556); MOZ_PretendNoReturn(); } } while (0)
8556 "use the public IsSelected() instead")do { if (!(!GetContent() || GetContent()->IsMaybeSelected(
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "use the public IsSelected() instead"
, "!GetContent() || GetContent()->IsMaybeSelected()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8556); MOZ_PretendNoReturn(); } } while (0)
;
8557 if (StaticPrefs::dom_shadowdom_selection_across_boundary_enabled()) {
8558 if (const ShadowRoot* shadowRoot =
8559 GetContent()->GetShadowRootForSelection()) {
8560 return shadowRoot->IsSelected(0, shadowRoot->GetChildCount());
8561 }
8562 }
8563 return GetContent()->IsSelected(0, GetContent()->GetChildCount());
8564}
8565
8566nsresult nsIFrame::GetPointFromOffset(int32_t inOffset, nsPoint* outPoint) {
8567 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8567); AnnotateMozCrashReason("MOZ_ASSERT" "(" "outPoint != nullptr"
") (" "Null parameter" ")"); do { *((volatile int*)__null) =
8567; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
;
8568 nsRect contentRect = GetContentRectRelativeToSelf();
8569 nsPoint pt = contentRect.TopLeft();
8570 if (mContent) {
8571 nsIContent* newContent = mContent->GetParent();
8572 if (newContent) {
8573 const int32_t newOffset = newContent->ComputeIndexOf_Deprecated(mContent);
8574
8575 // Find the direction of the frame from the EmbeddingLevelProperty,
8576 // which is the resolved bidi level set in
8577 // nsBidiPresUtils::ResolveParagraph (odd levels = right-to-left).
8578 // If the embedding level isn't set, just use the CSS direction
8579 // property.
8580 bool hasBidiData;
8581 FrameBidiData bidiData = GetProperty(BidiDataProperty(), &hasBidiData);
8582 bool isRTL = hasBidiData
8583 ? bidiData.embeddingLevel.IsRTL()
8584 : StyleVisibility()->mDirection == StyleDirection::Rtl;
8585 if ((!isRTL && inOffset > newOffset) ||
8586 (isRTL && inOffset <= newOffset)) {
8587 pt = contentRect.TopRight();
8588 }
8589 }
8590 }
8591 *outPoint = pt;
8592 return NS_OK;
8593}
8594
8595nsresult nsIFrame::GetCharacterRectsInRange(int32_t aInOffset, int32_t aLength,
8596 nsTArray<nsRect>& aOutRect) {
8597 /* no text */
8598 return NS_ERROR_FAILURE;
8599}
8600
8601nsresult nsIFrame::GetChildFrameContainingOffset(int32_t inContentOffset,
8602 bool inHint,
8603 int32_t* outFrameContentOffset,
8604 nsIFrame** outChildFrame) {
8605 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8605); AnnotateMozCrashReason("MOZ_ASSERT" "(" "outChildFrame && outFrameContentOffset"
") (" "Null parameter" ")"); do { *((volatile int*)__null) =
8605; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
;
8606 *outFrameContentOffset = (int32_t)inHint;
8607 // the best frame to reflect any given offset would be a visible frame if
8608 // possible i.e. we are looking for a valid frame to place the blinking caret
8609 nsRect rect = GetRect();
8610 if (!rect.width || !rect.height) {
8611 // if we have a 0 width or height then lets look for another frame that
8612 // possibly has the same content. If we have no frames in flow then just
8613 // let us return 'this' frame
8614 nsIFrame* nextFlow = GetNextInFlow();
8615 if (nextFlow)
8616 return nextFlow->GetChildFrameContainingOffset(
8617 inContentOffset, inHint, outFrameContentOffset, outChildFrame);
8618 }
8619 *outChildFrame = this;
8620 return NS_OK;
8621}
8622
8623//
8624// What I've pieced together about this routine:
8625// Starting with a block frame (from which a line frame can be gotten)
8626// and a line number, drill down and get the first/last selectable
8627// frame on that line, depending on aPos->mDirection.
8628// aOutSideLimit != 0 means ignore aLineStart, instead work from
8629// the end (if > 0) or beginning (if < 0).
8630//
8631static nsresult GetNextPrevLineFromBlockFrame(PeekOffsetStruct* aPos,
8632 nsIFrame* aBlockFrame,
8633 int32_t aLineStart,
8634 int8_t aOutSideLimit) {
8635 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8635); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPos" ")");
do { *((volatile int*)__null) = 8635; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8636 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8636); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aBlockFrame"
")"); do { *((volatile int*)__null) = 8636; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8637
8638 nsPresContext* pc = aBlockFrame->PresContext();
8639
8640 // magic numbers: aLineStart will be -1 for end of block, 0 will be start of
8641 // block.
8642
8643 aPos->mResultFrame = nullptr;
8644 aPos->mResultContent = nullptr;
8645 aPos->mAttach = aPos->mDirection == eDirNext ? CaretAssociationHint::After
8646 : CaretAssociationHint::Before;
8647
8648 AutoAssertNoDomMutations guard;
8649 nsILineIterator* it = aBlockFrame->GetLineIterator();
8650 if (!it) {
8651 return NS_ERROR_FAILURE;
8652 }
8653 int32_t searchingLine = aLineStart;
8654 int32_t countLines = it->GetNumLines();
8655 if (aOutSideLimit > 0) { // start at end
8656 searchingLine = countLines;
8657 } else if (aOutSideLimit < 0) { // start at beginning
8658 searchingLine = -1; //"next" will be 0
8659 } else if ((aPos->mDirection == eDirPrevious && searchingLine == 0) ||
8660 (aPos->mDirection == eDirNext &&
8661 searchingLine >= (countLines - 1))) {
8662 // Not found.
8663 return NS_ERROR_FAILURE;
8664 }
8665 nsIFrame* resultFrame = nullptr;
8666 nsIFrame* farStoppingFrame = nullptr; // we keep searching until we find a
8667 // "this" frame then we go to next line
8668 nsIFrame* nearStoppingFrame = nullptr; // if we are backing up from edge,
8669 // stop here
8670 bool isBeforeFirstFrame, isAfterLastFrame;
8671 bool found = false;
8672
8673 const bool forceInEditableRegion =
8674 aPos->mOptions.contains(PeekOffsetOption::ForceEditableRegion);
8675 while (!found) {
8676 if (aPos->mDirection == eDirPrevious) {
8677 searchingLine--;
8678 } else {
8679 searchingLine++;
8680 }
8681 if ((aPos->mDirection == eDirPrevious && searchingLine < 0) ||
8682 (aPos->mDirection == eDirNext && searchingLine >= countLines)) {
8683 // we need to jump to new block frame.
8684 return NS_ERROR_FAILURE;
8685 }
8686 {
8687 auto line = it->GetLine(searchingLine).unwrap();
8688 if (!line.mNumFramesOnLine) {
8689 continue;
8690 }
8691 nsIFrame* firstFrame = nullptr;
8692 nsIFrame* lastFrame = nullptr;
8693 nsIFrame* frame = line.mFirstFrameOnLine;
8694 int32_t i = line.mNumFramesOnLine;
8695 do {
8696 // If the caller wants a frame for a inclusive ancestor of the ancestor
8697 // limiter, ignore frames for outside the limiter.
8698 if (aPos->FrameContentIsInAncestorLimiter(frame)) {
8699 if (!firstFrame) {
8700 firstFrame = frame;
8701 }
8702 lastFrame = frame;
8703 }
8704 if (i == 1) {
8705 break;
8706 }
8707 frame = frame->GetNextSibling();
8708 if (!frame) {
8709 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8709); MOZ_PretendNoReturn(); } while (0)
;
8710 return NS_ERROR_FAILURE;
8711 }
8712 } while (--i);
8713 if (!lastFrame) {
8714 // If we're looking for an editable content frame, but all frames in the
8715 // line are not in the specified editing host, return error because we
8716 // must reach the editing host boundary.
8717 return NS_ERROR_FAILURE;
8718 }
8719 nsIFrame::GetLastLeaf(&lastFrame);
8720
8721 if (aPos->mDirection == eDirNext) {
8722 nearStoppingFrame = firstFrame;
8723 farStoppingFrame = lastFrame;
8724 } else {
8725 nearStoppingFrame = lastFrame;
8726 farStoppingFrame = firstFrame;
8727 }
8728 }
8729 nsPoint offset;
8730 nsView* view; // used for call of get offset from view
8731 aBlockFrame->GetOffsetFromView(offset, &view);
8732 nsPoint newDesiredPos =
8733 aPos->mDesiredCaretPos -
8734 offset; // get desired position into blockframe coords
8735 // TODO: nsILineIterator::FindFrameAt should take optional editing host
8736 // parameter and if it's set, it should return the nearest editable frame
8737 // for the editing host when the frame at the desired position is not
8738 // editable.
8739 nsresult rv = it->FindFrameAt(searchingLine, newDesiredPos, &resultFrame,
8740 &isBeforeFirstFrame, &isAfterLastFrame);
8741 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
8742 continue;
8743 }
8744
8745 if (resultFrame) {
8746 // If ancestor limiter is specified and we reached outside content of it,
8747 // return error because we reached its element boundary.
8748 if (!aPos->FrameContentIsInAncestorLimiter(resultFrame)) {
8749 return NS_ERROR_FAILURE;
8750 }
8751 // check to see if this is ANOTHER blockframe inside the other one if so
8752 // then call into its lines
8753 if (resultFrame->CanProvideLineIterator()) {
8754 aPos->mResultFrame = resultFrame;
8755 return NS_OK;
8756 }
8757 // resultFrame is not a block frame
8758 Maybe<nsFrameIterator> frameIterator;
8759 frameIterator.emplace(
8760 pc, resultFrame, nsFrameIterator::Type::PostOrder,
8761 false, // aVisual
8762 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller),
8763 false, // aFollowOOFs
8764 false // aSkipPopupChecks
8765 );
8766
8767 auto FoundValidFrame = [forceInEditableRegion, aPos](
8768 const nsIFrame::ContentOffsets& aOffsets,
8769 const nsIFrame* aFrame) {
8770 if (!aOffsets.content) {
8771 return false;
8772 }
8773 if (!aFrame->IsSelectable(nullptr)) {
8774 return false;
8775 }
8776 if (aPos->mAncestorLimiter &&
8777 !aOffsets.content->IsInclusiveDescendantOf(
8778 aPos->mAncestorLimiter)) {
8779 return false;
8780 }
8781 if (forceInEditableRegion && !aOffsets.content->IsEditable()) {
8782 return false;
8783 }
8784 return true;
8785 };
8786
8787 nsIFrame* storeOldResultFrame = resultFrame;
8788 while (!found) {
8789 nsPoint point;
8790 nsRect tempRect = resultFrame->GetRect();
8791 nsPoint offset;
8792 nsView* view; // used for call of get offset from view
8793 resultFrame->GetOffsetFromView(offset, &view);
8794 if (!view) {
8795 return NS_ERROR_FAILURE;
8796 }
8797 if (resultFrame->GetWritingMode().IsVertical()) {
8798 point.y = aPos->mDesiredCaretPos.y;
8799 point.x = tempRect.width + offset.x;
8800 } else {
8801 point.y = tempRect.height + offset.y;
8802 point.x = aPos->mDesiredCaretPos.x;
8803 }
8804
8805 if (!resultFrame->HasView()) {
8806 nsView* view;
8807 nsPoint offset;
8808 resultFrame->GetOffsetFromView(offset, &view);
8809 nsIFrame::ContentOffsets offsets =
8810 resultFrame->GetContentOffsetsFromPoint(
8811 point - offset, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
8812 aPos->mResultContent = offsets.content;
8813 aPos->mContentOffset = offsets.offset;
8814 aPos->mAttach = offsets.associate;
8815 if (FoundValidFrame(offsets, resultFrame)) {
8816 found = true;
8817 break;
8818 }
8819 }
8820
8821 if (aPos->mDirection == eDirPrevious &&
8822 resultFrame == farStoppingFrame) {
8823 break;
8824 }
8825 if (aPos->mDirection == eDirNext && resultFrame == nearStoppingFrame) {
8826 break;
8827 }
8828 // always try previous on THAT line if that fails go the other way
8829 resultFrame = frameIterator->Traverse(/* aForward = */ false);
8830 if (!resultFrame) {
8831 return NS_ERROR_FAILURE;
8832 }
8833 }
8834
8835 if (!found) {
8836 resultFrame = storeOldResultFrame;
8837 frameIterator.reset();
8838 frameIterator.emplace(
8839 pc, resultFrame, nsFrameIterator::Type::Leaf,
8840 false, // aVisual
8841 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller),
8842 false, // aFollowOOFs
8843 false // aSkipPopupChecks
8844 );
8845 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",
"/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8845); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frameIterator"
")"); do { *((volatile int*)__null) = 8845; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
8846 }
8847 while (!found) {
8848 nsPoint point = aPos->mDesiredCaretPos;
8849 nsView* view;
8850 nsPoint offset;
8851 resultFrame->GetOffsetFromView(offset, &view);
8852 nsIFrame::ContentOffsets offsets =
8853 resultFrame->GetContentOffsetsFromPoint(
8854 point - offset, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
8855 aPos->mResultContent = offsets.content;
8856 aPos->mContentOffset = offsets.offset;
8857 aPos->mAttach = offsets.associate;
8858 if (FoundValidFrame(offsets, resultFrame)) {
8859 found = true;
8860 aPos->mAttach = resultFrame == farStoppingFrame
8861 ? CaretAssociationHint::Before
8862 : CaretAssociationHint::After;
8863 break;
8864 }
8865 if (aPos->mDirection == eDirPrevious &&
8866 resultFrame == nearStoppingFrame) {
8867 break;
8868 }
8869 if (aPos->mDirection == eDirNext && resultFrame == farStoppingFrame) {
8870 break;
8871 }
8872 // previous didnt work now we try "next"
8873 nsIFrame* tempFrame = frameIterator->Traverse(/* aForward = */ true);
8874 if (!tempFrame) {
8875 break;
8876 }
8877 resultFrame = tempFrame;
8878 }
8879 aPos->mResultFrame = resultFrame;
8880 } else {
8881 // we need to jump to new block frame.
8882 aPos->mAmount = eSelectLine;
8883 aPos->mStartOffset = 0;
8884 aPos->mAttach = aPos->mDirection == eDirNext
8885 ? CaretAssociationHint::Before
8886 : CaretAssociationHint::After;
8887 if (aPos->mDirection == eDirPrevious) {
8888 aPos->mStartOffset = -1; // start from end
8889 }
8890 return aBlockFrame->PeekOffset(aPos);
8891 }
8892 }
8893 return NS_OK;
8894}
8895
8896nsIFrame::CaretPosition nsIFrame::GetExtremeCaretPosition(bool aStart) {
8897 CaretPosition result;
8898
8899 FrameTarget targetFrame = DrillDownToSelectionFrame(this, !aStart, 0);
8900 FrameContentRange range = GetRangeForFrame(targetFrame.frame);
8901 result.mResultContent = range.content;
8902 result.mContentOffset = aStart ? range.start : range.end;
8903 return result;
8904}
8905
8906// If this is a preformatted text frame, see if it ends with a newline
8907static nsContentAndOffset FindLineBreakInText(nsIFrame* aFrame,
8908 nsDirection aDirection) {
8909 nsContentAndOffset result;
8910
8911 if (aFrame->IsGeneratedContentFrame() ||
8912 !aFrame->HasSignificantTerminalNewline()) {
8913 return result;
8914 }
8915
8916 int32_t endOffset = aFrame->GetOffsets().second;
8917 result.mContent = aFrame->GetContent();
8918 result.mOffset = endOffset - (aDirection == eDirPrevious ? 0 : 1);
8919 return result;
8920}
8921
8922// Find the first (or last) descendant of the given frame
8923// which is either a block-level frame or a BRFrame, or some other kind of break
8924// which stops the line.
8925static nsContentAndOffset FindLineBreakingFrame(nsIFrame* aFrame,
8926 nsDirection aDirection) {
8927 nsContentAndOffset result;
8928
8929 if (aFrame->IsGeneratedContentFrame()) {
8930 return result;
8931 }
8932
8933 // Treat form controls as inline leaves
8934 // XXX we really need a way to determine whether a frame is inline-level
8935 if (static_cast<nsIFormControlFrame*>(do_QueryFrame(aFrame))) {
8936 return result;
8937 }
8938
8939 // Check the frame itself
8940 // Fall through block-in-inline split frames because their mContent is
8941 // the content of the inline frames they were created from. The
8942 // first/last child of such frames is the real block frame we're
8943 // looking for.
8944 if ((aFrame->IsBlockOutside() &&
8945 !aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) ||
8946 aFrame->IsBrFrame()) {
8947 nsIContent* content = aFrame->GetContent();
8948 result.mContent = content->GetParent();
8949 // In some cases (bug 310589, bug 370174) we end up here with a null
8950 // content. This probably shouldn't ever happen, but since it sometimes
8951 // does, we want to avoid crashing here.
8952 NS_ASSERTION(result.mContent, "Unexpected orphan content")do { if (!(result.mContent)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Unexpected orphan content", "result.mContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 8952); MOZ_PretendNoReturn(); } } while (0)
;
8953 if (result.mContent) {
8954 result.mOffset = result.mContent->ComputeIndexOf_Deprecated(content) +
8955 (aDirection == eDirPrevious ? 1 : 0);
8956 }
8957 return result;
8958 }
8959
8960 result = FindLineBreakInText(aFrame, aDirection);
8961 if (result.mContent) {
8962 return result;
8963 }
8964
8965 // Iterate over children and call ourselves recursively
8966 if (aDirection == eDirPrevious) {
8967 nsIFrame* child = aFrame->PrincipalChildList().LastChild();
8968 while (child && !result.mContent) {
8969 result = FindLineBreakingFrame(child, aDirection);
8970 child = child->GetPrevSibling();
8971 }
8972 } else { // eDirNext
8973 nsIFrame* child = aFrame->PrincipalChildList().FirstChild();
8974 while (child && !result.mContent) {
8975 result = FindLineBreakingFrame(child, aDirection);
8976 child = child->GetNextSibling();
8977 }
8978 }
8979 return result;
8980}
8981
8982nsresult nsIFrame::PeekOffsetForParagraph(PeekOffsetStruct* aPos) {
8983 nsIFrame* frame = this;
8984 nsContentAndOffset blockFrameOrBR;
8985 blockFrameOrBR.mContent = nullptr;
8986 bool reachedLimit = frame->IsBlockOutside() || IsEditingHost(frame);
8987
8988 auto traverse = [&aPos](nsIFrame* current) {
8989 return aPos->mDirection == eDirPrevious ? current->GetPrevSibling()
8990 : current->GetNextSibling();
8991 };
8992
8993 // Go through containing frames until reaching a block frame.
8994 // In each step, search the previous (or next) siblings for the closest
8995 // "stop frame" (a block frame or a BRFrame).
8996 // If found, set it to be the selection boundary and abort.
8997 while (!reachedLimit) {
8998 nsIFrame* parent = frame->GetParent();
8999 // Treat a frame associated with the root content as if it were a block
9000 // frame.
9001 if (!frame->mContent || !frame->mContent->GetParent()) {
9002 reachedLimit = true;
9003 break;
9004 }
9005
9006 if (aPos->mDirection == eDirNext) {
9007 // Try to find our own line-break before looking at our siblings.
9008 blockFrameOrBR = FindLineBreakInText(frame, eDirNext);
9009 }
9010
9011 nsIFrame* sibling = traverse(frame);
9012 while (sibling && !blockFrameOrBR.mContent) {
9013 blockFrameOrBR = FindLineBreakingFrame(sibling, aPos->mDirection);
9014 sibling = traverse(sibling);
9015 }
9016 if (blockFrameOrBR.mContent) {
9017 aPos->mResultContent = blockFrameOrBR.mContent;
9018 aPos->mContentOffset = blockFrameOrBR.mOffset;
9019 break;
9020 }
9021 frame = parent;
9022 reachedLimit = frame && (frame->IsBlockOutside() || IsEditingHost(frame));
9023 }
9024
9025 if (reachedLimit) { // no "stop frame" found
9026 aPos->mResultContent = frame->GetContent();
9027 if (ShadowRoot* shadowRoot =
9028 aPos->mResultContent->GetShadowRootForSelection()) {
9029 // Even if there's no children for this node,
9030 // the elements inside the shadow root is still
9031 // selectable
9032 aPos->mResultContent = shadowRoot;
9033 }
9034 if (aPos->mDirection == eDirPrevious) {
9035 aPos->mContentOffset = 0;
9036 } else if (aPos->mResultContent) {
9037 aPos->mContentOffset = aPos->mResultContent->GetChildCount();
9038 }
9039 }
9040 return NS_OK;
9041}
9042
9043// Determine movement direction relative to frame
9044static bool IsMovingInFrameDirection(const nsIFrame* frame,
9045 nsDirection aDirection, bool aVisual) {
9046 bool isReverseDirection =
9047 aVisual && nsBidiPresUtils::IsReversedDirectionFrame(frame);
9048 return aDirection == (isReverseDirection ? eDirPrevious : eDirNext);
9049}
9050
9051// Determines "are we looking for a boundary between whitespace and
9052// non-whitespace (in the direction we're moving in)". It is true when moving
9053// forward and looking for a beginning of a word, or when moving backwards and
9054// looking for an end of a word.
9055static bool ShouldWordSelectionEatSpace(const PeekOffsetStruct& aPos) {
9056 if (aPos.mWordMovementType != eDefaultBehavior) {
9057 // aPos->mWordMovementType possible values:
9058 // eEndWord: eat the space if we're moving backwards
9059 // eStartWord: eat the space if we're moving forwards
9060 return (aPos.mWordMovementType == eEndWord) ==
9061 (aPos.mDirection == eDirPrevious);
9062 }
9063 // Use the hidden preference which is based on operating system
9064 // behavior. This pref only affects whether moving forward by word
9065 // should go to the end of this word or start of the next word. When
9066 // going backwards, the start of the word is always used, on every
9067 // operating system.
9068 return aPos.mDirection == eDirNext &&
9069 StaticPrefs::layout_word_select_eat_space_to_next_word();
9070}
9071
9072enum class OffsetIsAtLineEdge : bool { No, Yes };
9073
9074static void SetPeekResultFromFrame(PeekOffsetStruct& aPos, nsIFrame* aFrame,
9075 int32_t aOffset,
9076 OffsetIsAtLineEdge aAtLineEdge) {
9077 FrameContentRange range = GetRangeForFrame(aFrame);
9078 aPos.mResultFrame = aFrame;
9079 aPos.mResultContent = range.content;
9080 // Output offset is relative to content, not frame
9081 aPos.mContentOffset =
9082 aOffset < 0 ? range.end + aOffset + 1 : range.start + aOffset;
9083 if (aAtLineEdge == OffsetIsAtLineEdge::Yes) {
9084 aPos.mAttach = aPos.mContentOffset == range.start
9085 ? CaretAssociationHint::After
9086 : CaretAssociationHint::Before;
9087 }
9088}
9089
9090void nsIFrame::SelectablePeekReport::TransferTo(PeekOffsetStruct& aPos) const {
9091 return SetPeekResultFromFrame(aPos, mFrame, mOffset, OffsetIsAtLineEdge::No);
9092}
9093
9094nsIFrame::SelectablePeekReport::SelectablePeekReport(
9095 const mozilla::GenericErrorResult<nsresult>&& aErr) {
9096 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)))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9096); AnnotateMozCrashReason("MOZ_ASSERT" "(" "((bool)(__builtin_expect(!!(NS_FAILED_impl(aErr.operator nsresult())), 0)))"
")"); do { *((volatile int*)__null) = 9096; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9097 // Return an empty report
9098}
9099
9100nsresult nsIFrame::PeekOffsetForCharacter(PeekOffsetStruct* aPos,
9101 int32_t aOffset) {
9102 SelectablePeekReport current{this, aOffset};
9103
9104 nsIFrame::FrameSearchResult peekSearchState = CONTINUE;
9105
9106 while (peekSearchState != FOUND) {
9107 const bool movingInFrameDirection = IsMovingInFrameDirection(
9108 current.mFrame, aPos->mDirection,
9109 aPos->mOptions.contains(PeekOffsetOption::Visual));
9110
9111 if (current.mJumpedLine) {
9112 // If we jumped lines, it's as if we found a character, but we still need
9113 // to eat non-renderable content on the new line.
9114 peekSearchState = current.PeekOffsetNoAmount(movingInFrameDirection);
9115 } else {
9116 PeekOffsetCharacterOptions options;
9117 options.mRespectClusters = aPos->mAmount == eSelectCluster;
9118 peekSearchState =
9119 current.PeekOffsetCharacter(movingInFrameDirection, options);
9120 }
9121
9122 current.mMovedOverNonSelectableText |=
9123 peekSearchState == CONTINUE_UNSELECTABLE;
9124
9125 if (peekSearchState != FOUND) {
9126 SelectablePeekReport next = current.mFrame->GetFrameFromDirection(*aPos);
9127 if (next.Failed()) {
9128 return NS_ERROR_FAILURE;
9129 }
9130 next.mJumpedLine |= current.mJumpedLine;
9131 next.mMovedOverNonSelectableText |= current.mMovedOverNonSelectableText;
9132 next.mHasSelectableFrame |= current.mHasSelectableFrame;
9133 current = next;
9134 }
9135
9136 // Found frame, but because we moved over non selectable text we want
9137 // the offset to be at the frame edge. Note that if we are extending the
9138 // selection, this doesn't matter.
9139 if (peekSearchState == FOUND && current.mMovedOverNonSelectableText &&
9140 (!aPos->mOptions.contains(PeekOffsetOption::Extend) ||
9141 current.mHasSelectableFrame)) {
9142 auto [start, end] = current.mFrame->GetOffsets();
9143 current.mOffset = aPos->mDirection == eDirNext ? 0 : end - start;
9144 }
9145 }
9146
9147 // Set outputs
9148 current.TransferTo(*aPos);
9149 // If we're dealing with a text frame and moving backward positions us at
9150 // the end of that line, decrease the offset by one to make sure that
9151 // we're placed before the linefeed character on the previous line.
9152 if (current.mOffset < 0 && current.mJumpedLine &&
9153 aPos->mDirection == eDirPrevious &&
9154 current.mFrame->HasSignificantTerminalNewline() &&
9155 !current.mIgnoredBrFrame) {
9156 --aPos->mContentOffset;
9157 }
9158 return NS_OK;
9159}
9160
9161nsresult nsIFrame::PeekOffsetForWord(PeekOffsetStruct* aPos, int32_t aOffset) {
9162 SelectablePeekReport current{this, aOffset};
9163 bool shouldStopAtHardBreak =
9164 aPos->mWordMovementType == eDefaultBehavior &&
9165 StaticPrefs::layout_word_select_eat_space_to_next_word();
9166 bool wordSelectEatSpace = ShouldWordSelectionEatSpace(*aPos);
9167
9168 PeekWordState state;
9169 while (true) {
9170 bool movingInFrameDirection = IsMovingInFrameDirection(
9171 current.mFrame, aPos->mDirection,
9172 aPos->mOptions.contains(PeekOffsetOption::Visual));
9173
9174 FrameSearchResult searchResult = current.mFrame->PeekOffsetWord(
9175 movingInFrameDirection, wordSelectEatSpace,
9176 aPos->mOptions.contains(PeekOffsetOption::IsKeyboardSelect),
9177 &current.mOffset, &state,
9178 !aPos->mOptions.contains(PeekOffsetOption::PreserveSpaces));
9179 if (searchResult == FOUND) {
9180 break;
9181 }
9182
9183 SelectablePeekReport next = [&]() {
9184 PeekOffsetOptions options = aPos->mOptions;
9185 if (state.mSawInlineCharacter) {
9186 // If we've already found a character, we don't want to stop at
9187 // placeholder frame boundary if there is in the word.
9188 options += PeekOffsetOption::StopAtPlaceholder;
9189 }
9190 return current.mFrame->GetFrameFromDirection(aPos->mDirection, options);
9191 }();
9192 if (next.Failed()) {
9193 // If we've crossed the line boundary, check to make sure that we
9194 // have not consumed a trailing newline as whitespace if it's
9195 // significant.
9196 if (next.mJumpedLine && wordSelectEatSpace &&
9197 current.mFrame->HasSignificantTerminalNewline() &&
9198 current.mFrame->StyleText()->mWhiteSpaceCollapse !=
9199 StyleWhiteSpaceCollapse::PreserveBreaks) {
9200 current.mOffset -= 1;
9201 }
9202 break;
9203 }
9204
9205 if ((next.mJumpedLine || next.mFoundPlaceholder) && !wordSelectEatSpace &&
9206 state.mSawBeforeType) {
9207 // We can't jump lines if we're looking for whitespace following
9208 // non-whitespace, and we already encountered non-whitespace.
9209 break;
9210 }
9211
9212 if (shouldStopAtHardBreak && next.mJumpedHardBreak) {
9213 /**
9214 * Prev, always: Jump and stop right there
9215 * Next, saw inline: just stop
9216 * Next, no inline: Jump and consume whitespaces
9217 */
9218 if (aPos->mDirection == eDirPrevious) {
9219 // Try moving to the previous line if exists
9220 current.TransferTo(*aPos);
9221 current.mFrame->PeekOffsetForCharacter(aPos, current.mOffset);
9222 return NS_OK;
9223 }
9224 if (state.mSawInlineCharacter || current.mJumpedHardBreak) {
9225 if (current.mFrame->HasSignificantTerminalNewline()) {
9226 current.mOffset -= 1;
9227 }
9228 current.TransferTo(*aPos);
9229 return NS_OK;
9230 }
9231 // Mark the state as whitespace and continue
9232 state.Update(false, true);
9233 }
9234
9235 if (next.mJumpedLine) {
9236 state.mContext.Truncate();
9237 }
9238 current = next;
9239 // Jumping a line is equivalent to encountering whitespace
9240 // This affects only when it already met an actual character
9241 if (wordSelectEatSpace && next.mJumpedLine) {
9242 state.SetSawBeforeType();
9243 }
9244 }
9245
9246 // Set outputs
9247 current.TransferTo(*aPos);
9248 return NS_OK;
9249}
9250
9251static nsIFrame* GetFirstSelectableDescendantWithLineIterator(
9252 const PeekOffsetStruct& aPeekOffsetStruct, nsIFrame* aParentFrame) {
9253 const bool forceEditableRegion = aPeekOffsetStruct.mOptions.contains(
9254 PeekOffsetOption::ForceEditableRegion);
9255 auto FoundValidFrame = [aPeekOffsetStruct,
9256 forceEditableRegion](const nsIFrame* aFrame) {
9257 if (!aFrame->IsSelectable(nullptr)) {
9258 return false;
9259 }
9260 if (!aPeekOffsetStruct.FrameContentIsInAncestorLimiter(aFrame)) {
9261 return false;
9262 }
9263 if (forceEditableRegion && !aFrame->ContentIsEditable()) {
9264 return false;
9265 }
9266 return true;
9267 };
9268
9269 for (nsIFrame* child : aParentFrame->PrincipalChildList()) {
9270 // some children may not be selectable, e.g. :before / :after pseudoelements
9271 // content with user-select: none, or contenteditable="false"
9272 // we need to skip them
9273 if (child->CanProvideLineIterator() && FoundValidFrame(child)) {
9274 return child;
9275 }
9276 if (nsIFrame* nested = GetFirstSelectableDescendantWithLineIterator(
9277 aPeekOffsetStruct, child)) {
9278 return nested;
9279 }
9280 }
9281 return nullptr;
9282}
9283
9284nsresult nsIFrame::PeekOffsetForLine(PeekOffsetStruct* aPos) {
9285 nsIFrame* blockFrame = this;
9286 nsresult result = NS_ERROR_FAILURE;
9287
9288 // outer loop
9289 // moving to a next block when no more blocks are available in a subtree
9290 AutoAssertNoDomMutations guard;
9291 while (NS_FAILED(result)((bool)(__builtin_expect(!!(NS_FAILED_impl(result)), 0)))) {
9292 auto [newBlock, lineFrame] = blockFrame->GetContainingBlockForLine(
9293 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller));
9294 if (!newBlock) {
9295 return NS_ERROR_FAILURE;
9296 }
9297 // FYI: If the editing host is an inline element, the block frame content
9298 // may be either not editable or editable but belonging to different editing
9299 // host.
9300 blockFrame = newBlock;
9301 nsILineIterator* iter = blockFrame->GetLineIterator();
9302 int32_t thisLine = iter->FindLineContaining(lineFrame);
9303 if (NS_WARN_IF(thisLine < 0)NS_warn_if_impl(thisLine < 0, "thisLine < 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9303)
) {
9304 return NS_ERROR_FAILURE;
9305 }
9306
9307 int8_t edgeCase = 0; // no edge case. This should look at thisLine
9308
9309 // this part will find a frame or a block frame. If it's a block frame
9310 // it will "drill down" to find a viable frame or it will return an
9311 // error.
9312 nsIFrame* lastFrame = this;
9313
9314 // inner loop - crawling the frames within a specific block subtree
9315 while (true) {
9316 result =
9317 GetNextPrevLineFromBlockFrame(aPos, blockFrame, thisLine, edgeCase);
9318 // we came back to same spot! keep going
9319 if (NS_SUCCEEDED(result)((bool)(__builtin_expect(!!(!NS_FAILED_impl(result)), 1))) &&
9320 (!aPos->mResultFrame || aPos->mResultFrame == lastFrame)) {
9321 aPos->mResultFrame = nullptr;
9322 lastFrame = nullptr;
9323 if (aPos->mDirection == eDirPrevious) {
9324 thisLine--;
9325 } else {
9326 thisLine++;
9327 }
9328 continue;
9329 }
9330
9331 if (NS_FAILED(result)((bool)(__builtin_expect(!!(NS_FAILED_impl(result)), 0)))) {
9332 break;
9333 }
9334
9335 lastFrame = aPos->mResultFrame; // set last frame
9336 /* SPECIAL CHECK FOR NAVIGATION INTO TABLES
9337 * when we hit a frame which doesn't have line iterator, we need to
9338 * drill down and find a child with the line iterator to prevent the
9339 * crawling process to prematurely finish. Note that this is only sound if
9340 * we're guaranteed to not have multiple children implementing
9341 * LineIterator.
9342 *
9343 * So far known cases are:
9344 * 1) table wrapper (drill down into table row group)
9345 * 2) table cell (drill down into its only anon child)
9346 */
9347 const bool shouldDrillIntoChildren =
9348 aPos->mResultFrame->IsTableWrapperFrame() ||
9349 aPos->mResultFrame->IsTableCellFrame();
9350
9351 if (shouldDrillIntoChildren) {
9352 nsIFrame* child = GetFirstSelectableDescendantWithLineIterator(
9353 *aPos, aPos->mResultFrame);
9354 if (child) {
9355 aPos->mResultFrame = child;
9356 }
9357 }
9358
9359 if (!aPos->mResultFrame->CanProvideLineIterator()) {
9360 // no more selectable content at this level
9361 break;
9362 }
9363
9364 if (aPos->mResultFrame == blockFrame) {
9365 // Make sure block element is not the same as the one we had before.
9366 break;
9367 }
9368
9369 // we've struck another block element with selectable content!
9370 if (aPos->mDirection == eDirPrevious) {
9371 edgeCase = 1; // far edge, search from end backwards
9372 } else {
9373 edgeCase = -1; // near edge search from beginning onwards
9374 }
9375 thisLine = 0; // this line means nothing now.
9376 // everything else means something so keep looking "inside" the
9377 // block
9378 blockFrame = aPos->mResultFrame;
9379 }
9380 }
9381 return result;
9382}
9383
9384nsresult nsIFrame::PeekOffsetForLineEdge(PeekOffsetStruct* aPos) {
9385 // Adjusted so that the caret can't get confused when content changes
9386 nsIFrame* frame = AdjustFrameForSelectionStyles(this);
9387 Element* editingHost = frame->GetContent()->GetEditingHost();
9388
9389 auto [blockFrame, lineFrame] = frame->GetContainingBlockForLine(
9390 aPos->mOptions.contains(PeekOffsetOption::StopAtScroller));
9391 if (!blockFrame) {
9392 return NS_ERROR_FAILURE;
9393 }
9394 AutoAssertNoDomMutations guard;
9395 nsILineIterator* it = blockFrame->GetLineIterator();
9396 int32_t thisLine = it->FindLineContaining(lineFrame);
9397 if (thisLine < 0) {
9398 return NS_ERROR_FAILURE;
9399 }
9400
9401 nsIFrame* baseFrame = nullptr;
9402 bool endOfLine = eSelectEndLine == aPos->mAmount;
9403
9404 if (aPos->mOptions.contains(PeekOffsetOption::Visual) &&
9405 PresContext()->BidiEnabled()) {
9406 nsIFrame* firstFrame;
9407 bool isReordered;
9408 nsIFrame* lastFrame;
9409 MOZ_TRY(do { auto mozTryTempResult_ = ::mozilla::ToResult(it->CheckLineOrder
(thisLine, &isReordered, &firstFrame, &lastFrame)
); if ((__builtin_expect(!!(mozTryTempResult_.isErr()), 0))) {
return mozTryTempResult_.propagateErr(); } } while (0)
9410 it->CheckLineOrder(thisLine, &isReordered, &firstFrame, &lastFrame))do { auto mozTryTempResult_ = ::mozilla::ToResult(it->CheckLineOrder
(thisLine, &isReordered, &firstFrame, &lastFrame)
); if ((__builtin_expect(!!(mozTryTempResult_.isErr()), 0))) {
return mozTryTempResult_.propagateErr(); } } while (0)
;
9411 baseFrame = endOfLine ? lastFrame : firstFrame;
9412 } else {
9413 auto line = it->GetLine(thisLine).unwrap();
9414
9415 nsIFrame* frame = line.mFirstFrameOnLine;
9416 bool lastFrameWasEditable = false;
9417 for (int32_t count = line.mNumFramesOnLine; count;
9418 --count, frame = frame->GetNextSibling()) {
9419 if (frame->IsGeneratedContentFrame()) {
9420 continue;
9421 }
9422 // When jumping to the end of the line with the "end" key,
9423 // try to skip over brFrames
9424 if (endOfLine && line.mNumFramesOnLine > 1 && frame->IsBrFrame() &&
9425 lastFrameWasEditable == frame->GetContent()->IsEditable()) {
9426 continue;
9427 }
9428 lastFrameWasEditable =
9429 frame->GetContent() && frame->GetContent()->IsEditable();
9430 baseFrame = frame;
9431 if (!endOfLine) {
9432 break;
9433 }
9434 }
9435 }
9436 if (!baseFrame) {
9437 return NS_ERROR_FAILURE;
9438 }
9439 // Make sure we are not leaving our inline editing host if exists
9440 if (editingHost) {
9441 if (nsIFrame* frame = editingHost->GetPrimaryFrame()) {
9442 if (frame->IsInlineOutside() &&
9443 !editingHost->Contains(baseFrame->GetContent())) {
9444 baseFrame = frame;
9445 if (endOfLine) {
9446 baseFrame = baseFrame->LastContinuation();
9447 }
9448 }
9449 }
9450 }
9451 FrameTarget targetFrame = DrillDownToSelectionFrame(
9452 baseFrame, endOfLine, nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE);
9453 SetPeekResultFromFrame(*aPos, targetFrame.frame, endOfLine ? -1 : 0,
9454 OffsetIsAtLineEdge::Yes);
9455 if (endOfLine && targetFrame.frame->HasSignificantTerminalNewline()) {
9456 // Do not position the caret after the terminating newline if we're
9457 // trying to move to the end of line (see bug 596506)
9458 --aPos->mContentOffset;
9459 }
9460 if (!aPos->mResultContent) {
9461 return NS_ERROR_FAILURE;
9462 }
9463 return NS_OK;
9464}
9465
9466nsresult nsIFrame::PeekOffset(PeekOffsetStruct* aPos) {
9467 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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9467); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPos" ")");
do { *((volatile int*)__null) = 9467; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9468
9469 if (NS_WARN_IF(HasAnyStateBits(NS_FRAME_IS_DIRTY))NS_warn_if_impl(HasAnyStateBits(NS_FRAME_IS_DIRTY), "HasAnyStateBits(NS_FRAME_IS_DIRTY)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9469)
) {
9470 // FIXME(Bug 1654362): <caption> currently can remain dirty.
9471 return NS_ERROR_UNEXPECTED;
9472 }
9473
9474 // Translate content offset to be relative to frame
9475 int32_t offset = aPos->mStartOffset - GetRangeForFrame(this).start;
9476
9477 switch (aPos->mAmount) {
9478 case eSelectCharacter:
9479 case eSelectCluster:
9480 return PeekOffsetForCharacter(aPos, offset);
9481 case eSelectWordNoSpace:
9482 // eSelectWordNoSpace means that we should not be eating any whitespace
9483 // when moving to the adjacent word. This means that we should set aPos->
9484 // mWordMovementType to eEndWord if we're moving forwards, and to
9485 // eStartWord if we're moving backwards.
9486 if (aPos->mDirection == eDirPrevious) {
9487 aPos->mWordMovementType = eStartWord;
9488 } else {
9489 aPos->mWordMovementType = eEndWord;
9490 }
9491 // Intentionally fall through the eSelectWord case.
9492 [[fallthrough]];
9493 case eSelectWord:
9494 return PeekOffsetForWord(aPos, offset);
9495 case eSelectLine:
9496 return PeekOffsetForLine(aPos);
9497 case eSelectBeginLine:
9498 case eSelectEndLine:
9499 return PeekOffsetForLineEdge(aPos);
9500 case eSelectParagraph:
9501 return PeekOffsetForParagraph(aPos);
9502 default: {
9503 NS_ASSERTION(false, "Invalid amount")do { if (!(false)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Invalid amount"
, "false", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9503); MOZ_PretendNoReturn(); } } while (0)
;
9504 return NS_ERROR_FAILURE;
9505 }
9506 }
9507}
9508
9509nsIFrame::FrameSearchResult nsIFrame::PeekOffsetNoAmount(bool aForward,
9510 int32_t* aOffset) {
9511 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9511); MOZ_PretendNoReturn(); } } while (0)
;
9512 // Sure, we can stop right here.
9513 return FOUND;
9514}
9515
9516nsIFrame::FrameSearchResult nsIFrame::PeekOffsetCharacter(
9517 bool aForward, int32_t* aOffset, PeekOffsetCharacterOptions aOptions) {
9518 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9518); MOZ_PretendNoReturn(); } } while (0)
;
9519 int32_t startOffset = *aOffset;
9520 // A negative offset means "end of frame", which in our case means offset 1.
9521 if (startOffset < 0) startOffset = 1;
9522 if (aForward == (startOffset == 0)) {
9523 // We're before the frame and moving forward, or after it and moving
9524 // backwards: skip to the other side and we're done.
9525 *aOffset = 1 - startOffset;
9526 return FOUND;
9527 }
9528 return CONTINUE;
9529}
9530
9531nsIFrame::FrameSearchResult nsIFrame::PeekOffsetWord(
9532 bool aForward, bool aWordSelectEatSpace, bool aIsKeyboardSelect,
9533 int32_t* aOffset, PeekWordState* aState, bool /*aTrimSpaces*/) {
9534 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9534); MOZ_PretendNoReturn(); } } while (0)
;
9535 int32_t startOffset = *aOffset;
9536 // This isn't text, so truncate the context
9537 aState->mContext.Truncate();
9538 if (startOffset < 0) startOffset = 1;
9539 if (aForward == (startOffset == 0)) {
9540 // We're before the frame and moving forward, or after it and moving
9541 // backwards. If we're looking for non-whitespace, we found it (without
9542 // skipping this frame).
9543 if (!aState->mAtStart) {
9544 if (aState->mLastCharWasPunctuation) {
9545 // We're not punctuation, so this is a punctuation boundary.
9546 if (BreakWordBetweenPunctuation(aState, aForward, false, false,
9547 aIsKeyboardSelect))
9548 return FOUND;
9549 } else {
9550 // This is not a punctuation boundary.
9551 if (aWordSelectEatSpace && aState->mSawBeforeType) return FOUND;
9552 }
9553 }
9554 // Otherwise skip to the other side and note that we encountered
9555 // non-whitespace.
9556 *aOffset = 1 - startOffset;
9557 aState->Update(false, // not punctuation
9558 false // not whitespace
9559 );
9560 if (!aWordSelectEatSpace) aState->SetSawBeforeType();
9561 }
9562 return CONTINUE;
9563}
9564
9565// static
9566bool nsIFrame::BreakWordBetweenPunctuation(const PeekWordState* aState,
9567 bool aForward, bool aPunctAfter,
9568 bool aWhitespaceAfter,
9569 bool aIsKeyboardSelect) {
9570 NS_ASSERTION(aPunctAfter != aState->mLastCharWasPunctuation,do { if (!(aPunctAfter != aState->mLastCharWasPunctuation)
) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Call this only at punctuation boundaries"
, "aPunctAfter != aState->mLastCharWasPunctuation", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9571); MOZ_PretendNoReturn(); } } while (0)
9571 "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", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9571); MOZ_PretendNoReturn(); } } while (0)
;
9572 if (aState->mLastCharWasWhitespace) {
9573 // We always stop between whitespace and punctuation
9574 return true;
9575 }
9576 if (!StaticPrefs::layout_word_select_stop_at_punctuation()) {
9577 // When this pref is false, we never stop at a punctuation boundary unless
9578 // it's followed by whitespace (in the relevant direction).
9579 return aWhitespaceAfter;
9580 }
9581 if (!aIsKeyboardSelect) {
9582 // mouse caret movement (e.g. word selection) always stops at every
9583 // punctuation boundary
9584 return true;
9585 }
9586 bool afterPunct = aForward ? aState->mLastCharWasPunctuation : aPunctAfter;
9587 if (!afterPunct) {
9588 // keyboard caret movement only stops after punctuation (in content order)
9589 return false;
9590 }
9591 // Stop only if we've seen some non-punctuation since the last whitespace;
9592 // don't stop after punctuation that follows whitespace.
9593 return aState->mSeenNonPunctuationSinceWhitespace;
9594}
9595
9596std::pair<nsIFrame*, nsIFrame*> nsIFrame::GetContainingBlockForLine(
9597 bool aLockScroll) const {
9598 const nsIFrame* parentFrame = this;
9599 const nsIFrame* frame;
9600 while (parentFrame) {
9601 frame = parentFrame;
9602 if (frame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
9603 // if we are searching for a frame that is not in flow we will not find
9604 // it. we must instead look for its placeholder
9605 if (frame->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
9606 // abspos continuations don't have placeholders, get the fif
9607 frame = frame->FirstInFlow();
9608 }
9609 frame = frame->GetPlaceholderFrame();
9610 if (!frame) {
9611 return std::pair(nullptr, nullptr);
9612 }
9613 }
9614 parentFrame = frame->GetParent();
9615 if (parentFrame) {
9616 if (aLockScroll && parentFrame->IsScrollContainerFrame()) {
9617 return std::pair(nullptr, nullptr);
9618 }
9619 if (parentFrame->CanProvideLineIterator()) {
9620 return std::pair(const_cast<nsIFrame*>(parentFrame),
9621 const_cast<nsIFrame*>(frame));
9622 }
9623 }
9624 }
9625 return std::pair(nullptr, nullptr);
9626}
9627
9628Result<bool, nsresult> nsIFrame::IsVisuallyAtLineEdge(
9629 nsILineIterator* aLineIterator, int32_t aLine, nsDirection aDirection) {
9630 auto line = aLineIterator->GetLine(aLine).unwrap();
9631
9632 const bool lineIsRTL = aLineIterator->IsLineIteratorFlowRTL();
9633
9634 nsIFrame *firstFrame = nullptr, *lastFrame = nullptr;
9635 bool isReordered = false;
9636 MOZ_TRY(aLineIterator->CheckLineOrder(aLine, &isReordered, &firstFrame,do { auto mozTryTempResult_ = ::mozilla::ToResult(aLineIterator
->CheckLineOrder(aLine, &isReordered, &firstFrame,
&lastFrame)); if ((__builtin_expect(!!(mozTryTempResult_
.isErr()), 0))) { return mozTryTempResult_.propagateErr(); } }
while (0)
9637 &lastFrame))do { auto mozTryTempResult_ = ::mozilla::ToResult(aLineIterator
->CheckLineOrder(aLine, &isReordered, &firstFrame,
&lastFrame)); if ((__builtin_expect(!!(mozTryTempResult_
.isErr()), 0))) { return mozTryTempResult_.propagateErr(); } }
while (0)
;
9638 if (!firstFrame || !lastFrame) {
9639 return true; // XXX: Why true? We check whether `this` is at the edge...
9640 }
9641
9642 nsIFrame* leftmostFrame = lineIsRTL ? lastFrame : firstFrame;
9643 nsIFrame* rightmostFrame = lineIsRTL ? firstFrame : lastFrame;
9644 auto FrameIsRTL = [](nsIFrame* aFrame) {
9645 return nsBidiPresUtils::FrameDirection(aFrame) ==
9646 mozilla::intl::BidiDirection::RTL;
9647 };
9648 if (!lineIsRTL == (aDirection == eDirPrevious)) {
9649 nsIFrame* maybeLeftmostFrame = leftmostFrame;
9650 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
9651 if (maybeLeftmostFrame == this) {
9652 return true;
9653 }
9654 // If left edge of the line starts with placeholder frames, we can ignore
9655 // them and should keep checking the following frames.
9656 if (!maybeLeftmostFrame->IsPlaceholderFrame()) {
9657 if ((FrameIsRTL(maybeLeftmostFrame) == lineIsRTL) ==
9658 (aDirection == eDirPrevious)) {
9659 nsIFrame::GetFirstLeaf(&maybeLeftmostFrame);
9660 } else {
9661 nsIFrame::GetLastLeaf(&maybeLeftmostFrame);
9662 }
9663 return maybeLeftmostFrame == this;
9664 }
9665 maybeLeftmostFrame = nsBidiPresUtils::GetFrameToRightOf(
9666 maybeLeftmostFrame, line.mFirstFrameOnLine, line.mNumFramesOnLine);
9667 if (!maybeLeftmostFrame) {
9668 return false;
9669 }
9670 }
9671 return false;
9672 }
9673
9674 nsIFrame* maybeRightmostFrame = rightmostFrame;
9675 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
9676 if (maybeRightmostFrame == this) {
9677 return true;
9678 }
9679 // If the line ends with placehlder frames, we can ignore them and should
9680 // keep checking the preceding frames.
9681 if (!maybeRightmostFrame->IsPlaceholderFrame()) {
9682 if ((FrameIsRTL(maybeRightmostFrame) == lineIsRTL) ==
9683 (aDirection == eDirPrevious)) {
9684 nsIFrame::GetFirstLeaf(&maybeRightmostFrame);
9685 } else {
9686 nsIFrame::GetLastLeaf(&maybeRightmostFrame);
9687 }
9688 return maybeRightmostFrame == this;
9689 }
9690 maybeRightmostFrame = nsBidiPresUtils::GetFrameToLeftOf(
9691 maybeRightmostFrame, line.mFirstFrameOnLine, line.mNumFramesOnLine);
9692 if (!maybeRightmostFrame) {
9693 return false;
9694 }
9695 }
9696 return false;
9697}
9698
9699Result<bool, nsresult> nsIFrame::IsLogicallyAtLineEdge(
9700 nsILineIterator* aLineIterator, int32_t aLine, nsDirection aDirection) {
9701 auto line = aLineIterator->GetLine(aLine).unwrap();
9702 if (!line.mNumFramesOnLine) {
9703 return false;
9704 }
9705 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9705); AnnotateMozCrashReason("MOZ_ASSERT" "(" "line.mFirstFrameOnLine"
")"); do { *((volatile int*)__null) = 9705; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9706
9707 if (aDirection == eDirPrevious) {
9708 nsIFrame* maybeFirstFrame = line.mFirstFrameOnLine;
9709 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
9710 if (maybeFirstFrame == this) {
9711 return true;
9712 }
9713 // If the line starts with placeholder frames, we can ignore them and
9714 // should keep checking the following frames.
9715 if (!maybeFirstFrame->IsPlaceholderFrame()) {
9716 nsIFrame::GetFirstLeaf(&maybeFirstFrame);
9717 return maybeFirstFrame == this;
9718 }
9719 maybeFirstFrame = maybeFirstFrame->GetNextSibling();
9720 if (!maybeFirstFrame) {
9721 return false;
9722 }
9723 }
9724 return false;
9725 }
9726
9727 // eDirNext
9728 nsIFrame* maybeLastFrame = line.GetLastFrameOnLine();
9729 for ([[maybe_unused]] int32_t i : IntegerRange(line.mNumFramesOnLine)) {
9730 if (maybeLastFrame == this) {
9731 return true;
9732 }
9733 // If the line ends with placehlder frames, we can ignore them and should
9734 // keep checking the preceding frames.
9735 if (!maybeLastFrame->IsPlaceholderFrame()) {
9736 nsIFrame::GetLastLeaf(&maybeLastFrame);
9737 return maybeLastFrame == this;
9738 }
9739 maybeLastFrame = maybeLastFrame->GetPrevSibling();
9740 }
9741 return false;
9742}
9743
9744nsIFrame::SelectablePeekReport nsIFrame::GetFrameFromDirection(
9745 nsDirection aDirection, const PeekOffsetOptions& aOptions) {
9746 SelectablePeekReport result;
9747
9748 nsPresContext* presContext = PresContext();
9749 const bool needsVisualTraversal =
9750 aOptions.contains(PeekOffsetOption::Visual) && presContext->BidiEnabled();
9751 const bool followOofs =
9752 !aOptions.contains(PeekOffsetOption::StopAtPlaceholder);
9753 nsFrameIterator frameIterator(
9754 presContext, this, nsFrameIterator::Type::Leaf, needsVisualTraversal,
9755 aOptions.contains(PeekOffsetOption::StopAtScroller), followOofs,
9756 false // aSkipPopupChecks
9757 );
9758
9759 // Find the prev/next selectable frame
9760 bool selectable = false;
9761 nsIFrame* traversedFrame = this;
9762 AutoAssertNoDomMutations guard;
9763 const nsIContent* const nativeAnonymousSubtreeContent =
9764 GetClosestNativeAnonymousSubtreeRoot();
9765 while (!selectable) {
9766 auto [blockFrame, lineFrame] = traversedFrame->GetContainingBlockForLine(
9767 aOptions.contains(PeekOffsetOption::StopAtScroller));
9768 if (!blockFrame) {
9769 return result;
9770 }
9771
9772 nsILineIterator* it = blockFrame->GetLineIterator();
9773 int32_t thisLine = it->FindLineContaining(lineFrame);
9774 if (thisLine < 0) {
9775 return result;
9776 }
9777
9778 bool atLineEdge;
9779 MOZ_TRY_VAR(do { auto mozTryVarTempResult_ = (needsVisualTraversal ? traversedFrame
->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame
->IsLogicallyAtLineEdge(it, thisLine, aDirection)); if ((__builtin_expect
(!!(mozTryVarTempResult_.isErr()), 0))) { return mozTryVarTempResult_
.propagateErr(); } (atLineEdge) = mozTryVarTempResult_.unwrap
(); } while (0)
9780 atLineEdge,do { auto mozTryVarTempResult_ = (needsVisualTraversal ? traversedFrame
->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame
->IsLogicallyAtLineEdge(it, thisLine, aDirection)); if ((__builtin_expect
(!!(mozTryVarTempResult_.isErr()), 0))) { return mozTryVarTempResult_
.propagateErr(); } (atLineEdge) = mozTryVarTempResult_.unwrap
(); } while (0)
9781 needsVisualTraversaldo { auto mozTryVarTempResult_ = (needsVisualTraversal ? traversedFrame
->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame
->IsLogicallyAtLineEdge(it, thisLine, aDirection)); if ((__builtin_expect
(!!(mozTryVarTempResult_.isErr()), 0))) { return mozTryVarTempResult_
.propagateErr(); } (atLineEdge) = mozTryVarTempResult_.unwrap
(); } while (0)
9782 ? traversedFrame->IsVisuallyAtLineEdge(it, thisLine, aDirection)do { auto mozTryVarTempResult_ = (needsVisualTraversal ? traversedFrame
->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame
->IsLogicallyAtLineEdge(it, thisLine, aDirection)); if ((__builtin_expect
(!!(mozTryVarTempResult_.isErr()), 0))) { return mozTryVarTempResult_
.propagateErr(); } (atLineEdge) = mozTryVarTempResult_.unwrap
(); } while (0)
9783 : traversedFrame->IsLogicallyAtLineEdge(it, thisLine, aDirection))do { auto mozTryVarTempResult_ = (needsVisualTraversal ? traversedFrame
->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame
->IsLogicallyAtLineEdge(it, thisLine, aDirection)); if ((__builtin_expect
(!!(mozTryVarTempResult_.isErr()), 0))) { return mozTryVarTempResult_
.propagateErr(); } (atLineEdge) = mozTryVarTempResult_.unwrap
(); } while (0)
;
9784 if (atLineEdge) {
9785 result.mJumpedLine = true;
9786 if (!aOptions.contains(PeekOffsetOption::JumpLines)) {
9787 return result; // we are done. cannot jump lines
9788 }
9789 int32_t lineToCheckWrap =
9790 aDirection == eDirPrevious ? thisLine - 1 : thisLine;
9791 if (lineToCheckWrap < 0 ||
9792 !it->GetLine(lineToCheckWrap).unwrap().mIsWrapped) {
9793 result.mJumpedHardBreak = true;
9794 }
9795 }
9796
9797 traversedFrame = frameIterator.Traverse(aDirection == eDirNext);
9798 if (!traversedFrame) {
9799 return result;
9800 }
9801
9802 if (aOptions.contains(PeekOffsetOption::StopAtPlaceholder) &&
9803 traversedFrame->IsPlaceholderFrame()) {
9804 // XXX If the placeholder frame does not have meaningful content, the user
9805 // may want to select as a word around the out-of-flow cotent. However,
9806 // non-text frame resets context in nsIFrame::PeekOffsetWord(). Therefore,
9807 // next text frame considers the new word starts from its edge. So, it's
9808 // not enough to implement such behavior with adding a check here whether
9809 // the real frame may change the word with its contents if it were not
9810 // out-of-flow.
9811 result.mFoundPlaceholder = true;
9812 return result;
9813 }
9814
9815 auto IsSelectable =
9816 [aOptions, nativeAnonymousSubtreeContent](const nsIFrame* aFrame) {
9817 if (!aFrame->IsSelectable(nullptr)) {
9818 return false;
9819 }
9820 // If the new frame is in a native anonymous subtree, we should treat
9821 // it as not selectable unless the frame and found frame are in same
9822 // subtree.
9823 if (aFrame->GetClosestNativeAnonymousSubtreeRoot() !=
9824 nativeAnonymousSubtreeContent) {
9825 return false;
9826 }
9827 return !aOptions.contains(PeekOffsetOption::ForceEditableRegion) ||
9828 aFrame->GetContent()->IsEditable();
9829 };
9830
9831 // Skip br frames, but only if we can select something before hitting the
9832 // end of the line or a non-selectable region.
9833 if (atLineEdge && aDirection == eDirPrevious &&
9834 traversedFrame->IsBrFrame()) {
9835 for (nsIFrame* current = traversedFrame->GetPrevSibling(); current;
9836 current = current->GetPrevSibling()) {
9837 if (!current->IsBlockOutside() && IsSelectable(current)) {
9838 if (!current->IsBrFrame()) {
9839 result.mIgnoredBrFrame = true;
9840 }
9841 break;
9842 }
9843 }
9844 if (result.mIgnoredBrFrame) {
9845 continue;
9846 }
9847 }
9848
9849 selectable = IsSelectable(traversedFrame);
9850 if (!selectable) {
9851 if (traversedFrame->IsSelectable(nullptr)) {
9852 result.mHasSelectableFrame = true;
9853 }
9854 result.mMovedOverNonSelectableText = true;
9855 }
9856 } // while (!selectable)
9857
9858 result.mOffset = (aDirection == eDirNext) ? 0 : -1;
9859
9860 if (aOptions.contains(PeekOffsetOption::Visual) &&
9861 nsBidiPresUtils::IsReversedDirectionFrame(traversedFrame)) {
9862 // The new frame is reverse-direction, go to the other end
9863 result.mOffset = -1 - result.mOffset;
9864 }
9865 result.mFrame = traversedFrame;
9866 return result;
9867}
9868
9869nsIFrame::SelectablePeekReport nsIFrame::GetFrameFromDirection(
9870 const PeekOffsetStruct& aPos) {
9871 return GetFrameFromDirection(aPos.mDirection, aPos.mOptions);
9872}
9873
9874nsView* nsIFrame::GetClosestView(nsPoint* aOffset) const {
9875 nsPoint offset(0, 0);
9876 for (const nsIFrame* f = this; f; f = f->GetParent()) {
9877 if (f->HasView()) {
9878 if (aOffset) *aOffset = offset;
9879 return f->GetView();
9880 }
9881 offset += f->GetPosition();
9882 }
9883
9884 MOZ_ASSERT_UNREACHABLE("No view on any parent? How did that happen?")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 view on any parent? How did that happen?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9884); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "No view on any parent? How did that happen?"
")"); do { *((volatile int*)__null) = 9884; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
9885 return nullptr;
9886}
9887
9888/* virtual */
9889void nsIFrame::ChildIsDirty(nsIFrame* aChild) {
9890 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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9892); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { *((volatile int*)
__null) = 9892; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
9891 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9892); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { *((volatile int*)
__null) = 9892; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
9892 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 9892); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "should never be called on a frame that doesn't "
"inherit from nsContainerFrame" ")"); do { *((volatile int*)
__null) = 9892; __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
9893}
9894
9895#ifdef ACCESSIBILITY1
9896a11y::AccType nsIFrame::AccessibleType() {
9897 if (IsTableCaption() && !GetRect().IsEmpty()) {
9898 return a11y::eHTMLCaptionType;
9899 }
9900 return a11y::eNoType;
9901}
9902#endif
9903
9904bool nsIFrame::ClearOverflowRects() {
9905 if (mOverflow.mType == OverflowStorageType::None) {
9906 return false;
9907 }
9908 if (mOverflow.mType == OverflowStorageType::Large) {
9909 RemoveProperty(OverflowAreasProperty());
9910 }
9911 mOverflow.mType = OverflowStorageType::None;
9912 return true;
9913}
9914
9915bool nsIFrame::SetOverflowAreas(const OverflowAreas& aOverflowAreas) {
9916 if (mOverflow.mType == OverflowStorageType::Large) {
9917 OverflowAreas* overflow = GetOverflowAreasProperty();
9918 bool changed = *overflow != aOverflowAreas;
9919 *overflow = aOverflowAreas;
9920
9921 // Don't bother with converting to the deltas form if we already
9922 // have a property.
9923 return changed;
9924 }
9925
9926 const nsRect& vis = aOverflowAreas.InkOverflow();
9927 uint32_t l = -vis.x, // left edge: positive delta is leftwards
9928 t = -vis.y, // top: positive is upwards
9929 r = vis.XMost() - mRect.width, // right: positive is rightwards
9930 b = vis.YMost() - mRect.height; // bottom: positive is downwards
9931 if (aOverflowAreas.ScrollableOverflow().IsEqualEdges(
9932 nsRect(nsPoint(0, 0), GetSize())) &&
9933 l <= InkOverflowDeltas::kMax && t <= InkOverflowDeltas::kMax &&
9934 r <= InkOverflowDeltas::kMax && b <= InkOverflowDeltas::kMax &&
9935 // we have to check these against zero because we *never* want to
9936 // set a frame as having no overflow in this function. This is
9937 // because FinishAndStoreOverflow calls this function prior to
9938 // SetRect based on whether the overflow areas match aNewSize.
9939 // In the case where the overflow areas exactly match mRect but
9940 // do not match aNewSize, we need to store overflow in a property
9941 // so that our eventual SetRect/SetSize will know that it has to
9942 // reset our overflow areas.
9943 (l | t | r | b) != 0) {
9944 InkOverflowDeltas oldDeltas = mOverflow.mInkOverflowDeltas;
9945 // It's a "small" overflow area so we store the deltas for each edge
9946 // directly in the frame, rather than allocating a separate rect.
9947 // If they're all zero, that's fine; we're setting things to
9948 // no-overflow.
9949 mOverflow.mInkOverflowDeltas.mLeft = l;
9950 mOverflow.mInkOverflowDeltas.mTop = t;
9951 mOverflow.mInkOverflowDeltas.mRight = r;
9952 mOverflow.mInkOverflowDeltas.mBottom = b;
9953 // There was no scrollable overflow before, and there isn't now.
9954 return oldDeltas != mOverflow.mInkOverflowDeltas;
9955 } else {
9956 bool changed =
9957 !aOverflowAreas.ScrollableOverflow().IsEqualEdges(
9958 nsRect(nsPoint(0, 0), GetSize())) ||
9959 !aOverflowAreas.InkOverflow().IsEqualEdges(InkOverflowFromDeltas());
9960
9961 // it's a large overflow area that we need to store as a property
9962 mOverflow.mType = OverflowStorageType::Large;
9963 AddProperty(OverflowAreasProperty(), new OverflowAreas(aOverflowAreas));
9964 return changed;
9965 }
9966}
9967
9968enum class ApplyTransform : bool { No, Yes };
9969
9970/**
9971 * Compute the outline inner rect (so without outline-width and outline-offset)
9972 * of aFrame, maybe iterating over its descendants, in aFrame's coordinate space
9973 * or its post-transform coordinate space (depending on aApplyTransform).
9974 */
9975static nsRect ComputeOutlineInnerRect(
9976 nsIFrame* aFrame, ApplyTransform aApplyTransform, bool& aOutValid,
9977 const nsSize* aSizeOverride = nullptr,
9978 const OverflowAreas* aOverflowOverride = nullptr) {
9979 const nsRect bounds(nsPoint(0, 0),
9980 aSizeOverride ? *aSizeOverride : aFrame->GetSize());
9981
9982 // The SVG container frames besides SVGTextFrame do not maintain
9983 // an accurate mRect. It will make the outline be larger than
9984 // we expect, we need to make them narrow to their children's outline.
9985 // aOutValid is set to false if the returned nsRect is not valid
9986 // and should not be included in the outline rectangle.
9987 aOutValid = !aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) ||
9988 !aFrame->IsSVGContainerFrame() || aFrame->IsSVGTextFrame();
9989
9990 nsRect u;
9991
9992 if (!aFrame->FrameMaintainsOverflow()) {
9993 return u;
9994 }
9995
9996 // Start from our border-box, transformed. See comment below about
9997 // transform of children.
9998 bool doTransform =
9999 aApplyTransform == ApplyTransform::Yes && aFrame->IsTransformed();
10000 TransformReferenceBox boundsRefBox(nullptr, bounds);
10001 if (doTransform) {
10002 u = nsDisplayTransform::TransformRect(bounds, aFrame, boundsRefBox);
10003 } else {
10004 u = bounds;
10005 }
10006
10007 if (aOutValid && !StaticPrefs::layout_outline_include_overflow()) {
10008 return u;
10009 }
10010
10011 // Only iterate through the children if the overflow areas suggest
10012 // that we might need to, and if the frame doesn't clip its overflow
10013 // anyway.
10014 if (aOverflowOverride) {
10015 if (!doTransform && bounds.IsEqualEdges(aOverflowOverride->InkOverflow()) &&
10016 bounds.IsEqualEdges(aOverflowOverride->ScrollableOverflow())) {
10017 return u;
10018 }
10019 } else {
10020 if (!doTransform && bounds.IsEqualEdges(aFrame->InkOverflowRect()) &&
10021 bounds.IsEqualEdges(aFrame->ScrollableOverflowRect())) {
10022 return u;
10023 }
10024 }
10025 const nsStyleDisplay* disp = aFrame->StyleDisplay();
10026 LayoutFrameType fType = aFrame->Type();
10027 if (fType == LayoutFrameType::ScrollContainer ||
10028 fType == LayoutFrameType::ListControl ||
10029 fType == LayoutFrameType::SVGOuterSVG) {
10030 return u;
10031 }
10032
10033 auto overflowClipAxes = aFrame->ShouldApplyOverflowClipping(disp);
10034 auto overflowClipMargin = aFrame->OverflowClipMargin(overflowClipAxes);
10035 if (overflowClipAxes == kPhysicalAxesBoth && overflowClipMargin == nsSize()) {
10036 return u;
10037 }
10038
10039 const nsStyleEffects* effects = aFrame->StyleEffects();
10040 Maybe<nsRect> clipPropClipRect =
10041 aFrame->GetClipPropClipRect(disp, effects, bounds.Size());
10042
10043 // Iterate over all children except pop-up, absolutely-positioned,
10044 // float, and overflow ones.
10045 const FrameChildListIDs skip = {
10046 FrameChildListID::Absolute, FrameChildListID::Fixed,
10047 FrameChildListID::Float, FrameChildListID::Overflow};
10048 for (const auto& [list, listID] : aFrame->ChildLists()) {
10049 if (skip.contains(listID)) {
10050 continue;
10051 }
10052
10053 for (nsIFrame* child : list) {
10054 if (child->IsPlaceholderFrame()) {
10055 continue;
10056 }
10057
10058 // Note that passing ApplyTransform::Yes when
10059 // child->Combines3DTransformWithAncestors() returns true is incorrect if
10060 // our aApplyTransform is No... but the opposite would be as well.
10061 // This is because elements within a preserve-3d scene are always
10062 // transformed up to the top of the scene. This means we don't have a
10063 // mechanism for getting a transform up to an intermediate point within
10064 // the scene. We choose to over-transform rather than under-transform
10065 // because this is consistent with other overflow areas.
10066 bool validRect = true;
10067 nsRect childRect =
10068 ComputeOutlineInnerRect(child, ApplyTransform::Yes, validRect) +
10069 child->GetPosition();
10070
10071 if (!validRect) {
10072 continue;
10073 }
10074
10075 if (clipPropClipRect) {
10076 // Intersect with the clip before transforming.
10077 childRect.IntersectRect(childRect, *clipPropClipRect);
10078 }
10079
10080 // Note that we transform each child separately according to
10081 // aFrame's transform, and then union, which gives a different
10082 // (smaller) result from unioning and then transforming the
10083 // union. This doesn't match the way we handle overflow areas
10084 // with 2-D transforms, though it does match the way we handle
10085 // overflow areas in preserve-3d 3-D scenes.
10086 if (doTransform && !child->Combines3DTransformWithAncestors()) {
10087 childRect =
10088 nsDisplayTransform::TransformRect(childRect, aFrame, boundsRefBox);
10089 }
10090
10091 // If a SVGContainer has a non-SVGContainer child, we assign
10092 // its child's outline to this SVGContainer directly.
10093 if (!aOutValid && validRect) {
10094 u = childRect;
10095 aOutValid = true;
10096 } else {
10097 u = u.UnionEdges(childRect);
10098 }
10099 }
10100 }
10101
10102 if (!overflowClipAxes.isEmpty()) {
10103 OverflowAreas::ApplyOverflowClippingOnRect(u, bounds, overflowClipAxes,
10104 overflowClipMargin);
10105 }
10106 return u;
10107}
10108
10109static void ComputeAndIncludeOutlineArea(nsIFrame* aFrame,
10110 OverflowAreas& aOverflowAreas,
10111 const nsSize& aNewSize) {
10112 const nsStyleOutline* outline = aFrame->StyleOutline();
10113 if (!outline->ShouldPaintOutline()) {
10114 return;
10115 }
10116
10117 // When the outline property is set on a :-moz-block-inside-inline-wrapper
10118 // pseudo-element, it inherited that outline from the inline that was broken
10119 // because it contained a block. In that case, we don't want a really wide
10120 // outline if the block inside the inline is narrow, so union the actual
10121 // contents of the anonymous blocks.
10122 nsIFrame* frameForArea = aFrame;
10123 do {
10124 PseudoStyleType pseudoType = frameForArea->Style()->GetPseudoType();
10125 if (pseudoType != PseudoStyleType::mozBlockInsideInlineWrapper) break;
10126 // If we're done, we really want it and all its later siblings.
10127 frameForArea = frameForArea->PrincipalChildList().FirstChild();
10128 NS_ASSERTION(frameForArea, "anonymous block with no children?")do { if (!(frameForArea)) { NS_DebugBreak(NS_DEBUG_ASSERTION,
"anonymous block with no children?", "frameForArea", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10128); MOZ_PretendNoReturn(); } } while (0)
;
10129 } while (frameForArea);
10130
10131 // Find the union of the border boxes of all descendants, or in
10132 // the block-in-inline case, all descendants we care about.
10133 //
10134 // Note that the interesting perspective-related cases are taken
10135 // care of by the code that handles those issues for overflow
10136 // calling FinishAndStoreOverflow again, which in turn calls this
10137 // function again. We still need to deal with preserve-3d a bit.
10138 nsRect innerRect;
10139 bool validRect = false;
10140 if (frameForArea == aFrame) {
10141 innerRect = ComputeOutlineInnerRect(aFrame, ApplyTransform::No, validRect,
10142 &aNewSize, &aOverflowAreas);
10143 } else {
10144 for (; frameForArea; frameForArea = frameForArea->GetNextSibling()) {
10145 nsRect r =
10146 ComputeOutlineInnerRect(frameForArea, ApplyTransform::Yes, validRect);
10147
10148 // Adjust for offsets transforms up to aFrame's pre-transform
10149 // (i.e., normal) coordinate space; see comments in
10150 // UnionBorderBoxes for some of the subtlety here.
10151 for (nsIFrame *f = frameForArea, *parent = f->GetParent();
10152 /* see middle of loop */; f = parent, parent = f->GetParent()) {
10153 r += f->GetPosition();
10154 if (parent == aFrame) {
10155 break;
10156 }
10157 if (parent->IsTransformed() && !f->Combines3DTransformWithAncestors()) {
10158 TransformReferenceBox refBox(parent);
10159 r = nsDisplayTransform::TransformRect(r, parent, refBox);
10160 }
10161 }
10162
10163 innerRect.UnionRect(innerRect, r);
10164 }
10165 }
10166
10167 // Keep this code in sync with nsDisplayOutline::GetInnerRect.
10168 if (innerRect == aFrame->GetRectRelativeToSelf()) {
10169 aFrame->RemoveProperty(nsIFrame::OutlineInnerRectProperty());
10170 } else {
10171 SetOrUpdateRectValuedProperty(aFrame, nsIFrame::OutlineInnerRectProperty(),
10172 innerRect);
10173 }
10174
10175 nsRect outerRect(innerRect);
10176 outerRect.Inflate(outline->EffectiveOffsetFor(outerRect));
10177
10178 if (outline->mOutlineStyle.IsAuto()) {
10179 nsPresContext* pc = aFrame->PresContext();
10180
10181 pc->Theme()->GetWidgetOverflow(pc->DeviceContext(), aFrame,
10182 StyleAppearance::FocusOutline, &outerRect);
10183 } else {
10184 const nscoord width = outline->GetOutlineWidth();
10185 outerRect.Inflate(width);
10186 }
10187
10188 nsRect& vo = aOverflowAreas.InkOverflow();
10189 vo = vo.UnionEdges(innerRect.Union(outerRect));
10190}
10191
10192bool nsIFrame::FinishAndStoreOverflow(OverflowAreas& aOverflowAreas,
10193 nsSize aNewSize, nsSize* aOldSize,
10194 const nsStyleDisplay* aStyleDisplay) {
10195 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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10196); AnnotateMozCrashReason("MOZ_ASSERT" "(" "FrameMaintainsOverflow()"
") (" "Don't call - overflow rects not maintained on these SVG frames"
")"); do { *((volatile int*)__null) = 10196; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
10196 "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"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10196); AnnotateMozCrashReason("MOZ_ASSERT" "(" "FrameMaintainsOverflow()"
") (" "Don't call - overflow rects not maintained on these SVG frames"
")"); do { *((volatile int*)__null) = 10196; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10197
10198 const nsStyleDisplay* disp = StyleDisplayWithOptionalParam(aStyleDisplay);
10199 bool hasTransform = IsTransformed();
10200
10201 nsRect bounds(nsPoint(0, 0), aNewSize);
10202 // Store the passed in overflow area if we are a preserve-3d frame or we have
10203 // a transform, and it's not just the frame bounds.
10204 if (hasTransform || Combines3DTransformWithAncestors()) {
10205 if (!aOverflowAreas.InkOverflow().IsEqualEdges(bounds) ||
10206 !aOverflowAreas.ScrollableOverflow().IsEqualEdges(bounds)) {
10207 OverflowAreas* initial = GetProperty(nsIFrame::InitialOverflowProperty());
10208 if (!initial) {
10209 AddProperty(nsIFrame::InitialOverflowProperty(),
10210 new OverflowAreas(aOverflowAreas));
10211 } else if (initial != &aOverflowAreas) {
10212 *initial = aOverflowAreas;
10213 }
10214 } else {
10215 RemoveProperty(nsIFrame::InitialOverflowProperty());
10216 }
10217#ifdef DEBUG1
10218 SetProperty(nsIFrame::DebugInitialOverflowPropertyApplied(), true);
10219#endif
10220 } else {
10221#ifdef DEBUG1
10222 RemoveProperty(nsIFrame::DebugInitialOverflowPropertyApplied());
10223#endif
10224 }
10225
10226 nsSize oldSize = mRect.Size();
10227 bool sizeChanged = ((aOldSize ? *aOldSize : oldSize) != aNewSize);
10228
10229 // Our frame size may not have been computed and set yet, but code under
10230 // functions such as ComputeEffectsRect (which we're about to call) use the
10231 // values that are stored in our frame rect to compute their results. We
10232 // need the results from those functions to be based on the frame size that
10233 // we *will* have, so we temporarily set our frame size here before calling
10234 // those functions.
10235 //
10236 // XXX Someone should document here why we revert the frame size before we
10237 // return rather than just leaving it set.
10238 //
10239 // We pass false here to avoid invalidating display items for this temporary
10240 // change. We sometimes reflow frames multiple times, with the final size
10241 // being the same as the initial. The single call to SetSize after reflow is
10242 // done will take care of invalidating display items if the size has actually
10243 // changed.
10244 SetSize(aNewSize, false);
10245
10246 const auto overflowClipAxes = ShouldApplyOverflowClipping(disp);
10247
10248 if (ChildrenHavePerspective(disp) && sizeChanged) {
10249 RecomputePerspectiveChildrenOverflow(this);
10250
10251 if (overflowClipAxes != kPhysicalAxesBoth) {
10252 aOverflowAreas.SetAllTo(bounds);
10253 DebugOnly<bool> ok = ComputeCustomOverflow(aOverflowAreas);
10254
10255 // ComputeCustomOverflow() should not return false, when
10256 // FrameMaintainsOverflow() returns true.
10257 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()"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10257); AnnotateMozCrashReason("MOZ_ASSERT" "(" "ok" ") (" "FrameMaintainsOverflow() != ComputeCustomOverflow()"
")"); do { *((volatile int*)__null) = 10257; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10258
10259 UnionChildOverflow(aOverflowAreas);
10260 }
10261 }
10262
10263 // This is now called FinishAndStoreOverflow() instead of
10264 // StoreOverflow() because frame-generic ways of adding overflow
10265 // can happen here, e.g. CSS2 outline and native theme.
10266 // If the overflow area width or height is nscoord_MAX, then a saturating
10267 // union may have encountered an overflow, so the overflow may not contain the
10268 // frame border-box. Don't warn in that case.
10269 // Don't warn for SVG either, since SVG doesn't need the overflow area
10270 // to contain the frame bounds.
10271#ifdef DEBUG1
10272 for (const auto otype : AllOverflowTypes()) {
10273 const nsRect& r = aOverflowAreas.Overflow(otype);
10274 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))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10278); MOZ_PretendNoReturn(); } } while (0)
10275 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))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10278); MOZ_PretendNoReturn(); } } while (0)
10276 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))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10278); MOZ_PretendNoReturn(); } } while (0)
10277 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))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10278); MOZ_PretendNoReturn(); } } while (0)
10278 "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))"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10278); MOZ_PretendNoReturn(); } } while (0)
;
10279 }
10280#endif
10281
10282 // Overflow area must always include the frame's top-left and bottom-right,
10283 // even if the frame rect is empty (so we can scroll to those positions).
10284 const bool shouldIncludeBounds = [&] {
10285 if (aNewSize.width == 0 && IsInlineFrame()) {
10286 // Pending a real fix for bug 426879, don't do this for inline frames with
10287 // zero width.
10288 return false;
10289 }
10290 if (HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
10291 // Do not do this for SVG either, since it will usually massively increase
10292 // the area unnecessarily (except for SVG that applies clipping, since
10293 // that's the pre-existing behavior, and breaks pre-rendering otherwise).
10294 // FIXME(bug 1770704): This check most likely wants to be removed or check
10295 // for specific frame types at least.
10296 return !overflowClipAxes.isEmpty();
10297 }
10298 return true;
10299 }();
10300
10301 if (shouldIncludeBounds) {
10302 for (const auto otype : AllOverflowTypes()) {
10303 nsRect& o = aOverflowAreas.Overflow(otype);
10304 o = o.UnionEdges(bounds);
10305 }
10306 }
10307
10308 // If we clip our children, clear accumulated overflow area in the affected
10309 // dimension(s). The children are actually clipped to the padding-box, but
10310 // since the overflow area should include the entire border-box, just set it
10311 // to the border-box size here.
10312 if (!overflowClipAxes.isEmpty()) {
10313 aOverflowAreas.ApplyClipping(bounds, overflowClipAxes,
10314 OverflowClipMargin(overflowClipAxes));
10315 }
10316
10317 ComputeAndIncludeOutlineArea(this, aOverflowAreas, aNewSize);
10318
10319 // Nothing in here should affect scrollable overflow.
10320 aOverflowAreas.InkOverflow() =
10321 ComputeEffectsRect(this, aOverflowAreas.InkOverflow(), aNewSize);
10322
10323 // Absolute position clipping
10324 const nsStyleEffects* effects = StyleEffects();
10325 Maybe<nsRect> clipPropClipRect = GetClipPropClipRect(disp, effects, aNewSize);
10326 if (clipPropClipRect) {
10327 for (const auto otype : AllOverflowTypes()) {
10328 nsRect& o = aOverflowAreas.Overflow(otype);
10329 o.IntersectRect(o, *clipPropClipRect);
10330 }
10331 }
10332
10333 /* If we're transformed, transform the overflow rect by the current
10334 * transformation. */
10335 if (hasTransform) {
10336 SetProperty(nsIFrame::PreTransformOverflowAreasProperty(),
10337 new OverflowAreas(aOverflowAreas));
10338
10339 if (Combines3DTransformWithAncestors()) {
10340 /* If we're a preserve-3d leaf frame, then our pre-transform overflow
10341 * should be correct. Our post-transform overflow is empty though, because
10342 * we only contribute to the overflow area of the preserve-3d root frame.
10343 * If we're an intermediate frame then the pre-transform overflow should
10344 * contain all our non-preserve-3d children, which is what we want. Again
10345 * we have no post-transform overflow.
10346 */
10347 aOverflowAreas.SetAllTo(nsRect());
10348 } else {
10349 TransformReferenceBox refBox(this);
10350 for (const auto otype : AllOverflowTypes()) {
10351 nsRect& o = aOverflowAreas.Overflow(otype);
10352 o = nsDisplayTransform::TransformRect(o, this, refBox);
10353 }
10354
10355 /* If we're the root of the 3d context, then we want to include the
10356 * overflow areas of all the participants. This won't have happened yet as
10357 * the code above set their overflow area to empty. Manually collect these
10358 * overflow areas now.
10359 */
10360 if (Extend3DContext(disp, effects)) {
10361 ComputePreserve3DChildrenOverflow(aOverflowAreas);
10362 }
10363 }
10364 } else {
10365 RemoveProperty(nsIFrame::PreTransformOverflowAreasProperty());
10366 }
10367
10368 /* Revert the size change in case some caller is depending on this. */
10369 SetSize(oldSize, false);
10370
10371 bool anyOverflowChanged;
10372 if (aOverflowAreas != OverflowAreas(bounds, bounds)) {
10373 anyOverflowChanged = SetOverflowAreas(aOverflowAreas);
10374 } else {
10375 anyOverflowChanged = ClearOverflowRects();
10376 }
10377
10378 if (anyOverflowChanged) {
10379 SVGObserverUtils::InvalidateDirectRenderingObservers(this);
10380 if (nsBlockFrame* block = do_QueryFrame(this)) {
10381 // NOTE(emilio): we need to use BeforeReflow::Yes, because we want to
10382 // invalidate in cases where we _used_ to have an overflow marker and no
10383 // longer do.
10384 if (TextOverflow::CanHaveOverflowMarkers(
10385 block, TextOverflow::BeforeReflow::Yes)) {
10386 DiscardDisplayItems(this, [](nsDisplayItem* aItem) {
10387 return aItem->GetType() == DisplayItemType::TYPE_TEXT_OVERFLOW;
10388 });
10389 SchedulePaint(PAINT_DEFAULT);
10390 }
10391 }
10392 }
10393 return anyOverflowChanged;
10394}
10395
10396void nsIFrame::RecomputePerspectiveChildrenOverflow(
10397 const nsIFrame* aStartFrame) {
10398 for (const auto& childList : ChildLists()) {
10399 for (nsIFrame* child : childList.mList) {
10400 if (!child->FrameMaintainsOverflow()) {
10401 continue; // frame does not maintain overflow rects
10402 }
10403 if (child->HasPerspective()) {
10404 OverflowAreas* overflow =
10405 child->GetProperty(nsIFrame::InitialOverflowProperty());
10406 nsRect bounds(nsPoint(0, 0), child->GetSize());
10407 if (overflow) {
10408 OverflowAreas overflowCopy = *overflow;
10409 child->FinishAndStoreOverflow(overflowCopy, bounds.Size());
10410 } else {
10411 OverflowAreas boundsOverflow;
10412 boundsOverflow.SetAllTo(bounds);
10413 child->FinishAndStoreOverflow(boundsOverflow, bounds.Size());
10414 }
10415 } else if (child->GetContent() == aStartFrame->GetContent() ||
10416 child->GetClosestFlattenedTreeAncestorPrimaryFrame() ==
10417 aStartFrame) {
10418 // If a frame is using perspective, then the size used to compute
10419 // perspective-origin is the size of the frame belonging to its parent
10420 // style. We must find any descendant frames using our size
10421 // (by recursing into frames that have the same containing block)
10422 // to update their overflow rects too.
10423 child->RecomputePerspectiveChildrenOverflow(aStartFrame);
10424 }
10425 }
10426 }
10427}
10428
10429void nsIFrame::ComputePreserve3DChildrenOverflow(
10430 OverflowAreas& aOverflowAreas) {
10431 // Find all descendants that participate in the 3d context, and include their
10432 // overflow. These descendants have an empty overflow, so won't have been
10433 // included in the normal overflow calculation. Any children that don't
10434 // participate have normal overflow, so will have been included already.
10435
10436 nsRect childVisual;
10437 nsRect childScrollable;
10438 for (const auto& childList : ChildLists()) {
10439 for (nsIFrame* child : childList.mList) {
10440 // If this child participates in the 3d context, then take the
10441 // pre-transform region (which contains all descendants that aren't
10442 // participating in the 3d context) and transform it into the 3d context
10443 // root coordinate space.
10444 if (child->Combines3DTransformWithAncestors()) {
10445 OverflowAreas childOverflow = child->GetOverflowAreasRelativeToSelf();
10446 TransformReferenceBox refBox(child);
10447 for (const auto otype : AllOverflowTypes()) {
10448 nsRect& o = childOverflow.Overflow(otype);
10449 o = nsDisplayTransform::TransformRect(o, child, refBox);
10450 }
10451
10452 aOverflowAreas.UnionWith(childOverflow);
10453
10454 // If this child also extends the 3d context, then recurse into it
10455 // looking for more participants.
10456 if (child->Extend3DContext()) {
10457 child->ComputePreserve3DChildrenOverflow(aOverflowAreas);
10458 }
10459 }
10460 }
10461 }
10462}
10463
10464bool nsIFrame::ZIndexApplies() const {
10465 return StyleDisplay()->IsPositionedStyle() || IsFlexOrGridItem() ||
10466 IsMenuPopupFrame();
10467}
10468
10469Maybe<int32_t> nsIFrame::ZIndex() const {
10470 if (!ZIndexApplies()) {
10471 return Nothing();
10472 }
10473 const auto& zIndex = StylePosition()->mZIndex;
10474 if (zIndex.IsAuto()) {
10475 return Nothing();
10476 }
10477 return Some(zIndex.AsInteger());
10478}
10479
10480bool nsIFrame::IsScrollAnchor(ScrollAnchorContainer** aOutContainer) {
10481 if (!mInScrollAnchorChain) {
10482 return false;
10483 }
10484
10485 nsIFrame* f = this;
10486
10487 // FIXME(emilio, bug 1629280): We should find a non-null anchor if we have the
10488 // flag set, but bug 1629280 makes it so that we cannot really assert it /
10489 // make this just a `while (true)`, and uncomment the below assertion.
10490 while (auto* container = ScrollAnchorContainer::FindFor(f)) {
10491 // MOZ_ASSERT(f->IsInScrollAnchorChain());
10492 if (nsIFrame* anchor = container->AnchorNode()) {
10493 if (anchor != this) {
10494 return false;
10495 }
10496 if (aOutContainer) {
10497 *aOutContainer = container;
10498 }
10499 return true;
10500 }
10501
10502 f = container->Frame();
10503 }
10504
10505 return false;
10506}
10507
10508bool nsIFrame::IsInScrollAnchorChain() const { return mInScrollAnchorChain; }
10509
10510void nsIFrame::SetInScrollAnchorChain(bool aInChain) {
10511 mInScrollAnchorChain = aInChain;
10512}
10513
10514uint32_t nsIFrame::GetDepthInFrameTree() const {
10515 uint32_t result = 0;
10516 for (nsContainerFrame* ancestor = GetParent(); ancestor;
10517 ancestor = ancestor->GetParent()) {
10518 result++;
10519 }
10520 return result;
10521}
10522
10523/**
10524 * This function takes a frame that is part of a block-in-inline split,
10525 * and _if_ that frame is an anonymous block created by an ib split it
10526 * returns the block's preceding inline. This is needed because the
10527 * split inline's style is the parent of the anonymous block's style.
10528 *
10529 * If aFrame is not an anonymous block, null is returned.
10530 */
10531static nsIFrame* GetIBSplitSiblingForAnonymousBlock(const nsIFrame* aFrame) {
10532 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!"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10532); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame" ") ("
"Must have a non-null frame!" ")"); do { *((volatile int*)__null
) = 10532; __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
10533 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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10534); MOZ_PretendNoReturn(); } } while (0)
10534 "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)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10534); MOZ_PretendNoReturn(); } } while (0)
;
10535
10536 if (aFrame->Style()->GetPseudoType() !=
10537 PseudoStyleType::mozBlockInsideInlineWrapper) {
10538 // it's not an anonymous block
10539 return nullptr;
10540 }
10541
10542 // Find the first continuation of the frame. (Ugh. This ends up
10543 // being O(N^2) when it is called O(N) times.)
10544 aFrame = aFrame->FirstContinuation();
10545
10546 /*
10547 * Now look up the nsGkAtoms::IBSplitPrevSibling
10548 * property.
10549 */
10550 nsIFrame* ibSplitSibling =
10551 aFrame->GetProperty(nsIFrame::IBSplitPrevSibling());
10552 NS_ASSERTION(ibSplitSibling, "Broken frame tree?")do { if (!(ibSplitSibling)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Broken frame tree?", "ibSplitSibling", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10552); MOZ_PretendNoReturn(); } } while (0)
;
10553 return ibSplitSibling;
10554}
10555
10556/**
10557 * Get the parent, corrected for the mangled frame tree resulting from
10558 * having a block within an inline. The result only differs from the
10559 * result of |GetParent| when |GetParent| returns an anonymous block
10560 * that was created for an element that was 'display: inline' because
10561 * that element contained a block.
10562 *
10563 * Also skip anonymous scrolled-content parents; inherit directly from the
10564 * outer scroll frame.
10565 *
10566 * Also skip NAC parents if the child frame is NAC.
10567 */
10568static nsIFrame* GetCorrectedParent(const nsIFrame* aFrame) {
10569 nsIFrame* parent = aFrame->GetParent();
10570 if (!parent) {
10571 return nullptr;
10572 }
10573
10574 // For a table caption we want the _inner_ table frame (unless it's anonymous)
10575 // as the style parent.
10576 if (aFrame->IsTableCaption()) {
10577 nsIFrame* innerTable = parent->PrincipalChildList().FirstChild();
10578 if (!innerTable->Style()->IsAnonBox()) {
10579 return innerTable;
10580 }
10581 }
10582
10583 // Table wrappers are always anon boxes; if we're in here for an outer
10584 // table, that actually means its the _inner_ table that wants to
10585 // know its parent. So get the pseudo of the inner in that case.
10586 auto pseudo = aFrame->Style()->GetPseudoType();
10587 if (pseudo == PseudoStyleType::tableWrapper) {
10588 pseudo =
10589 aFrame->PrincipalChildList().FirstChild()->Style()->GetPseudoType();
10590 }
10591
10592 // Prevent a NAC pseudo-element from inheriting from its NAC parent, and
10593 // inherit from the NAC generator element instead.
10594 if (pseudo != PseudoStyleType::NotPseudo) {
10595 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10595); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame->GetContent()"
")"); do { *((volatile int*)__null) = 10595; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10596 Element* element = Element::FromNode(aFrame->GetContent());
10597 // Make sure to avoid doing the fixup for non-element-backed pseudos like
10598 // ::first-line and such.
10599 if (element && !element->IsRootOfNativeAnonymousSubtree() &&
10600 element->GetPseudoElementType() == aFrame->Style()->GetPseudoType()) {
10601 while (parent->GetContent() &&
10602 !parent->GetContent()->IsRootOfNativeAnonymousSubtree()) {
10603 parent = parent->GetInFlowParent();
10604 }
10605 parent = parent->GetInFlowParent();
10606 }
10607 }
10608
10609 return nsIFrame::CorrectStyleParentFrame(parent, pseudo);
10610}
10611
10612/* static */
10613nsIFrame* nsIFrame::CorrectStyleParentFrame(nsIFrame* aProspectiveParent,
10614 PseudoStyleType aChildPseudo) {
10615 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10615); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aProspectiveParent"
") (" "Must have a prospective parent" ")"); do { *((volatile
int*)__null) = 10615; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
10616
10617 if (aChildPseudo != PseudoStyleType::NotPseudo) {
10618 // Non-inheriting anon boxes have no style parent frame at all.
10619 if (PseudoStyle::IsNonInheritingAnonBox(aChildPseudo)) {
10620 return nullptr;
10621 }
10622
10623 // Other anon boxes are parented to their actual parent already, except
10624 // for non-elements. Those should not be treated as an anon box.
10625 if (PseudoStyle::IsAnonBox(aChildPseudo) &&
10626 !nsCSSAnonBoxes::IsNonElement(aChildPseudo)) {
10627 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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10629); MOZ_PretendNoReturn(); } } while (0)
10628 "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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10629); MOZ_PretendNoReturn(); } } while (0)
10629 "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"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10629); MOZ_PretendNoReturn(); } } while (0)
;
10630 return aProspectiveParent;
10631 }
10632 }
10633
10634 // Otherwise, walk up out of all anon boxes. For placeholder frames, walk out
10635 // of all pseudo-elements as well. Otherwise ReparentComputedStyle could
10636 // cause style data to be out of sync with the frame tree.
10637 nsIFrame* parent = aProspectiveParent;
10638 do {
10639 if (parent->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
10640 nsIFrame* sibling = GetIBSplitSiblingForAnonymousBlock(parent);
10641
10642 if (sibling) {
10643 // |parent| was a block in an {ib} split; use the inline as
10644 // |the style parent.
10645 parent = sibling;
10646 }
10647 }
10648
10649 if (!parent->Style()->IsPseudoOrAnonBox()) {
10650 return parent;
10651 }
10652
10653 if (!parent->Style()->IsAnonBox() && aChildPseudo != PseudoStyleType::MAX) {
10654 // nsPlaceholderFrame passes in PseudoStyleType::MAX for
10655 // aChildPseudo (even though that's not a valid pseudo-type) just to
10656 // trigger this behavior of walking up to the nearest non-pseudo
10657 // ancestor.
10658 return parent;
10659 }
10660
10661 parent = parent->GetInFlowParent();
10662 } while (parent);
10663
10664 if (aProspectiveParent->Style()->GetPseudoType() ==
10665 PseudoStyleType::viewportScroll) {
10666 // aProspectiveParent is the scrollframe for a viewport
10667 // and the kids are the anonymous scrollbars
10668 return aProspectiveParent;
10669 }
10670
10671 // We can get here if the root element is absolutely positioned.
10672 // We can't test for this very accurately, but it can only happen
10673 // when the prospective parent is a canvas frame.
10674 NS_ASSERTION(aProspectiveParent->IsCanvasFrame(),do { if (!(aProspectiveParent->IsCanvasFrame())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Should have found a parent before this"
, "aProspectiveParent->IsCanvasFrame()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10675); MOZ_PretendNoReturn(); } } while (0)
10675 "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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10675); MOZ_PretendNoReturn(); } } while (0)
;
10676 return nullptr;
10677}
10678
10679ComputedStyle* nsIFrame::DoGetParentComputedStyle(
10680 nsIFrame** aProviderFrame) const {
10681 *aProviderFrame = nullptr;
10682
10683 // Handle display:contents and the root frame, when there's no parent frame
10684 // to inherit from.
10685 if (MOZ_LIKELY(mContent)(__builtin_expect(!!(mContent), 1))) {
10686 Element* parentElement = mContent->GetFlattenedTreeParentElement();
10687 if (MOZ_LIKELY(parentElement)(__builtin_expect(!!(parentElement), 1))) {
10688 auto pseudo = Style()->GetPseudoType();
10689 if (pseudo == PseudoStyleType::NotPseudo || !mContent->IsElement() ||
10690 (!PseudoStyle::IsAnonBox(pseudo) &&
10691 // Ensure that we don't return the display:contents style
10692 // of the parent content for pseudos that have the same content
10693 // as their primary frame (like -moz-list-bullets do):
10694 IsPrimaryFrame()) ||
10695 /* if next is true then it's really a request for the table frame's
10696 parent context, see nsTable[Outer]Frame::GetParentComputedStyle. */
10697 pseudo == PseudoStyleType::tableWrapper) {
10698 // In some edge cases involving display: contents, we may end up here
10699 // for something that's pending to be reframed. In this case we return
10700 // the wrong style from here (because we've already lost track of it!),
10701 // but it's not a big deal as we're going to be reframed anyway.
10702 if (MOZ_LIKELY(parentElement->HasServoData())(__builtin_expect(!!(parentElement->HasServoData()), 1)) &&
10703 Servo_Element_IsDisplayContents(parentElement)) {
10704 RefPtr<ComputedStyle> style =
10705 ServoStyleSet::ResolveServoStyle(*parentElement);
10706 // NOTE(emilio): we return a weak reference because the element also
10707 // holds the style context alive. This is a bit silly (we could've
10708 // returned a weak ref directly), but it's probably not worth
10709 // optimizing, given this function has just one caller which is rare,
10710 // and this path is rare itself.
10711 return style;
10712 }
10713 }
10714 } else {
10715 if (Style()->GetPseudoType() == PseudoStyleType::NotPseudo) {
10716 // We're a frame for the root. We have no style parent.
10717 return nullptr;
10718 }
10719 }
10720 }
10721
10722 if (!HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
10723 /*
10724 * If this frame is an anonymous block created when an inline with a block
10725 * inside it got split, then the parent style is on its preceding inline. We
10726 * can get to it using GetIBSplitSiblingForAnonymousBlock.
10727 */
10728 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
10729 nsIFrame* ibSplitSibling = GetIBSplitSiblingForAnonymousBlock(this);
10730 if (ibSplitSibling) {
10731 return (*aProviderFrame = ibSplitSibling)->Style();
10732 }
10733 }
10734
10735 // If this frame is one of the blocks that split an inline, we must
10736 // return the "special" inline parent, i.e., the parent that this
10737 // frame would have if we didn't mangle the frame structure.
10738 *aProviderFrame = GetCorrectedParent(this);
10739 return *aProviderFrame ? (*aProviderFrame)->Style() : nullptr;
10740 }
10741
10742 // We're an out-of-flow frame. For out-of-flow frames, we must
10743 // resolve underneath the placeholder's parent. The placeholder is
10744 // reached from the first-in-flow.
10745 nsPlaceholderFrame* placeholder = FirstInFlow()->GetPlaceholderFrame();
10746 if (!placeholder) {
10747 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10747); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "no placeholder frame for out-of-flow frame"
")"); do { *((volatile int*)__null) = 10747; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10748 *aProviderFrame = GetCorrectedParent(this);
10749 return *aProviderFrame ? (*aProviderFrame)->Style() : nullptr;
10750 }
10751 return placeholder->GetParentComputedStyleForOutOfFlow(aProviderFrame);
10752}
10753
10754void nsIFrame::GetLastLeaf(nsIFrame** aFrame) {
10755 if (!aFrame || !*aFrame ||
10756 // Don't enter into native anoymous subtree from the root like <input> or
10757 // <textarea>.
10758 (*aFrame)->ContentIsRootOfNativeAnonymousSubtree()) {
10759 return;
10760 }
10761 for (nsIFrame* maybeLastLeaf = (*aFrame)->PrincipalChildList().LastChild();
10762 maybeLastLeaf;) {
10763 nsIFrame* lastChildNotInSubTree = nullptr;
10764 for (nsIFrame* child = maybeLastLeaf; child;
10765 child = child->GetPrevSibling()) {
10766 // ignore anonymous elements, e.g. mozTableAdd* mozTableRemove*
10767 // see bug 278197 comment #12 #13 for details
10768 if (!child->ContentIsRootOfNativeAnonymousSubtree()) {
10769 lastChildNotInSubTree = child;
10770 break;
10771 }
10772 }
10773 if (!lastChildNotInSubTree) {
10774 return;
10775 }
10776 *aFrame = lastChildNotInSubTree;
10777 maybeLastLeaf = lastChildNotInSubTree->PrincipalChildList().LastChild();
10778 }
10779}
10780
10781void nsIFrame::GetFirstLeaf(nsIFrame** aFrame) {
10782 if (!aFrame || !*aFrame) return;
10783 nsIFrame* child = *aFrame;
10784 while (true) {
10785 child = child->PrincipalChildList().FirstChild();
10786 if (!child) return; // nothing to do
10787 *aFrame = child;
10788 }
10789}
10790
10791bool nsIFrame::IsFocusableDueToScrollFrame() {
10792 if (!IsScrollContainerFrame()) {
10793 if (nsFieldSetFrame* fieldset = do_QueryFrame(this)) {
10794 // TODO: Do we have similar special-cases like this where we can have
10795 // anonymous scrollable boxes hanging off a primary frame?
10796 if (nsIFrame* inner = fieldset->GetInner()) {
10797 return inner->IsFocusableDueToScrollFrame();
10798 }
10799 }
10800 return false;
10801 }
10802 if (!mContent->IsHTMLElement()) {
10803 return false;
10804 }
10805 if (mContent->IsRootOfNativeAnonymousSubtree()) {
10806 return false;
10807 }
10808 if (!mContent->GetParent()) {
10809 return false;
10810 }
10811 if (mContent->AsElement()->HasAttr(nsGkAtoms::tabindex)) {
10812 return false;
10813 }
10814 // Elements with scrollable view are focusable with script & tabbable
10815 // Otherwise you couldn't scroll them with keyboard, which is an accessibility
10816 // issue (e.g. Section 508 rules) However, we don't make them to be focusable
10817 // with the mouse, because the extra focus outlines are considered
10818 // unnecessarily ugly. When clicked on, the selection position within the
10819 // element will be enough to make them keyboard scrollable.
10820 auto* scrollContainer = static_cast<ScrollContainerFrame*>(this);
10821 if (scrollContainer->GetScrollStyles().IsHiddenInBothDirections()) {
10822 return false;
10823 }
10824 if (scrollContainer->GetScrollRange().IsEqualEdges(nsRect())) {
10825 return false;
10826 }
10827 return true;
10828}
10829
10830Focusable nsIFrame::IsFocusable(IsFocusableFlags aFlags) {
10831 // cannot focus content in print preview mode. Only the root can be focused,
10832 // but that's handled elsewhere.
10833 if (PresContext()->Type() == nsPresContext::eContext_PrintPreview) {
10834 return {};
10835 }
10836
10837 if (!mContent || !mContent->IsElement()) {
10838 return {};
10839 }
10840
10841 if (!(aFlags & IsFocusableFlags::IgnoreVisibility) &&
10842 !IsVisibleConsideringAncestors()) {
10843 return {};
10844 }
10845
10846 const StyleUserFocus uf = StyleUI()->UserFocus();
10847 if (uf == StyleUserFocus::None) {
10848 return {};
10849 }
10850 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10850); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!StyleUI()->IsInert()"
") (" "inert implies -moz-user-focus: none" ")"); do { *((volatile
int*)__null) = 10850; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
10851
10852 const PseudoStyleType pseudo = Style()->GetPseudoType();
10853 if (pseudo == PseudoStyleType::anonymousItem) {
10854 return {};
10855 }
10856
10857 Focusable focusable;
10858 if (auto* xul = nsXULElement::FromNode(mContent)) {
10859 // As a legacy special-case, -moz-user-focus controls focusability and
10860 // tabability of XUL elements in some circumstances (which default to
10861 // -moz-user-focus: ignore).
10862 auto focusability = xul->GetXULFocusability(aFlags);
10863 focusable.mFocusable =
10864 focusability.mForcedFocusable.valueOr(uf == StyleUserFocus::Normal);
10865 if (focusable) {
10866 focusable.mTabIndex = focusability.mForcedTabIndexIfFocusable.valueOr(0);
10867 }
10868 } else {
10869 focusable = mContent->IsFocusableWithoutStyle(aFlags);
10870 }
10871
10872 if (focusable) {
10873 return focusable;
10874 }
10875
10876 // If we're focusing with the mouse we never focus scroll areas.
10877 if (!(aFlags & IsFocusableFlags::WithMouse) &&
10878 IsFocusableDueToScrollFrame()) {
10879 return {true, 0};
10880 }
10881
10882 // FIXME(emilio): some callers rely on somewhat broken return values
10883 // (focusable = false, but non-negative tab-index) from
10884 // IsFocusableWithoutStyle (for image maps in particular).
10885 return focusable;
10886}
10887
10888/**
10889 * @return true if this text frame ends with a newline character which is
10890 * treated as preformatted. It should return false if this is not a text frame.
10891 */
10892bool nsIFrame::HasSignificantTerminalNewline() const { return false; }
10893
10894static StyleVerticalAlignKeyword ConvertSVGDominantBaselineToVerticalAlign(
10895 StyleDominantBaseline aDominantBaseline) {
10896 // Most of these are approximate mappings.
10897 switch (aDominantBaseline) {
10898 case StyleDominantBaseline::Hanging:
10899 case StyleDominantBaseline::TextBeforeEdge:
10900 return StyleVerticalAlignKeyword::TextTop;
10901 case StyleDominantBaseline::TextAfterEdge:
10902 case StyleDominantBaseline::Ideographic:
10903 return StyleVerticalAlignKeyword::TextBottom;
10904 case StyleDominantBaseline::Central:
10905 case StyleDominantBaseline::Middle:
10906 case StyleDominantBaseline::Mathematical:
10907 return StyleVerticalAlignKeyword::Middle;
10908 case StyleDominantBaseline::Auto:
10909 case StyleDominantBaseline::Alphabetic:
10910 return StyleVerticalAlignKeyword::Baseline;
10911 default:
10912 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10912); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "unexpected aDominantBaseline value"
")"); do { *((volatile int*)__null) = 10912; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
10913 return StyleVerticalAlignKeyword::Baseline;
10914 }
10915}
10916
10917Maybe<StyleVerticalAlignKeyword> nsIFrame::VerticalAlignEnum() const {
10918 if (IsInSVGTextSubtree()) {
10919 StyleDominantBaseline dominantBaseline = StyleSVG()->mDominantBaseline;
10920 return Some(ConvertSVGDominantBaselineToVerticalAlign(dominantBaseline));
10921 }
10922
10923 const auto& verticalAlign = StyleDisplay()->mVerticalAlign;
10924 if (verticalAlign.IsKeyword()) {
10925 return Some(verticalAlign.AsKeyword());
10926 }
10927
10928 return Nothing();
10929}
10930
10931void nsIFrame::UpdateStyleOfChildAnonBox(nsIFrame* aChildFrame,
10932 ServoRestyleState& aRestyleState) {
10933#ifdef DEBUG1
10934 nsIFrame* parent = aChildFrame->GetInFlowParent();
10935 if (aChildFrame->IsTableFrame()) {
10936 parent = parent->GetParent();
10937 }
10938 if (parent->IsLineFrame()) {
10939 parent = parent->GetParent();
10940 }
10941 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10942); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
") (" "This should only be used for children!" ")"); do { *(
(volatile int*)__null) = 10942; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
10942 "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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10942); AnnotateMozCrashReason("MOZ_ASSERT" "(" "nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent) == this"
") (" "This should only be used for children!" ")"); do { *(
(volatile int*)__null) = 10942; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
10943#endif // DEBUG
10944 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10946); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { *((volatile
int*)__null) = 10946; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
10945 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10946); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { *((volatile
int*)__null) = 10946; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
10946 "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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10946); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetContent() || !aChildFrame->GetContent() || aChildFrame->GetContent() == GetContent()"
") (" "What content node is it a frame for?" ")"); do { *((volatile
int*)__null) = 10946; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
10947 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10948); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetPrevContinuation()"
") (" "Only first continuations should end up here" ")"); do
{ *((volatile int*)__null) = 10948; __attribute__((nomerge))
::abort(); } while (false); } } while (false)
10948 "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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10948); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetPrevContinuation()"
") (" "Only first continuations should end up here" ")"); do
{ *((volatile int*)__null) = 10948; __attribute__((nomerge))
::abort(); } while (false); } } while (false)
;
10949
10950 // We could force the caller to pass in the pseudo, since some callers know it
10951 // statically... But this API is a bit nicer.
10952 auto pseudo = aChildFrame->Style()->GetPseudoType();
10953 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?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10953); AnnotateMozCrashReason("MOZ_ASSERT" "(" "PseudoStyle::IsAnonBox(pseudo)"
") (" "Child is not an anon box?" ")"); do { *((volatile int
*)__null) = 10953; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
10954 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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10955); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
") (" "Why did the caller bother calling us?" ")"); do { *((
volatile int*)__null) = 10955; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
10955 "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?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10955); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!PseudoStyle::IsNonInheritingAnonBox(pseudo)"
") (" "Why did the caller bother calling us?" ")"); do { *((
volatile int*)__null) = 10955; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
10956
10957 // Anon boxes inherit from their parent; that's us.
10958 RefPtr<ComputedStyle> newContext =
10959 aRestyleState.StyleSet().ResolveInheritingAnonymousBoxStyle(pseudo,
10960 Style());
10961
10962 nsChangeHint childHint =
10963 UpdateStyleOfOwnedChildFrame(aChildFrame, newContext, aRestyleState);
10964
10965 // Now that we've updated the style on aChildFrame, check whether it itself
10966 // has anon boxes to deal with.
10967 ServoRestyleState childrenState(*aChildFrame, aRestyleState, childHint,
10968 ServoRestyleState::CanUseHandledHints::Yes);
10969 aChildFrame->UpdateStyleOfOwnedAnonBoxes(childrenState);
10970
10971 // Assuming anon boxes don't have ::backdrop associated with them... if that
10972 // ever changes, we'd need to handle that here, like we do in
10973 // RestyleManager::ProcessPostTraversal
10974
10975 // We do need to handle block pseudo-elements here, though. Especially list
10976 // bullets.
10977 if (nsBlockFrame* block = do_QueryFrame(aChildFrame)) {
10978 block->UpdatePseudoElementStyles(childrenState);
10979 }
10980}
10981
10982/* static */
10983nsChangeHint nsIFrame::UpdateStyleOfOwnedChildFrame(
10984 nsIFrame* aChildFrame, ComputedStyle* aNewComputedStyle,
10985 ServoRestyleState& aRestyleState,
10986 const Maybe<ComputedStyle*>& aContinuationComputedStyle) {
10987 MOZ_ASSERT(!aChildFrame->GetAdditionalComputedStyle(0),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aChildFrame->GetAdditionalComputedStyle(0))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!aChildFrame->GetAdditionalComputedStyle(0)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("!aChildFrame->GetAdditionalComputedStyle(0)"
" (" "We don't handle additional styles here" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10988); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetAdditionalComputedStyle(0)"
") (" "We don't handle additional styles here" ")"); do { *(
(volatile int*)__null) = 10988; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
10988 "We don't handle additional styles here")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aChildFrame->GetAdditionalComputedStyle(0))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!aChildFrame->GetAdditionalComputedStyle(0)))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("!aChildFrame->GetAdditionalComputedStyle(0)"
" (" "We don't handle additional styles here" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 10988); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aChildFrame->GetAdditionalComputedStyle(0)"
") (" "We don't handle additional styles here" ")"); do { *(
(volatile int*)__null) = 10988; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
10989
10990 // Figure out whether we have an actual change. It's important that we do
10991 // this, for several reasons:
10992 //
10993 // 1) Even if all the child's changes are due to properties it inherits from
10994 // us, it's possible that no one ever asked us for those style structs and
10995 // hence changes to them aren't reflected in the changes handled at all.
10996 //
10997 // 2) Content can change stylesheets that change the styles of pseudos, and
10998 // extensions can add/remove stylesheets that change the styles of
10999 // anonymous boxes directly.
11000 uint32_t equalStructs; // Not used, actually.
11001 nsChangeHint childHint = aChildFrame->Style()->CalcStyleDifference(
11002 *aNewComputedStyle, &equalStructs);
11003
11004 // If aChildFrame is out of flow, then aRestyleState's "changes handled by the
11005 // parent" doesn't apply to it, because it may have some other parent in the
11006 // frame tree.
11007 if (!aChildFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
11008 childHint = NS_RemoveSubsumedHints(
11009 childHint, aRestyleState.ChangesHandledFor(aChildFrame));
11010 }
11011 if (childHint) {
11012 if (childHint & nsChangeHint_ReconstructFrame) {
11013 // If we generate a reconstruct here, remove any non-reconstruct hints we
11014 // may have already generated for this content.
11015 aRestyleState.ChangeList().PopChangesForContent(
11016 aChildFrame->GetContent());
11017 }
11018 aRestyleState.ChangeList().AppendChange(
11019 aChildFrame, aChildFrame->GetContent(), childHint);
11020 }
11021
11022 aChildFrame->SetComputedStyle(aNewComputedStyle);
11023 ComputedStyle* continuationStyle = aContinuationComputedStyle
11024 ? *aContinuationComputedStyle
11025 : aNewComputedStyle;
11026 for (nsIFrame* kid = aChildFrame->GetNextContinuation(); kid;
11027 kid = kid->GetNextContinuation()) {
11028 MOZ_ASSERT(!kid->GetAdditionalComputedStyle(0))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!kid->GetAdditionalComputedStyle(0))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!kid->GetAdditionalComputedStyle(0)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!kid->GetAdditionalComputedStyle(0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11028); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!kid->GetAdditionalComputedStyle(0)"
")"); do { *((volatile int*)__null) = 11028; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11029 kid->SetComputedStyle(continuationStyle);
11030 }
11031
11032 return childHint;
11033}
11034
11035/* static */
11036void nsIFrame::AddInPopupStateBitToDescendants(nsIFrame* aFrame) {
11037 if (!aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP) &&
11038 aFrame->TrackingVisibility()) {
11039 // Assume all frames in popups are visible.
11040 aFrame->IncApproximateVisibleCount();
11041 }
11042
11043 aFrame->AddStateBits(NS_FRAME_IN_POPUP);
11044
11045 for (const auto& childList : aFrame->CrossDocChildLists()) {
11046 for (nsIFrame* child : childList.mList) {
11047 AddInPopupStateBitToDescendants(child);
11048 }
11049 }
11050}
11051
11052/* static */
11053void nsIFrame::RemoveInPopupStateBitFromDescendants(nsIFrame* aFrame) {
11054 if (!aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP) ||
11055 nsLayoutUtils::IsPopup(aFrame)) {
11056 return;
11057 }
11058
11059 aFrame->RemoveStateBits(NS_FRAME_IN_POPUP);
11060
11061 if (aFrame->TrackingVisibility()) {
11062 // We assume all frames in popups are visible, so this decrement balances
11063 // out the increment in AddInPopupStateBitToDescendants above.
11064 aFrame->DecApproximateVisibleCount();
11065 }
11066 for (const auto& childList : aFrame->CrossDocChildLists()) {
11067 for (nsIFrame* child : childList.mList) {
11068 RemoveInPopupStateBitFromDescendants(child);
11069 }
11070 }
11071}
11072
11073void nsIFrame::SetParent(nsContainerFrame* aParent) {
11074 // If our parent is a wrapper anon box, our new parent should be too. We
11075 // _can_ change parent if our parent is a wrapper anon box, because some
11076 // wrapper anon boxes can have continuations.
11077 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11078); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->Style()->IsInheritingAnonBox()"
")"); do { *((volatile int*)__null) = 11078; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false); } } while
(false)
11078 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()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11078); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent->Style()->IsInheritingAnonBox()"
")"); do { *((volatile int*)__null) = 11078; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false); } } while
(false)
;
11079
11080 // Note that the current mParent may already be destroyed at this point.
11081 mParent = aParent;
11082 MOZ_DIAGNOSTIC_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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11082); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "!mParent || PresShell() == mParent->PresShell()"
")"); do { *((volatile int*)__null) = 11082; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11083
11084 if (HasAnyStateBits(NS_FRAME_HAS_VIEW | NS_FRAME_HAS_CHILD_WITH_VIEW)) {
11085 for (nsIFrame* f = aParent;
11086 f && !f->HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW);
11087 f = f->GetParent()) {
11088 f->AddStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW);
11089 }
11090 }
11091
11092 if (HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
11093 for (nsIFrame* f = aParent; f; f = f->GetParent()) {
11094 if (f->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
11095 break;
11096 }
11097 f->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
11098 }
11099 }
11100
11101 if (HasAnyStateBits(NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE)) {
11102 for (nsIFrame* f = aParent; f; f = f->GetParent()) {
11103 if (f->HasAnyStateBits(
11104 NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE)) {
11105 break;
11106 }
11107 f->AddStateBits(NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE);
11108 }
11109 }
11110
11111 if (HasInvalidFrameInSubtree()) {
11112 for (nsIFrame* f = aParent;
11113 f && !f->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT |
11114 NS_FRAME_IS_NONDISPLAY);
11115 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
11116 f->AddStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT);
11117 }
11118 }
11119
11120 if (aParent->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
11121 AddInPopupStateBitToDescendants(this);
11122 } else {
11123 RemoveInPopupStateBitFromDescendants(this);
11124 }
11125
11126 // If our new parent only has invalid children, then we just invalidate
11127 // ourselves too. This is probably faster than clearing the flag all
11128 // the way up the frame tree.
11129 if (aParent->HasAnyStateBits(NS_FRAME_ALL_DESCENDANTS_NEED_PAINT)) {
11130 InvalidateFrame();
11131 } else {
11132 SchedulePaint();
11133 }
11134}
11135
11136bool nsIFrame::IsStackingContext(const nsStyleDisplay* aStyleDisplay,
11137 const nsStyleEffects* aStyleEffects) {
11138 // Properties that influence the output of this function should be handled in
11139 // change_bits_for_longhand as well.
11140 if (HasOpacity(aStyleDisplay, aStyleEffects, nullptr)) {
11141 return true;
11142 }
11143 if (IsTransformed()) {
11144 return true;
11145 }
11146 auto willChange = aStyleDisplay->mWillChange.bits;
11147 if (aStyleDisplay->IsContainPaint() || aStyleDisplay->IsContainLayout() ||
11148 willChange & StyleWillChangeBits::CONTAIN) {
11149 if (SupportsContainLayoutAndPaint()) {
11150 return true;
11151 }
11152 }
11153 // strictly speaking, 'perspective' doesn't require visual atomicity,
11154 // but the spec says it acts like the rest of these
11155 if (aStyleDisplay->HasPerspectiveStyle() ||
11156 willChange & StyleWillChangeBits::PERSPECTIVE) {
11157 if (SupportsCSSTransforms()) {
11158 return true;
11159 }
11160 }
11161 if (!StylePosition()->mZIndex.IsAuto() ||
11162 willChange & StyleWillChangeBits::Z_INDEX) {
11163 if (ZIndexApplies()) {
11164 return true;
11165 }
11166 }
11167 return aStyleEffects->mMixBlendMode != StyleBlend::Normal ||
11168 SVGIntegrationUtils::UsingEffectsForFrame(this) ||
11169 aStyleDisplay->IsPositionForcingStackingContext() ||
11170 aStyleDisplay->mIsolation != StyleIsolation::Auto ||
11171 willChange & StyleWillChangeBits::STACKING_CONTEXT_UNCONDITIONAL;
11172}
11173
11174bool nsIFrame::IsStackingContext() {
11175 return IsStackingContext(StyleDisplay(), StyleEffects());
11176}
11177
11178static bool IsFrameScrolledOutOfView(const nsIFrame* aTarget,
11179 const nsRect& aTargetRect,
11180 const nsIFrame* aParent) {
11181 // The ancestor frame we are checking if it clips out aTargetRect relative to
11182 // aTarget.
11183 nsIFrame* clipParent = nullptr;
11184
11185 // find the first scrollable frame or root frame if we are in a fixed pos
11186 // subtree
11187 for (nsIFrame* f = const_cast<nsIFrame*>(aParent); f;
11188 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
11189 ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(f);
11190 if (scrollContainerFrame) {
11191 clipParent = f;
11192 break;
11193 }
11194 if (f->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
11195 nsLayoutUtils::IsReallyFixedPos(f)) {
11196 clipParent = f->GetParent();
11197 break;
11198 }
11199 }
11200
11201 if (!clipParent) {
11202 // Even if we couldn't find the nearest scrollable frame, it might mean we
11203 // are in an out-of-process iframe, try to see if |aTarget| frame is
11204 // scrolled out of view in an scrollable frame in a cross-process ancestor
11205 // document.
11206 return nsLayoutUtils::FrameIsScrolledOutOfViewInCrossProcess(aTarget);
11207 }
11208
11209 nsRect clipRect = clipParent->InkOverflowRectRelativeToSelf();
11210 // We consider that the target is scrolled out if the scrollable (or root)
11211 // frame is empty.
11212 if (clipRect.IsEmpty()) {
11213 return true;
11214 }
11215
11216 nsRect transformedRect = nsLayoutUtils::TransformFrameRectToAncestor(
11217 aTarget, aTargetRect, clipParent);
11218
11219 if (transformedRect.IsEmpty()) {
11220 // If the transformed rect is empty it represents a line or a point that we
11221 // should check is outside the the scrollable rect.
11222 if (transformedRect.x > clipRect.XMost() ||
11223 transformedRect.y > clipRect.YMost() ||
11224 clipRect.x > transformedRect.XMost() ||
11225 clipRect.y > transformedRect.YMost()) {
11226 return true;
11227 }
11228 } else if (!transformedRect.Intersects(clipRect)) {
11229 return true;
11230 }
11231
11232 nsIFrame* parent = clipParent->GetParent();
11233 if (!parent) {
11234 return false;
11235 }
11236
11237 return IsFrameScrolledOutOfView(aTarget, aTargetRect, parent);
11238}
11239
11240bool nsIFrame::IsScrolledOutOfView() const {
11241 nsRect rect = InkOverflowRectRelativeToSelf();
11242 return IsFrameScrolledOutOfView(this, rect, this);
11243}
11244
11245gfx::Matrix nsIFrame::ComputeWidgetTransform() const {
11246 const nsStyleUIReset* uiReset = StyleUIReset();
11247 if (uiReset->mMozWindowTransform.IsNone()) {
11248 return gfx::Matrix();
11249 }
11250
11251 TransformReferenceBox refBox(nullptr, nsRect(nsPoint(), GetSize()));
11252
11253 nsPresContext* presContext = PresContext();
11254 int32_t appUnitsPerDevPixel = presContext->AppUnitsPerDevPixel();
11255 gfx::Matrix4x4 matrix = nsStyleTransformMatrix::ReadTransforms(
11256 uiReset->mMozWindowTransform, refBox, float(appUnitsPerDevPixel));
11257
11258 // Apply the -moz-window-transform-origin translation to the matrix.
11259 const StyleTransformOrigin& origin = uiReset->mWindowTransformOrigin;
11260 Point transformOrigin = nsStyleTransformMatrix::Convert2DPosition(
11261 origin.horizontal, origin.vertical, refBox, appUnitsPerDevPixel);
11262 matrix.ChangeBasis(Point3D(transformOrigin.x, transformOrigin.y, 0));
11263
11264 gfx::Matrix result2d;
11265 if (!matrix.CanDraw2D(&result2d)) {
11266 // FIXME: It would be preferable to reject non-2D transforms at parse time.
11267 NS_WARNING(NS_DebugBreak(NS_DEBUG_WARNING, "-moz-window-transform does not describe a 2D transform, "
"but only 2d transforms are supported", nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11269)
11268 "-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, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11269)
11269 "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, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11269)
;
11270 return gfx::Matrix();
11271 }
11272
11273 return result2d;
11274}
11275
11276void nsIFrame::DoUpdateStyleOfOwnedAnonBoxes(ServoRestyleState& aRestyleState) {
11277 // As a special case, we check for {ib}-split block frames here, rather
11278 // than have an nsInlineFrame::AppendDirectlyOwnedAnonBoxes implementation
11279 // that returns them.
11280 //
11281 // (If we did handle them in AppendDirectlyOwnedAnonBoxes, we would have to
11282 // return *all* of the in-flow {ib}-split block frames, not just the first
11283 // one. For restyling, we really just need the first in flow, and the other
11284 // user of the AppendOwnedAnonBoxes API, AllChildIterator, doesn't need to
11285 // know about them at all, since these block frames never create NAC. So we
11286 // avoid any unncessary hashtable lookups for the {ib}-split frames by calling
11287 // UpdateStyleOfOwnedAnonBoxesForIBSplit directly here.)
11288 if (IsInlineFrame()) {
11289 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
11290 static_cast<nsInlineFrame*>(this)->UpdateStyleOfOwnedAnonBoxesForIBSplit(
11291 aRestyleState);
11292 }
11293 return;
11294 }
11295
11296 AutoTArray<OwnedAnonBox, 4> frames;
11297 AppendDirectlyOwnedAnonBoxes(frames);
11298 for (OwnedAnonBox& box : frames) {
11299 if (box.mUpdateStyleFn) {
11300 box.mUpdateStyleFn(this, box.mAnonBoxFrame, aRestyleState);
11301 } else {
11302 UpdateStyleOfChildAnonBox(box.mAnonBoxFrame, aRestyleState);
11303 }
11304 }
11305}
11306
11307/* virtual */
11308void nsIFrame::AppendDirectlyOwnedAnonBoxes(nsTArray<OwnedAnonBox>& aResult) {
11309 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11309); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)"
")"); do { *((volatile int*)__null) = 11309; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11310 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11312); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { *((volatile int*)__null) = 11312; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
11311 "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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11312); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { *((volatile int*)__null) = 11312; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
11312 "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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11312); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Subclasses that have directly owned anonymous boxes should override "
"this method!" ")"); do { *((volatile int*)__null) = 11312; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
11313}
11314
11315void nsIFrame::DoAppendOwnedAnonBoxes(nsTArray<OwnedAnonBox>& aResult) {
11316 size_t i = aResult.Length();
11317 AppendDirectlyOwnedAnonBoxes(aResult);
11318
11319 // After appending the directly owned anonymous boxes of this frame to
11320 // aResult above, we need to check each of them to see if they own
11321 // any anonymous boxes themselves. Note that we keep progressing
11322 // through aResult, looking for additional entries in aResult from these
11323 // subsequent AppendDirectlyOwnedAnonBoxes calls. (Thus we can't
11324 // use a ranged for loop here.)
11325
11326 while (i < aResult.Length()) {
11327 nsIFrame* f = aResult[i].mAnonBoxFrame;
11328 if (f->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES)) {
11329 f->AppendDirectlyOwnedAnonBoxes(aResult);
11330 }
11331 ++i;
11332 }
11333}
11334
11335nsIFrame::CaretPosition::CaretPosition() : mContentOffset(0) {}
11336
11337nsIFrame::CaretPosition::~CaretPosition() = default;
11338
11339bool nsIFrame::HasCSSAnimations() {
11340 auto* collection = AnimationCollection<CSSAnimation>::Get(this);
11341 return collection && !collection->mAnimations.IsEmpty();
11342}
11343
11344bool nsIFrame::HasCSSTransitions() {
11345 auto* collection = AnimationCollection<CSSTransition>::Get(this);
11346 return collection && !collection->mAnimations.IsEmpty();
11347}
11348
11349void nsIFrame::AddSizeOfExcludingThisForTree(nsWindowSizes& aSizes) const {
11350 aSizes.mLayoutFramePropertiesSize +=
11351 mProperties.SizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
11352
11353 // We don't do this for Gecko because this stuff is stored in the nsPresArena
11354 // and so measured elsewhere.
11355 if (!aSizes.mState.HaveSeenPtr(mComputedStyle)) {
11356 mComputedStyle->AddSizeOfIncludingThis(aSizes,
11357 &aSizes.mLayoutComputedValuesNonDom);
11358 }
11359
11360 // And our additional styles.
11361 int32_t index = 0;
11362 while (auto* extra = GetAdditionalComputedStyle(index++)) {
11363 if (!aSizes.mState.HaveSeenPtr(extra)) {
11364 extra->AddSizeOfIncludingThis(aSizes,
11365 &aSizes.mLayoutComputedValuesNonDom);
11366 }
11367 }
11368
11369 for (const auto& childList : ChildLists()) {
11370 for (const nsIFrame* f : childList.mList) {
11371 f->AddSizeOfExcludingThisForTree(aSizes);
11372 }
11373 }
11374}
11375
11376nsRect nsIFrame::GetCompositorHitTestArea(nsDisplayListBuilder* aBuilder) {
11377 nsRect area;
11378
11379 ScrollContainerFrame* scrollContainerFrame =
11380 nsLayoutUtils::GetScrollContainerFrameFor(this);
11381 if (scrollContainerFrame) {
11382 // If this frame is the scrolled frame of a scroll container frame, then we
11383 // need to pick up the area corresponding to the overflow rect as well.
11384 // Otherwise the parts of the overflow that are not occupied by descendants
11385 // get skipped and the APZ code sends touch events to the content underneath
11386 // instead. See https://bugzilla.mozilla.org/show_bug.cgi?id=1127773#c15.
11387 area = ScrollableOverflowRect();
11388 } else {
11389 area = GetRectRelativeToSelf();
11390 }
11391
11392 if (!area.IsEmpty()) {
11393 return area + aBuilder->ToReferenceFrame(this);
11394 }
11395
11396 return area;
11397}
11398
11399CompositorHitTestInfo nsIFrame::GetCompositorHitTestInfo(
11400 nsDisplayListBuilder* aBuilder) {
11401 CompositorHitTestInfo result = CompositorHitTestInvisibleToHit;
11402
11403 if (aBuilder->IsInsidePointerEventsNoneDoc()) {
11404 // Somewhere up the parent document chain is a subdocument with pointer-
11405 // events:none set on it.
11406 return result;
11407 }
11408 if (!GetParent()) {
11409 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()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11409); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsViewportFrame()"
")"); do { *((volatile int*)__null) = 11409; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11410 // Viewport frames are never event targets, other frames, like canvas
11411 // frames, are the event targets for any regions viewport frames may cover.
11412 return result;
11413 }
11414 if (Style()->PointerEvents() == StylePointerEvents::None) {
11415 return result;
11416 }
11417 if (!StyleVisibility()->IsVisible()) {
11418 return result;
11419 }
11420
11421 // Anything that didn't match the above conditions is visible to hit-testing.
11422 result = CompositorHitTestFlags::eVisibleToHitTest;
11423 SVGUtils::MaskUsage maskUsage = SVGUtils::DetermineMaskUsage(this, false);
11424 if (maskUsage.UsingMaskOrClipPath()) {
11425 // If WebRender is enabled, simple clip-paths can be converted into WR
11426 // clips that WR knows how to hit-test against, so we don't need to mark
11427 // it as an irregular area.
11428 if (!maskUsage.IsSimpleClipShape()) {
11429 result += CompositorHitTestFlags::eIrregularArea;
11430 }
11431 }
11432
11433 if (aBuilder->IsBuildingNonLayerizedScrollbar()) {
11434 // Scrollbars may be painted into a layer below the actual layer they will
11435 // scroll, and therefore wheel events may be dispatched to the outer frame
11436 // instead of the intended scrollframe. To address this, we force a d-t-c
11437 // region on scrollbar frames that won't be placed in their own layer. See
11438 // bug 1213324 for details.
11439 result += CompositorHitTestFlags::eInactiveScrollframe;
11440 } else if (aBuilder->GetAncestorHasApzAwareEventHandler()) {
11441 result += CompositorHitTestFlags::eApzAwareListeners;
11442 } else if (IsRangeFrame()) {
11443 // Range frames handle touch events directly without having a touch listener
11444 // so we need to let APZ know that this area cares about events.
11445 result += CompositorHitTestFlags::eApzAwareListeners;
11446 }
11447
11448 if (aBuilder->IsTouchEventPrefEnabledDoc()) {
11449 // Inherit the touch-action flags from the parent, if there is one. We do
11450 // this because of how the touch-action on a frame combines the touch-action
11451 // from ancestor DOM elements. Refer to the documentation in
11452 // TouchActionHelper.cpp for details; this code is meant to be equivalent to
11453 // that code, but woven into the top-down recursive display list building
11454 // process.
11455 CompositorHitTestInfo inheritedTouchAction =
11456 aBuilder->GetCompositorHitTestInfo() & CompositorHitTestTouchActionMask;
11457
11458 nsIFrame* touchActionFrame = this;
11459 if (ScrollContainerFrame* scrollContainerFrame =
11460 nsLayoutUtils::GetScrollContainerFrameFor(this)) {
11461 ScrollStyles ss = scrollContainerFrame->GetScrollStyles();
11462 if (ss.mVertical != StyleOverflow::Hidden ||
11463 ss.mHorizontal != StyleOverflow::Hidden) {
11464 touchActionFrame = scrollContainerFrame;
11465 // On scrollframes, stop inheriting the pan-x and pan-y flags; instead,
11466 // reset them back to zero to allow panning on the scrollframe unless we
11467 // encounter an element that disables it that's inside the scrollframe.
11468 // This is equivalent to the |considerPanning| variable in
11469 // TouchActionHelper.cpp, but for a top-down traversal.
11470 CompositorHitTestInfo panMask(
11471 CompositorHitTestFlags::eTouchActionPanXDisabled,
11472 CompositorHitTestFlags::eTouchActionPanYDisabled);
11473 inheritedTouchAction -= panMask;
11474 }
11475 }
11476
11477 result += inheritedTouchAction;
11478
11479 const StyleTouchAction touchAction = touchActionFrame->UsedTouchAction();
11480 // The CSS allows the syntax auto | none | [pan-x || pan-y] | manipulation
11481 // so we can eliminate some combinations of things.
11482 if (touchAction == StyleTouchAction::AUTO) {
11483 // nothing to do
11484 } else if (touchAction & StyleTouchAction::MANIPULATION) {
11485 result += CompositorHitTestFlags::eTouchActionAnimatingZoomDisabled;
11486 } else {
11487 // This path handles the cases none | [pan-x || pan-y || pinch-zoom] so
11488 // double-tap is disabled in here.
11489 if (!(touchAction & StyleTouchAction::PINCH_ZOOM)) {
11490 result += CompositorHitTestFlags::eTouchActionPinchZoomDisabled;
11491 }
11492
11493 result += CompositorHitTestFlags::eTouchActionAnimatingZoomDisabled;
11494
11495 if (!(touchAction & StyleTouchAction::PAN_X)) {
11496 result += CompositorHitTestFlags::eTouchActionPanXDisabled;
11497 }
11498 if (!(touchAction & StyleTouchAction::PAN_Y)) {
11499 result += CompositorHitTestFlags::eTouchActionPanYDisabled;
11500 }
11501 if (touchAction & StyleTouchAction::NONE) {
11502 // all the touch-action disabling flags will already have been set above
11503 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11503); AnnotateMozCrashReason("MOZ_ASSERT" "(" "result.contains(CompositorHitTestTouchActionMask)"
")"); do { *((volatile int*)__null) = 11503; __attribute__((
nomerge)) ::abort(); } while (false); } } while (false)
;
11504 }
11505 }
11506 }
11507
11508 const Maybe<ScrollDirection> scrollDirection =
11509 aBuilder->GetCurrentScrollbarDirection();
11510 if (scrollDirection.isSome()) {
11511 if (GetContent()->IsXULElement(nsGkAtoms::thumb)) {
11512 const bool thumbGetsLayer = aBuilder->GetCurrentScrollbarTarget() !=
11513 layers::ScrollableLayerGuid::NULL_SCROLL_ID;
11514 if (thumbGetsLayer) {
11515 result += CompositorHitTestFlags::eScrollbarThumb;
11516 } else {
11517 result += CompositorHitTestFlags::eInactiveScrollframe;
11518 }
11519 }
11520
11521 if (*scrollDirection == ScrollDirection::eVertical) {
11522 result += CompositorHitTestFlags::eScrollbarVertical;
11523 }
11524
11525 // includes the ScrollbarFrame, SliderFrame, anything else that
11526 // might be inside the xul:scrollbar
11527 result += CompositorHitTestFlags::eScrollbar;
11528 }
11529
11530 return result;
11531}
11532
11533// Returns true if we can guarantee there is no visible descendants.
11534static bool HasNoVisibleDescendants(const nsIFrame* aFrame) {
11535 for (const auto& childList : aFrame->ChildLists()) {
11536 for (nsIFrame* f : childList.mList) {
11537 if (nsPlaceholderFrame::GetRealFrameFor(f)
11538 ->IsVisibleOrMayHaveVisibleDescendants()) {
11539 return false;
11540 }
11541 }
11542 }
11543 return true;
11544}
11545
11546void nsIFrame::UpdateVisibleDescendantsState() {
11547 if (StyleVisibility()->IsVisible()) {
11548 // Notify invisible ancestors that a visible descendant exists now.
11549 nsIFrame* ancestor;
11550 for (ancestor = GetInFlowParent();
11551 ancestor && !ancestor->StyleVisibility()->IsVisible();
11552 ancestor = ancestor->GetInFlowParent()) {
11553 ancestor->mAllDescendantsAreInvisible = false;
11554 }
11555 } else {
11556 mAllDescendantsAreInvisible = HasNoVisibleDescendants(this);
11557 }
11558}
11559
11560PhysicalAxes nsIFrame::ShouldApplyOverflowClipping(
11561 const nsStyleDisplay* aDisp) const {
11562 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" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11562); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aDisp == StyleDisplay()"
") (" "Wrong display struct" ")"); do { *((volatile int*)__null
) = 11562; __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
11563
11564 // 'contain:paint', which we handle as 'overflow:clip' here. Except for
11565 // scrollframes we don't need contain:paint to add any clipping, because
11566 // the scrollable frame will already clip overflowing content, and because
11567 // 'contain:paint' should prevent all means of escaping that clipping
11568 // (e.g. because it forms a fixed-pos containing block).
11569 if (aDisp->IsContainPaint() && !IsScrollContainerFrame() &&
11570 SupportsContainLayoutAndPaint()) {
11571 return kPhysicalAxesBoth;
11572 }
11573
11574 // and overflow:hidden that we should interpret as clip
11575 if (aDisp->mOverflowX == StyleOverflow::Hidden &&
11576 aDisp->mOverflowY == StyleOverflow::Hidden) {
11577 // REVIEW: these are the frame types that set up clipping.
11578 LayoutFrameType type = Type();
11579 switch (type) {
11580 case LayoutFrameType::CheckboxRadio:
11581 case LayoutFrameType::ComboboxControl:
11582 case LayoutFrameType::HTMLButtonControl:
11583 case LayoutFrameType::ListControl:
11584 case LayoutFrameType::Meter:
11585 case LayoutFrameType::Progress:
11586 case LayoutFrameType::Range:
11587 case LayoutFrameType::SubDocument:
11588 case LayoutFrameType::SVGForeignObject:
11589 case LayoutFrameType::SVGInnerSVG:
11590 case LayoutFrameType::SVGOuterSVG:
11591 case LayoutFrameType::SVGSymbol:
11592 case LayoutFrameType::Table:
11593 case LayoutFrameType::TableCell:
11594 return kPhysicalAxesBoth;
11595 case LayoutFrameType::TextInput:
11596 // It has an anonymous scroll container frame that handles any overflow.
11597 return PhysicalAxes();
11598 default:
11599 break;
11600 }
11601 }
11602
11603 // clip overflow:clip, except for nsListControlFrame which is
11604 // a ScrollContainerFrame sub-class.
11605 if (MOZ_UNLIKELY((aDisp->mOverflowX == mozilla::StyleOverflow::Clip ||(__builtin_expect(!!((aDisp->mOverflowX == mozilla::StyleOverflow
::Clip || aDisp->mOverflowY == mozilla::StyleOverflow::Clip
) && !IsListControlFrame()), 0))
11606 aDisp->mOverflowY == mozilla::StyleOverflow::Clip) &&(__builtin_expect(!!((aDisp->mOverflowX == mozilla::StyleOverflow
::Clip || aDisp->mOverflowY == mozilla::StyleOverflow::Clip
) && !IsListControlFrame()), 0))
11607 !IsListControlFrame())(__builtin_expect(!!((aDisp->mOverflowX == mozilla::StyleOverflow
::Clip || aDisp->mOverflowY == mozilla::StyleOverflow::Clip
) && !IsListControlFrame()), 0))
) {
11608 // FIXME: we could use GetViewportScrollStylesOverrideElement() here instead
11609 // if that worked correctly in a print context. (see bug 1654667)
11610 const auto* element = Element::FromNodeOrNull(GetContent());
11611 if (!element ||
11612 !PresContext()->ElementWouldPropagateScrollStyles(*element)) {
11613 PhysicalAxes axes;
11614 if (aDisp->mOverflowX == mozilla::StyleOverflow::Clip) {
11615 axes += PhysicalAxis::Horizontal;
11616 }
11617 if (aDisp->mOverflowY == mozilla::StyleOverflow::Clip) {
11618 axes += PhysicalAxis::Vertical;
11619 }
11620 return axes;
11621 }
11622 }
11623
11624 if (HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
11625 return PhysicalAxes();
11626 }
11627
11628 return IsSuppressedScrollableBlockForPrint() ? kPhysicalAxesBoth
11629 : PhysicalAxes();
11630}
11631
11632bool nsIFrame::IsSuppressedScrollableBlockForPrint() const {
11633 // This condition needs to match the suppressScrollFrame logic in the frame
11634 // constructor.
11635 if (!PresContext()->IsPaginated() || !IsBlockFrame() ||
11636 !StyleDisplay()->IsScrollableOverflow() ||
11637 !StyleDisplay()->IsBlockOutsideStyle() ||
11638 mContent->IsInNativeAnonymousSubtree()) {
11639 return false;
11640 }
11641 if (auto* element = Element::FromNode(mContent);
11642 element && PresContext()->ElementWouldPropagateScrollStyles(*element)) {
11643 return false;
11644 }
11645 return true;
11646}
11647
11648bool nsIFrame::HasUnreflowedContainerQueryAncestor() const {
11649 // If this frame has done the first reflow, its ancestors are guaranteed to
11650 // have as well.
11651 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) ||
11652 !PresContext()->HasContainerQueryFrames()) {
11653 return false;
11654 }
11655 for (nsIFrame* cur = GetInFlowParent(); cur; cur = cur->GetInFlowParent()) {
11656 if (!cur->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
11657 // Done first reflow from this ancestor up, including query containers.
11658 return false;
11659 }
11660 if (cur->StyleDisplay()->IsQueryContainer()) {
11661 return true;
11662 }
11663 }
11664 // No query container from this frame up to root.
11665 return false;
11666}
11667
11668bool nsIFrame::ShouldBreakBefore(
11669 const ReflowInput::BreakType aBreakType) const {
11670 const auto* display = StyleDisplay();
11671 return ShouldBreakBetween(display, display->mBreakBefore, aBreakType);
11672}
11673
11674bool nsIFrame::ShouldBreakAfter(const ReflowInput::BreakType aBreakType) const {
11675 const auto* display = StyleDisplay();
11676 return ShouldBreakBetween(display, display->mBreakAfter, aBreakType);
11677}
11678
11679bool nsIFrame::ShouldBreakBetween(
11680 const nsStyleDisplay* aDisplay, const StyleBreakBetween aBreakBetween,
11681 const ReflowInput::BreakType aBreakType) const {
11682 const bool shouldBreakBetween = [&] {
11683 switch (aBreakBetween) {
11684 case StyleBreakBetween::Always:
11685 return true;
11686 case StyleBreakBetween::Auto:
11687 case StyleBreakBetween::Avoid:
11688 return false;
11689 case StyleBreakBetween::Page:
11690 case StyleBreakBetween::Left:
11691 case StyleBreakBetween::Right:
11692 return aBreakType == ReflowInput::BreakType::Page;
11693 }
11694 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!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11694); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown break-between value!" ")"
); do { *((volatile int*)__null) = 11694; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
11695 return false;
11696 }();
11697
11698 if (!shouldBreakBetween) {
11699 return false;
11700 }
11701 if (IsAbsolutelyPositioned(aDisplay)) {
11702 // 'break-before' and 'break-after' properties does not apply to
11703 // absolutely-positioned boxes.
11704 return false;
11705 }
11706 return true;
11707}
11708
11709#ifdef DEBUG1
11710static void GetTagName(nsIFrame* aFrame, nsIContent* aContent, int aResultSize,
11711 char* aResult) {
11712 if (aContent) {
11713 snprintf(aResult, aResultSize, "%s@%p",
11714 nsAtomCString(aContent->NodeInfo()->NameAtom()).get(), aFrame);
11715 } else {
11716 snprintf(aResult, aResultSize, "@%p", aFrame);
11717 }
11718}
11719
11720void nsIFrame::Trace(const char* aMethod, bool aEnter) {
11721 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
11722 char tagbuf[40];
11723 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
11724 printf_stderr("%s: %s %s", tagbuf, aEnter ? "enter" : "exit", aMethod);
11725 }
11726}
11727
11728void nsIFrame::Trace(const char* aMethod, bool aEnter,
11729 const nsReflowStatus& aStatus) {
11730 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
11731 char tagbuf[40];
11732 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
11733 printf_stderr("%s: %s %s, status=%scomplete%s", tagbuf,
11734 aEnter ? "enter" : "exit", aMethod,
11735 aStatus.IsIncomplete() ? "not" : "",
11736 (aStatus.NextInFlowNeedsReflow()) ? "+reflow" : "");
11737 }
11738}
11739
11740void nsIFrame::TraceMsg(const char* aFormatString, ...) {
11741 if (NS_FRAME_LOG_TEST(sFrameLogModule, NS_FRAME_TRACE_CALLS)(int(((mozilla::LogModule*)(sFrameLogModule))->Level()) &
(0x1))
) {
11742 // Format arguments into a buffer
11743 char argbuf[200];
11744 va_list ap;
11745 va_start(ap, aFormatString)__builtin_va_start(ap, aFormatString);
11746 VsprintfLiteral(argbuf, aFormatString, ap);
11747 va_end(ap)__builtin_va_end(ap);
11748
11749 char tagbuf[40];
11750 GetTagName(this, mContent, sizeof(tagbuf), tagbuf);
11751 printf_stderr("%s: %s", tagbuf, argbuf);
11752 }
11753}
11754
11755void nsIFrame::VerifyDirtyBitSet(const nsFrameList& aFrameList) {
11756 for (nsIFrame* f : aFrameList) {
11757 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)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsIFrame.cpp"
, 11757); MOZ_PretendNoReturn(); } } while (0)
;
11758 }
11759}
11760
11761// Validation of SideIsVertical.
11762# define CASE(side, result) \
11763 static_assert(SideIsVertical(side) == result, "SideIsVertical is wrong")
11764CASE(eSideTop, false);
11765CASE(eSideRight, true);
11766CASE(eSideBottom, false);
11767CASE(eSideLeft, true);
11768# undef CASE
11769
11770// Validation of HalfCornerIsX.
11771# define CASE(corner, result) \
11772 static_assert(HalfCornerIsX(corner) == result, "HalfCornerIsX is wrong")
11773CASE(eCornerTopLeftX, true);
11774CASE(eCornerTopLeftY, false);
11775CASE(eCornerTopRightX, true);
11776CASE(eCornerTopRightY, false);
11777CASE(eCornerBottomRightX, true);
11778CASE(eCornerBottomRightY, false);
11779CASE(eCornerBottomLeftX, true);
11780CASE(eCornerBottomLeftY, false);
11781# undef CASE
11782
11783// Validation of HalfToFullCorner.
11784# define CASE(corner, result) \
11785 static_assert(HalfToFullCorner(corner) == result, \
11786 "HalfToFullCorner is " \
11787 "wrong")
11788CASE(eCornerTopLeftX, eCornerTopLeft);
11789CASE(eCornerTopLeftY, eCornerTopLeft);
11790CASE(eCornerTopRightX, eCornerTopRight);
11791CASE(eCornerTopRightY, eCornerTopRight);
11792CASE(eCornerBottomRightX, eCornerBottomRight);
11793CASE(eCornerBottomRightY, eCornerBottomRight);
11794CASE(eCornerBottomLeftX, eCornerBottomLeft);
11795CASE(eCornerBottomLeftY, eCornerBottomLeft);
11796# undef CASE
11797
11798// Validation of FullToHalfCorner.
11799# define CASE(corner, vert, result) \
11800 static_assert(FullToHalfCorner(corner, vert) == result, \
11801 "FullToHalfCorner is wrong")
11802CASE(eCornerTopLeft, false, eCornerTopLeftX);
11803CASE(eCornerTopLeft, true, eCornerTopLeftY);
11804CASE(eCornerTopRight, false, eCornerTopRightX);
11805CASE(eCornerTopRight, true, eCornerTopRightY);
11806CASE(eCornerBottomRight, false, eCornerBottomRightX);
11807CASE(eCornerBottomRight, true, eCornerBottomRightY);
11808CASE(eCornerBottomLeft, false, eCornerBottomLeftX);
11809CASE(eCornerBottomLeft, true, eCornerBottomLeftY);
11810# undef CASE
11811
11812// Validation of SideToFullCorner.
11813# define CASE(side, second, result) \
11814 static_assert(SideToFullCorner(side, second) == result, \
11815 "SideToFullCorner is wrong")
11816CASE(eSideTop, false, eCornerTopLeft);
11817CASE(eSideTop, true, eCornerTopRight);
11818
11819CASE(eSideRight, false, eCornerTopRight);
11820CASE(eSideRight, true, eCornerBottomRight);
11821
11822CASE(eSideBottom, false, eCornerBottomRight);
11823CASE(eSideBottom, true, eCornerBottomLeft);
11824
11825CASE(eSideLeft, false, eCornerBottomLeft);
11826CASE(eSideLeft, true, eCornerTopLeft);
11827# undef CASE
11828
11829// Validation of SideToHalfCorner.
11830# define CASE(side, second, parallel, result) \
11831 static_assert(SideToHalfCorner(side, second, parallel) == result, \
11832 "SideToHalfCorner is wrong")
11833CASE(eSideTop, false, true, eCornerTopLeftX);
11834CASE(eSideTop, false, false, eCornerTopLeftY);
11835CASE(eSideTop, true, true, eCornerTopRightX);
11836CASE(eSideTop, true, false, eCornerTopRightY);
11837
11838CASE(eSideRight, false, false, eCornerTopRightX);
11839CASE(eSideRight, false, true, eCornerTopRightY);
11840CASE(eSideRight, true, false, eCornerBottomRightX);
11841CASE(eSideRight, true, true, eCornerBottomRightY);
11842
11843CASE(eSideBottom, false, true, eCornerBottomRightX);
11844CASE(eSideBottom, false, false, eCornerBottomRightY);
11845CASE(eSideBottom, true, true, eCornerBottomLeftX);
11846CASE(eSideBottom, true, false, eCornerBottomLeftY);
11847
11848CASE(eSideLeft, false, false, eCornerBottomLeftX);
11849CASE(eSideLeft, false, true, eCornerBottomLeftY);
11850CASE(eSideLeft, true, false, eCornerTopLeftX);
11851CASE(eSideLeft, true, true, eCornerTopLeftY);
11852# undef CASE
11853
11854#endif