Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp
Warning:line 4761, column 14
Value stored to 'end' during its initialization 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_svg1.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/svg -fcoverage-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/svg -resource-dir /usr/lib/llvm-20/lib/clang/20 -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 _GLIBCXX_ASSERTIONS -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/svg -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/svg -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/widget -I /var/lib/jenkins/workspace/firefox-scan-build/layout/base -I /var/lib/jenkins/workspace/firefox-scan-build/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/layout/painting -I /var/lib/jenkins/workspace/firefox-scan-build/layout/style -I /var/lib/jenkins/workspace/firefox-scan-build/layout/xul -I /var/lib/jenkins/workspace/firefox-scan-build/dom/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/svg -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 -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-20/lib/clang/20/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 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fno-sized-deallocation -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-2025-01-20-090804-167946-1 -x c++ Unified_cpp_layout_svg1.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// Main header first:
8#include "SVGTextFrame.h"
9
10// Keep others in (case-insensitive) order:
11#include "DOMSVGPoint.h"
12#include "gfx2DGlue.h"
13#include "gfxContext.h"
14#include "gfxFont.h"
15#include "gfxSkipChars.h"
16#include "gfxTypes.h"
17#include "gfxUtils.h"
18#include "LookAndFeel.h"
19#include "nsBidiPresUtils.h"
20#include "nsBlockFrame.h"
21#include "nsCaret.h"
22#include "nsContentUtils.h"
23#include "nsGkAtoms.h"
24#include "SVGPaintServerFrame.h"
25#include "nsTArray.h"
26#include "nsTextFrame.h"
27#include "SVGAnimatedNumberList.h"
28#include "SVGContentUtils.h"
29#include "SVGContextPaint.h"
30#include "SVGLengthList.h"
31#include "SVGNumberList.h"
32#include "nsLayoutUtils.h"
33#include "nsFrameSelection.h"
34#include "nsStyleStructInlines.h"
35#include "mozilla/CaretAssociationHint.h"
36#include "mozilla/DisplaySVGItem.h"
37#include "mozilla/Likely.h"
38#include "mozilla/PresShell.h"
39#include "mozilla/SVGObserverUtils.h"
40#include "mozilla/SVGOuterSVGFrame.h"
41#include "mozilla/SVGUtils.h"
42#include "mozilla/dom/DOMPointBinding.h"
43#include "mozilla/dom/Selection.h"
44#include "mozilla/dom/SVGGeometryElement.h"
45#include "mozilla/dom/SVGRect.h"
46#include "mozilla/dom/SVGTextContentElementBinding.h"
47#include "mozilla/dom/SVGTextPathElement.h"
48#include "mozilla/dom/Text.h"
49#include "mozilla/gfx/2D.h"
50#include "mozilla/gfx/PatternHelpers.h"
51#include <algorithm>
52#include <cmath>
53#include <limits>
54
55using namespace mozilla::dom;
56using namespace mozilla::dom::SVGTextContentElement_Binding;
57using namespace mozilla::gfx;
58using namespace mozilla::image;
59
60namespace mozilla {
61
62// ============================================================================
63// Utility functions
64
65/**
66 * Using the specified gfxSkipCharsIterator, converts an offset and length
67 * in original char indexes to skipped char indexes.
68 *
69 * @param aIterator The gfxSkipCharsIterator to use for the conversion.
70 * @param aOriginalOffset The original offset.
71 * @param aOriginalLength The original length.
72 */
73static gfxTextRun::Range ConvertOriginalToSkipped(
74 gfxSkipCharsIterator& aIterator, uint32_t aOriginalOffset,
75 uint32_t aOriginalLength) {
76 uint32_t start = aIterator.ConvertOriginalToSkipped(aOriginalOffset);
77 aIterator.AdvanceOriginal(aOriginalLength);
78 return gfxTextRun::Range(start, aIterator.GetSkippedOffset());
79}
80
81/**
82 * Converts an nsPoint from app units to user space units using the specified
83 * nsPresContext and returns it as a gfxPoint.
84 */
85static gfxPoint AppUnitsToGfxUnits(const nsPoint& aPoint,
86 const nsPresContext* aContext) {
87 return gfxPoint(aContext->AppUnitsToGfxUnits(aPoint.x),
88 aContext->AppUnitsToGfxUnits(aPoint.y));
89}
90
91/**
92 * Converts a gfxRect that is in app units to CSS pixels using the specified
93 * nsPresContext and returns it as a gfxRect.
94 */
95static gfxRect AppUnitsToFloatCSSPixels(const gfxRect& aRect,
96 const nsPresContext* aContext) {
97 return gfxRect(nsPresContext::AppUnitsToFloatCSSPixels(aRect.x),
98 nsPresContext::AppUnitsToFloatCSSPixels(aRect.y),
99 nsPresContext::AppUnitsToFloatCSSPixels(aRect.width),
100 nsPresContext::AppUnitsToFloatCSSPixels(aRect.height));
101}
102
103/**
104 * Returns whether a gfxPoint lies within a gfxRect.
105 */
106static bool Inside(const gfxRect& aRect, const gfxPoint& aPoint) {
107 return aPoint.x >= aRect.x && aPoint.x < aRect.XMost() &&
108 aPoint.y >= aRect.y && aPoint.y < aRect.YMost();
109}
110
111/**
112 * Gets the measured ascent and descent of the text in the given nsTextFrame
113 * in app units.
114 *
115 * @param aFrame The text frame.
116 * @param aAscent The ascent in app units (output).
117 * @param aDescent The descent in app units (output).
118 */
119static void GetAscentAndDescentInAppUnits(nsTextFrame* aFrame,
120 gfxFloat& aAscent,
121 gfxFloat& aDescent) {
122 gfxSkipCharsIterator it = aFrame->EnsureTextRun(nsTextFrame::eInflated);
123 gfxTextRun* textRun = aFrame->GetTextRun(nsTextFrame::eInflated);
124
125 gfxTextRun::Range range = ConvertOriginalToSkipped(
126 it, aFrame->GetContentOffset(), aFrame->GetContentLength());
127
128 textRun->GetLineHeightMetrics(range, aAscent, aDescent);
129}
130
131/**
132 * Updates an interval by intersecting it with another interval.
133 * The intervals are specified using a start index and a length.
134 */
135static void IntersectInterval(uint32_t& aStart, uint32_t& aLength,
136 uint32_t aStartOther, uint32_t aLengthOther) {
137 uint32_t aEnd = aStart + aLength;
138 uint32_t aEndOther = aStartOther + aLengthOther;
139
140 if (aStartOther >= aEnd || aStart >= aEndOther) {
141 aLength = 0;
142 } else {
143 if (aStartOther >= aStart) {
144 aStart = aStartOther;
145 }
146 aLength = std::min(aEnd, aEndOther) - aStart;
147 }
148}
149
150/**
151 * Intersects an interval as IntersectInterval does but by taking
152 * the offset and length of the other interval from a
153 * nsTextFrame::TrimmedOffsets object.
154 */
155static void TrimOffsets(uint32_t& aStart, uint32_t& aLength,
156 const nsTextFrame::TrimmedOffsets& aTrimmedOffsets) {
157 IntersectInterval(aStart, aLength, aTrimmedOffsets.mStart,
158 aTrimmedOffsets.mLength);
159}
160
161/**
162 * Returns the closest ancestor-or-self node that is not an SVG <a>
163 * element.
164 */
165static nsIContent* GetFirstNonAAncestor(nsIContent* aContent) {
166 while (aContent && aContent->IsSVGElement(nsGkAtoms::a)) {
167 aContent = aContent->GetParent();
168 }
169 return aContent;
170}
171
172/**
173 * Returns whether the given node is a text content element[1], taking into
174 * account whether it has a valid parent.
175 *
176 * For example, in:
177 *
178 * <svg xmlns="http://www.w3.org/2000/svg">
179 * <text><a/><text/></text>
180 * <tspan/>
181 * </svg>
182 *
183 * true would be returned for the outer <text> element and the <a> element,
184 * and false for the inner <text> element (since a <text> is not allowed
185 * to be a child of another <text>) and the <tspan> element (because it
186 * must be inside a <text> subtree).
187 *
188 * Note that we don't support the <tref> element yet and this function
189 * returns false for it.
190 *
191 * [1] https://svgwg.org/svg2-draft/intro.html#TermTextContentElement
192 */
193static bool IsTextContentElement(nsIContent* aContent) {
194 if (aContent->IsSVGElement(nsGkAtoms::text)) {
195 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
196 return !parent || !IsTextContentElement(parent);
197 }
198
199 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
200 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
201 return parent && parent->IsSVGElement(nsGkAtoms::text);
202 }
203
204 return aContent->IsAnyOfSVGElements(nsGkAtoms::a, nsGkAtoms::tspan);
205}
206
207/**
208 * Returns whether the specified frame is an nsTextFrame that has some text
209 * content.
210 */
211static bool IsNonEmptyTextFrame(nsIFrame* aFrame) {
212 nsTextFrame* textFrame = do_QueryFrame(aFrame);
213 if (!textFrame) {
214 return false;
215 }
216
217 return textFrame->GetContentLength() != 0;
218}
219
220/**
221 * Takes an nsIFrame and if it is a text frame that has some text content,
222 * returns it as an nsTextFrame and its corresponding Text.
223 *
224 * @param aFrame The frame to look at.
225 * @param aTextFrame aFrame as an nsTextFrame (output).
226 * @param aTextNode The Text content of aFrame (output).
227 * @return true if aFrame is a non-empty text frame, false otherwise.
228 */
229static bool GetNonEmptyTextFrameAndNode(nsIFrame* aFrame,
230 nsTextFrame*& aTextFrame,
231 Text*& aTextNode) {
232 nsTextFrame* text = do_QueryFrame(aFrame);
233 bool isNonEmptyTextFrame = text && text->GetContentLength() != 0;
234
235 if (isNonEmptyTextFrame) {
236 nsIContent* content = text->GetContent();
237 NS_ASSERTION(content && content->IsText(),do { if (!(content && content->IsText())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "unexpected content type for nsTextFrame"
, "content && content->IsText()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 238); MOZ_PretendNoReturn(); } } while (0)
238 "unexpected content type for nsTextFrame")do { if (!(content && content->IsText())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "unexpected content type for nsTextFrame"
, "content && content->IsText()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 238); MOZ_PretendNoReturn(); } } while (0)
;
239
240 Text* node = content->AsText();
241 MOZ_ASSERT(node->TextLength() != 0,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node->TextLength() != 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node->TextLength() != 0))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("node->TextLength() != 0"
" (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 243); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node->TextLength() != 0"
") (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")"); do { *((volatile int*)__null) = 243; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
242 "frame's GetContentLength() should be 0 if the text node "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node->TextLength() != 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node->TextLength() != 0))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("node->TextLength() != 0"
" (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 243); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node->TextLength() != 0"
") (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")"); do { *((volatile int*)__null) = 243; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
243 "has no content")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(node->TextLength() != 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(node->TextLength() != 0))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("node->TextLength() != 0"
" (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 243); AnnotateMozCrashReason("MOZ_ASSERT" "(" "node->TextLength() != 0"
") (" "frame's GetContentLength() should be 0 if the text node "
"has no content" ")"); do { *((volatile int*)__null) = 243; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
244
245 aTextFrame = text;
246 aTextNode = node;
247 }
248
249 MOZ_ASSERT(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame"
" (" "our logic should agree with IsNonEmptyTextFrame" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 250); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame"
") (" "our logic should agree with IsNonEmptyTextFrame" ")")
; do { *((volatile int*)__null) = 250; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
250 "our logic should agree with IsNonEmptyTextFrame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame"
" (" "our logic should agree with IsNonEmptyTextFrame" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 250); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame"
") (" "our logic should agree with IsNonEmptyTextFrame" ")")
; do { *((volatile int*)__null) = 250; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
251 return isNonEmptyTextFrame;
252}
253
254/**
255 * Returns whether the specified atom is for one of the five
256 * glyph positioning attributes that can appear on SVG text
257 * elements -- x, y, dx, dy or rotate.
258 */
259static bool IsGlyphPositioningAttribute(nsAtom* aAttribute) {
260 return aAttribute == nsGkAtoms::x || aAttribute == nsGkAtoms::y ||
261 aAttribute == nsGkAtoms::dx || aAttribute == nsGkAtoms::dy ||
262 aAttribute == nsGkAtoms::rotate;
263}
264
265/**
266 * Returns the position in app units of a given baseline (using an
267 * SVG dominant-baseline property value) for a given nsTextFrame.
268 *
269 * @param aFrame The text frame to inspect.
270 * @param aTextRun The text run of aFrame.
271 * @param aDominantBaseline The dominant-baseline value to use.
272 */
273static nscoord GetBaselinePosition(nsTextFrame* aFrame, gfxTextRun* aTextRun,
274 StyleDominantBaseline aDominantBaseline,
275 float aFontSizeScaleFactor) {
276 WritingMode writingMode = aFrame->GetWritingMode();
277 gfxFloat ascent, descent;
278 aTextRun->GetLineHeightMetrics(ascent, descent);
279
280 auto convertIfVerticalRL = [&](gfxFloat dominantBaseline) {
281 return writingMode.IsVerticalRL() ? ascent + descent - dominantBaseline
282 : dominantBaseline;
283 };
284
285 switch (aDominantBaseline) {
286 case StyleDominantBaseline::Hanging:
287 return convertIfVerticalRL(ascent * 0.2);
288 case StyleDominantBaseline::TextBeforeEdge:
289 return convertIfVerticalRL(0);
290
291 case StyleDominantBaseline::Alphabetic:
292 return writingMode.IsVerticalRL()
293 ? ascent * 0.5
294 : aFrame->GetLogicalBaseline(writingMode);
295
296 case StyleDominantBaseline::Auto:
297 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
298
299 case StyleDominantBaseline::Middle:
300 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode) -
301 SVGContentUtils::GetFontXHeight(aFrame) / 2.0 *
302 AppUnitsPerCSSPixel() *
303 aFontSizeScaleFactor);
304
305 case StyleDominantBaseline::TextAfterEdge:
306 case StyleDominantBaseline::Ideographic:
307 return writingMode.IsVerticalLR() ? 0 : ascent + descent;
308
309 case StyleDominantBaseline::Central:
310 return (ascent + descent) / 2.0;
311 case StyleDominantBaseline::Mathematical:
312 return convertIfVerticalRL(ascent / 2.0);
313 }
314
315 MOZ_ASSERT_UNREACHABLE("unexpected dominant-baseline 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 dominant-baseline value" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 315); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "unexpected dominant-baseline value"
")"); do { *((volatile int*)__null) = 315; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
316 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
317}
318
319/**
320 * Truncates an array to be at most the length of another array.
321 *
322 * @param aArrayToTruncate The array to truncate.
323 * @param aReferenceArray The array whose length will be used to truncate
324 * aArrayToTruncate to.
325 */
326template <typename T, typename U>
327static void TruncateTo(nsTArray<T>& aArrayToTruncate,
328 const nsTArray<U>& aReferenceArray) {
329 uint32_t length = aReferenceArray.Length();
330 if (aArrayToTruncate.Length() > length) {
331 aArrayToTruncate.TruncateLength(length);
332 }
333}
334
335/**
336 * Asserts that the anonymous block child of the SVGTextFrame has been
337 * reflowed (or does not exist). Returns null if the child has not been
338 * reflowed, and the frame otherwise.
339 *
340 * We check whether the kid has been reflowed and not the frame itself
341 * since we sometimes need to call this function during reflow, after the
342 * kid has been reflowed but before we have cleared the dirty bits on the
343 * frame itself.
344 */
345static SVGTextFrame* FrameIfAnonymousChildReflowed(SVGTextFrame* aFrame) {
346 MOZ_ASSERT(aFrame, "aFrame must not be null")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFrame)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aFrame))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aFrame" " (" "aFrame must not be null"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 346); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFrame" ") ("
"aFrame must not be null" ")"); do { *((volatile int*)__null
) = 346; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
347 nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
348 if (kid->IsSubtreeDirty()) {
349 MOZ_ASSERT(false, "should have already reflowed the anonymous block child")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "should have already reflowed the anonymous block child"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 349); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"should have already reflowed the anonymous block child" ")"
); do { *((volatile int*)__null) = 349; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
350 return nullptr;
351 }
352 return aFrame;
353}
354
355// FIXME(emilio): SVG is a special-case where transforms affect layout. We don't
356// want that to go outside the SVG stuff (and really we should aim to remove
357// that).
358static float GetContextScale(SVGTextFrame* aFrame) {
359 if (aFrame->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
360 // When we are non-display, we could be painted in different coordinate
361 // spaces, and we don't want to have to reflow for each of these. We just
362 // assume that the context scale is 1.0 for them all, so we don't get stuck
363 // with a font size scale factor based on whichever referencing frame
364 // happens to reflow first.
365 return 1.0f;
366 }
367 auto matrix = nsLayoutUtils::GetTransformToAncestor(
368 RelativeTo{aFrame}, RelativeTo{SVGUtils::GetOuterSVGFrame(aFrame)});
369 Matrix transform2D;
370 if (!matrix.CanDraw2D(&transform2D)) {
371 return 1.0f;
372 }
373 auto scales = transform2D.ScaleFactors();
374 return std::max(0.0f, std::max(scales.xScale, scales.yScale));
375}
376
377// ============================================================================
378// Utility classes
379
380// ----------------------------------------------------------------------------
381// TextRenderedRun
382
383/**
384 * A run of text within a single nsTextFrame whose glyphs can all be painted
385 * with a single call to nsTextFrame::PaintText. A text rendered run can
386 * be created for a sequence of two or more consecutive glyphs as long as:
387 *
388 * - Only the first glyph has (or none of the glyphs have) been positioned
389 * with SVG text positioning attributes
390 * - All of the glyphs have zero rotation
391 * - The glyphs are not on a text path
392 * - The glyphs correspond to content within the one nsTextFrame
393 *
394 * A TextRenderedRunIterator produces TextRenderedRuns required for painting a
395 * whole SVGTextFrame.
396 */
397struct TextRenderedRun {
398 using Range = gfxTextRun::Range;
399
400 /**
401 * Constructs a TextRenderedRun that is uninitialized except for mFrame
402 * being null.
403 */
404 TextRenderedRun() : mFrame(nullptr) {}
405
406 /**
407 * Constructs a TextRenderedRun with all of the information required to
408 * paint it. See the comments documenting the member variables below
409 * for descriptions of the arguments.
410 */
411 TextRenderedRun(nsTextFrame* aFrame, const gfxPoint& aPosition,
412 float aLengthAdjustScaleFactor, double aRotate,
413 float aFontSizeScaleFactor, nscoord aBaseline,
414 uint32_t aTextFrameContentOffset,
415 uint32_t aTextFrameContentLength,
416 uint32_t aTextElementCharIndex)
417 : mFrame(aFrame),
418 mPosition(aPosition),
419 mLengthAdjustScaleFactor(aLengthAdjustScaleFactor),
420 mRotate(static_cast<float>(aRotate)),
421 mFontSizeScaleFactor(aFontSizeScaleFactor),
422 mBaseline(aBaseline),
423 mTextFrameContentOffset(aTextFrameContentOffset),
424 mTextFrameContentLength(aTextFrameContentLength),
425 mTextElementCharIndex(aTextElementCharIndex) {}
426
427 /**
428 * Returns the text run for the text frame that this rendered run is part of.
429 */
430 gfxTextRun* GetTextRun() const {
431 mFrame->EnsureTextRun(nsTextFrame::eInflated);
432 return mFrame->GetTextRun(nsTextFrame::eInflated);
433 }
434
435 /**
436 * Returns whether this rendered run is RTL.
437 */
438 bool IsRightToLeft() const { return GetTextRun()->IsRightToLeft(); }
439
440 /**
441 * Returns whether this rendered run is vertical.
442 */
443 bool IsVertical() const { return GetTextRun()->IsVertical(); }
444
445 /**
446 * Returns the transform that converts from a <text> element's user space into
447 * the coordinate space that rendered runs can be painted directly in.
448 *
449 * The difference between this method and
450 * GetTransformFromRunUserSpaceToUserSpace is that when calling in to
451 * nsTextFrame::PaintText, it will already take into account any left clip
452 * edge (that is, it doesn't just apply a visual clip to the rendered text, it
453 * shifts the glyphs over so that they are painted with their left edge at the
454 * x coordinate passed in to it). Thus we need to account for this in our
455 * transform.
456 *
457 *
458 * Assume that we have:
459 *
460 * <text x="100" y="100" rotate="0 0 1 0 0 * 1">abcdef</text>.
461 *
462 * This would result in four text rendered runs:
463 *
464 * - one for "ab"
465 * - one for "c"
466 * - one for "de"
467 * - one for "f"
468 *
469 * Assume now that we are painting the third TextRenderedRun. It will have
470 * a left clip edge that is the sum of the advances of "abc", and it will
471 * have a right clip edge that is the advance of "f". In
472 * SVGTextFrame::PaintSVG(), we pass in nsPoint() (i.e., the origin)
473 * as the point at which to paint the text frame, and we pass in the
474 * clip edge values. The nsTextFrame will paint the substring of its
475 * text such that the top-left corner of the "d"'s glyph cell will be at
476 * (0, 0) in the current coordinate system.
477 *
478 * Thus, GetTransformFromUserSpaceForPainting must return a transform from
479 * whatever user space the <text> element is in to a coordinate space in
480 * device pixels (as that's what nsTextFrame works in) where the origin is at
481 * the same position as our user space mPositions[i].mPosition value for
482 * the "d" glyph, which will be (100 + userSpaceAdvance("abc"), 100).
483 * The translation required to do this (ignoring the scale to get from
484 * user space to device pixels, and ignoring the
485 * (100 + userSpaceAdvance("abc"), 100) translation) is:
486 *
487 * (-leftEdge, -baseline)
488 *
489 * where baseline is the distance between the baseline of the text and the top
490 * edge of the nsTextFrame. We translate by -leftEdge horizontally because
491 * the nsTextFrame will already shift the glyphs over by that amount and start
492 * painting glyphs at x = 0. We translate by -baseline vertically so that
493 * painting the top edges of the glyphs at y = 0 will result in their
494 * baselines being at our desired y position.
495 *
496 *
497 * Now for an example with RTL text. Assume our content is now
498 * <text x="100" y="100" rotate="0 0 1 0 0 1">WERBEH</text>. We'd have
499 * the following text rendered runs:
500 *
501 * - one for "EH"
502 * - one for "B"
503 * - one for "ER"
504 * - one for "W"
505 *
506 * Again, we are painting the third TextRenderedRun. The left clip edge
507 * is the advance of the "W" and the right clip edge is the sum of the
508 * advances of "BEH". Our translation to get the rendered "ER" glyphs
509 * in the right place this time is:
510 *
511 * (-frameWidth + rightEdge, -baseline)
512 *
513 * which is equivalent to:
514 *
515 * (-(leftEdge + advance("ER")), -baseline)
516 *
517 * The reason we have to shift left additionally by the width of the run
518 * of glyphs we are painting is that although the nsTextFrame is RTL,
519 * we still supply the top-left corner to paint the frame at when calling
520 * nsTextFrame::PaintText, even though our user space positions for each
521 * glyph in mPositions specifies the origin of each glyph, which for RTL
522 * glyphs is at the right edge of the glyph cell.
523 *
524 *
525 * For any other use of an nsTextFrame in the context of a particular run
526 * (such as hit testing, or getting its rectangle),
527 * GetTransformFromRunUserSpaceToUserSpace should be used.
528 *
529 * @param aContext The context to use for unit conversions.
530 */
531 gfxMatrix GetTransformFromUserSpaceForPainting(
532 nsPresContext* aContext, const nscoord aVisIStartEdge,
533 const nscoord aVisIEndEdge) const;
534
535 /**
536 * Returns the transform that converts from "run user space" to a <text>
537 * element's user space. Run user space is a coordinate system that has the
538 * same size as the <text>'s user space but rotated and translated such that
539 * (0,0) is the top-left of the rectangle that bounds the text.
540 *
541 * @param aContext The context to use for unit conversions.
542 */
543 gfxMatrix GetTransformFromRunUserSpaceToUserSpace(
544 nsPresContext* aContext) const;
545
546 /**
547 * Returns the transform that converts from "run user space" to float pixels
548 * relative to the nsTextFrame that this rendered run is a part of.
549 *
550 * @param aContext The context to use for unit conversions.
551 */
552 gfxMatrix GetTransformFromRunUserSpaceToFrameUserSpace(
553 nsPresContext* aContext) const;
554
555 /**
556 * Flag values used for the aFlags arguments of GetRunUserSpaceRect,
557 * GetFrameUserSpaceRect and GetUserSpaceRect.
558 */
559 enum {
560 // Includes the fill geometry of the text in the returned rectangle.
561 eIncludeFill = 1,
562 // Includes the stroke geometry of the text in the returned rectangle.
563 eIncludeStroke = 2,
564 // Don't include any horizontal glyph overflow in the returned rectangle.
565 eNoHorizontalOverflow = 4
566 };
567
568 /**
569 * Returns a rectangle that bounds the fill and/or stroke of the rendered run
570 * in run user space.
571 *
572 * @param aContext The context to use for unit conversions.
573 * @param aFlags A combination of the flags above (eIncludeFill and
574 * eIncludeStroke) indicating what parts of the text to include in
575 * the rectangle.
576 */
577 SVGBBox GetRunUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
578
579 /**
580 * Returns a rectangle that covers the fill and/or stroke of the rendered run
581 * in "frame user space".
582 *
583 * Frame user space is a coordinate space of the same scale as the <text>
584 * element's user space, but with its rotation set to the rotation of
585 * the glyphs within this rendered run and its origin set to the position
586 * such that placing the nsTextFrame there would result in the glyphs in
587 * this rendered run being at their correct positions.
588 *
589 * For example, say we have <text x="100 150" y="100">ab</text>. Assume
590 * the advance of both the "a" and the "b" is 12 user units, and the
591 * ascent of the text is 8 user units and its descent is 6 user units,
592 * and that we are not measuing the stroke of the text, so that we stay
593 * entirely within the glyph cells.
594 *
595 * There will be two text rendered runs, one for "a" and one for "b".
596 *
597 * The frame user space for the "a" run will have its origin at
598 * (100, 100 - 8) in the <text> element's user space and will have its
599 * axes aligned with the user space (since there is no rotate="" or
600 * text path involve) and with its scale the same as the user space.
601 * The rect returned by this method will be (0, 0, 12, 14), since the "a"
602 * glyph is right at the left of the nsTextFrame.
603 *
604 * The frame user space for the "b" run will have its origin at
605 * (150 - 12, 100 - 8), and scale/rotation the same as above. The rect
606 * returned by this method will be (12, 0, 12, 14), since we are
607 * advance("a") horizontally in to the text frame.
608 *
609 * @param aContext The context to use for unit conversions.
610 * @param aFlags A combination of the flags above (eIncludeFill and
611 * eIncludeStroke) indicating what parts of the text to include in
612 * the rectangle.
613 */
614 SVGBBox GetFrameUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
615
616 /**
617 * Returns a rectangle that covers the fill and/or stroke of the rendered run
618 * in the <text> element's user space.
619 *
620 * @param aContext The context to use for unit conversions.
621 * @param aFlags A combination of the flags above indicating what parts of
622 * the text to include in the rectangle.
623 * @param aAdditionalTransform An additional transform to apply to the
624 * frame user space rectangle before its bounds are transformed into
625 * user space.
626 */
627 SVGBBox GetUserSpaceRect(
628 nsPresContext* aContext, uint32_t aFlags,
629 const gfxMatrix* aAdditionalTransform = nullptr) const;
630
631 /**
632 * Gets the app unit amounts to clip from the left and right edges of
633 * the nsTextFrame in order to paint just this rendered run.
634 *
635 * Note that if clip edge amounts land in the middle of a glyph, the
636 * glyph won't be painted at all. The clip edges are thus more of
637 * a selection mechanism for which glyphs will be painted, rather
638 * than a geometric clip.
639 */
640 void GetClipEdges(nscoord& aVisIStartEdge, nscoord& aVisIEndEdge) const;
641
642 /**
643 * Returns the advance width of the whole rendered run.
644 */
645 nscoord GetAdvanceWidth() const;
646
647 /**
648 * Returns the index of the character into this rendered run whose
649 * glyph cell contains the given point, or -1 if there is no such
650 * character. This does not hit test against any overflow.
651 *
652 * @param aContext The context to use for unit conversions.
653 * @param aPoint The point in the user space of the <text> element.
654 */
655 int32_t GetCharNumAtPosition(nsPresContext* aContext,
656 const gfxPoint& aPoint) const;
657
658 /**
659 * The text frame that this rendered run lies within.
660 */
661 nsTextFrame* mFrame;
662
663 /**
664 * The point in user space that the text is positioned at.
665 *
666 * For a horizontal run:
667 * The x coordinate is the left edge of a LTR run of text or the right edge of
668 * an RTL run. The y coordinate is the baseline of the text.
669 * For a vertical run:
670 * The x coordinate is the baseline of the text.
671 * The y coordinate is the top edge of a LTR run, or bottom of RTL.
672 */
673 gfxPoint mPosition;
674
675 /**
676 * The horizontal scale factor to apply when painting glyphs to take
677 * into account textLength="".
678 */
679 float mLengthAdjustScaleFactor;
680
681 /**
682 * The rotation in radians in the user coordinate system that the text has.
683 */
684 float mRotate;
685
686 /**
687 * The scale factor that was used to transform the text run's original font
688 * size into a sane range for painting and measurement.
689 */
690 double mFontSizeScaleFactor;
691
692 /**
693 * The baseline in app units of this text run. The measurement is from the
694 * top of the text frame. (From the left edge if vertical.)
695 */
696 nscoord mBaseline;
697
698 /**
699 * The offset and length in mFrame's content Text that corresponds to
700 * this text rendered run. These are original char indexes.
701 */
702 uint32_t mTextFrameContentOffset;
703 uint32_t mTextFrameContentLength;
704
705 /**
706 * The character index in the whole SVG <text> element that this text rendered
707 * run begins at.
708 */
709 uint32_t mTextElementCharIndex;
710};
711
712gfxMatrix TextRenderedRun::GetTransformFromUserSpaceForPainting(
713 nsPresContext* aContext, const nscoord aVisIStartEdge,
714 const nscoord aVisIEndEdge) const {
715 // We transform to device pixels positioned such that painting the text frame
716 // at (0,0) with aItem will result in the text being in the right place.
717
718 gfxMatrix m;
719 if (!mFrame) {
720 return m;
721 }
722
723 float cssPxPerDevPx =
724 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
725
726 // Glyph position in user space.
727 m.PreTranslate(mPosition / cssPxPerDevPx);
728
729 // Take into account any font size scaling and scaling due to textLength="".
730 m.PreScale(1.0 / mFontSizeScaleFactor, 1.0 / mFontSizeScaleFactor);
731
732 // Rotation due to rotate="" or a <textPath>.
733 m.PreRotate(mRotate);
734
735 // Scale for textLength="" and translate to get the text frame
736 // to the right place.
737 nsPoint t;
738 if (IsVertical()) {
739 m.PreScale(1.0, mLengthAdjustScaleFactor);
740 t = nsPoint(-mBaseline, IsRightToLeft()
741 ? -mFrame->GetRect().height + aVisIEndEdge
742 : -aVisIStartEdge);
743 } else {
744 m.PreScale(mLengthAdjustScaleFactor, 1.0);
745 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + aVisIEndEdge
746 : -aVisIStartEdge,
747 -mBaseline);
748 }
749 m.PreTranslate(AppUnitsToGfxUnits(t, aContext));
750
751 return m;
752}
753
754gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToUserSpace(
755 nsPresContext* aContext) const {
756 gfxMatrix m;
757 if (!mFrame) {
758 return m;
759 }
760
761 float cssPxPerDevPx =
762 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
763
764 nscoord start, end;
765 GetClipEdges(start, end);
766
767 // Glyph position in user space.
768 m.PreTranslate(mPosition);
769
770 // Rotation due to rotate="" or a <textPath>.
771 m.PreRotate(mRotate);
772
773 // Scale for textLength="" and translate to get the text frame
774 // to the right place.
775
776 nsPoint t;
777 if (IsVertical()) {
778 m.PreScale(1.0, mLengthAdjustScaleFactor);
779 t = nsPoint(-mBaseline,
780 IsRightToLeft() ? -mFrame->GetRect().height + start + end : 0);
781 } else {
782 m.PreScale(mLengthAdjustScaleFactor, 1.0);
783 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + start + end : 0,
784 -mBaseline);
785 }
786 m.PreTranslate(AppUnitsToGfxUnits(t, aContext) * cssPxPerDevPx /
787 mFontSizeScaleFactor);
788
789 return m;
790}
791
792gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
793 nsPresContext* aContext) const {
794 gfxMatrix m;
795 if (!mFrame) {
796 return m;
797 }
798
799 nscoord start, end;
800 GetClipEdges(start, end);
801
802 // Translate by the horizontal distance into the text frame this
803 // rendered run is.
804 gfxFloat appPerCssPx = AppUnitsPerCSSPixel();
805 gfxPoint t = IsVertical() ? gfxPoint(0, start / appPerCssPx)
806 : gfxPoint(start / appPerCssPx, 0);
807 return m.PreTranslate(t);
808}
809
810SVGBBox TextRenderedRun::GetRunUserSpaceRect(nsPresContext* aContext,
811 uint32_t aFlags) const {
812 SVGBBox r;
813 if (!mFrame) {
814 return r;
815 }
816
817 // Determine the amount of overflow around frame's mRect.
818 //
819 // We need to call InkOverflowRectRelativeToSelf because this includes
820 // overflowing decorations, which the MeasureText call below does not.
821 nsRect self = mFrame->InkOverflowRectRelativeToSelf();
822 nsRect rect = mFrame->GetRect();
823 bool vertical = IsVertical();
824 nsMargin inkOverflow(
825 vertical ? -self.x : -self.y,
826 vertical ? self.YMost() - rect.height : self.XMost() - rect.width,
827 vertical ? self.XMost() - rect.width : self.YMost() - rect.height,
828 vertical ? -self.y : -self.x);
829
830 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
831 gfxSkipCharsIterator start = it;
832 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
833
834 // Get the content range for this rendered run.
835 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
836 mTextFrameContentLength);
837 if (range.Length() == 0) {
838 return r;
839 }
840
841 // FIXME(heycam): We could create a single PropertyProvider for all
842 // TextRenderedRuns that correspond to the text frame, rather than recreate
843 // it each time here.
844 nsTextFrame::PropertyProvider provider(mFrame, start);
845
846 // Measure that range.
847 gfxTextRun::Metrics metrics = textRun->MeasureText(
848 range, gfxFont::LOOSE_INK_EXTENTS, nullptr, &provider);
849 // Make sure it includes the font-box.
850 gfxRect fontBox(0, -metrics.mAscent, metrics.mAdvanceWidth,
851 metrics.mAscent + metrics.mDescent);
852 metrics.mBoundingBox.UnionRect(metrics.mBoundingBox, fontBox);
853
854 // Determine the rectangle that covers the rendered run's fill,
855 // taking into account the measured overflow due to decorations.
856 nscoord baseline =
857 NSToCoordRoundWithClamp(metrics.mBoundingBox.y + metrics.mAscent);
858 gfxFloat x, width;
859 if (aFlags & eNoHorizontalOverflow) {
860 x = 0.0;
861 width = textRun->GetAdvanceWidth(range, &provider);
862 if (width < 0.0) {
863 x = width;
864 width = -width;
865 }
866 } else {
867 x = metrics.mBoundingBox.x;
868 width = metrics.mBoundingBox.width;
869 }
870 nsRect fillInAppUnits(NSToCoordRoundWithClamp(x), baseline,
871 NSToCoordRoundWithClamp(width),
872 NSToCoordRoundWithClamp(metrics.mBoundingBox.height));
873 fillInAppUnits.Inflate(inkOverflow);
874 if (textRun->IsVertical()) {
875 // Swap line-relative textMetrics dimensions to physical coordinates.
876 std::swap(fillInAppUnits.x, fillInAppUnits.y);
877 std::swap(fillInAppUnits.width, fillInAppUnits.height);
878 }
879
880 // Convert the app units rectangle to user units.
881 gfxRect fill = AppUnitsToFloatCSSPixels(
882 gfxRect(fillInAppUnits.x, fillInAppUnits.y, fillInAppUnits.width,
883 fillInAppUnits.height),
884 aContext);
885
886 // Scale the rectangle up due to any mFontSizeScaleFactor.
887 fill.Scale(1.0 / mFontSizeScaleFactor);
888
889 // Include the fill if requested.
890 if (aFlags & eIncludeFill) {
891 r = fill;
892 }
893
894 // Include the stroke if requested.
895 if ((aFlags & eIncludeStroke) && !fill.IsEmpty() &&
896 SVGUtils::GetStrokeWidth(mFrame) > 0) {
897 r.UnionEdges(
898 SVGUtils::PathExtentsToMaxStrokeExtents(fill, mFrame, gfxMatrix()));
899 }
900
901 return r;
902}
903
904SVGBBox TextRenderedRun::GetFrameUserSpaceRect(nsPresContext* aContext,
905 uint32_t aFlags) const {
906 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
907 if (r.IsEmpty()) {
908 return r;
909 }
910 gfxMatrix m = GetTransformFromRunUserSpaceToFrameUserSpace(aContext);
911 return m.TransformBounds(r.ToThebesRect());
912}
913
914SVGBBox TextRenderedRun::GetUserSpaceRect(
915 nsPresContext* aContext, uint32_t aFlags,
916 const gfxMatrix* aAdditionalTransform) const {
917 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
918 if (r.IsEmpty()) {
919 return r;
920 }
921 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
922 if (aAdditionalTransform) {
923 m *= *aAdditionalTransform;
924 }
925 return m.TransformBounds(r.ToThebesRect());
926}
927
928void TextRenderedRun::GetClipEdges(nscoord& aVisIStartEdge,
929 nscoord& aVisIEndEdge) const {
930 uint32_t contentLength = mFrame->GetContentLength();
931 if (mTextFrameContentOffset == 0 &&
932 mTextFrameContentLength == contentLength) {
933 // If the rendered run covers the entire content, we know we don't need
934 // to clip without having to measure anything.
935 aVisIStartEdge = 0;
936 aVisIEndEdge = 0;
937 return;
938 }
939
940 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
941 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
942 nsTextFrame::PropertyProvider provider(mFrame, it);
943
944 // Get the covered content offset/length for this rendered run in skipped
945 // characters, since that is what GetAdvanceWidth expects.
946 Range runRange = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
947 mTextFrameContentLength);
948
949 // Get the offset/length of the whole nsTextFrame.
950 uint32_t frameOffset = mFrame->GetContentOffset();
951 uint32_t frameLength = mFrame->GetContentLength();
952
953 // Trim the whole-nsTextFrame offset/length to remove any leading/trailing
954 // white space, as the nsTextFrame when painting does not include them when
955 // interpreting clip edges.
956 nsTextFrame::TrimmedOffsets trimmedOffsets =
957 mFrame->GetTrimmedOffsets(mFrame->TextFragment());
958 TrimOffsets(frameOffset, frameLength, trimmedOffsets);
959
960 // Convert the trimmed whole-nsTextFrame offset/length into skipped
961 // characters.
962 Range frameRange = ConvertOriginalToSkipped(it, frameOffset, frameLength);
963
964 // Measure the advance width in the text run between the start of
965 // frame's content and the start of the rendered run's content,
966 nscoord startEdge = textRun->GetAdvanceWidth(
967 Range(frameRange.start, runRange.start), &provider);
968
969 // and between the end of the rendered run's content and the end
970 // of the frame's content.
971 nscoord endEdge =
972 textRun->GetAdvanceWidth(Range(runRange.end, frameRange.end), &provider);
973
974 if (textRun->IsRightToLeft()) {
975 aVisIStartEdge = endEdge;
976 aVisIEndEdge = startEdge;
977 } else {
978 aVisIStartEdge = startEdge;
979 aVisIEndEdge = endEdge;
980 }
981}
982
983nscoord TextRenderedRun::GetAdvanceWidth() const {
984 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
985 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
986 nsTextFrame::PropertyProvider provider(mFrame, it);
987
988 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
989 mTextFrameContentLength);
990
991 return textRun->GetAdvanceWidth(range, &provider);
992}
993
994int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext* aContext,
995 const gfxPoint& aPoint) const {
996 if (mTextFrameContentLength == 0) {
997 return -1;
998 }
999
1000 float cssPxPerDevPx =
1001 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
1002
1003 // Convert the point from user space into run user space, and take
1004 // into account any mFontSizeScaleFactor.
1005 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
1006 if (!m.Invert()) {
1007 return -1;
1008 }
1009 gfxPoint p = m.TransformPoint(aPoint) / cssPxPerDevPx * mFontSizeScaleFactor;
1010
1011 // First check that the point lies vertically between the top and bottom
1012 // edges of the text.
1013 gfxFloat ascent, descent;
1014 GetAscentAndDescentInAppUnits(mFrame, ascent, descent);
1015
1016 WritingMode writingMode = mFrame->GetWritingMode();
1017 if (writingMode.IsVertical()) {
1018 gfxFloat leftEdge = mFrame->GetLogicalBaseline(writingMode) -
1019 (writingMode.IsVerticalRL() ? ascent : descent);
1020 gfxFloat rightEdge = leftEdge + ascent + descent;
1021 if (p.x < aContext->AppUnitsToGfxUnits(leftEdge) ||
1022 p.x > aContext->AppUnitsToGfxUnits(rightEdge)) {
1023 return -1;
1024 }
1025 } else {
1026 gfxFloat topEdge = mFrame->GetLogicalBaseline(writingMode) - ascent;
1027 gfxFloat bottomEdge = topEdge + ascent + descent;
1028 if (p.y < aContext->AppUnitsToGfxUnits(topEdge) ||
1029 p.y > aContext->AppUnitsToGfxUnits(bottomEdge)) {
1030 return -1;
1031 }
1032 }
1033
1034 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
1035 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
1036 nsTextFrame::PropertyProvider provider(mFrame, it);
1037
1038 // Next check that the point lies horizontally within the left and right
1039 // edges of the text.
1040 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
1041 mTextFrameContentLength);
1042 gfxFloat runAdvance =
1043 aContext->AppUnitsToGfxUnits(textRun->GetAdvanceWidth(range, &provider));
1044
1045 gfxFloat pos = writingMode.IsVertical() ? p.y : p.x;
1046 if (pos < 0 || pos >= runAdvance) {
1047 return -1;
1048 }
1049
1050 // Finally, measure progressively smaller portions of the rendered run to
1051 // find which glyph it lies within. This will need to change once we
1052 // support letter-spacing and word-spacing.
1053 bool rtl = textRun->IsRightToLeft();
1054 for (int32_t i = mTextFrameContentLength - 1; i >= 0; i--) {
1055 range = ConvertOriginalToSkipped(it, mTextFrameContentOffset, i);
1056 gfxFloat advance = aContext->AppUnitsToGfxUnits(
1057 textRun->GetAdvanceWidth(range, &provider));
1058 if ((rtl && pos < runAdvance - advance) || (!rtl && pos >= advance)) {
1059 return i;
1060 }
1061 }
1062 return -1;
1063}
1064
1065// ----------------------------------------------------------------------------
1066// TextNodeIterator
1067
1068enum SubtreePosition { eBeforeSubtree, eWithinSubtree, eAfterSubtree };
1069
1070/**
1071 * An iterator class for Text that are descendants of a given node, the
1072 * root. Nodes are iterated in document order. An optional subtree can be
1073 * specified, in which case the iterator will track whether the current state of
1074 * the traversal over the tree is within that subtree or is past that subtree.
1075 */
1076class TextNodeIterator {
1077 public:
1078 /**
1079 * Constructs a TextNodeIterator with the specified root node and optional
1080 * subtree.
1081 */
1082 explicit TextNodeIterator(nsIContent* aRoot, nsIContent* aSubtree = nullptr)
1083 : mRoot(aRoot),
1084 mSubtree(aSubtree == aRoot ? nullptr : aSubtree),
1085 mCurrent(aRoot),
1086 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1087 NS_ASSERTION(aRoot, "expected non-null root")do { if (!(aRoot)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected non-null root"
, "aRoot", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1087); MOZ_PretendNoReturn(); } } while (0)
;
1088 if (!aRoot->IsText()) {
1089 Next();
1090 }
1091 }
1092
1093 /**
1094 * Returns the current Text, or null if the iterator has finished.
1095 */
1096 Text* Current() const { return mCurrent ? mCurrent->AsText() : nullptr; }
1097
1098 /**
1099 * Advances to the next Text and returns it, or null if the end of
1100 * iteration has been reached.
1101 */
1102 Text* Next();
1103
1104 /**
1105 * Returns whether the iterator is currently within the subtree rooted
1106 * at mSubtree. Returns true if we are not tracking a subtree (we consider
1107 * that we're always within the subtree).
1108 */
1109 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1110
1111 /**
1112 * Returns whether the iterator is past the subtree rooted at mSubtree.
1113 * Returns false if we are not tracking a subtree.
1114 */
1115 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1116
1117 private:
1118 /**
1119 * The root under which all Text will be iterated over.
1120 */
1121 nsIContent* const mRoot;
1122
1123 /**
1124 * The node rooting the subtree to track.
1125 */
1126 nsIContent* const mSubtree;
1127
1128 /**
1129 * The current node during iteration.
1130 */
1131 nsIContent* mCurrent;
1132
1133 /**
1134 * The current iterator position relative to mSubtree.
1135 */
1136 SubtreePosition mSubtreePosition;
1137};
1138
1139Text* TextNodeIterator::Next() {
1140 // Starting from mCurrent, we do a non-recursive traversal to the next
1141 // Text beneath mRoot, updating mSubtreePosition appropriately if we
1142 // encounter mSubtree.
1143 if (mCurrent) {
1144 do {
1145 nsIContent* next =
1146 IsTextContentElement(mCurrent) ? mCurrent->GetFirstChild() : nullptr;
1147 if (next) {
1148 mCurrent = next;
1149 if (mCurrent == mSubtree) {
1150 mSubtreePosition = eWithinSubtree;
1151 }
1152 } else {
1153 for (;;) {
1154 if (mCurrent == mRoot) {
1155 mCurrent = nullptr;
1156 break;
1157 }
1158 if (mCurrent == mSubtree) {
1159 mSubtreePosition = eAfterSubtree;
1160 }
1161 next = mCurrent->GetNextSibling();
1162 if (next) {
1163 mCurrent = next;
1164 if (mCurrent == mSubtree) {
1165 mSubtreePosition = eWithinSubtree;
1166 }
1167 break;
1168 }
1169 if (mCurrent == mSubtree) {
1170 mSubtreePosition = eAfterSubtree;
1171 }
1172 mCurrent = mCurrent->GetParent();
1173 }
1174 }
1175 } while (mCurrent && !mCurrent->IsText());
1176 }
1177
1178 return mCurrent ? mCurrent->AsText() : nullptr;
1179}
1180
1181// ----------------------------------------------------------------------------
1182// TextNodeCorrespondenceRecorder
1183
1184/**
1185 * TextNodeCorrespondence is used as the value of a frame property that
1186 * is stored on all its descendant nsTextFrames. It stores the number of DOM
1187 * characters between it and the previous nsTextFrame that did not have an
1188 * nsTextFrame created for them, due to either not being in a correctly
1189 * parented text content element, or because they were display:none.
1190 * These are called "undisplayed characters".
1191 *
1192 * See also TextNodeCorrespondenceRecorder below, which is what sets the
1193 * frame property.
1194 */
1195struct TextNodeCorrespondence {
1196 explicit TextNodeCorrespondence(uint32_t aUndisplayedCharacters)
1197 : mUndisplayedCharacters(aUndisplayedCharacters) {}
1198
1199 uint32_t mUndisplayedCharacters;
1200};
1201
1202NS_DECLARE_FRAME_PROPERTY_DELETABLE(TextNodeCorrespondenceProperty,static const mozilla::FramePropertyDescriptor<TextNodeCorrespondence
>* TextNodeCorrespondenceProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<TextNodeCorrespondence
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
1203 TextNodeCorrespondence)static const mozilla::FramePropertyDescriptor<TextNodeCorrespondence
>* TextNodeCorrespondenceProperty() { static const auto descriptor
= mozilla::FramePropertyDescriptor<TextNodeCorrespondence
>::NewWithDestructor<DeleteValue>(); return &descriptor
; }
1204
1205/**
1206 * Returns the number of undisplayed characters before the specified
1207 * nsTextFrame.
1208 */
1209static uint32_t GetUndisplayedCharactersBeforeFrame(nsTextFrame* aFrame) {
1210 void* value = aFrame->GetProperty(TextNodeCorrespondenceProperty());
1211 TextNodeCorrespondence* correspondence =
1212 static_cast<TextNodeCorrespondence*>(value);
1213 if (!correspondence) {
1214 // FIXME bug 903785
1215 NS_ERROR(do { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected a TextNodeCorrespondenceProperty on nsTextFrame "
"used for SVG text", "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1217); MOZ_PretendNoReturn(); } while (0)
1216 "expected a TextNodeCorrespondenceProperty on nsTextFrame "do { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected a TextNodeCorrespondenceProperty on nsTextFrame "
"used for SVG text", "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1217); MOZ_PretendNoReturn(); } while (0)
1217 "used for SVG text")do { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected a TextNodeCorrespondenceProperty on nsTextFrame "
"used for SVG text", "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1217); MOZ_PretendNoReturn(); } while (0)
;
1218 return 0;
1219 }
1220 return correspondence->mUndisplayedCharacters;
1221}
1222
1223/**
1224 * Traverses the nsTextFrames for an SVGTextFrame and records a
1225 * TextNodeCorrespondenceProperty on each for the number of undisplayed DOM
1226 * characters between each frame. This is done by iterating simultaneously
1227 * over the Text and nsTextFrames and noting when Text (or
1228 * parts of them) are skipped when finding the next nsTextFrame.
1229 */
1230class TextNodeCorrespondenceRecorder {
1231 public:
1232 /**
1233 * Entry point for the TextNodeCorrespondenceProperty recording.
1234 */
1235 static void RecordCorrespondence(SVGTextFrame* aRoot);
1236
1237 private:
1238 explicit TextNodeCorrespondenceRecorder(SVGTextFrame* aRoot)
1239 : mNodeIterator(aRoot->GetContent()),
1240 mPreviousNode(nullptr),
1241 mNodeCharIndex(0) {}
1242
1243 void Record(SVGTextFrame* aRoot);
1244 void TraverseAndRecord(nsIFrame* aFrame);
1245
1246 /**
1247 * Returns the next non-empty Text.
1248 */
1249 Text* NextNode();
1250
1251 /**
1252 * The iterator over the Text that we use as we simultaneously
1253 * iterate over the nsTextFrames.
1254 */
1255 TextNodeIterator mNodeIterator;
1256
1257 /**
1258 * The previous Text we iterated over.
1259 */
1260 Text* mPreviousNode;
1261
1262 /**
1263 * The index into the current Text's character content.
1264 */
1265 uint32_t mNodeCharIndex;
1266};
1267
1268/* static */
1269void TextNodeCorrespondenceRecorder::RecordCorrespondence(SVGTextFrame* aRoot) {
1270 if (aRoot->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)) {
1271 // Resolve bidi so that continuation frames are created if necessary:
1272 aRoot->MaybeResolveBidiForAnonymousBlockChild();
1273 TextNodeCorrespondenceRecorder recorder(aRoot);
1274 recorder.Record(aRoot);
1275 aRoot->RemoveStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
1276 }
1277}
1278
1279void TextNodeCorrespondenceRecorder::Record(SVGTextFrame* aRoot) {
1280 if (!mNodeIterator.Current()) {
1281 // If there are no Text nodes then there is nothing to do.
1282 return;
1283 }
1284
1285 // Traverse over all the nsTextFrames and record the number of undisplayed
1286 // characters.
1287 TraverseAndRecord(aRoot);
1288
1289 // Find how many undisplayed characters there are after the final nsTextFrame.
1290 uint32_t undisplayed = 0;
1291 if (mNodeIterator.Current()) {
1292 if (mPreviousNode && mPreviousNode->TextLength() != mNodeCharIndex) {
1293 // The last nsTextFrame ended part way through a Text node. The
1294 // remaining characters count as undisplayed.
1295 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1297); MOZ_PretendNoReturn(); } } while (0)
1296 "incorrect tracking of undisplayed characters in "do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1297); MOZ_PretendNoReturn(); } } while (0)
1297 "text nodes")do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1297); MOZ_PretendNoReturn(); } } while (0)
;
1298 undisplayed += mPreviousNode->TextLength() - mNodeCharIndex;
1299 }
1300 // All the remaining Text that we iterate must also be undisplayed.
1301 for (Text* textNode = mNodeIterator.Current(); textNode;
1302 textNode = NextNode()) {
1303 undisplayed += textNode->TextLength();
1304 }
1305 }
1306
1307 // Record the trailing number of undisplayed characters on the
1308 // SVGTextFrame.
1309 aRoot->mTrailingUndisplayedCharacters = undisplayed;
1310}
1311
1312Text* TextNodeCorrespondenceRecorder::NextNode() {
1313 mPreviousNode = mNodeIterator.Current();
1314 Text* next;
1315 do {
1316 next = mNodeIterator.Next();
1317 } while (next && next->TextLength() == 0);
1318 return next;
1319}
1320
1321void TextNodeCorrespondenceRecorder::TraverseAndRecord(nsIFrame* aFrame) {
1322 // Recursively iterate over the frame tree, for frames that correspond
1323 // to text content elements.
1324 if (IsTextContentElement(aFrame->GetContent())) {
1325 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1326 TraverseAndRecord(f);
1327 }
1328 return;
1329 }
1330
1331 nsTextFrame* frame; // The current text frame.
1332 Text* node; // The text node for the current text frame.
1333 if (!GetNonEmptyTextFrameAndNode(aFrame, frame, node)) {
1334 // If this isn't an nsTextFrame, or is empty, nothing to do.
1335 return;
1336 }
1337
1338 NS_ASSERTION(frame->GetContentOffset() >= 0,do { if (!(frame->GetContentOffset() >= 0)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "don't know how to handle negative content indexes"
, "frame->GetContentOffset() >= 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1339); MOZ_PretendNoReturn(); } } while (0)
1339 "don't know how to handle negative content indexes")do { if (!(frame->GetContentOffset() >= 0)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "don't know how to handle negative content indexes"
, "frame->GetContentOffset() >= 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1339); MOZ_PretendNoReturn(); } } while (0)
;
1340
1341 uint32_t undisplayed = 0;
1342 if (!mPreviousNode) {
1343 // Must be the very first text frame.
1344 NS_ASSERTION(mNodeCharIndex == 0,do { if (!(mNodeCharIndex == 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed " "characters in text nodes"
, "mNodeCharIndex == 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1346); MOZ_PretendNoReturn(); } } while (0)
1345 "incorrect tracking of undisplayed "do { if (!(mNodeCharIndex == 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed " "characters in text nodes"
, "mNodeCharIndex == 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1346); MOZ_PretendNoReturn(); } } while (0)
1346 "characters in text nodes")do { if (!(mNodeCharIndex == 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed " "characters in text nodes"
, "mNodeCharIndex == 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1346); MOZ_PretendNoReturn(); } } while (0)
;
1347 if (!mNodeIterator.Current()) {
1348 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: "
"incorrect tracking of correspondence between " "text frames and text nodes"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "incorrect tracking of correspondence between "
"text frames and text nodes" ")"); do { *((volatile int*)__null
) = 1350; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
1349 "incorrect tracking of correspondence between "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: "
"incorrect tracking of correspondence between " "text frames and text nodes"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "incorrect tracking of correspondence between "
"text frames and text nodes" ")"); do { *((volatile int*)__null
) = 1350; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
1350 "text frames and text nodes")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: "
"incorrect tracking of correspondence between " "text frames and text nodes"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1350); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "incorrect tracking of correspondence between "
"text frames and text nodes" ")"); do { *((volatile int*)__null
) = 1350; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
1351 } else {
1352 // Each whole Text we find before we get to the text node for the
1353 // first text frame must be undisplayed.
1354 while (mNodeIterator.Current() != node) {
1355 undisplayed += mNodeIterator.Current()->TextLength();
1356 NextNode();
1357 }
1358 // If the first text frame starts at a non-zero content offset, then those
1359 // earlier characters are also undisplayed.
1360 undisplayed += frame->GetContentOffset();
1361 NextNode();
1362 }
1363 } else if (mPreviousNode == node) {
1364 // Same text node as last time.
1365 if (static_cast<uint32_t>(frame->GetContentOffset()) != mNodeCharIndex) {
1366 // We have some characters in the middle of the text node
1367 // that are undisplayed.
1368 NS_ASSERTION(do { if (!(mNodeCharIndex < static_cast<uint32_t>(frame
->GetContentOffset()))) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed characters in " "text nodes"
, "mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1371); MOZ_PretendNoReturn(); } } while (0)
1369 mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset()),do { if (!(mNodeCharIndex < static_cast<uint32_t>(frame
->GetContentOffset()))) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed characters in " "text nodes"
, "mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1371); MOZ_PretendNoReturn(); } } while (0)
1370 "incorrect tracking of undisplayed characters in "do { if (!(mNodeCharIndex < static_cast<uint32_t>(frame
->GetContentOffset()))) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed characters in " "text nodes"
, "mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1371); MOZ_PretendNoReturn(); } } while (0)
1371 "text nodes")do { if (!(mNodeCharIndex < static_cast<uint32_t>(frame
->GetContentOffset()))) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "incorrect tracking of undisplayed characters in " "text nodes"
, "mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1371); MOZ_PretendNoReturn(); } } while (0)
;
1372 undisplayed = frame->GetContentOffset() - mNodeCharIndex;
1373 }
1374 } else {
1375 // Different text node from last time.
1376 if (mPreviousNode->TextLength() != mNodeCharIndex) {
1377 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1379); MOZ_PretendNoReturn(); } } while (0)
1378 "incorrect tracking of undisplayed characters in "do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1379); MOZ_PretendNoReturn(); } } while (0)
1379 "text nodes")do { if (!(mNodeCharIndex < mPreviousNode->TextLength()
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "incorrect tracking of undisplayed characters in "
"text nodes", "mNodeCharIndex < mPreviousNode->TextLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1379); MOZ_PretendNoReturn(); } } while (0)
;
1380 // Any trailing characters at the end of the previous Text are
1381 // undisplayed.
1382 undisplayed = mPreviousNode->TextLength() - mNodeCharIndex;
1383 }
1384 // Each whole Text we find before we get to the text node for
1385 // the current text frame must be undisplayed.
1386 while (mNodeIterator.Current() && mNodeIterator.Current() != node) {
1387 undisplayed += mNodeIterator.Current()->TextLength();
1388 NextNode();
1389 }
1390 // If the current text frame starts at a non-zero content offset, then those
1391 // earlier characters are also undisplayed.
1392 undisplayed += frame->GetContentOffset();
1393 NextNode();
1394 }
1395
1396 // Set the frame property.
1397 frame->SetProperty(TextNodeCorrespondenceProperty(),
1398 new TextNodeCorrespondence(undisplayed));
1399
1400 // Remember how far into the current Text we are.
1401 mNodeCharIndex = frame->GetContentEnd();
1402}
1403
1404// ----------------------------------------------------------------------------
1405// TextFrameIterator
1406
1407/**
1408 * An iterator class for nsTextFrames that are descendants of an
1409 * SVGTextFrame. The iterator can optionally track whether the
1410 * current nsTextFrame is for a descendant of, or past, a given subtree
1411 * content node or frame. (This functionality is used for example by the SVG
1412 * DOM text methods to get only the nsTextFrames for a particular <tspan>.)
1413 *
1414 * TextFrameIterator also tracks and exposes other information about the
1415 * current nsTextFrame:
1416 *
1417 * * how many undisplayed characters came just before it
1418 * * its position (in app units) relative to the SVGTextFrame's anonymous
1419 * block frame
1420 * * what nsInlineFrame corresponding to a <textPath> element it is a
1421 * descendant of
1422 * * what computed dominant-baseline value applies to it
1423 *
1424 * Note that any text frames that are empty -- whose ContentLength() is 0 --
1425 * will be skipped over.
1426 */
1427class MOZ_STACK_CLASS TextFrameIterator {
1428 public:
1429 /**
1430 * Constructs a TextFrameIterator for the specified SVGTextFrame
1431 * with an optional frame subtree to restrict iterated text frames to.
1432 */
1433 explicit TextFrameIterator(SVGTextFrame* aRoot,
1434 const nsIFrame* aSubtree = nullptr)
1435 : mRootFrame(aRoot),
1436 mSubtree(aSubtree),
1437 mCurrentFrame(aRoot),
1438 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1439 Init();
1440 }
1441
1442 /**
1443 * Constructs a TextFrameIterator for the specified SVGTextFrame
1444 * with an optional frame content subtree to restrict iterated text frames to.
1445 */
1446 TextFrameIterator(SVGTextFrame* aRoot, nsIContent* aSubtree)
1447 : mRootFrame(aRoot),
1448 mSubtree(aRoot && aSubtree && aSubtree != aRoot->GetContent()
1449 ? aSubtree->GetPrimaryFrame()
1450 : nullptr),
1451 mCurrentFrame(aRoot),
1452 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1453 Init();
1454 }
1455
1456 /**
1457 * Returns the root SVGTextFrame this TextFrameIterator is iterating over.
1458 */
1459 SVGTextFrame* Root() const { return mRootFrame; }
1460
1461 /**
1462 * Returns the current nsTextFrame.
1463 */
1464 nsTextFrame* Current() const { return do_QueryFrame(mCurrentFrame); }
1465
1466 /**
1467 * Returns the number of undisplayed characters in the DOM just before the
1468 * current frame.
1469 */
1470 uint32_t UndisplayedCharacters() const;
1471
1472 /**
1473 * Returns the current frame's position, in app units, relative to the
1474 * root SVGTextFrame's anonymous block frame.
1475 */
1476 nsPoint Position() const { return mCurrentPosition; }
1477
1478 /**
1479 * Advances to the next nsTextFrame and returns it.
1480 */
1481 nsTextFrame* Next();
1482
1483 /**
1484 * Returns whether the iterator is within the subtree.
1485 */
1486 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1487
1488 /**
1489 * Returns whether the iterator is past the subtree.
1490 */
1491 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1492
1493 /**
1494 * Returns the frame corresponding to the <textPath> element, if we
1495 * are inside one.
1496 */
1497 nsIFrame* TextPathFrame() const {
1498 return mTextPathFrames.IsEmpty() ? nullptr : mTextPathFrames.LastElement();
1499 }
1500
1501 /**
1502 * Returns the current frame's computed dominant-baseline value.
1503 */
1504 StyleDominantBaseline DominantBaseline() const {
1505 return mBaselines.LastElement();
1506 }
1507
1508 /**
1509 * Finishes the iterator.
1510 */
1511 void Close() { mCurrentFrame = nullptr; }
1512
1513 private:
1514 /**
1515 * Initializes the iterator and advances to the first item.
1516 */
1517 void Init() {
1518 if (!mRootFrame) {
1519 return;
1520 }
1521
1522 mBaselines.AppendElement(mRootFrame->StyleSVG()->mDominantBaseline);
1523 Next();
1524 }
1525
1526 /**
1527 * Pushes the specified frame's computed dominant-baseline value.
1528 * If the value of the property is "auto", then the parent frame's
1529 * computed value is used.
1530 */
1531 void PushBaseline(nsIFrame* aNextFrame);
1532
1533 /**
1534 * Pops the current dominant-baseline off the stack.
1535 */
1536 void PopBaseline();
1537
1538 /**
1539 * The root frame we are iterating through.
1540 */
1541 SVGTextFrame* const mRootFrame;
1542
1543 /**
1544 * The frame for the subtree we are also interested in tracking.
1545 */
1546 const nsIFrame* const mSubtree;
1547
1548 /**
1549 * The current value of the iterator.
1550 */
1551 nsIFrame* mCurrentFrame;
1552
1553 /**
1554 * The position, in app units, of the current frame relative to mRootFrame.
1555 */
1556 nsPoint mCurrentPosition;
1557
1558 /**
1559 * Stack of frames corresponding to <textPath> elements that are in scope
1560 * for the current frame.
1561 */
1562 AutoTArray<nsIFrame*, 1> mTextPathFrames;
1563
1564 /**
1565 * Stack of dominant-baseline values to record as we traverse through the
1566 * frame tree.
1567 */
1568 AutoTArray<StyleDominantBaseline, 8> mBaselines;
1569
1570 /**
1571 * The iterator's current position relative to mSubtree.
1572 */
1573 SubtreePosition mSubtreePosition;
1574};
1575
1576uint32_t TextFrameIterator::UndisplayedCharacters() const {
1577 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
" (" "Text correspondence must be up to date" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1579); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
") (" "Text correspondence must be up to date" ")"); do { *(
(volatile int*)__null) = 1579; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
1578 !mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
" (" "Text correspondence must be up to date" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1579); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
") (" "Text correspondence must be up to date" ")"); do { *(
(volatile int*)__null) = 1579; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
1579 "Text correspondence must be up to date")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
" (" "Text correspondence must be up to date" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1579); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)"
") (" "Text correspondence must be up to date" ")"); do { *(
(volatile int*)__null) = 1579; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
1580
1581 if (!mCurrentFrame) {
1582 return mRootFrame->mTrailingUndisplayedCharacters;
1583 }
1584
1585 nsTextFrame* frame = do_QueryFrame(mCurrentFrame);
1586 return GetUndisplayedCharactersBeforeFrame(frame);
1587}
1588
1589nsTextFrame* TextFrameIterator::Next() {
1590 // Starting from mCurrentFrame, we do a non-recursive traversal to the next
1591 // nsTextFrame beneath mRoot, updating mSubtreePosition appropriately if we
1592 // encounter mSubtree.
1593 if (mCurrentFrame) {
1594 do {
1595 nsIFrame* next = IsTextContentElement(mCurrentFrame->GetContent())
1596 ? mCurrentFrame->PrincipalChildList().FirstChild()
1597 : nullptr;
1598 if (next) {
1599 // Descend into this frame, and accumulate its position.
1600 mCurrentPosition += next->GetPosition();
1601 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1602 // Record this <textPath> frame.
1603 mTextPathFrames.AppendElement(next);
1604 }
1605 // Record the frame's baseline.
1606 PushBaseline(next);
1607 mCurrentFrame = next;
1608 if (mCurrentFrame == mSubtree) {
1609 // If the current frame is mSubtree, we have now moved into it.
1610 mSubtreePosition = eWithinSubtree;
1611 }
1612 } else {
1613 for (;;) {
1614 // We want to move past the current frame.
1615 if (mCurrentFrame == mRootFrame) {
1616 // If we've reached the root frame, we're finished.
1617 mCurrentFrame = nullptr;
1618 break;
1619 }
1620 // Remove the current frame's position.
1621 mCurrentPosition -= mCurrentFrame->GetPosition();
1622 if (mCurrentFrame->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1623 // Pop off the <textPath> frame if this is a <textPath>.
1624 mTextPathFrames.RemoveLastElement();
1625 }
1626 // Pop off the current baseline.
1627 PopBaseline();
1628 if (mCurrentFrame == mSubtree) {
1629 // If this was mSubtree, we have now moved past it.
1630 mSubtreePosition = eAfterSubtree;
1631 }
1632 next = mCurrentFrame->GetNextSibling();
1633 if (next) {
1634 // Moving to the next sibling.
1635 mCurrentPosition += next->GetPosition();
1636 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1637 // Record this <textPath> frame.
1638 mTextPathFrames.AppendElement(next);
1639 }
1640 // Record the frame's baseline.
1641 PushBaseline(next);
1642 mCurrentFrame = next;
1643 if (mCurrentFrame == mSubtree) {
1644 // If the current frame is mSubtree, we have now moved into it.
1645 mSubtreePosition = eWithinSubtree;
1646 }
1647 break;
1648 }
1649 if (mCurrentFrame == mSubtree) {
1650 // If there is no next sibling frame, and the current frame is
1651 // mSubtree, we have now moved past it.
1652 mSubtreePosition = eAfterSubtree;
1653 }
1654 // Ascend out of this frame.
1655 mCurrentFrame = mCurrentFrame->GetParent();
1656 }
1657 }
1658 } while (mCurrentFrame && !IsNonEmptyTextFrame(mCurrentFrame));
1659 }
1660
1661 return Current();
1662}
1663
1664void TextFrameIterator::PushBaseline(nsIFrame* aNextFrame) {
1665 StyleDominantBaseline baseline = aNextFrame->StyleSVG()->mDominantBaseline;
1666 mBaselines.AppendElement(baseline);
1667}
1668
1669void TextFrameIterator::PopBaseline() {
1670 NS_ASSERTION(!mBaselines.IsEmpty(), "popped too many baselines")do { if (!(!mBaselines.IsEmpty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "popped too many baselines", "!mBaselines.IsEmpty()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1670); MOZ_PretendNoReturn(); } } while (0)
;
1671 mBaselines.RemoveLastElement();
1672}
1673
1674// -----------------------------------------------------------------------------
1675// TextRenderedRunIterator
1676
1677/**
1678 * Iterator for TextRenderedRun objects for the SVGTextFrame.
1679 */
1680class TextRenderedRunIterator {
1681 public:
1682 /**
1683 * Values for the aFilter argument of the constructor, to indicate which
1684 * frames we should be limited to iterating TextRenderedRun objects for.
1685 */
1686 enum RenderedRunFilter {
1687 // Iterate TextRenderedRuns for all nsTextFrames.
1688 eAllFrames,
1689 // Iterate only TextRenderedRuns for nsTextFrames that are
1690 // visibility:visible.
1691 eVisibleFrames
1692 };
1693
1694 /**
1695 * Constructs a TextRenderedRunIterator with an optional frame subtree to
1696 * restrict iterated rendered runs to.
1697 *
1698 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1699 * through.
1700 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1701 * nsTextFrames.
1702 * @param aSubtree An optional frame subtree to restrict iterated rendered
1703 * runs to.
1704 */
1705 explicit TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1706 RenderedRunFilter aFilter = eAllFrames,
1707 const nsIFrame* aSubtree = nullptr)
1708 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1709 mFilter(aFilter),
1710 mTextElementCharIndex(0),
1711 mFrameStartTextElementCharIndex(0),
1712 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1713 mCurrent(First()) {}
1714
1715 /**
1716 * Constructs a TextRenderedRunIterator with a content subtree to restrict
1717 * iterated rendered runs to.
1718 *
1719 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1720 * through.
1721 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1722 * nsTextFrames.
1723 * @param aSubtree A content subtree to restrict iterated rendered runs to.
1724 */
1725 TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1726 RenderedRunFilter aFilter, nsIContent* aSubtree)
1727 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1728 mFilter(aFilter),
1729 mTextElementCharIndex(0),
1730 mFrameStartTextElementCharIndex(0),
1731 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1732 mCurrent(First()) {}
1733
1734 /**
1735 * Returns the current TextRenderedRun.
1736 */
1737 TextRenderedRun Current() const { return mCurrent; }
1738
1739 /**
1740 * Advances to the next TextRenderedRun and returns it.
1741 */
1742 TextRenderedRun Next();
1743
1744 private:
1745 /**
1746 * Returns the root SVGTextFrame this iterator is for.
1747 */
1748 SVGTextFrame* Root() const { return mFrameIterator.Root(); }
1749
1750 /**
1751 * Advances to the first TextRenderedRun and returns it.
1752 */
1753 TextRenderedRun First();
1754
1755 /**
1756 * The frame iterator to use.
1757 */
1758 TextFrameIterator mFrameIterator;
1759
1760 /**
1761 * The filter indicating which TextRenderedRuns to return.
1762 */
1763 RenderedRunFilter mFilter;
1764
1765 /**
1766 * The character index across the entire <text> element we are currently
1767 * up to.
1768 */
1769 uint32_t mTextElementCharIndex;
1770
1771 /**
1772 * The character index across the entire <text> for the start of the current
1773 * frame.
1774 */
1775 uint32_t mFrameStartTextElementCharIndex;
1776
1777 /**
1778 * The font-size scale factor we used when constructing the nsTextFrames.
1779 */
1780 double mFontSizeScaleFactor;
1781
1782 /**
1783 * The current TextRenderedRun.
1784 */
1785 TextRenderedRun mCurrent;
1786};
1787
1788TextRenderedRun TextRenderedRunIterator::Next() {
1789 if (!mFrameIterator.Current()) {
1790 // If there are no more frames, then there are no more rendered runs to
1791 // return.
1792 mCurrent = TextRenderedRun();
1793 return mCurrent;
1794 }
1795
1796 // The values we will use to initialize the TextRenderedRun with.
1797 nsTextFrame* frame;
1798 gfxPoint pt;
1799 double rotate;
1800 nscoord baseline;
1801 uint32_t offset, length;
1802 uint32_t charIndex;
1803
1804 // We loop, because we want to skip over rendered runs that either aren't
1805 // within our subtree of interest, because they don't match the filter,
1806 // or because they are hidden due to having fallen off the end of a
1807 // <textPath>.
1808 for (;;) {
1809 if (mFrameIterator.IsAfterSubtree()) {
1810 mCurrent = TextRenderedRun();
1811 return mCurrent;
1812 }
1813
1814 frame = mFrameIterator.Current();
1815
1816 charIndex = mTextElementCharIndex;
1817
1818 // Find the end of the rendered run, by looking through the
1819 // SVGTextFrame's positions array until we find one that is recorded
1820 // as a run boundary.
1821 uint32_t runStart,
1822 runEnd; // XXX Replace runStart with mTextElementCharIndex.
1823 runStart = mTextElementCharIndex;
1824 runEnd = runStart + 1;
1825 while (runEnd < Root()->mPositions.Length() &&
1826 !Root()->mPositions[runEnd].mRunBoundary) {
1827 runEnd++;
1828 }
1829
1830 // Convert the global run start/end indexes into an offset/length into the
1831 // current frame's Text.
1832 offset =
1833 frame->GetContentOffset() + runStart - mFrameStartTextElementCharIndex;
1834 length = runEnd - runStart;
1835
1836 // If the end of the frame's content comes before the run boundary we found
1837 // in SVGTextFrame's position array, we need to shorten the rendered run.
1838 uint32_t contentEnd = frame->GetContentEnd();
1839 if (offset + length > contentEnd) {
1840 length = contentEnd - offset;
1841 }
1842
1843 NS_ASSERTION(offset >= uint32_t(frame->GetContentOffset()),do { if (!(offset >= uint32_t(frame->GetContentOffset()
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "invalid offset", "offset >= uint32_t(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1844); MOZ_PretendNoReturn(); } } while (0)
1844 "invalid offset")do { if (!(offset >= uint32_t(frame->GetContentOffset()
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "invalid offset", "offset >= uint32_t(frame->GetContentOffset())"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1844); MOZ_PretendNoReturn(); } } while (0)
;
1845 NS_ASSERTION(offset + length <= contentEnd, "invalid offset or length")do { if (!(offset + length <= contentEnd)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "invalid offset or length", "offset + length <= contentEnd"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 1845); MOZ_PretendNoReturn(); } } while (0)
;
1846
1847 // Get the frame's baseline position.
1848 frame->EnsureTextRun(nsTextFrame::eInflated);
1849 baseline = GetBaselinePosition(
1850 frame, frame->GetTextRun(nsTextFrame::eInflated),
1851 mFrameIterator.DominantBaseline(), mFontSizeScaleFactor);
1852
1853 // Trim the offset/length to remove any leading/trailing white space.
1854 uint32_t untrimmedOffset = offset;
1855 uint32_t untrimmedLength = length;
1856 nsTextFrame::TrimmedOffsets trimmedOffsets =
1857 frame->GetTrimmedOffsets(frame->TextFragment());
1858 TrimOffsets(offset, length, trimmedOffsets);
1859 charIndex += offset - untrimmedOffset;
1860
1861 // Get the position and rotation of the character that begins this
1862 // rendered run.
1863 pt = Root()->mPositions[charIndex].mPosition;
1864 rotate = Root()->mPositions[charIndex].mAngle;
1865
1866 // Determine if we should skip this rendered run.
1867 bool skip = !mFrameIterator.IsWithinSubtree() ||
1868 Root()->mPositions[mTextElementCharIndex].mHidden;
1869 if (mFilter == eVisibleFrames) {
1870 skip = skip || !frame->StyleVisibility()->IsVisible();
1871 }
1872
1873 // Update our global character index to move past the characters
1874 // corresponding to this rendered run.
1875 mTextElementCharIndex += untrimmedLength;
1876
1877 // If we have moved past the end of the current frame's content, we need to
1878 // advance to the next frame.
1879 if (offset + untrimmedLength >= contentEnd) {
1880 mFrameIterator.Next();
1881 mTextElementCharIndex += mFrameIterator.UndisplayedCharacters();
1882 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1883 }
1884
1885 if (!mFrameIterator.Current()) {
1886 if (skip) {
1887 // That was the last frame, and we skipped this rendered run. So we
1888 // have no rendered run to return.
1889 mCurrent = TextRenderedRun();
1890 return mCurrent;
1891 }
1892 break;
1893 }
1894
1895 if (length && !skip) {
1896 // Only return a rendered run if it didn't get collapsed away entirely
1897 // (due to it being all white space) and if we don't want to skip it.
1898 break;
1899 }
1900 }
1901
1902 mCurrent = TextRenderedRun(frame, pt, Root()->mLengthAdjustScaleFactor,
1903 rotate, mFontSizeScaleFactor, baseline, offset,
1904 length, charIndex);
1905 return mCurrent;
1906}
1907
1908TextRenderedRun TextRenderedRunIterator::First() {
1909 if (!mFrameIterator.Current()) {
1910 return TextRenderedRun();
1911 }
1912
1913 if (Root()->mPositions.IsEmpty()) {
1914 mFrameIterator.Close();
1915 return TextRenderedRun();
1916 }
1917
1918 // Get the character index for the start of this rendered run, by skipping
1919 // any undisplayed characters.
1920 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
1921 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1922
1923 return Next();
1924}
1925
1926// -----------------------------------------------------------------------------
1927// CharIterator
1928
1929/**
1930 * Iterator for characters within an SVGTextFrame.
1931 */
1932class MOZ_STACK_CLASS CharIterator {
1933 using Range = gfxTextRun::Range;
1934
1935 public:
1936 /**
1937 * Values for the aFilter argument of the constructor, to indicate which
1938 * characters we should be iterating over.
1939 */
1940 enum CharacterFilter {
1941 // Iterate over all original characters from the DOM that are within valid
1942 // text content elements.
1943 eOriginal,
1944 // Iterate only over characters that are not skipped characters.
1945 eUnskipped,
1946 // Iterate only over characters that are addressable by the positioning
1947 // attributes x="", y="", etc. This includes all characters after
1948 // collapsing white space as required by the value of 'white-space'.
1949 eAddressable,
1950 };
1951
1952 /**
1953 * Constructs a CharIterator.
1954 *
1955 * @param aSVGTextFrame The SVGTextFrame whose characters to iterate
1956 * through.
1957 * @param aFilter Indicates which characters to iterate over.
1958 * @param aSubtree A content subtree to track whether the current character
1959 * is within.
1960 */
1961 CharIterator(SVGTextFrame* aSVGTextFrame, CharacterFilter aFilter,
1962 nsIContent* aSubtree, bool aPostReflow = true);
1963
1964 /**
1965 * Returns whether the iterator is finished.
1966 */
1967 bool AtEnd() const { return !mFrameIterator.Current(); }
1968
1969 /**
1970 * Advances to the next matching character. Returns true if there was a
1971 * character to advance to, and false otherwise.
1972 */
1973 bool Next();
1974
1975 /**
1976 * Advances ahead aCount matching characters. Returns true if there were
1977 * enough characters to advance past, and false otherwise.
1978 */
1979 bool Next(uint32_t aCount);
1980
1981 /**
1982 * Advances ahead up to aCount matching characters.
1983 */
1984 void NextWithinSubtree(uint32_t aCount);
1985
1986 /**
1987 * Advances to the character with the specified index. The index is in the
1988 * space of original characters (i.e., all DOM characters under the <text>
1989 * that are within valid text content elements).
1990 */
1991 bool AdvanceToCharacter(uint32_t aTextElementCharIndex);
1992
1993 /**
1994 * Advances to the first matching character after the current nsTextFrame.
1995 */
1996 bool AdvancePastCurrentFrame();
1997
1998 /**
1999 * Advances to the first matching character after the frames within
2000 * the current <textPath>.
2001 */
2002 bool AdvancePastCurrentTextPathFrame();
2003
2004 /**
2005 * Advances to the first matching character of the subtree. Returns true
2006 * if we successfully advance to the subtree, or if we are already within
2007 * the subtree. Returns false if we are past the subtree.
2008 */
2009 bool AdvanceToSubtree();
2010
2011 /**
2012 * Returns the nsTextFrame for the current character.
2013 */
2014 nsTextFrame* TextFrame() const { return mFrameIterator.Current(); }
2015
2016 /**
2017 * Returns whether the iterator is within the subtree.
2018 */
2019 bool IsWithinSubtree() const { return mFrameIterator.IsWithinSubtree(); }
2020
2021 /**
2022 * Returns whether the iterator is past the subtree.
2023 */
2024 bool IsAfterSubtree() const { return mFrameIterator.IsAfterSubtree(); }
2025
2026 /**
2027 * Returns whether the current character is a skipped character.
2028 */
2029 bool IsOriginalCharSkipped() const {
2030 return mSkipCharsIterator.IsOriginalCharSkipped();
2031 }
2032
2033 /**
2034 * Returns whether the current character is the start of a cluster and
2035 * ligature group.
2036 */
2037 bool IsClusterAndLigatureGroupStart() const {
2038 return mTextRun->IsLigatureGroupStart(
2039 mSkipCharsIterator.GetSkippedOffset()) &&
2040 mTextRun->IsClusterStart(mSkipCharsIterator.GetSkippedOffset());
2041 }
2042
2043 /**
2044 * Returns the glyph run for the current character.
2045 */
2046 const gfxTextRun::GlyphRun& GlyphRun() const {
2047 return *mTextRun->FindFirstGlyphRunContaining(
2048 mSkipCharsIterator.GetSkippedOffset());
2049 }
2050
2051 /**
2052 * Returns whether the current character is trimmed away when painting,
2053 * due to it being leading/trailing white space.
2054 */
2055 bool IsOriginalCharTrimmed() const;
2056
2057 /**
2058 * Returns whether the current character is unaddressable from the SVG glyph
2059 * positioning attributes.
2060 */
2061 bool IsOriginalCharUnaddressable() const {
2062 return IsOriginalCharSkipped() || IsOriginalCharTrimmed();
2063 }
2064
2065 /**
2066 * Returns the text run for the current character.
2067 */
2068 gfxTextRun* TextRun() const { return mTextRun; }
2069
2070 /**
2071 * Returns the current character index.
2072 */
2073 uint32_t TextElementCharIndex() const { return mTextElementCharIndex; }
2074
2075 /**
2076 * Returns the character index for the start of the cluster/ligature group it
2077 * is part of.
2078 */
2079 uint32_t GlyphStartTextElementCharIndex() const {
2080 return mGlyphStartTextElementCharIndex;
2081 }
2082
2083 /**
2084 * Gets the advance, in user units, of the current character. If the
2085 * character is a part of ligature, then the advance returned will be
2086 * a fraction of the ligature glyph's advance.
2087 *
2088 * @param aContext The context to use for unit conversions.
2089 */
2090 gfxFloat GetAdvance(nsPresContext* aContext) const;
2091
2092 /**
2093 * Returns the frame corresponding to the <textPath> that the current
2094 * character is within.
2095 */
2096 nsIFrame* TextPathFrame() const { return mFrameIterator.TextPathFrame(); }
2097
2098#ifdef DEBUG1
2099 /**
2100 * Returns the subtree we were constructed with.
2101 */
2102 nsIContent* GetSubtree() const { return mSubtree; }
2103
2104 /**
2105 * Returns the CharacterFilter mode in use.
2106 */
2107 CharacterFilter Filter() const { return mFilter; }
2108#endif
2109
2110 private:
2111 /**
2112 * Advances to the next character without checking it against the filter.
2113 * Returns true if there was a next character to advance to, or false
2114 * otherwise.
2115 */
2116 bool NextCharacter();
2117
2118 /**
2119 * Returns whether the current character matches the filter.
2120 */
2121 bool MatchesFilter() const;
2122
2123 /**
2124 * If this is the start of a glyph, record it.
2125 */
2126 void UpdateGlyphStartTextElementCharIndex() {
2127 if (!IsOriginalCharSkipped() && IsClusterAndLigatureGroupStart()) {
2128 mGlyphStartTextElementCharIndex = mTextElementCharIndex;
2129 }
2130 }
2131
2132 /**
2133 * The filter to use.
2134 */
2135 CharacterFilter mFilter;
2136
2137 /**
2138 * The iterator for text frames.
2139 */
2140 TextFrameIterator mFrameIterator;
2141
2142#ifdef DEBUG1
2143 /**
2144 * The subtree we were constructed with.
2145 */
2146 nsIContent* const mSubtree;
2147#endif
2148
2149 /**
2150 * A gfxSkipCharsIterator for the text frame the current character is
2151 * a part of.
2152 */
2153 gfxSkipCharsIterator mSkipCharsIterator;
2154
2155 // Cache for information computed by IsOriginalCharTrimmed.
2156 mutable nsTextFrame* mFrameForTrimCheck;
2157 mutable uint32_t mTrimmedOffset;
2158 mutable uint32_t mTrimmedLength;
2159
2160 /**
2161 * The text run the current character is a part of.
2162 */
2163 gfxTextRun* mTextRun;
2164
2165 /**
2166 * The current character's index.
2167 */
2168 uint32_t mTextElementCharIndex;
2169
2170 /**
2171 * The index of the character that starts the cluster/ligature group the
2172 * current character is a part of.
2173 */
2174 uint32_t mGlyphStartTextElementCharIndex;
2175
2176 /**
2177 * The scale factor to apply to glyph advances returned by
2178 * GetAdvance etc. to take into account textLength="".
2179 */
2180 float mLengthAdjustScaleFactor;
2181
2182 /**
2183 * Whether the instance of this class is being used after reflow has occurred
2184 * or not.
2185 */
2186 bool mPostReflow;
2187};
2188
2189CharIterator::CharIterator(SVGTextFrame* aSVGTextFrame,
2190 CharIterator::CharacterFilter aFilter,
2191 nsIContent* aSubtree, bool aPostReflow)
2192 : mFilter(aFilter),
2193 mFrameIterator(aSVGTextFrame, aSubtree),
2194#ifdef DEBUG1
2195 mSubtree(aSubtree),
2196#endif
2197 mFrameForTrimCheck(nullptr),
2198 mTrimmedOffset(0),
2199 mTrimmedLength(0),
2200 mTextRun(nullptr),
2201 mTextElementCharIndex(0),
2202 mGlyphStartTextElementCharIndex(0),
2203 mLengthAdjustScaleFactor(aSVGTextFrame->mLengthAdjustScaleFactor),
2204 mPostReflow(aPostReflow) {
2205 if (!AtEnd()) {
2206 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2207 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2208 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
2209 UpdateGlyphStartTextElementCharIndex();
2210 if (!MatchesFilter()) {
2211 Next();
2212 }
2213 }
2214}
2215
2216bool CharIterator::Next() {
2217 while (NextCharacter()) {
2218 if (MatchesFilter()) {
2219 return true;
2220 }
2221 }
2222 return false;
2223}
2224
2225bool CharIterator::Next(uint32_t aCount) {
2226 if (aCount == 0 && AtEnd()) {
2227 return false;
2228 }
2229 while (aCount) {
2230 if (!Next()) {
2231 return false;
2232 }
2233 aCount--;
2234 }
2235 return true;
2236}
2237
2238void CharIterator::NextWithinSubtree(uint32_t aCount) {
2239 while (IsWithinSubtree() && aCount) {
2240 --aCount;
2241 if (!Next()) {
2242 return;
2243 }
2244 }
2245}
2246
2247bool CharIterator::AdvanceToCharacter(uint32_t aTextElementCharIndex) {
2248 while (mTextElementCharIndex < aTextElementCharIndex) {
2249 if (!Next()) {
2250 return false;
2251 }
2252 }
2253 return true;
2254}
2255
2256bool CharIterator::AdvancePastCurrentFrame() {
2257 // XXX Can do this better than one character at a time if it matters.
2258 nsTextFrame* currentFrame = TextFrame();
2259 do {
2260 if (!Next()) {
2261 return false;
2262 }
2263 } while (TextFrame() == currentFrame);
2264 return true;
2265}
2266
2267bool CharIterator::AdvancePastCurrentTextPathFrame() {
2268 nsIFrame* currentTextPathFrame = TextPathFrame();
2269 NS_ASSERTION(currentTextPathFrame,do { if (!(currentTextPathFrame)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "expected AdvancePastCurrentTextPathFrame to be called only "
"within a text path frame", "currentTextPathFrame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2271); MOZ_PretendNoReturn(); } } while (0)
2270 "expected AdvancePastCurrentTextPathFrame to be called only "do { if (!(currentTextPathFrame)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "expected AdvancePastCurrentTextPathFrame to be called only "
"within a text path frame", "currentTextPathFrame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2271); MOZ_PretendNoReturn(); } } while (0)
2271 "within a text path frame")do { if (!(currentTextPathFrame)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "expected AdvancePastCurrentTextPathFrame to be called only "
"within a text path frame", "currentTextPathFrame", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2271); MOZ_PretendNoReturn(); } } while (0)
;
2272 do {
2273 if (!AdvancePastCurrentFrame()) {
2274 return false;
2275 }
2276 } while (TextPathFrame() == currentTextPathFrame);
2277 return true;
2278}
2279
2280bool CharIterator::AdvanceToSubtree() {
2281 while (!IsWithinSubtree()) {
2282 if (IsAfterSubtree()) {
2283 return false;
2284 }
2285 if (!AdvancePastCurrentFrame()) {
2286 return false;
2287 }
2288 }
2289 return true;
2290}
2291
2292bool CharIterator::IsOriginalCharTrimmed() const {
2293 if (mFrameForTrimCheck != TextFrame()) {
2294 // Since we do a lot of trim checking, we cache the trimmed offsets and
2295 // lengths while we are in the same frame.
2296 mFrameForTrimCheck = TextFrame();
2297 uint32_t offset = mFrameForTrimCheck->GetContentOffset();
2298 uint32_t length = mFrameForTrimCheck->GetContentLength();
2299 nsTextFrame::TrimmedOffsets trim = mFrameForTrimCheck->GetTrimmedOffsets(
2300 mFrameForTrimCheck->TextFragment(),
2301 (mPostReflow ? nsTextFrame::TrimmedOffsetFlags::Default
2302 : nsTextFrame::TrimmedOffsetFlags::NotPostReflow));
2303 TrimOffsets(offset, length, trim);
2304 mTrimmedOffset = offset;
2305 mTrimmedLength = length;
2306 }
2307
2308 // A character is trimmed if it is outside the mTrimmedOffset/mTrimmedLength
2309 // range and it is not a significant newline character.
2310 uint32_t index = mSkipCharsIterator.GetOriginalOffset();
2311 return !(
2312 (index >= mTrimmedOffset && index < mTrimmedOffset + mTrimmedLength) ||
2313 (index >= mTrimmedOffset + mTrimmedLength &&
2314 mFrameForTrimCheck->StyleText()->NewlineIsSignificant(
2315 mFrameForTrimCheck) &&
2316 mFrameForTrimCheck->TextFragment()->CharAt(index) == '\n'));
2317}
2318
2319gfxFloat CharIterator::GetAdvance(nsPresContext* aContext) const {
2320 float cssPxPerDevPx =
2321 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
2322
2323 gfxSkipCharsIterator start =
2324 TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2325 nsTextFrame::PropertyProvider provider(TextFrame(), start);
2326
2327 uint32_t offset = mSkipCharsIterator.GetSkippedOffset();
2328 gfxFloat advance =
2329 mTextRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
2330 return aContext->AppUnitsToGfxUnits(advance) * mLengthAdjustScaleFactor *
2331 cssPxPerDevPx;
2332}
2333
2334bool CharIterator::NextCharacter() {
2335 if (AtEnd()) {
2336 return false;
2337 }
2338
2339 mTextElementCharIndex++;
2340
2341 // Advance within the current text run.
2342 mSkipCharsIterator.AdvanceOriginal(1);
2343 if (mSkipCharsIterator.GetOriginalOffset() < TextFrame()->GetContentEnd()) {
2344 // We're still within the part of the text run for the current text frame.
2345 UpdateGlyphStartTextElementCharIndex();
2346 return true;
2347 }
2348
2349 // Advance to the next frame.
2350 mFrameIterator.Next();
2351
2352 // Skip any undisplayed characters.
2353 uint32_t undisplayed = mFrameIterator.UndisplayedCharacters();
2354 mTextElementCharIndex += undisplayed;
2355 if (!TextFrame()) {
2356 // We're at the end.
2357 mSkipCharsIterator = gfxSkipCharsIterator();
2358 return false;
2359 }
2360
2361 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2362 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2363 UpdateGlyphStartTextElementCharIndex();
2364 return true;
2365}
2366
2367bool CharIterator::MatchesFilter() const {
2368 switch (mFilter) {
2369 case eOriginal:
2370 return true;
2371 case eUnskipped:
2372 return !IsOriginalCharSkipped();
2373 case eAddressable:
2374 return !IsOriginalCharSkipped() && !IsOriginalCharUnaddressable();
2375 }
2376 MOZ_ASSERT_UNREACHABLE("Invalid mFilter 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: "
"Invalid mFilter value" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2376); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Invalid mFilter value" ")"); do {
*((volatile int*)__null) = 2376; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
2377 return true;
2378}
2379
2380// -----------------------------------------------------------------------------
2381// SVGTextDrawPathCallbacks
2382
2383/**
2384 * Text frame draw callback class that paints the text and text decoration parts
2385 * of an nsTextFrame using SVG painting properties, and selection backgrounds
2386 * and decorations as they would normally.
2387 *
2388 * An instance of this class is passed to nsTextFrame::PaintText if painting
2389 * cannot be done directly (e.g. if we are using an SVG pattern fill, stroking
2390 * the text, etc.).
2391 */
2392class SVGTextDrawPathCallbacks final : public nsTextFrame::DrawPathCallbacks {
2393 using imgDrawingParams = image::imgDrawingParams;
2394
2395 public:
2396 /**
2397 * Constructs an SVGTextDrawPathCallbacks.
2398 *
2399 * @param aSVGTextFrame The ancestor text frame.
2400 * @param aContext The context to use for painting.
2401 * @param aFrame The nsTextFrame to paint.
2402 * @param aCanvasTM The transformation matrix to set when painting; this
2403 * should be the FOR_OUTERSVG_TM canvas TM of the text, so that
2404 * paint servers are painted correctly.
2405 * @param aImgParams Whether we need to synchronously decode images.
2406 * @param aShouldPaintSVGGlyphs Whether SVG glyphs should be painted.
2407 */
2408 SVGTextDrawPathCallbacks(SVGTextFrame* aSVGTextFrame, gfxContext& aContext,
2409 nsTextFrame* aFrame, const gfxMatrix& aCanvasTM,
2410 imgDrawingParams& aImgParams,
2411 bool aShouldPaintSVGGlyphs)
2412 : DrawPathCallbacks(aShouldPaintSVGGlyphs),
2413 mSVGTextFrame(aSVGTextFrame),
2414 mContext(aContext),
2415 mFrame(aFrame),
2416 mCanvasTM(aCanvasTM),
2417 mImgParams(aImgParams) {}
2418
2419 void NotifySelectionBackgroundNeedsFill(const Rect& aBackgroundRect,
2420 nscolor aColor,
2421 DrawTarget& aDrawTarget) override;
2422 void PaintDecorationLine(Rect aPath, bool aPaintingShadows,
2423 nscolor aColor) override;
2424 void PaintSelectionDecorationLine(Rect aPath, bool aPaintingShadows,
2425 nscolor aColor) override;
2426 void NotifyBeforeText(bool aPaintingShadows, nscolor aColor) override;
2427 void NotifyGlyphPathEmitted() override;
2428 void NotifyAfterText() override;
2429
2430 private:
2431 void SetupContext();
2432
2433 bool IsClipPathChild() const {
2434 return mSVGTextFrame->HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD);
2435 }
2436
2437 /**
2438 * Paints a piece of text geometry. This is called when glyphs
2439 * or text decorations have been emitted to the gfxContext.
2440 */
2441 void HandleTextGeometry();
2442
2443 /**
2444 * Sets the gfxContext paint to the appropriate color or pattern
2445 * for filling text geometry.
2446 */
2447 void MakeFillPattern(GeneralPattern* aOutPattern);
2448
2449 /**
2450 * Fills and strokes a piece of text geometry, using group opacity
2451 * if the selection style requires it.
2452 */
2453 void FillAndStrokeGeometry();
2454
2455 /**
2456 * Fills a piece of text geometry.
2457 */
2458 void FillGeometry();
2459
2460 /**
2461 * Strokes a piece of text geometry.
2462 */
2463 void StrokeGeometry();
2464
2465 /*
2466 * Takes a colour and modifies it to account for opacity properties.
2467 */
2468 void ApplyOpacity(sRGBColor& aColor, const StyleSVGPaint& aPaint,
2469 const StyleSVGOpacity& aOpacity) const;
2470
2471 SVGTextFrame* const mSVGTextFrame;
2472 gfxContext& mContext;
2473 nsTextFrame* const mFrame;
2474 const gfxMatrix& mCanvasTM;
2475 imgDrawingParams& mImgParams;
2476
2477 /**
2478 * The color that we were last told from one of the path callback functions.
2479 * This color can be the special NS_SAME_AS_FOREGROUND_COLOR,
2480 * NS_40PERCENT_FOREGROUND_COLOR and NS_TRANSPARENT colors when we are
2481 * painting selections or IME decorations.
2482 */
2483 nscolor mColor = NS_RGBA(0, 0, 0, 0)((nscolor)(((0) << 24) | ((0) << 16) | ((0) <<
8) | (0)))
;
2484
2485 /**
2486 * Whether we're painting text shadows.
2487 */
2488 bool mPaintingShadows = false;
2489};
2490
2491void SVGTextDrawPathCallbacks::NotifySelectionBackgroundNeedsFill(
2492 const Rect& aBackgroundRect, nscolor aColor, DrawTarget& aDrawTarget) {
2493 if (IsClipPathChild()) {
2494 // Don't paint selection backgrounds when in a clip path.
2495 return;
2496 }
2497
2498 mColor = aColor; // currently needed by MakeFillPattern
2499 mPaintingShadows = false;
2500
2501 GeneralPattern fillPattern;
2502 MakeFillPattern(&fillPattern);
2503 if (fillPattern.GetPattern()) {
2504 DrawOptions drawOptions(aColor == NS_40PERCENT_FOREGROUND_COLOR ? 0.4
2505 : 1.0);
2506 aDrawTarget.FillRect(aBackgroundRect, fillPattern, drawOptions);
2507 }
2508}
2509
2510void SVGTextDrawPathCallbacks::NotifyBeforeText(bool aPaintingShadows,
2511 nscolor aColor) {
2512 mColor = aColor;
2513 mPaintingShadows = aPaintingShadows;
2514 SetupContext();
2515 mContext.NewPath();
2516}
2517
2518void SVGTextDrawPathCallbacks::NotifyGlyphPathEmitted() {
2519 HandleTextGeometry();
2520 mContext.NewPath();
2521}
2522
2523void SVGTextDrawPathCallbacks::NotifyAfterText() { mContext.Restore(); }
2524
2525void SVGTextDrawPathCallbacks::PaintDecorationLine(Rect aPath,
2526 bool aPaintingShadows,
2527 nscolor aColor) {
2528 mColor = aColor;
2529 mPaintingShadows = aPaintingShadows;
2530 AntialiasMode aaMode =
2531 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2532
2533 mContext.Save();
2534 mContext.NewPath();
2535 mContext.SetAntialiasMode(aaMode);
2536 mContext.Rectangle(ThebesRect(aPath));
2537 HandleTextGeometry();
2538 mContext.NewPath();
2539 mContext.Restore();
2540}
2541
2542void SVGTextDrawPathCallbacks::PaintSelectionDecorationLine(
2543 Rect aPath, bool aPaintingShadows, nscolor aColor) {
2544 if (IsClipPathChild()) {
2545 // Don't paint selection decorations when in a clip path.
2546 return;
2547 }
2548
2549 mColor = aColor;
2550 mPaintingShadows = aPaintingShadows;
2551
2552 mContext.Save();
2553 mContext.NewPath();
2554 mContext.Rectangle(ThebesRect(aPath));
2555 FillAndStrokeGeometry();
2556 mContext.Restore();
2557}
2558
2559void SVGTextDrawPathCallbacks::SetupContext() {
2560 mContext.Save();
2561
2562 // XXX This is copied from nsSVGGlyphFrame::Render, but cairo doesn't actually
2563 // seem to do anything with the antialias mode. So we can perhaps remove it,
2564 // or make SetAntialiasMode set cairo text antialiasing too.
2565 mContext.SetAntialiasMode(
2566 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering));
2567}
2568
2569void SVGTextDrawPathCallbacks::HandleTextGeometry() {
2570 if (IsClipPathChild()) {
2571 RefPtr<Path> path = mContext.GetPath();
2572 ColorPattern white(
2573 DeviceColor(1.f, 1.f, 1.f, 1.f)); // for masking, so no ToDeviceColor
2574 mContext.GetDrawTarget()->Fill(path, white);
2575 } else {
2576 // Normal painting.
2577 gfxContextMatrixAutoSaveRestore saveMatrix(&mContext);
2578 mContext.SetMatrixDouble(mCanvasTM);
2579
2580 FillAndStrokeGeometry();
2581 }
2582}
2583
2584void SVGTextDrawPathCallbacks::ApplyOpacity(
2585 sRGBColor& aColor, const StyleSVGPaint& aPaint,
2586 const StyleSVGOpacity& aOpacity) const {
2587 if (aPaint.kind.tag == StyleSVGPaintKind::Tag::Color) {
2588 aColor.a *=
2589 sRGBColor::FromABGR(aPaint.kind.AsColor().CalcColor(*mFrame->Style()))
2590 .a;
2591 }
2592 aColor.a *= SVGUtils::GetOpacity(aOpacity, /*aContextPaint*/ nullptr);
2593}
2594
2595void SVGTextDrawPathCallbacks::MakeFillPattern(GeneralPattern* aOutPattern) {
2596 if (mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2597 mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2598 SVGUtils::MakeFillPatternFor(mFrame, &mContext, aOutPattern, mImgParams);
2599 return;
2600 }
2601
2602 if (mColor == NS_TRANSPARENT) {
2603 return;
2604 }
2605
2606 sRGBColor color(sRGBColor::FromABGR(mColor));
2607 if (mPaintingShadows) {
2608 ApplyOpacity(color, mFrame->StyleSVG()->mFill,
2609 mFrame->StyleSVG()->mFillOpacity);
2610 }
2611 aOutPattern->InitColorPattern(ToDeviceColor(color));
2612}
2613
2614void SVGTextDrawPathCallbacks::FillAndStrokeGeometry() {
2615 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&mContext);
2616 if (mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2617 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 0.4f);
2618 }
2619
2620 uint32_t paintOrder = mFrame->StyleSVG()->mPaintOrder;
2621 if (!paintOrder) {
2622 FillGeometry();
2623 StrokeGeometry();
2624 } else {
2625 while (paintOrder) {
2626 auto component = StylePaintOrder(paintOrder & kPaintOrderMask);
2627 switch (component) {
2628 case StylePaintOrder::Fill:
2629 FillGeometry();
2630 break;
2631 case StylePaintOrder::Stroke:
2632 StrokeGeometry();
2633 break;
2634 default:
2635 MOZ_FALLTHROUGH_ASSERT("Unknown paint-order value")do { do { } while (false); MOZ_ReportCrash("" "MOZ_FALLTHROUGH_ASSERT: "
"Unknown paint-order value", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2635); AnnotateMozCrashReason("MOZ_CRASH(" "MOZ_FALLTHROUGH_ASSERT: "
"Unknown paint-order value" ")"); do { *((volatile int*)__null
) = 2635; __attribute__((nomerge)) ::abort(); } while (false)
; } while (false)
;
2636 case StylePaintOrder::Markers:
2637 case StylePaintOrder::Normal:
2638 break;
2639 }
2640 paintOrder >>= kPaintOrderShift;
2641 }
2642 }
2643}
2644
2645void SVGTextDrawPathCallbacks::FillGeometry() {
2646 if (mFrame->StyleSVG()->mFill.kind.IsNone()) {
2647 return;
2648 }
2649 GeneralPattern fillPattern;
2650 MakeFillPattern(&fillPattern);
2651 if (fillPattern.GetPattern()) {
2652 RefPtr<Path> path = mContext.GetPath();
2653 FillRule fillRule = SVGUtils::ToFillRule(mFrame->StyleSVG()->mFillRule);
2654 if (fillRule != path->GetFillRule()) {
2655 Path::SetFillRule(path, fillRule);
2656 }
2657 mContext.GetDrawTarget()->Fill(path, fillPattern);
2658 }
2659}
2660
2661void SVGTextDrawPathCallbacks::StrokeGeometry() {
2662 // We don't paint the stroke when we are filling with a selection color.
2663 if (!(mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2664 mColor == NS_40PERCENT_FOREGROUND_COLOR || mPaintingShadows)) {
2665 return;
2666 }
2667
2668 if (!SVGUtils::HasStroke(mFrame, /*aContextPaint*/ nullptr)) {
2669 return;
2670 }
2671
2672 GeneralPattern strokePattern;
2673 if (mPaintingShadows) {
2674 sRGBColor color(sRGBColor::FromABGR(mColor));
2675 ApplyOpacity(color, mFrame->StyleSVG()->mStroke,
2676 mFrame->StyleSVG()->mStrokeOpacity);
2677 strokePattern.InitColorPattern(ToDeviceColor(color));
2678 } else {
2679 SVGUtils::MakeStrokePatternFor(mFrame, &mContext, &strokePattern,
2680 mImgParams, /*aContextPaint*/ nullptr);
2681 }
2682 if (strokePattern.GetPattern()) {
2683 SVGElement* svgOwner =
2684 SVGElement::FromNode(mFrame->GetParent()->GetContent());
2685
2686 // Apply any stroke-specific transform
2687 gfxMatrix outerSVGToUser;
2688 if (SVGUtils::GetNonScalingStrokeTransform(mFrame, &outerSVGToUser) &&
2689 outerSVGToUser.Invert()) {
2690 mContext.Multiply(outerSVGToUser);
2691 }
2692
2693 RefPtr<Path> path = mContext.GetPath();
2694 SVGContentUtils::AutoStrokeOptions strokeOptions;
2695 SVGContentUtils::GetStrokeOptions(&strokeOptions, svgOwner, mFrame->Style(),
2696 /*aContextPaint*/ nullptr);
2697 DrawOptions drawOptions;
2698 drawOptions.mAntialiasMode =
2699 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2700 mContext.GetDrawTarget()->Stroke(path, strokePattern, strokeOptions);
2701 }
2702}
2703
2704// ============================================================================
2705// SVGTextFrame
2706
2707// ----------------------------------------------------------------------------
2708// Display list item
2709
2710class DisplaySVGText final : public DisplaySVGItem {
2711 public:
2712 DisplaySVGText(nsDisplayListBuilder* aBuilder, SVGTextFrame* aFrame)
2713 : DisplaySVGItem(aBuilder, aFrame) {
2714 MOZ_COUNT_CTOR(DisplaySVGText)do { static_assert(std::is_class_v<DisplaySVGText>, "Token '"
"DisplaySVGText" "' is not a class type."); static_assert(!std
::is_base_of<nsISupports, DisplaySVGText>::value, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogCtor((void*)this, "DisplaySVGText"
, sizeof(*this)); } while (0)
;
2715 }
2716
2717 MOZ_COUNTED_DTOR_FINAL(DisplaySVGText)~DisplaySVGText() final { do { static_assert(std::is_class_v<
DisplaySVGText>, "Token '" "DisplaySVGText" "' is not a class type."
); static_assert(!std::is_base_of<nsISupports, DisplaySVGText
>::value, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogDtor((void*)this, "DisplaySVGText"
, sizeof(*this)); } while (0); }
2718
2719 NS_DISPLAY_DECL_NAME("DisplaySVGText", TYPE_SVG_TEXT)const char* Name() const override { return "DisplaySVGText"; }
constexpr static DisplayItemType ItemType() { return DisplayItemType
::TYPE_SVG_TEXT; } private: void* operator new(size_t aSize, nsDisplayListBuilder
* aBuilder) { return aBuilder->Allocate(aSize, DisplayItemType
::TYPE_SVG_TEXT); } template <typename T, typename F, typename
... Args> friend T* mozilla::MakeDisplayItemWithIndex( nsDisplayListBuilder
* aBuilder, F* aFrame, const uint16_t aIndex, Args&&...
aArgs); public:
2720
2721 nsDisplayItemGeometry* AllocateGeometry(
2722 nsDisplayListBuilder* aBuilder) override {
2723 return new nsDisplayItemGenericGeometry(this, aBuilder);
2724 }
2725
2726 nsRect GetComponentAlphaBounds(
2727 nsDisplayListBuilder* aBuilder) const override {
2728 bool snap;
2729 return GetBounds(aBuilder, &snap);
2730 }
2731};
2732
2733// ---------------------------------------------------------------------
2734// nsQueryFrame methods
2735
2736NS_QUERYFRAME_HEAD(SVGTextFrame)void* SVGTextFrame ::QueryFrame(FrameIID id) const { switch (
id) {
2737 NS_QUERYFRAME_ENTRY(SVGTextFrame)case SVGTextFrame ::kFrameIID: { static_assert( std::is_same_v
<SVGTextFrame, SVGTextFrame ::Has_NS_DECL_QUERYFRAME_TARGET
>, "SVGTextFrame" " must declare itself as a queryframe target"
); return const_cast<SVGTextFrame*>(static_cast<const
SVGTextFrame*>(this)); }
2738NS_QUERYFRAME_TAIL_INHERITING(SVGDisplayContainerFrame)default: break; } return SVGDisplayContainerFrame ::QueryFrame
(id); }
2739
2740} // namespace mozilla
2741
2742// ---------------------------------------------------------------------
2743// Implementation
2744
2745nsIFrame* NS_NewSVGTextFrame(mozilla::PresShell* aPresShell,
2746 mozilla::ComputedStyle* aStyle) {
2747 return new (aPresShell)
2748 mozilla::SVGTextFrame(aStyle, aPresShell->GetPresContext());
2749}
2750
2751namespace mozilla {
2752
2753NS_IMPL_FRAMEARENA_HELPERS(SVGTextFrame)void* SVGTextFrame ::operator new(size_t sz, mozilla::PresShell
* aShell) { return aShell->AllocateFrame(nsQueryFrame::SVGTextFrame_id
, sz); }
2754
2755// ---------------------------------------------------------------------
2756// nsIFrame methods
2757
2758void SVGTextFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
2759 nsIFrame* aPrevInFlow) {
2760 NS_ASSERTION(aContent->IsSVGElement(nsGkAtoms::text),do { if (!(aContent->IsSVGElement(nsGkAtoms::text))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Content is not an SVG text", "aContent->IsSVGElement(nsGkAtoms::text)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2761); MOZ_PretendNoReturn(); } } while (0)
2761 "Content is not an SVG text")do { if (!(aContent->IsSVGElement(nsGkAtoms::text))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Content is not an SVG text", "aContent->IsSVGElement(nsGkAtoms::text)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2761); MOZ_PretendNoReturn(); } } while (0)
;
2762
2763 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
2764 AddStateBits(aParent->GetStateBits() & NS_STATE_SVG_CLIPPATH_CHILD);
2765
2766 mMutationObserver = new MutationObserver(this);
2767
2768 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2769 // We're inserting a new <text> element into a non-display context.
2770 // Ensure that we get reflowed.
2771 ScheduleReflowSVGNonDisplayText(
2772 IntrinsicDirty::FrameAncestorsAndDescendants);
2773 }
2774}
2775
2776void SVGTextFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
2777 const nsDisplayListSet& aLists) {
2778 if (IsSubtreeDirty()) {
2779 // We can sometimes be asked to paint before reflow happens and we
2780 // have updated mPositions, etc. In this case, we just avoid
2781 // painting.
2782 return;
2783 }
2784 if (!IsVisibleForPainting() && aBuilder->IsForPainting()) {
2785 return;
2786 }
2787 DisplayOutline(aBuilder, aLists);
2788 aLists.Content()->AppendNewToTop<DisplaySVGText>(aBuilder, this);
2789}
2790
2791void SVGTextFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
2792 SVGDisplayContainerFrame::DidSetComputedStyle(aOldComputedStyle);
2793 if (StyleSVGReset()->HasNonScalingStroke() &&
2794 (!aOldComputedStyle ||
2795 !aOldComputedStyle->StyleSVGReset()->HasNonScalingStroke())) {
2796 SVGUtils::UpdateNonScalingStrokeStateBit(this);
2797 }
2798}
2799
2800nsresult SVGTextFrame::AttributeChanged(int32_t aNameSpaceID,
2801 nsAtom* aAttribute, int32_t aModType) {
2802 if (aNameSpaceID != kNameSpaceID_None) {
2803 return NS_OK;
2804 }
2805
2806 if (aAttribute == nsGkAtoms::transform) {
2807 // We don't invalidate for transform changes (the layers code does that).
2808 // Also note that SVGTransformableElement::GetAttributeChangeHint will
2809 // return nsChangeHint_UpdateOverflow for "transform" attribute changes
2810 // and cause DoApplyRenderingChangeToTree to make the SchedulePaint call.
2811
2812 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && mCanvasTM &&
2813 mCanvasTM->IsSingular()) {
2814 // We won't have calculated the glyph positions correctly.
2815 NotifyGlyphMetricsChange(false);
2816 }
2817 mCanvasTM = nullptr;
2818 } else if (IsGlyphPositioningAttribute(aAttribute) ||
2819 aAttribute == nsGkAtoms::textLength ||
2820 aAttribute == nsGkAtoms::lengthAdjust) {
2821 NotifyGlyphMetricsChange(false);
2822 }
2823
2824 return NS_OK;
2825}
2826
2827void SVGTextFrame::ReflowSVGNonDisplayText() {
2828 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2830); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")"); do { *((volatile int*)__null) = 2830
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
2829 "only call ReflowSVGNonDisplayText when an outer SVG frame is "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2830); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")"); do { *((volatile int*)__null) = 2830
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
2830 "under ReflowSVG")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2830); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "only call ReflowSVGNonDisplayText when an outer SVG frame is "
"under ReflowSVG" ")"); do { *((volatile int*)__null) = 2830
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
2831 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
" (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2833); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
") (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")"); do { *((volatile int*)__null) = 2833; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2832 "only call ReflowSVGNonDisplayText if the frame is "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
" (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2833); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
") (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")"); do { *((volatile int*)__null) = 2833; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2833 "NS_FRAME_IS_NONDISPLAY")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
" (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2833); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
") (" "only call ReflowSVGNonDisplayText if the frame is " "NS_FRAME_IS_NONDISPLAY"
")"); do { *((volatile int*)__null) = 2833; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2834
2835 // We had a style change, so we mark this frame as dirty so that the next
2836 // time it is painted, we reflow the anonymous block frame.
2837 this->MarkSubtreeDirty();
2838
2839 // Finally, we need to actually reflow the anonymous block frame and update
2840 // mPositions, in case we are being reflowed immediately after a DOM
2841 // mutation that needs frame reconstruction.
2842 MaybeReflowAnonymousBlockChild();
2843 UpdateGlyphPositioning();
2844}
2845
2846void SVGTextFrame::ScheduleReflowSVGNonDisplayText(IntrinsicDirty aReason) {
2847 MOZ_ASSERT(!SVGUtils::OuterSVGIsCallingReflowSVG(this),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!SVGUtils::OuterSVGIsCallingReflowSVG(this))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!SVGUtils::OuterSVGIsCallingReflowSVG(this)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
" (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2849); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
") (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")"); do { *((volatile int*)__null
) = 2849; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
2848 "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!SVGUtils::OuterSVGIsCallingReflowSVG(this))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!SVGUtils::OuterSVGIsCallingReflowSVG(this)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
" (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2849); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
") (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")"); do { *((volatile int*)__null
) = 2849; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
2849 "frame is under ReflowSVG")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!SVGUtils::OuterSVGIsCallingReflowSVG(this))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!SVGUtils::OuterSVGIsCallingReflowSVG(this)))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
" (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2849); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!SVGUtils::OuterSVGIsCallingReflowSVG(this)"
") (" "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
"frame is under ReflowSVG" ")"); do { *((volatile int*)__null
) = 2849; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
2850 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
" (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2852); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
") (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")"); do { *((volatile int*)__null) =
2852; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
2851 "do not call ScheduleReflowSVGNonDisplayText while reflowing the "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
" (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2852); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
") (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")"); do { *((volatile int*)__null) =
2852; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
2852 "anonymous block child")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
" (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2852); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
") (" "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
"anonymous block child" ")"); do { *((volatile int*)__null) =
2852; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
;
2853
2854 // We need to find an ancestor frame that we can call FrameNeedsReflow
2855 // on that will cause the document to be marked as needing relayout,
2856 // and for that ancestor (or some further ancestor) to be marked as
2857 // a root to reflow. We choose the closest ancestor frame that is not
2858 // NS_FRAME_IS_NONDISPLAY and which is either an outer SVG frame or a
2859 // non-SVG frame. (We don't consider displayed SVG frame ancestors other
2860 // than SVGOuterSVGFrame, since calling FrameNeedsReflow on those other
2861 // SVG frames would do a bunch of unnecessary work on the SVG frames up to
2862 // the SVGOuterSVGFrame.)
2863
2864 nsIFrame* f = this;
2865 while (f) {
2866 if (!f->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2867 if (f->IsSubtreeDirty()) {
2868 // This is a displayed frame, so if it is already dirty, we will be
2869 // reflowed soon anyway. No need to call FrameNeedsReflow again, then.
2870 return;
2871 }
2872 if (!f->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
2873 break;
2874 }
2875 f->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
2876 }
2877 f = f->GetParent();
2878 }
2879
2880 MOZ_ASSERT(f, "should have found an ancestor frame to reflow")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(f)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(f))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("f" " (" "should have found an ancestor frame to reflow" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2880); AnnotateMozCrashReason("MOZ_ASSERT" "(" "f" ") (" "should have found an ancestor frame to reflow"
")"); do { *((volatile int*)__null) = 2880; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2881
2882 PresShell()->FrameNeedsReflow(f, aReason, NS_FRAME_IS_DIRTY);
2883}
2884
2885NS_IMPL_ISUPPORTS(SVGTextFrame::MutationObserver, nsIMutationObserver)MozExternalRefCountType SVGTextFrame::MutationObserver::AddRef
(void) { static_assert(!std::is_destructible_v<SVGTextFrame
::MutationObserver>, "Reference-counted class " "SVGTextFrame::MutationObserver"
" should not have a public destructor. " "Make this class's destructor non-public"
); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) >= 0))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) >= 0"
" (" "illegal refcnt" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2885); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) >= 0"
") (" "illegal refcnt" ")"); do { *((volatile int*)__null) =
2885; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("SVGTextFrame::MutationObserver" != nullptr)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!("SVGTextFrame::MutationObserver" != nullptr))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("\"SVGTextFrame::MutationObserver\" != nullptr"
" (" "Must specify a name" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2885); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"SVGTextFrame::MutationObserver\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 2885; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("SVGTextFrame::MutationObserver" " not thread-safe"
); nsrefcnt count = ++mRefCnt; NS_LogAddRef((this), (count), (
"SVGTextFrame::MutationObserver"), (uint32_t)(sizeof(*this)))
; return count; } MozExternalRefCountType SVGTextFrame::MutationObserver
::Release(void) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) > 0))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) > 0"
" (" "dup release" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2885); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) > 0"
") (" "dup release" ")"); do { *((volatile int*)__null) = 2885
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("SVGTextFrame::MutationObserver" != nullptr)>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!("SVGTextFrame::MutationObserver" != nullptr))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("\"SVGTextFrame::MutationObserver\" != nullptr"
" (" "Must specify a name" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2885); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"SVGTextFrame::MutationObserver\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 2885; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("SVGTextFrame::MutationObserver" " not thread-safe"
); const char* const nametmp = "SVGTextFrame::MutationObserver"
; nsrefcnt count = --mRefCnt; NS_LogRelease((this), (count), (
nametmp)); if (count == 0) { mRefCnt = 1; delete (this); return
0; } return count; } nsresult SVGTextFrame::MutationObserver
::QueryInterface(const nsIID& aIID, void** aInstancePtr) {
do { if (!(aInstancePtr)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "QueryInterface requires a non-NULL destination!", "aInstancePtr"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2885); MOZ_PretendNoReturn(); } } while (0); nsresult rv = NS_ERROR_FAILURE
; static_assert(1 > 0, "Need more arguments to NS_INTERFACE_TABLE"
); static const QITableEntry table[] = { {&mozilla::detail
::kImplementedIID<SVGTextFrame::MutationObserver, nsIMutationObserver
>, int32_t( reinterpret_cast<char*>(static_cast<nsIMutationObserver
*>((SVGTextFrame::MutationObserver*)0x1000)) - reinterpret_cast
<char*>((SVGTextFrame::MutationObserver*)0x1000))}, {&
mozilla::detail::kImplementedIID<SVGTextFrame::MutationObserver
, nsISupports>, int32_t(reinterpret_cast<char*>(static_cast
<nsISupports*>( static_cast<nsIMutationObserver*>
((SVGTextFrame::MutationObserver*)0x1000))) - reinterpret_cast
<char*>((SVGTextFrame::MutationObserver*)0x1000))}, { nullptr
, 0 } } ; static_assert(std::size(table) > 1, "need at least 1 interface"
); rv = NS_TableDrivenQI(static_cast<void*>(this), aIID
, aInstancePtr, table); return rv; }
2886
2887void SVGTextFrame::MutationObserver::ContentAppended(
2888 nsIContent* aFirstNewContent) {
2889 mFrame->NotifyGlyphMetricsChange(true);
2890}
2891
2892void SVGTextFrame::MutationObserver::ContentInserted(nsIContent* aChild) {
2893 mFrame->NotifyGlyphMetricsChange(true);
2894}
2895
2896void SVGTextFrame::MutationObserver::ContentWillBeRemoved(
2897 nsIContent* aChild, const BatchRemovalState* aState) {
2898 if (aState && !aState->mIsFirst) {
2899 return;
2900 }
2901 mFrame->NotifyGlyphMetricsChange(true);
2902}
2903
2904void SVGTextFrame::MutationObserver::CharacterDataChanged(
2905 nsIContent* aContent, const CharacterDataChangeInfo&) {
2906 mFrame->NotifyGlyphMetricsChange(true);
2907}
2908
2909void SVGTextFrame::MutationObserver::AttributeChanged(
2910 Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
2911 int32_t aModType, const nsAttrValue* aOldValue) {
2912 if (!aElement->IsSVGElement()) {
2913 return;
2914 }
2915
2916 // Attribute changes on this element will be handled by
2917 // SVGTextFrame::AttributeChanged.
2918 if (aElement == mFrame->GetContent()) {
2919 return;
2920 }
2921
2922 mFrame->HandleAttributeChangeInDescendant(aElement, aNameSpaceID, aAttribute);
2923}
2924
2925void SVGTextFrame::HandleAttributeChangeInDescendant(Element* aElement,
2926 int32_t aNameSpaceID,
2927 nsAtom* aAttribute) {
2928 if (aElement->IsSVGElement(nsGkAtoms::textPath)) {
2929 if (aNameSpaceID == kNameSpaceID_None &&
2930 (aAttribute == nsGkAtoms::startOffset ||
2931 aAttribute == nsGkAtoms::path || aAttribute == nsGkAtoms::side_)) {
2932 NotifyGlyphMetricsChange(false);
2933 } else if ((aNameSpaceID == kNameSpaceID_XLink4 ||
2934 aNameSpaceID == kNameSpaceID_None) &&
2935 aAttribute == nsGkAtoms::href) {
2936 // Blow away our reference, if any
2937 nsIFrame* childElementFrame = aElement->GetPrimaryFrame();
2938 if (childElementFrame) {
2939 SVGObserverUtils::RemoveTextPathObserver(childElementFrame);
2940 NotifyGlyphMetricsChange(false);
2941 }
2942 }
2943 } else {
2944 if (aNameSpaceID == kNameSpaceID_None &&
2945 IsGlyphPositioningAttribute(aAttribute)) {
2946 NotifyGlyphMetricsChange(false);
2947 }
2948 }
2949}
2950
2951void SVGTextFrame::FindCloserFrameForSelection(
2952 const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
2953 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2954 return;
2955 }
2956
2957 UpdateGlyphPositioning();
2958
2959 nsPresContext* presContext = PresContext();
2960
2961 // Find the frame that has the closest rendered run rect to aPoint.
2962 TextRenderedRunIterator it(this);
2963 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
2964 uint32_t flags = TextRenderedRun::eIncludeFill |
2965 TextRenderedRun::eIncludeStroke |
2966 TextRenderedRun::eNoHorizontalOverflow;
2967 SVGBBox userRect = run.GetUserSpaceRect(presContext, flags);
2968 float devPxPerCSSPx = presContext->CSSPixelsToDevPixels(1.f);
2969 userRect.Scale(devPxPerCSSPx);
2970
2971 if (!userRect.IsEmpty()) {
2972 gfxMatrix m;
2973 nsRect rect =
2974 SVGUtils::ToCanvasBounds(userRect.ToThebesRect(), m, presContext);
2975
2976 if (nsLayoutUtils::PointIsCloserToRect(aPoint, rect,
2977 aCurrentBestFrame->mXDistance,
2978 aCurrentBestFrame->mYDistance)) {
2979 aCurrentBestFrame->mFrame = run.mFrame;
2980 }
2981 }
2982 }
2983}
2984
2985//----------------------------------------------------------------------
2986// ISVGDisplayableFrame methods
2987
2988void SVGTextFrame::NotifySVGChanged(uint32_t aFlags) {
2989 MOZ_ASSERT(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED)" " ("
"Invalidation logic may need adjusting" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2990); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED)"
") (" "Invalidation logic may need adjusting" ")"); do { *((
volatile int*)__null) = 2990; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
2990 "Invalidation logic may need adjusting")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED)" " ("
"Invalidation logic may need adjusting" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 2990); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED)"
") (" "Invalidation logic may need adjusting" ")"); do { *((
volatile int*)__null) = 2990; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
2991
2992 bool needNewBounds = false;
2993 bool needGlyphMetricsUpdate = false;
2994 if ((aFlags & COORD_CONTEXT_CHANGED) &&
2995 HasAnyStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES)) {
2996 needGlyphMetricsUpdate = true;
2997 }
2998
2999 if (aFlags & TRANSFORM_CHANGED) {
3000 if (mCanvasTM && mCanvasTM->IsSingular()) {
3001 // We won't have calculated the glyph positions correctly.
3002 needNewBounds = true;
3003 needGlyphMetricsUpdate = true;
3004 }
3005 mCanvasTM = nullptr;
3006 if (StyleSVGReset()->HasNonScalingStroke()) {
3007 // Stroke currently contributes to our mRect, and our stroke depends on
3008 // the transform to our outer-<svg> if |vector-effect:non-scaling-stroke|.
3009 needNewBounds = true;
3010 }
3011
3012 // If the scale at which we computed our mFontSizeScaleFactor has changed by
3013 // at least a factor of two, reflow the text. This avoids reflowing text at
3014 // every tick of a transform animation, but ensures our glyph metrics
3015 // do not get too far out of sync with the final font size on the screen.
3016 const float scale = GetContextScale(this);
3017 if (scale != mLastContextScale) {
3018 if (mLastContextScale == 0.0f) {
3019 needNewBounds = true;
3020 needGlyphMetricsUpdate = true;
3021 } else {
3022 float change = scale / mLastContextScale;
3023 if (change >= 2.0f || change <= 0.5f) {
3024 needNewBounds = true;
3025 needGlyphMetricsUpdate = true;
3026 }
3027 }
3028 }
3029 }
3030
3031 if (needNewBounds) {
3032 // Ancestor changes can't affect how we render from the perspective of
3033 // any rendering observers that we may have, so we don't need to
3034 // invalidate them. We also don't need to invalidate ourself, since our
3035 // changed ancestor will have invalidated its entire area, which includes
3036 // our area.
3037 ScheduleReflowSVG();
3038 }
3039
3040 if (needGlyphMetricsUpdate) {
3041 // If we are positioned using percentage values we need to update our
3042 // position whenever our viewport's dimensions change. But only do this if
3043 // we have been reflowed once, otherwise the glyph positioning will be
3044 // wrong. (We need to wait until bidi reordering has been done.)
3045 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
3046 NotifyGlyphMetricsChange(false);
3047 }
3048 }
3049}
3050
3051/**
3052 * Gets the offset into a DOM node that the specified caret is positioned at.
3053 */
3054static int32_t GetCaretOffset(nsCaret* aCaret) {
3055 RefPtr<Selection> selection = aCaret->GetSelection();
3056 if (!selection) {
3057 return -1;
3058 }
3059
3060 return selection->AnchorOffset();
3061}
3062
3063/**
3064 * Returns whether the caret should be painted for a given TextRenderedRun
3065 * by checking whether the caret is in the range covered by the rendered run.
3066 *
3067 * @param aThisRun The TextRenderedRun to be painted.
3068 * @param aCaret The caret.
3069 */
3070static bool ShouldPaintCaret(const TextRenderedRun& aThisRun, nsCaret* aCaret) {
3071 int32_t caretOffset = GetCaretOffset(aCaret);
3072
3073 if (caretOffset < 0) {
3074 return false;
3075 }
3076
3077 return uint32_t(caretOffset) >= aThisRun.mTextFrameContentOffset &&
3078 uint32_t(caretOffset) < aThisRun.mTextFrameContentOffset +
3079 aThisRun.mTextFrameContentLength;
3080}
3081
3082void SVGTextFrame::PaintSVG(gfxContext& aContext, const gfxMatrix& aTransform,
3083 imgDrawingParams& aImgParams) {
3084 DrawTarget& aDrawTarget = *aContext.GetDrawTarget();
3085 nsIFrame* kid = PrincipalChildList().FirstChild();
3086 if (!kid) {
3087 return;
3088 }
3089
3090 nsPresContext* presContext = PresContext();
3091
3092 gfxMatrix initialMatrix = aContext.CurrentMatrixDouble();
3093
3094 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3095 // If we are in a canvas DrawWindow call that used the
3096 // DRAWWINDOW_DO_NOT_FLUSH flag, then we may still have out
3097 // of date frames. Just don't paint anything if they are
3098 // dirty.
3099 if (presContext->PresShell()->InDrawWindowNotFlushing() &&
3100 IsSubtreeDirty()) {
3101 return;
3102 }
3103 // Text frames inside <clipPath>, <mask>, etc. will never have had
3104 // ReflowSVG called on them, so call UpdateGlyphPositioning to do this now.
3105 UpdateGlyphPositioning();
3106 } else if (IsSubtreeDirty()) {
3107 // If we are asked to paint before reflow has recomputed mPositions etc.
3108 // directly via PaintSVG, rather than via a display list, then we need
3109 // to bail out here too.
3110 return;
3111 }
3112
3113 const float epsilon = 0.0001;
3114 if (abs(mLengthAdjustScaleFactor) < epsilon) {
3115 // A zero scale factor can be caused by having forced the text length to
3116 // zero. In this situation there is nothing to show.
3117 return;
3118 }
3119
3120 if (aTransform.IsSingular()) {
3121 NS_WARNING("Can't render text element!")NS_DebugBreak(NS_DEBUG_WARNING, "Can't render text element!",
nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3121)
;
3122 return;
3123 }
3124
3125 gfxMatrix matrixForPaintServers = aTransform * initialMatrix;
3126
3127 // SVG frames' PaintSVG methods paint in CSS px, but normally frames paint in
3128 // dev pixels. Here we multiply a CSS-px-to-dev-pixel factor onto aTransform
3129 // so our non-SVG nsTextFrame children paint correctly.
3130 auto auPerDevPx = presContext->AppUnitsPerDevPixel();
3131 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(auPerDevPx);
3132 gfxMatrix canvasTMForChildren = aTransform;
3133 canvasTMForChildren.PreScale(cssPxPerDevPx, cssPxPerDevPx);
3134 initialMatrix.PreScale(1 / cssPxPerDevPx, 1 / cssPxPerDevPx);
3135
3136 gfxContextMatrixAutoSaveRestore matSR(&aContext);
3137 aContext.NewPath();
3138 aContext.Multiply(canvasTMForChildren);
3139 gfxMatrix currentMatrix = aContext.CurrentMatrixDouble();
3140
3141 RefPtr<nsCaret> caret = presContext->PresShell()->GetCaret();
3142 nsIFrame* caretFrame = caret->GetPaintGeometry();
3143
3144 gfxContextAutoSaveRestore ctxSR;
3145 TextRenderedRunIterator it(this, TextRenderedRunIterator::eVisibleFrames);
3146 TextRenderedRun run = it.Current();
3147
3148 SVGContextPaint* outerContextPaint =
3149 SVGContextPaint::GetContextPaint(GetContent());
3150
3151 while (run.mFrame) {
3152 nsTextFrame* frame = run.mFrame;
3153
3154 auto contextPaint = MakeRefPtr<SVGContextPaintImpl>();
3155 DrawMode drawMode = contextPaint->Init(&aDrawTarget, initialMatrix, frame,
3156 outerContextPaint, aImgParams);
3157 if (drawMode & DrawMode::GLYPH_STROKE) {
3158 ctxSR.EnsureSaved(&aContext);
3159 // This may change the gfxContext's transform (for non-scaling stroke),
3160 // in which case this needs to happen before we call SetMatrix() below.
3161 SVGUtils::SetupStrokeGeometry(frame->GetParent(), &aContext,
3162 outerContextPaint);
3163 }
3164
3165 nscoord startEdge, endEdge;
3166 run.GetClipEdges(startEdge, endEdge);
3167
3168 // Set up the transform for painting the text frame for the substring
3169 // indicated by the run.
3170 gfxMatrix runTransform = run.GetTransformFromUserSpaceForPainting(
3171 presContext, startEdge, endEdge) *
3172 currentMatrix;
3173 aContext.SetMatrixDouble(runTransform);
3174
3175 if (drawMode != DrawMode(0)) {
3176 bool paintSVGGlyphs;
3177 nsTextFrame::PaintTextParams params(&aContext);
3178 params.framePt = Point();
3179 params.dirtyRect =
3180 LayoutDevicePixel::FromAppUnits(frame->InkOverflowRect(), auPerDevPx);
3181 params.contextPaint = contextPaint;
3182 bool isSelected;
3183 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
3184 params.state = nsTextFrame::PaintTextParams::GenerateTextMask;
3185 isSelected = false;
3186 } else {
3187 isSelected = frame->IsSelected();
3188 }
3189 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&aContext);
3190 float opacity = 1.0f;
3191 nsIFrame* ancestor = frame->GetParent();
3192 while (ancestor != this) {
3193 opacity *= ancestor->StyleEffects()->mOpacity;
3194 ancestor = ancestor->GetParent();
3195 }
3196 if (opacity < 1.0f) {
3197 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA,
3198 opacity);
3199 }
3200
3201 if (ShouldRenderAsPath(frame, paintSVGGlyphs)) {
3202 SVGTextDrawPathCallbacks callbacks(this, aContext, frame,
3203 matrixForPaintServers, aImgParams,
3204 paintSVGGlyphs);
3205 params.callbacks = &callbacks;
3206 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3207 } else {
3208 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3209 }
3210 }
3211
3212 if (frame == caretFrame && ShouldPaintCaret(run, caret)) {
3213 // XXX Should we be looking at the fill/stroke colours to paint the
3214 // caret with, rather than using the color property?
3215 caret->PaintCaret(aDrawTarget, frame, nsPoint());
3216 aContext.NewPath();
3217 }
3218
3219 run = it.Next();
3220 }
3221}
3222
3223nsIFrame* SVGTextFrame::GetFrameForPoint(const gfxPoint& aPoint) {
3224 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame")do { if (!(PrincipalChildList().FirstChild())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "must have a child frame", "PrincipalChildList().FirstChild()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3224); MOZ_PretendNoReturn(); } } while (0)
;
3225
3226 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3227 // Text frames inside <clipPath> will never have had ReflowSVG called on
3228 // them, so call UpdateGlyphPositioning to do this now. (Text frames
3229 // inside <mask> and other non-display containers will never need to
3230 // be hit tested.)
3231 UpdateGlyphPositioning();
3232 } else {
3233 NS_ASSERTION(!IsSubtreeDirty(), "reflow should have happened")do { if (!(!IsSubtreeDirty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "reflow should have happened", "!IsSubtreeDirty()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3233); MOZ_PretendNoReturn(); } } while (0)
;
3234 }
3235
3236 // Hit-testing any clip-path will typically be a lot quicker than the
3237 // hit-testing of our text frames in the loop below, so we do the former up
3238 // front to avoid unnecessarily wasting cycles on the latter.
3239 if (!SVGUtils::HitTestClip(this, aPoint)) {
3240 return nullptr;
3241 }
3242
3243 nsPresContext* presContext = PresContext();
3244
3245 // Ideally we'd iterate backwards so that we can just return the first frame
3246 // that is under aPoint. In practice this will rarely matter though since it
3247 // is rare for text in/under an SVG <text> element to overlap (i.e. the first
3248 // text frame that is hit will likely be the only text frame that is hit).
3249
3250 TextRenderedRunIterator it(this);
3251 nsIFrame* hit = nullptr;
3252 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3253 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3254 if (!hitTestFlags) {
3255 continue;
3256 }
3257
3258 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
3259 if (!m.Invert()) {
3260 return nullptr;
3261 }
3262
3263 gfxPoint pointInRunUserSpace = m.TransformPoint(aPoint);
3264 gfxRect frameRect = run.GetRunUserSpaceRect(
3265 presContext, TextRenderedRun::eIncludeFill |
3266 TextRenderedRun::eIncludeStroke)
3267 .ToThebesRect();
3268
3269 if (Inside(frameRect, pointInRunUserSpace)) {
3270 hit = run.mFrame;
3271 }
3272 }
3273 return hit;
3274}
3275
3276void SVGTextFrame::ReflowSVG() {
3277 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "This call is probaby a wasteful mistake" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3278); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "This call is probaby a wasteful mistake" ")"); do { *
((volatile int*)__null) = 3278; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
3278 "This call is probaby a wasteful mistake")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "This call is probaby a wasteful mistake" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3278); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "This call is probaby a wasteful mistake" ")"); do { *
((volatile int*)__null) = 3278; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
3279
3280 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
" (" "ReflowSVG mechanism not designed for this" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3281); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
") (" "ReflowSVG mechanism not designed for this" ")"); do {
*((volatile int*)__null) = 3281; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
3281 "ReflowSVG mechanism not designed for this")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
" (" "ReflowSVG mechanism not designed for this" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3281); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)"
") (" "ReflowSVG mechanism not designed for this" ")"); do {
*((volatile int*)__null) = 3281; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
3282
3283 if (!SVGUtils::NeedsReflowSVG(this)) {
3284 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY)))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
" (" "How did this happen?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3286); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
") (" "How did this happen?" ")"); do { *((volatile int*)__null
) = 3286; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3285 NS_STATE_SVG_POSITIONING_DIRTY),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY)))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
" (" "How did this happen?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3286); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
") (" "How did this happen?" ")"); do { *((volatile int*)__null
) = 3286; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3286 "How did this happen?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
| NS_STATE_SVG_POSITIONING_DIRTY)))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
" (" "How did this happen?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3286); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY | NS_STATE_SVG_POSITIONING_DIRTY)"
") (" "How did this happen?" ")"); do { *((volatile int*)__null
) = 3286; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
3287 return;
3288 }
3289
3290 MaybeReflowAnonymousBlockChild();
3291 UpdateGlyphPositioning();
3292
3293 nsPresContext* presContext = PresContext();
3294
3295 SVGBBox r;
3296 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames);
3297 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3298 uint32_t runFlags = 0;
3299 if (!run.mFrame->StyleSVG()->mFill.kind.IsNone()) {
3300 runFlags |= TextRenderedRun::eIncludeFill;
3301 }
3302 if (SVGUtils::HasStroke(run.mFrame)) {
3303 runFlags |= TextRenderedRun::eIncludeStroke;
3304 }
3305 // Our "visual" overflow rect needs to be valid for building display lists
3306 // for hit testing, which means that for certain values of 'pointer-events'
3307 // it needs to include the geometry of the fill or stroke even when the
3308 // fill/ stroke don't actually render (e.g. when stroke="none" or
3309 // stroke-opacity="0"). GetGeometryHitTestFlags accounts for
3310 // 'pointer-events'. The text-shadow is not part of the hit-test area.
3311 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3312 if (hitTestFlags & SVG_HIT_TEST_FILL0x01) {
3313 runFlags |= TextRenderedRun::eIncludeFill;
3314 }
3315 if (hitTestFlags & SVG_HIT_TEST_STROKE0x02) {
3316 runFlags |= TextRenderedRun::eIncludeStroke;
3317 }
3318
3319 if (runFlags) {
3320 r.UnionEdges(run.GetUserSpaceRect(presContext, runFlags));
3321 }
3322 }
3323
3324 if (r.IsEmpty()) {
3325 mRect.SetEmpty();
3326 } else {
3327 mRect = nsLayoutUtils::RoundGfxRectToAppRect(r.ToThebesRect(),
3328 AppUnitsPerCSSPixel());
3329
3330 // Due to rounding issues when we have a transform applied, we sometimes
3331 // don't include an additional row of pixels. For now, just inflate our
3332 // covered region.
3333 if (mLastContextScale != 0.0f) {
3334 mRect.Inflate(
3335 ceil(presContext->AppUnitsPerDevPixel() / mLastContextScale));
3336 }
3337 }
3338
3339 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
3340 // Make sure we have our filter property (if any) before calling
3341 // FinishAndStoreOverflow (subsequent filter changes are handled off
3342 // nsChangeHint_UpdateEffects):
3343 SVGObserverUtils::UpdateEffects(this);
3344 }
3345
3346 // Now unset the various reflow bits. Do this before calling
3347 // FinishAndStoreOverflow since FinishAndStoreOverflow can require glyph
3348 // positions (to resolve transform-origin).
3349 RemoveStateBits(NS_FRAME_FIRST_REFLOW | NS_FRAME_IS_DIRTY |
3350 NS_FRAME_HAS_DIRTY_CHILDREN);
3351
3352 nsRect overflow = nsRect(nsPoint(0, 0), mRect.Size());
3353 OverflowAreas overflowAreas(overflow, overflow);
3354 FinishAndStoreOverflow(overflowAreas, mRect.Size());
3355}
3356
3357/**
3358 * Converts SVGUtils::eBBox* flags into TextRenderedRun flags appropriate
3359 * for the specified rendered run.
3360 */
3361static uint32_t TextRenderedRunFlagsForBBoxContribution(
3362 const TextRenderedRun& aRun, uint32_t aBBoxFlags) {
3363 uint32_t flags = 0;
3364 if ((aBBoxFlags & SVGUtils::eBBoxIncludeFillGeometry) ||
3365 ((aBBoxFlags & SVGUtils::eBBoxIncludeFill) &&
3366 !aRun.mFrame->StyleSVG()->mFill.kind.IsNone())) {
3367 flags |= TextRenderedRun::eIncludeFill;
3368 }
3369 if ((aBBoxFlags & SVGUtils::eBBoxIncludeStrokeGeometry) ||
3370 ((aBBoxFlags & SVGUtils::eBBoxIncludeStroke) &&
3371 SVGUtils::HasStroke(aRun.mFrame))) {
3372 flags |= TextRenderedRun::eIncludeStroke;
3373 }
3374 return flags;
3375}
3376
3377SVGBBox SVGTextFrame::GetBBoxContribution(const Matrix& aToBBoxUserspace,
3378 uint32_t aFlags) {
3379 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame")do { if (!(PrincipalChildList().FirstChild())) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "must have a child frame", "PrincipalChildList().FirstChild()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3379); MOZ_PretendNoReturn(); } } while (0)
;
3380 SVGBBox bbox;
3381
3382 if (aFlags & SVGUtils::eForGetClientRects) {
3383 Rect rect = NSRectToRect(mRect, AppUnitsPerCSSPixel());
3384 if (!rect.IsEmpty()) {
3385 bbox = aToBBoxUserspace.TransformBounds(rect);
3386 }
3387 return bbox;
3388 }
3389
3390 nsIFrame* kid = PrincipalChildList().FirstChild();
3391 if (kid && kid->IsSubtreeDirty()) {
3392 // Return an empty bbox if our kid's subtree is dirty. This may be called
3393 // in that situation, e.g. when we're building a display list after an
3394 // interrupted reflow. This can also be called during reflow before we've
3395 // been reflowed, e.g. if an earlier sibling is calling
3396 // FinishAndStoreOverflow and needs our parent's perspective matrix, which
3397 // depends on the SVG bbox contribution of this frame. In the latter
3398 // situation, when all siblings have been reflowed, the parent will compute
3399 // its perspective and rerun FinishAndStoreOverflow for all its children.
3400 return bbox;
3401 }
3402
3403 UpdateGlyphPositioning();
3404
3405 nsPresContext* presContext = PresContext();
3406
3407 TextRenderedRunIterator it(this);
3408 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3409 uint32_t flags = TextRenderedRunFlagsForBBoxContribution(run, aFlags);
3410 gfxMatrix m = ThebesMatrix(aToBBoxUserspace);
3411 SVGBBox bboxForRun = run.GetUserSpaceRect(presContext, flags, &m);
3412 bbox.UnionEdges(bboxForRun);
3413 }
3414
3415 return bbox;
3416}
3417
3418//----------------------------------------------------------------------
3419// SVGTextFrame SVG DOM methods
3420
3421/**
3422 * Returns whether the specified node has any non-empty Text
3423 * beneath it.
3424 */
3425static bool HasTextContent(nsIContent* aContent) {
3426 NS_ASSERTION(aContent, "expected non-null aContent")do { if (!(aContent)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected non-null aContent"
, "aContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3426); MOZ_PretendNoReturn(); } } while (0)
;
3427
3428 TextNodeIterator it(aContent);
3429 for (Text* text = it.Current(); text; text = it.Next()) {
3430 if (text->TextLength() != 0) {
3431 return true;
3432 }
3433 }
3434 return false;
3435}
3436
3437/**
3438 * Returns the number of DOM characters beneath the specified node.
3439 */
3440static uint32_t GetTextContentLength(nsIContent* aContent) {
3441 NS_ASSERTION(aContent, "expected non-null aContent")do { if (!(aContent)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected non-null aContent"
, "aContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3441); MOZ_PretendNoReturn(); } } while (0)
;
3442
3443 uint32_t length = 0;
3444 TextNodeIterator it(aContent);
3445 for (Text* text = it.Current(); text; text = it.Next()) {
3446 length += text->TextLength();
3447 }
3448 return length;
3449}
3450
3451int32_t SVGTextFrame::ConvertTextElementCharIndexToAddressableIndex(
3452 int32_t aIndex, nsIContent* aContent) {
3453 CharIterator it(this, CharIterator::eOriginal, aContent);
3454 if (!it.AdvanceToSubtree()) {
3455 return -1;
3456 }
3457 int32_t result = 0;
3458 int32_t textElementCharIndex;
3459 while (!it.AtEnd() && it.IsWithinSubtree()) {
3460 bool addressable = !it.IsOriginalCharUnaddressable();
3461 textElementCharIndex = it.TextElementCharIndex();
3462 it.Next();
3463 uint32_t delta = it.TextElementCharIndex() - textElementCharIndex;
3464 aIndex -= delta;
3465 if (addressable) {
3466 if (aIndex < 0) {
3467 return result;
3468 }
3469 result += delta;
3470 }
3471 }
3472 return -1;
3473}
3474
3475/**
3476 * Implements the SVG DOM GetNumberOfChars method for the specified
3477 * text content element.
3478 */
3479uint32_t SVGTextFrame::GetNumberOfChars(nsIContent* aContent) {
3480 nsIFrame* kid = PrincipalChildList().FirstChild();
3481 if (kid->IsSubtreeDirty()) {
3482 // We're never reflowed if we're under a non-SVG element that is
3483 // never reflowed (such as the HTML 'caption' element).
3484 return 0;
3485 }
3486
3487 UpdateGlyphPositioning();
3488
3489 uint32_t n = 0;
3490 CharIterator it(this, CharIterator::eAddressable, aContent);
3491 if (it.AdvanceToSubtree()) {
3492 while (!it.AtEnd() && it.IsWithinSubtree()) {
3493 n++;
3494 it.Next();
3495 }
3496 }
3497 return n;
3498}
3499
3500/**
3501 * Implements the SVG DOM GetComputedTextLength method for the specified
3502 * text child element.
3503 */
3504float SVGTextFrame::GetComputedTextLength(nsIContent* aContent) {
3505 nsIFrame* kid = PrincipalChildList().FirstChild();
3506 if (kid->IsSubtreeDirty()) {
3507 // We're never reflowed if we're under a non-SVG element that is
3508 // never reflowed (such as the HTML 'caption' element).
3509 //
3510 // If we ever decide that we need to return accurate values here,
3511 // we could do similar work to GetSubStringLength.
3512 return 0;
3513 }
3514
3515 UpdateGlyphPositioning();
3516
3517 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3518 PresContext()->AppUnitsPerDevPixel());
3519
3520 nscoord length = 0;
3521 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3522 aContent);
3523 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3524 length += run.GetAdvanceWidth();
3525 }
3526
3527 return PresContext()->AppUnitsToGfxUnits(length) * cssPxPerDevPx *
3528 mLengthAdjustScaleFactor / mFontSizeScaleFactor;
3529}
3530
3531/**
3532 * Implements the SVG DOM SelectSubString method for the specified
3533 * text content element.
3534 */
3535void SVGTextFrame::SelectSubString(nsIContent* aContent, uint32_t charnum,
3536 uint32_t nchars, ErrorResult& aRv) {
3537 nsIFrame* kid = PrincipalChildList().FirstChild();
3538 if (kid->IsSubtreeDirty()) {
3539 // We're never reflowed if we're under a non-SVG element that is
3540 // never reflowed (such as the HTML 'caption' element).
3541 // XXXbz Should this just return without throwing like the no-frame case?
3542 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3543 return;
3544 }
3545
3546 UpdateGlyphPositioning();
3547
3548 // Convert charnum/nchars from addressable characters relative to
3549 // aContent to global character indices.
3550 CharIterator chit(this, CharIterator::eAddressable, aContent);
3551 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3552 chit.IsAfterSubtree()) {
3553 aRv.ThrowIndexSizeError("Character index out of range");
3554 return;
3555 }
3556 charnum = chit.TextElementCharIndex();
3557 const RefPtr<nsIContent> content = chit.TextFrame()->GetContent();
3558 chit.NextWithinSubtree(nchars);
3559 nchars = chit.TextElementCharIndex() - charnum;
3560
3561 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
3562
3563 frameSelection->HandleClick(content, charnum, charnum + nchars,
3564 nsFrameSelection::FocusMode::kCollapseToNewPoint,
3565 CaretAssociationHint::Before);
3566}
3567
3568/**
3569 * For some content we cannot (or currently cannot) compute the length
3570 * without reflowing. In those cases we need to fall back to using
3571 * GetSubStringLengthSlowFallback.
3572 *
3573 * We fall back for textPath since we need glyph positioning in order to
3574 * tell if any characters should be ignored due to having fallen off the
3575 * end of the textPath.
3576 *
3577 * We fall back for bidi because GetTrimmedOffsets does not produce the
3578 * correct results for bidi continuations when passed aPostReflow = false.
3579 * XXX It may be possible to determine which continuations to trim from (and
3580 * which sides), but currently we don't do that. It would require us to
3581 * identify the visual (rather than logical) start and end of the line, to
3582 * avoid trimming at line-internal frame boundaries. Maybe nsBidiPresUtils
3583 * methods like GetFrameToRightOf and GetFrameToLeftOf would help?
3584 *
3585 */
3586bool SVGTextFrame::RequiresSlowFallbackForSubStringLength() {
3587 TextFrameIterator frameIter(this);
3588 for (nsTextFrame* frame = frameIter.Current(); frame;
3589 frame = frameIter.Next()) {
3590 if (frameIter.TextPathFrame() || frame->GetNextContinuation()) {
3591 return true;
3592 }
3593 }
3594 return false;
3595}
3596
3597/**
3598 * Implements the SVG DOM GetSubStringLength method for the specified
3599 * text content element.
3600 */
3601float SVGTextFrame::GetSubStringLengthFastPath(nsIContent* aContent,
3602 uint32_t charnum,
3603 uint32_t nchars,
3604 ErrorResult& aRv) {
3605 MOZ_ASSERT(!RequiresSlowFallbackForSubStringLength())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!RequiresSlowFallbackForSubStringLength())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!RequiresSlowFallbackForSubStringLength()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!RequiresSlowFallbackForSubStringLength()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3605); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!RequiresSlowFallbackForSubStringLength()"
")"); do { *((volatile int*)__null) = 3605; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3606
3607 // We only need our text correspondence to be up to date (no need to call
3608 // UpdateGlyphPositioning).
3609 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
3610
3611 // Convert charnum/nchars from addressable characters relative to
3612 // aContent to global character indices.
3613 CharIterator chit(this, CharIterator::eAddressable, aContent,
3614 /* aPostReflow */ false);
3615 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3616 chit.IsAfterSubtree()) {
3617 aRv.ThrowIndexSizeError("Character index out of range");
3618 return 0;
3619 }
3620
3621 // We do this after the ThrowIndexSizeError() bit so JS calls correctly throw
3622 // when necessary.
3623 if (nchars == 0) {
3624 return 0.0f;
3625 }
3626
3627 charnum = chit.TextElementCharIndex();
3628 chit.NextWithinSubtree(nchars);
3629 nchars = chit.TextElementCharIndex() - charnum;
3630
3631 // Sum of the substring advances.
3632 nscoord textLength = 0;
3633
3634 TextFrameIterator frit(this); // aSubtree = nullptr
3635
3636 // Index of the first non-skipped char in the frame, and of a subsequent char
3637 // that we're interested in. Both are relative to the index of the first
3638 // non-skipped char in the ancestor <text> element.
3639 uint32_t frameStartTextElementCharIndex = 0;
3640 uint32_t textElementCharIndex;
3641
3642 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
3643 frameStartTextElementCharIndex += frit.UndisplayedCharacters();
3644 textElementCharIndex = frameStartTextElementCharIndex;
3645
3646 // Offset into frame's Text:
3647 const uint32_t untrimmedOffset = frame->GetContentOffset();
3648 const uint32_t untrimmedLength = frame->GetContentEnd() - untrimmedOffset;
3649
3650 // Trim the offset/length to remove any leading/trailing white space.
3651 uint32_t trimmedOffset = untrimmedOffset;
3652 uint32_t trimmedLength = untrimmedLength;
3653 nsTextFrame::TrimmedOffsets trimmedOffsets = frame->GetTrimmedOffsets(
3654 frame->TextFragment(), nsTextFrame::TrimmedOffsetFlags::NotPostReflow);
3655 TrimOffsets(trimmedOffset, trimmedLength, trimmedOffsets);
3656
3657 textElementCharIndex += trimmedOffset - untrimmedOffset;
3658
3659 if (textElementCharIndex >= charnum + nchars) {
3660 break; // we're past the end of the substring
3661 }
3662
3663 uint32_t offset = textElementCharIndex;
3664
3665 // Intersect the substring we are interested in with the range covered by
3666 // the nsTextFrame.
3667 IntersectInterval(offset, trimmedLength, charnum, nchars);
3668
3669 if (trimmedLength != 0) {
3670 // Convert offset into an index into the frame.
3671 offset += trimmedOffset - textElementCharIndex;
3672
3673 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
3674 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
3675 nsTextFrame::PropertyProvider provider(frame, it);
3676
3677 Range range = ConvertOriginalToSkipped(it, offset, trimmedLength);
3678
3679 // Accumulate the advance.
3680 textLength += textRun->GetAdvanceWidth(range, &provider);
3681 }
3682
3683 // Advance, ready for next call:
3684 frameStartTextElementCharIndex += untrimmedLength;
3685 }
3686
3687 nsPresContext* presContext = PresContext();
3688 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3689 presContext->AppUnitsPerDevPixel());
3690
3691 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3692 mFontSizeScaleFactor;
3693}
3694
3695float SVGTextFrame::GetSubStringLengthSlowFallback(nsIContent* aContent,
3696 uint32_t charnum,
3697 uint32_t nchars,
3698 ErrorResult& aRv) {
3699 UpdateGlyphPositioning();
3700
3701 // Convert charnum/nchars from addressable characters relative to
3702 // aContent to global character indices.
3703 CharIterator chit(this, CharIterator::eAddressable, aContent);
3704 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3705 chit.IsAfterSubtree()) {
3706 aRv.ThrowIndexSizeError("Character index out of range");
3707 return 0;
3708 }
3709
3710 if (nchars == 0) {
3711 return 0.0f;
3712 }
3713
3714 charnum = chit.TextElementCharIndex();
3715 chit.NextWithinSubtree(nchars);
3716 nchars = chit.TextElementCharIndex() - charnum;
3717
3718 // Find each rendered run that intersects with the range defined
3719 // by charnum/nchars.
3720 nscoord textLength = 0;
3721 TextRenderedRunIterator runIter(this, TextRenderedRunIterator::eAllFrames);
3722 TextRenderedRun run = runIter.Current();
3723 while (run.mFrame) {
3724 // If this rendered run is past the substring we are interested in, we
3725 // are done.
3726 uint32_t offset = run.mTextElementCharIndex;
3727 if (offset >= charnum + nchars) {
3728 break;
3729 }
3730
3731 // Intersect the substring we are interested in with the range covered by
3732 // the rendered run.
3733 uint32_t length = run.mTextFrameContentLength;
3734 IntersectInterval(offset, length, charnum, nchars);
3735
3736 if (length != 0) {
3737 // Convert offset into an index into the frame.
3738 offset += run.mTextFrameContentOffset - run.mTextElementCharIndex;
3739
3740 gfxSkipCharsIterator it =
3741 run.mFrame->EnsureTextRun(nsTextFrame::eInflated);
3742 gfxTextRun* textRun = run.mFrame->GetTextRun(nsTextFrame::eInflated);
3743 nsTextFrame::PropertyProvider provider(run.mFrame, it);
3744
3745 Range range = ConvertOriginalToSkipped(it, offset, length);
3746
3747 // Accumulate the advance.
3748 textLength += textRun->GetAdvanceWidth(range, &provider);
3749 }
3750
3751 run = runIter.Next();
3752 }
3753
3754 nsPresContext* presContext = PresContext();
3755 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3756 presContext->AppUnitsPerDevPixel());
3757
3758 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3759 mFontSizeScaleFactor;
3760}
3761
3762/**
3763 * Implements the SVG DOM GetCharNumAtPosition method for the specified
3764 * text content element.
3765 */
3766int32_t SVGTextFrame::GetCharNumAtPosition(nsIContent* aContent,
3767 const DOMPointInit& aPoint) {
3768 nsIFrame* kid = PrincipalChildList().FirstChild();
3769 if (kid->IsSubtreeDirty()) {
3770 // We're never reflowed if we're under a non-SVG element that is
3771 // never reflowed (such as the HTML 'caption' element).
3772 return -1;
3773 }
3774
3775 UpdateGlyphPositioning();
3776
3777 nsPresContext* context = PresContext();
3778
3779 gfxPoint p(aPoint.mX, aPoint.mY);
3780
3781 int32_t result = -1;
3782
3783 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3784 aContent);
3785 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3786 // Hit test this rendered run. Later runs will override earlier ones.
3787 int32_t index = run.GetCharNumAtPosition(context, p);
3788 if (index != -1) {
3789 result = index + run.mTextElementCharIndex;
3790 }
3791 }
3792
3793 if (result == -1) {
3794 return result;
3795 }
3796
3797 return ConvertTextElementCharIndexToAddressableIndex(result, aContent);
3798}
3799
3800/**
3801 * Implements the SVG DOM GetStartPositionOfChar method for the specified
3802 * text content element.
3803 */
3804already_AddRefed<DOMSVGPoint> SVGTextFrame::GetStartPositionOfChar(
3805 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3806 nsIFrame* kid = PrincipalChildList().FirstChild();
3807 if (kid->IsSubtreeDirty()) {
3808 // We're never reflowed if we're under a non-SVG element that is
3809 // never reflowed (such as the HTML 'caption' element).
3810 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3811 return nullptr;
3812 }
3813
3814 UpdateGlyphPositioning();
3815
3816 CharIterator it(this, CharIterator::eAddressable, aContent);
3817 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3818 aRv.ThrowIndexSizeError("Character index out of range");
3819 return nullptr;
3820 }
3821
3822 // We need to return the start position of the whole glyph.
3823 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3824
3825 return do_AddRef(new DOMSVGPoint(ToPoint(mPositions[startIndex].mPosition)));
3826}
3827
3828/**
3829 * Returns the advance of the entire glyph whose starting character is at
3830 * aTextElementCharIndex.
3831 *
3832 * aIterator, if provided, must be a CharIterator that already points to
3833 * aTextElementCharIndex that is restricted to aContent and is using
3834 * filter mode eAddressable.
3835 */
3836static gfxFloat GetGlyphAdvance(SVGTextFrame* aFrame, nsIContent* aContent,
3837 uint32_t aTextElementCharIndex,
3838 CharIterator* aIterator) {
3839 MOZ_ASSERT(!aIterator || (aIterator->Filter() == CharIterator::eAddressable &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIterator || (aIterator->Filter() == CharIterator
::eAddressable && aIterator->GetSubtree() == aContent
&& aIterator->GlyphStartTextElementCharIndex() ==
aTextElementCharIndex))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIterator || (aIterator->
Filter() == CharIterator::eAddressable && aIterator->
GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex
() == aTextElementCharIndex)))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
" (" "Invalid aIterator" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3843); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
") (" "Invalid aIterator" ")"); do { *((volatile int*)__null
) = 3843; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3840 aIterator->GetSubtree() == aContent &&do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIterator || (aIterator->Filter() == CharIterator
::eAddressable && aIterator->GetSubtree() == aContent
&& aIterator->GlyphStartTextElementCharIndex() ==
aTextElementCharIndex))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIterator || (aIterator->
Filter() == CharIterator::eAddressable && aIterator->
GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex
() == aTextElementCharIndex)))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
" (" "Invalid aIterator" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3843); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
") (" "Invalid aIterator" ")"); do { *((volatile int*)__null
) = 3843; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3841 aIterator->GlyphStartTextElementCharIndex() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIterator || (aIterator->Filter() == CharIterator
::eAddressable && aIterator->GetSubtree() == aContent
&& aIterator->GlyphStartTextElementCharIndex() ==
aTextElementCharIndex))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIterator || (aIterator->
Filter() == CharIterator::eAddressable && aIterator->
GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex
() == aTextElementCharIndex)))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
" (" "Invalid aIterator" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3843); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
") (" "Invalid aIterator" ")"); do { *((volatile int*)__null
) = 3843; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3842 aTextElementCharIndex),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIterator || (aIterator->Filter() == CharIterator
::eAddressable && aIterator->GetSubtree() == aContent
&& aIterator->GlyphStartTextElementCharIndex() ==
aTextElementCharIndex))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIterator || (aIterator->
Filter() == CharIterator::eAddressable && aIterator->
GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex
() == aTextElementCharIndex)))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
" (" "Invalid aIterator" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3843); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
") (" "Invalid aIterator" ")"); do { *((volatile int*)__null
) = 3843; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
3843 "Invalid aIterator")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIterator || (aIterator->Filter() == CharIterator
::eAddressable && aIterator->GetSubtree() == aContent
&& aIterator->GlyphStartTextElementCharIndex() ==
aTextElementCharIndex))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIterator || (aIterator->
Filter() == CharIterator::eAddressable && aIterator->
GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex
() == aTextElementCharIndex)))), 0))) { do { } while (false);
MOZ_ReportAssertionFailure("!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
" (" "Invalid aIterator" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3843); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIterator || (aIterator->Filter() == CharIterator::eAddressable && aIterator->GetSubtree() == aContent && aIterator->GlyphStartTextElementCharIndex() == aTextElementCharIndex)"
") (" "Invalid aIterator" ")"); do { *((volatile int*)__null
) = 3843; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
3844
3845 Maybe<CharIterator> newIterator;
3846 CharIterator* it = aIterator;
3847 if (!it) {
3848 newIterator.emplace(aFrame, CharIterator::eAddressable, aContent);
3849 if (!newIterator->AdvanceToSubtree()) {
3850 MOZ_ASSERT_UNREACHABLE("Invalid aContent")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: "
"Invalid aContent" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3850); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Invalid aContent" ")"); do { *((
volatile int*)__null) = 3850; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
3851 return 0.0;
3852 }
3853 it = newIterator.ptr();
3854 }
3855
3856 while (it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3857 if (!it->Next()) {
3858 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex")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: "
"Invalid aTextElementCharIndex" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3858); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Invalid aTextElementCharIndex" ")"
); do { *((volatile int*)__null) = 3858; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3859 return 0.0;
3860 }
3861 }
3862
3863 if (it->AtEnd()) {
3864 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex")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: "
"Invalid aTextElementCharIndex" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 3864); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Invalid aTextElementCharIndex" ")"
); do { *((volatile int*)__null) = 3864; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3865 return 0.0;
3866 }
3867
3868 nsPresContext* presContext = aFrame->PresContext();
3869 gfxFloat advance = 0.0;
3870
3871 for (;;) {
3872 advance += it->GetAdvance(presContext);
3873 if (!it->Next() ||
3874 it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3875 break;
3876 }
3877 }
3878
3879 return advance;
3880}
3881
3882/**
3883 * Implements the SVG DOM GetEndPositionOfChar method for the specified
3884 * text content element.
3885 */
3886already_AddRefed<DOMSVGPoint> SVGTextFrame::GetEndPositionOfChar(
3887 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3888 nsIFrame* kid = PrincipalChildList().FirstChild();
3889 if (kid->IsSubtreeDirty()) {
3890 // We're never reflowed if we're under a non-SVG element that is
3891 // never reflowed (such as the HTML 'caption' element).
3892 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3893 return nullptr;
3894 }
3895
3896 UpdateGlyphPositioning();
3897
3898 CharIterator it(this, CharIterator::eAddressable, aContent);
3899 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3900 aRv.ThrowIndexSizeError("Character index out of range");
3901 return nullptr;
3902 }
3903
3904 // We need to return the end position of the whole glyph.
3905 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3906
3907 // Get the advance of the glyph.
3908 gfxFloat advance =
3909 GetGlyphAdvance(this, aContent, startIndex,
3910 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3911 if (it.TextRun()->IsRightToLeft()) {
3912 advance = -advance;
3913 }
3914
3915 // The end position is the start position plus the advance in the direction
3916 // of the glyph's rotation.
3917 Matrix m = Matrix::Rotation(mPositions[startIndex].mAngle) *
3918 Matrix::Translation(ToPoint(mPositions[startIndex].mPosition));
3919 Point p = m.TransformPoint(Point(advance / mFontSizeScaleFactor, 0));
3920
3921 return do_AddRef(new DOMSVGPoint(p));
3922}
3923
3924/**
3925 * Implements the SVG DOM GetExtentOfChar method for the specified
3926 * text content element.
3927 */
3928already_AddRefed<SVGRect> SVGTextFrame::GetExtentOfChar(nsIContent* aContent,
3929 uint32_t aCharNum,
3930 ErrorResult& aRv) {
3931 nsIFrame* kid = PrincipalChildList().FirstChild();
3932 if (kid->IsSubtreeDirty()) {
3933 // We're never reflowed if we're under a non-SVG element that is
3934 // never reflowed (such as the HTML 'caption' element).
3935 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3936 return nullptr;
3937 }
3938
3939 UpdateGlyphPositioning();
3940
3941 // Search for the character whose addressable index is aCharNum.
3942 CharIterator it(this, CharIterator::eAddressable, aContent);
3943 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3944 aRv.ThrowIndexSizeError("Character index out of range");
3945 return nullptr;
3946 }
3947
3948 nsPresContext* presContext = PresContext();
3949 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3950 presContext->AppUnitsPerDevPixel());
3951
3952 nsTextFrame* textFrame = it.TextFrame();
3953 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3954 bool isRTL = it.TextRun()->IsRightToLeft();
3955 bool isVertical = it.TextRun()->IsVertical();
3956
3957 // Get the glyph advance.
3958 gfxFloat advance =
3959 GetGlyphAdvance(this, aContent, startIndex,
3960 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3961 gfxFloat x = isRTL ? -advance : 0.0;
3962
3963 // The ascent and descent gives the height of the glyph.
3964 gfxFloat ascent, descent;
3965 GetAscentAndDescentInAppUnits(textFrame, ascent, descent);
3966
3967 // The horizontal extent is the origin of the glyph plus the advance
3968 // in the direction of the glyph's rotation.
3969 gfxMatrix m;
3970 m.PreTranslate(mPositions[startIndex].mPosition);
3971 m.PreRotate(mPositions[startIndex].mAngle);
3972 m.PreScale(1 / mFontSizeScaleFactor, 1 / mFontSizeScaleFactor);
3973
3974 gfxRect glyphRect;
3975 if (isVertical) {
3976 glyphRect = gfxRect(
3977 -presContext->AppUnitsToGfxUnits(descent) * cssPxPerDevPx, x,
3978 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx,
3979 advance);
3980 } else {
3981 glyphRect = gfxRect(
3982 x, -presContext->AppUnitsToGfxUnits(ascent) * cssPxPerDevPx, advance,
3983 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx);
3984 }
3985
3986 // Transform the glyph's rect into user space.
3987 gfxRect r = m.TransformBounds(glyphRect);
3988
3989 return do_AddRef(new SVGRect(aContent, ToRect(r)));
3990}
3991
3992/**
3993 * Implements the SVG DOM GetRotationOfChar method for the specified
3994 * text content element.
3995 */
3996float SVGTextFrame::GetRotationOfChar(nsIContent* aContent, uint32_t aCharNum,
3997 ErrorResult& aRv) {
3998 nsIFrame* kid = PrincipalChildList().FirstChild();
3999 if (kid->IsSubtreeDirty()) {
4000 // We're never reflowed if we're under a non-SVG element that is
4001 // never reflowed (such as the HTML 'caption' element).
4002 aRv.ThrowInvalidStateError("No layout information available for SVG text");
4003 return 0;
4004 }
4005
4006 UpdateGlyphPositioning();
4007
4008 CharIterator it(this, CharIterator::eAddressable, aContent);
4009 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
4010 aRv.ThrowIndexSizeError("Character index out of range");
4011 return 0;
4012 }
4013
4014 // we need to account for the glyph's underlying orientation
4015 const gfxTextRun::GlyphRun& glyphRun = it.GlyphRun();
4016 int32_t glyphOrientation =
4017 90 * (glyphRun.IsSidewaysRight() - glyphRun.IsSidewaysLeft());
4018
4019 return mPositions[it.TextElementCharIndex()].mAngle * 180.0 / M_PI3.14159265358979323846 +
4020 glyphOrientation;
4021}
4022
4023//----------------------------------------------------------------------
4024// SVGTextFrame text layout methods
4025
4026/**
4027 * Given the character position array before values have been filled in
4028 * to any unspecified positions, and an array of dx/dy values, returns whether
4029 * a character at a given index should start a new rendered run.
4030 *
4031 * @param aPositions The array of character positions before unspecified
4032 * positions have been filled in and dx/dy values have been added to them.
4033 * @param aDeltas The array of dx/dy values.
4034 * @param aIndex The character index in question.
4035 */
4036static bool ShouldStartRunAtIndex(const nsTArray<CharPosition>& aPositions,
4037 const nsTArray<gfxPoint>& aDeltas,
4038 uint32_t aIndex) {
4039 if (aIndex == 0) {
4040 return true;
4041 }
4042
4043 if (aIndex < aPositions.Length()) {
4044 // If an explicit x or y value was given, start a new run.
4045 if (aPositions[aIndex].IsXSpecified() ||
4046 aPositions[aIndex].IsYSpecified()) {
4047 return true;
4048 }
4049
4050 // If a non-zero rotation was given, or the previous character had a non-
4051 // zero rotation, start a new run.
4052 if ((aPositions[aIndex].IsAngleSpecified() &&
4053 aPositions[aIndex].mAngle != 0.0f) ||
4054 (aPositions[aIndex - 1].IsAngleSpecified() &&
4055 (aPositions[aIndex - 1].mAngle != 0.0f))) {
4056 return true;
4057 }
4058 }
4059
4060 if (aIndex < aDeltas.Length()) {
4061 // If a non-zero dx or dy value was given, start a new run.
4062 if (aDeltas[aIndex].x != 0.0 || aDeltas[aIndex].y != 0.0) {
4063 return true;
4064 }
4065 }
4066
4067 return false;
4068}
4069
4070bool SVGTextFrame::ResolvePositionsForNode(nsIContent* aContent,
4071 uint32_t& aIndex, bool aInTextPath,
4072 bool& aForceStartOfChunk,
4073 nsTArray<gfxPoint>& aDeltas) {
4074 if (aContent->IsText()) {
4075 // We found a text node.
4076 uint32_t length = aContent->AsText()->TextLength();
4077 if (length) {
4078 uint32_t end = aIndex + length;
4079 if (MOZ_UNLIKELY(end > mPositions.Length())(__builtin_expect(!!(end > mPositions.Length()), 0))) {
4080 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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4082); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4082; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4081 "length of mPositions does not match characters "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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4082); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4082; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4082 "found by iterating content")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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4082); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4082; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
4083 return false;
4084 }
4085 if (aForceStartOfChunk) {
4086 // Note this character as starting a new anchored chunk.
4087 mPositions[aIndex].mStartOfChunk = true;
4088 aForceStartOfChunk = false;
4089 }
4090 while (aIndex < end) {
4091 // Record whether each of these characters should start a new rendered
4092 // run. That is always the case for characters on a text path.
4093 //
4094 // Run boundaries due to rotate="" values are handled in
4095 // DoGlyphPositioning.
4096 if (aInTextPath || ShouldStartRunAtIndex(mPositions, aDeltas, aIndex)) {
4097 mPositions[aIndex].mRunBoundary = true;
4098 }
4099 aIndex++;
4100 }
4101 }
4102 return true;
4103 }
4104
4105 // Skip past elements that aren't text content elements.
4106 if (!IsTextContentElement(aContent)) {
4107 return true;
4108 }
4109
4110 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4111 // Any ‘y’ attributes on horizontal <textPath> elements are ignored.
4112 // Similarly, for vertical <texPath>s x attributes are ignored.
4113 // <textPath> elements behave as if they have x="0" y="0" on them, but only
4114 // if there is not a value for the non-ignored coordinate that got inherited
4115 // from a parent. We skip this if there is no text content, so that empty
4116 // <textPath>s don't interrupt the layout of text in the parent element.
4117 if (HasTextContent(aContent)) {
4118 if (MOZ_UNLIKELY(aIndex >= mPositions.Length())(__builtin_expect(!!(aIndex >= mPositions.Length()), 0))) {
4119 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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4121); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4121; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4120 "length of mPositions does not match characters "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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4121); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4121; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4121 "found by iterating content")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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4121); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4121; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
4122 return false;
4123 }
4124 bool vertical = GetWritingMode().IsVertical();
4125 if (vertical || !mPositions[aIndex].IsXSpecified()) {
4126 mPositions[aIndex].mPosition.x = 0.0;
4127 }
4128 if (!vertical || !mPositions[aIndex].IsYSpecified()) {
4129 mPositions[aIndex].mPosition.y = 0.0;
4130 }
4131 mPositions[aIndex].mStartOfChunk = true;
4132 }
4133 } else if (!aContent->IsSVGElement(nsGkAtoms::a)) {
4134 MOZ_ASSERT(aContent->IsSVGElement())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aContent->IsSVGElement())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aContent->IsSVGElement())
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("aContent->IsSVGElement()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4134); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aContent->IsSVGElement()"
")"); do { *((volatile int*)__null) = 4134; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4135
4136 // We have a text content element that can have x/y/dx/dy/rotate attributes.
4137 SVGElement* element = static_cast<SVGElement*>(aContent);
4138
4139 // Get x, y, dx, dy.
4140 SVGUserUnitList x, y, dx, dy;
4141 element->GetAnimatedLengthListValues(&x, &y, &dx, &dy, nullptr);
4142
4143 // Get rotate.
4144 const SVGNumberList* rotate = nullptr;
4145 SVGAnimatedNumberList* animatedRotate =
4146 element->GetAnimatedNumberList(nsGkAtoms::rotate);
4147 if (animatedRotate) {
4148 rotate = &animatedRotate->GetAnimValue();
4149 }
4150
4151 bool percentages = false;
4152 uint32_t count = GetTextContentLength(aContent);
4153
4154 if (MOZ_UNLIKELY(aIndex + count > mPositions.Length())(__builtin_expect(!!(aIndex + count > mPositions.Length())
, 0))
) {
4155 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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4157); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4157; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4156 "length of mPositions does not match characters "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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4157); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4157; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
4157 "found by iterating content")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: "
"length of mPositions does not match characters " "found by iterating content"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4157); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "length of mPositions does not match characters "
"found by iterating content" ")"); do { *((volatile int*)__null
) = 4157; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
4158 return false;
4159 }
4160
4161 // New text anchoring chunks start at each character assigned a position
4162 // with x="" or y="", or if we forced one with aForceStartOfChunk due to
4163 // being just after a <textPath>.
4164 uint32_t newChunkCount = std::max(x.Length(), y.Length());
4165 if (!newChunkCount && aForceStartOfChunk) {
4166 newChunkCount = 1;
4167 }
4168 for (uint32_t i = 0, j = 0; i < newChunkCount && j < count; j++) {
4169 if (!mPositions[aIndex + j].mUnaddressable) {
4170 mPositions[aIndex + j].mStartOfChunk = true;
4171 i++;
4172 }
4173 }
4174
4175 // Copy dx="" and dy="" values into aDeltas.
4176 if (!dx.IsEmpty() || !dy.IsEmpty()) {
4177 // Any unspecified deltas when we grow the array just get left as 0s.
4178 aDeltas.EnsureLengthAtLeast(aIndex + count);
4179 for (uint32_t i = 0, j = 0; i < dx.Length() && j < count; j++) {
4180 if (!mPositions[aIndex + j].mUnaddressable) {
4181 aDeltas[aIndex + j].x = dx[i];
4182 percentages = percentages || dx.HasPercentageValueAt(i);
4183 i++;
4184 }
4185 }
4186 for (uint32_t i = 0, j = 0; i < dy.Length() && j < count; j++) {
4187 if (!mPositions[aIndex + j].mUnaddressable) {
4188 aDeltas[aIndex + j].y = dy[i];
4189 percentages = percentages || dy.HasPercentageValueAt(i);
4190 i++;
4191 }
4192 }
4193 }
4194
4195 // Copy x="" and y="" values.
4196 for (uint32_t i = 0, j = 0; i < x.Length() && j < count; j++) {
4197 if (!mPositions[aIndex + j].mUnaddressable) {
4198 mPositions[aIndex + j].mPosition.x = x[i];
4199 percentages = percentages || x.HasPercentageValueAt(i);
4200 i++;
4201 }
4202 }
4203 for (uint32_t i = 0, j = 0; i < y.Length() && j < count; j++) {
4204 if (!mPositions[aIndex + j].mUnaddressable) {
4205 mPositions[aIndex + j].mPosition.y = y[i];
4206 percentages = percentages || y.HasPercentageValueAt(i);
4207 i++;
4208 }
4209 }
4210
4211 // Copy rotate="" values.
4212 if (rotate && !rotate->IsEmpty()) {
4213 uint32_t i = 0, j = 0;
4214 while (i < rotate->Length() && j < count) {
4215 if (!mPositions[aIndex + j].mUnaddressable) {
4216 mPositions[aIndex + j].mAngle = M_PI3.14159265358979323846 * (*rotate)[i] / 180.0;
4217 i++;
4218 }
4219 j++;
4220 }
4221 // Propagate final rotate="" value to the end of this element.
4222 while (j < count) {
4223 mPositions[aIndex + j].mAngle = mPositions[aIndex + j - 1].mAngle;
4224 j++;
4225 }
4226 }
4227
4228 if (percentages) {
4229 AddStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4230 }
4231 }
4232
4233 // Recurse to children.
4234 bool inTextPath = aInTextPath || aContent->IsSVGElement(nsGkAtoms::textPath);
4235 for (nsIContent* child = aContent->GetFirstChild(); child;
4236 child = child->GetNextSibling()) {
4237 bool ok = ResolvePositionsForNode(child, aIndex, inTextPath,
4238 aForceStartOfChunk, aDeltas);
4239 if (!ok) {
4240 return false;
4241 }
4242 }
4243
4244 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4245 // Force a new anchored chunk just after a <textPath>.
4246 aForceStartOfChunk = true;
4247 }
4248
4249 return true;
4250}
4251
4252bool SVGTextFrame::ResolvePositions(nsTArray<gfxPoint>& aDeltas,
4253 bool aRunPerGlyph) {
4254 NS_ASSERTION(mPositions.IsEmpty(), "expected mPositions to be empty")do { if (!(mPositions.IsEmpty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "expected mPositions to be empty", "mPositions.IsEmpty()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4254); MOZ_PretendNoReturn(); } } while (0)
;
4255 RemoveStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4256
4257 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4258 if (it.AtEnd()) {
4259 return false;
4260 }
4261
4262 // We assume the first character position is (0,0) unless we later see
4263 // otherwise, and note it as unaddressable if it is.
4264 bool firstCharUnaddressable = it.IsOriginalCharUnaddressable();
4265 mPositions.AppendElement(CharPosition::Unspecified(firstCharUnaddressable));
4266
4267 // Fill in unspecified positions for all remaining characters, noting
4268 // them as unaddressable if they are.
4269 uint32_t index = 0;
4270 while (it.Next()) {
4271 while (++index < it.TextElementCharIndex()) {
4272 mPositions.AppendElement(CharPosition::Unspecified(false));
4273 }
4274 mPositions.AppendElement(
4275 CharPosition::Unspecified(it.IsOriginalCharUnaddressable()));
4276 }
4277 while (++index < it.TextElementCharIndex()) {
4278 mPositions.AppendElement(CharPosition::Unspecified(false));
4279 }
4280
4281 // Recurse over the content and fill in character positions as we go.
4282 bool forceStartOfChunk = false;
4283 index = 0;
4284 bool ok = ResolvePositionsForNode(mContent, index, aRunPerGlyph,
4285 forceStartOfChunk, aDeltas);
4286 return ok && index > 0;
4287}
4288
4289void SVGTextFrame::DetermineCharPositions(nsTArray<nsPoint>& aPositions) {
4290 NS_ASSERTION(aPositions.IsEmpty(), "expected aPositions to be empty")do { if (!(aPositions.IsEmpty())) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "expected aPositions to be empty", "aPositions.IsEmpty()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4290); MOZ_PretendNoReturn(); } } while (0)
;
4291
4292 nsPoint position;
4293
4294 TextFrameIterator frit(this);
4295 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
4296 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
4297 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
4298 nsTextFrame::PropertyProvider provider(frame, it);
4299
4300 // Reset the position to the new frame's position.
4301 position = frit.Position();
4302 if (textRun->IsVertical()) {
4303 if (textRun->IsRightToLeft()) {
4304 position.y += frame->GetRect().height;
4305 }
4306 position.x += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4307 mFontSizeScaleFactor);
4308 } else {
4309 if (textRun->IsRightToLeft()) {
4310 position.x += frame->GetRect().width;
4311 }
4312 position.y += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4313 mFontSizeScaleFactor);
4314 }
4315
4316 // Any characters not in a frame, e.g. when display:none.
4317 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4318 aPositions.AppendElement(position);
4319 }
4320
4321 // Any white space characters trimmed at the start of the line of text.
4322 nsTextFrame::TrimmedOffsets trimmedOffsets =
4323 frame->GetTrimmedOffsets(frame->TextFragment());
4324 while (it.GetOriginalOffset() < trimmedOffsets.mStart) {
4325 aPositions.AppendElement(position);
4326 it.AdvanceOriginal(1);
4327 }
4328
4329 // Visible characters in the text frame.
4330 while (it.GetOriginalOffset() < frame->GetContentEnd()) {
4331 aPositions.AppendElement(position);
4332 if (!it.IsOriginalCharSkipped()) {
4333 // Accumulate partial ligature advance into position. (We must get
4334 // partial advances rather than get the advance of the whole ligature
4335 // group / cluster at once, since the group may span text frames, and
4336 // the PropertyProvider only has spacing information for the current
4337 // text frame.)
4338 uint32_t offset = it.GetSkippedOffset();
4339 nscoord advance =
4340 textRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
4341 (textRun->IsVertical() ? position.y : position.x) +=
4342 textRun->IsRightToLeft() ? -advance : advance;
4343 }
4344 it.AdvanceOriginal(1);
4345 }
4346 }
4347
4348 // Finally any characters at the end that are not in a frame.
4349 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4350 aPositions.AppendElement(position);
4351 }
4352}
4353
4354/**
4355 * Physical text-anchor values.
4356 */
4357enum TextAnchorSide { eAnchorLeft, eAnchorMiddle, eAnchorRight };
4358
4359/**
4360 * Converts a logical text-anchor value to its physical value, based on whether
4361 * it is for an RTL frame.
4362 */
4363static TextAnchorSide ConvertLogicalTextAnchorToPhysical(
4364 StyleTextAnchor aTextAnchor, bool aIsRightToLeft) {
4365 NS_ASSERTION(uint8_t(aTextAnchor) <= 3, "unexpected value for aTextAnchor")do { if (!(uint8_t(aTextAnchor) <= 3)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "unexpected value for aTextAnchor", "uint8_t(aTextAnchor) <= 3"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4365); MOZ_PretendNoReturn(); } } while (0)
;
4366 if (!aIsRightToLeft) {
4367 return TextAnchorSide(uint8_t(aTextAnchor));
4368 }
4369 return TextAnchorSide(2 - uint8_t(aTextAnchor));
4370}
4371
4372/**
4373 * Shifts the recorded character positions for an anchored chunk.
4374 *
4375 * @param aCharPositions The recorded character positions.
4376 * @param aChunkStart The character index the starts the anchored chunk. This
4377 * character's initial position is the anchor point.
4378 * @param aChunkEnd The character index just after the end of the anchored
4379 * chunk.
4380 * @param aVisIStartEdge The left/top-most edge of any of the glyphs within the
4381 * anchored chunk.
4382 * @param aVisIEndEdge The right/bottom-most edge of any of the glyphs within
4383 * the anchored chunk.
4384 * @param aAnchorSide The direction to anchor.
4385 */
4386static void ShiftAnchoredChunk(nsTArray<CharPosition>& aCharPositions,
4387 uint32_t aChunkStart, uint32_t aChunkEnd,
4388 gfxFloat aVisIStartEdge, gfxFloat aVisIEndEdge,
4389 TextAnchorSide aAnchorSide, bool aVertical) {
4390 NS_ASSERTION(aVisIStartEdge <= aVisIEndEdge,do { if (!(aVisIStartEdge <= aVisIEndEdge)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "unexpected anchored chunk edges", "aVisIStartEdge <= aVisIEndEdge"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4391); MOZ_PretendNoReturn(); } } while (0)
4391 "unexpected anchored chunk edges")do { if (!(aVisIStartEdge <= aVisIEndEdge)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "unexpected anchored chunk edges", "aVisIStartEdge <= aVisIEndEdge"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4391); MOZ_PretendNoReturn(); } } while (0)
;
4392 NS_ASSERTION(aChunkStart < aChunkEnd,do { if (!(aChunkStart < aChunkEnd)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "unexpected values for aChunkStart and aChunkEnd", "aChunkStart < aChunkEnd"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4393); MOZ_PretendNoReturn(); } } while (0)
4393 "unexpected values for aChunkStart and aChunkEnd")do { if (!(aChunkStart < aChunkEnd)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "unexpected values for aChunkStart and aChunkEnd", "aChunkStart < aChunkEnd"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4393); MOZ_PretendNoReturn(); } } while (0)
;
4394
4395 gfxFloat shift = aVertical ? aCharPositions[aChunkStart].mPosition.y
4396 : aCharPositions[aChunkStart].mPosition.x;
4397 switch (aAnchorSide) {
4398 case eAnchorLeft:
4399 shift -= aVisIStartEdge;
4400 break;
4401 case eAnchorMiddle:
4402 shift -= (aVisIStartEdge + aVisIEndEdge) / 2;
4403 break;
4404 case eAnchorRight:
4405 shift -= aVisIEndEdge;
4406 break;
4407 default:
4408 MOZ_ASSERT_UNREACHABLE("unexpected value for aAnchorSide")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 value for aAnchorSide" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4408); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "unexpected value for aAnchorSide"
")"); do { *((volatile int*)__null) = 4408; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4409 }
4410
4411 if (shift != 0.0) {
4412 if (aVertical) {
4413 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4414 aCharPositions[i].mPosition.y += shift;
4415 }
4416 } else {
4417 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4418 aCharPositions[i].mPosition.x += shift;
4419 }
4420 }
4421 }
4422}
4423
4424void SVGTextFrame::AdjustChunksForLineBreaks() {
4425 nsBlockFrame* block = do_QueryFrame(PrincipalChildList().FirstChild());
4426 NS_ASSERTION(block, "expected block frame")do { if (!(block)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "expected block frame"
, "block", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4426); MOZ_PretendNoReturn(); } } while (0)
;
4427
4428 nsBlockFrame::LineIterator line = block->LinesBegin();
4429
4430 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4431 while (!it.AtEnd() && line != block->LinesEnd()) {
4432 if (it.TextFrame() == line->mFirstChild) {
4433 mPositions[it.TextElementCharIndex()].mStartOfChunk = true;
4434 line++;
4435 }
4436 it.AdvancePastCurrentFrame();
4437 }
4438}
4439
4440void SVGTextFrame::AdjustPositionsForClusters() {
4441 nsPresContext* presContext = PresContext();
4442
4443 // Find all of the characters that are in the middle of a cluster or
4444 // ligature group, and adjust their positions and rotations to match
4445 // the first character of the cluster/group.
4446 //
4447 // Also move the boundaries of text rendered runs and anchored chunks to
4448 // not lie in the middle of cluster/group.
4449
4450 // The partial advance of the current cluster or ligature group that we
4451 // have accumulated.
4452 gfxFloat partialAdvance = 0.0;
4453
4454 CharIterator it(this, CharIterator::eUnskipped, /* aSubtree */ nullptr);
4455 bool isFirst = true;
4456 while (!it.AtEnd()) {
4457 if (it.IsClusterAndLigatureGroupStart() || isFirst) {
4458 // If we're at the start of a new cluster or ligature group, reset our
4459 // accumulated partial advance. Also treat the beginning of the text as
4460 // an anchor, even if it is a combining character and therefore was
4461 // marked as being a Unicode cluster continuation.
4462 partialAdvance = 0.0;
4463 isFirst = false;
4464 } else {
4465 // Otherwise, we're in the middle of a cluster or ligature group, and
4466 // we need to use the currently accumulated partial advance to adjust
4467 // the character's position and rotation.
4468
4469 // Find the start of the cluster/ligature group.
4470 uint32_t charIndex = it.TextElementCharIndex();
4471 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
4472 MOZ_ASSERT(charIndex != startIndex,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(charIndex != startIndex)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(charIndex != startIndex))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("charIndex != startIndex"
" (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4475); AnnotateMozCrashReason("MOZ_ASSERT" "(" "charIndex != startIndex"
") (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")"); do { *((volatile int*)__null) = 4475; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
4473 "If the current character is in the middle of a cluster or "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(charIndex != startIndex)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(charIndex != startIndex))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("charIndex != startIndex"
" (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4475); AnnotateMozCrashReason("MOZ_ASSERT" "(" "charIndex != startIndex"
") (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")"); do { *((volatile int*)__null) = 4475; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
4474 "ligature group, then charIndex must be different from "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(charIndex != startIndex)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(charIndex != startIndex))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("charIndex != startIndex"
" (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4475); AnnotateMozCrashReason("MOZ_ASSERT" "(" "charIndex != startIndex"
") (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")"); do { *((volatile int*)__null) = 4475; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
4475 "startIndex")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(charIndex != startIndex)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(charIndex != startIndex))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("charIndex != startIndex"
" (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4475); AnnotateMozCrashReason("MOZ_ASSERT" "(" "charIndex != startIndex"
") (" "If the current character is in the middle of a cluster or "
"ligature group, then charIndex must be different from " "startIndex"
")"); do { *((volatile int*)__null) = 4475; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4476
4477 mPositions[charIndex].mClusterOrLigatureGroupMiddle = true;
4478
4479 // Don't allow different rotations on ligature parts.
4480 bool rotationAdjusted = false;
4481 double angle = mPositions[startIndex].mAngle;
4482 if (mPositions[charIndex].mAngle != angle) {
4483 mPositions[charIndex].mAngle = angle;
4484 rotationAdjusted = true;
4485 }
4486
4487 // Update the character position.
4488 gfxFloat advance = partialAdvance / mFontSizeScaleFactor;
4489 gfxPoint direction = gfxPoint(cos(angle), sin(angle)) *
4490 (it.TextRun()->IsRightToLeft() ? -1.0 : 1.0);
4491 if (it.TextRun()->IsVertical()) {
4492 std::swap(direction.x, direction.y);
4493 }
4494 mPositions[charIndex].mPosition =
4495 mPositions[startIndex].mPosition + direction * advance;
4496
4497 // Ensure any runs that would end in the middle of a ligature now end just
4498 // after the ligature.
4499 if (mPositions[charIndex].mRunBoundary) {
4500 mPositions[charIndex].mRunBoundary = false;
4501 if (charIndex + 1 < mPositions.Length()) {
4502 mPositions[charIndex + 1].mRunBoundary = true;
4503 }
4504 } else if (rotationAdjusted) {
4505 if (charIndex + 1 < mPositions.Length()) {
4506 mPositions[charIndex + 1].mRunBoundary = true;
4507 }
4508 }
4509
4510 // Ensure any anchored chunks that would begin in the middle of a ligature
4511 // now begin just after the ligature.
4512 if (mPositions[charIndex].mStartOfChunk) {
4513 mPositions[charIndex].mStartOfChunk = false;
4514 if (charIndex + 1 < mPositions.Length()) {
4515 mPositions[charIndex + 1].mStartOfChunk = true;
4516 }
4517 }
4518 }
4519
4520 // Accumulate the current character's partial advance.
4521 partialAdvance += it.GetAdvance(presContext);
4522
4523 it.Next();
4524 }
4525}
4526
4527already_AddRefed<Path> SVGTextFrame::GetTextPath(nsIFrame* aTextPathFrame) {
4528 nsIContent* content = aTextPathFrame->GetContent();
4529 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4530 if (tp->mPath.IsRendered()) {
4531 // This is just an attribute so there's no transform that can apply
4532 // so we can just return the path directly.
4533 return tp->mPath.GetAnimValue().BuildPathForMeasuring(
4534 aTextPathFrame->Style()->EffectiveZoom().ToFloat());
4535 }
4536
4537 SVGGeometryElement* geomElement =
4538 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4539 if (!geomElement) {
4540 return nullptr;
4541 }
4542
4543 RefPtr<Path> path = geomElement->GetOrBuildPathForMeasuring();
4544 if (!path) {
4545 return nullptr;
4546 }
4547
4548 // Apply the geometry element's transform if appropriate.
4549 auto matrix = geomElement->LocalTransform();
4550 if (!matrix.IsIdentity()) {
4551 Path::Transform(path, matrix);
4552 }
4553
4554 return path.forget();
4555}
4556
4557gfxFloat SVGTextFrame::GetOffsetScale(nsIFrame* aTextPathFrame) {
4558 nsIContent* content = aTextPathFrame->GetContent();
4559 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4560 if (tp->mPath.IsRendered()) {
4561 // A path attribute has no pathLength or transform
4562 // so we return a unit scale.
4563 return 1.0;
4564 }
4565
4566 SVGGeometryElement* geomElement =
4567 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4568 if (!geomElement) {
4569 return 1.0;
4570 }
4571 return geomElement->GetPathLengthScale(SVGGeometryElement::eForTextPath);
4572}
4573
4574gfxFloat SVGTextFrame::GetStartOffset(nsIFrame* aTextPathFrame) {
4575 SVGTextPathElement* tp =
4576 static_cast<SVGTextPathElement*>(aTextPathFrame->GetContent());
4577 SVGAnimatedLength* length =
4578 &tp->mLengthAttributes[SVGTextPathElement::STARTOFFSET];
4579
4580 if (length->IsPercentage()) {
4581 if (!std::isfinite(GetOffsetScale(aTextPathFrame))) {
4582 // Either pathLength="0" for this path or the path has 0 length.
4583 return 0.0;
4584 }
4585 RefPtr<Path> data = GetTextPath(aTextPathFrame);
4586 return data ? length->GetAnimValInSpecifiedUnits() * data->ComputeLength() /
4587 100.0
4588 : 0.0;
4589 }
4590 float lengthValue = length->GetAnimValueWithZoom(tp);
4591 // If offsetScale is infinity we want to return 0 not NaN
4592 return lengthValue == 0 ? 0.0 : lengthValue * GetOffsetScale(aTextPathFrame);
4593}
4594
4595void SVGTextFrame::DoTextPathLayout() {
4596 nsPresContext* context = PresContext();
4597
4598 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4599 while (!it.AtEnd()) {
4600 nsIFrame* textPathFrame = it.TextPathFrame();
4601 if (!textPathFrame) {
4602 // Skip past this frame if we're not in a text path.
4603 it.AdvancePastCurrentFrame();
4604 continue;
4605 }
4606
4607 // Get the path itself.
4608 RefPtr<Path> path = GetTextPath(textPathFrame);
4609 if (!path) {
4610 uint32_t start = it.TextElementCharIndex();
4611 it.AdvancePastCurrentTextPathFrame();
4612 uint32_t end = it.TextElementCharIndex();
4613 for (uint32_t i = start; i < end; i++) {
4614 mPositions[i].mHidden = true;
4615 }
4616 continue;
4617 }
4618
4619 SVGTextPathElement* textPath =
4620 static_cast<SVGTextPathElement*>(textPathFrame->GetContent());
4621 uint16_t side =
4622 textPath->EnumAttributes()[SVGTextPathElement::SIDE].GetAnimValue();
4623
4624 gfxFloat offset = GetStartOffset(textPathFrame);
4625 Float pathLength = path->ComputeLength();
4626
4627 // If the first character within the text path is in the middle of a
4628 // cluster or ligature group, just skip it and don't apply text path
4629 // positioning.
4630 while (!it.AtEnd()) {
4631 if (it.IsOriginalCharSkipped()) {
4632 it.Next();
4633 continue;
4634 }
4635 if (it.IsClusterAndLigatureGroupStart()) {
4636 break;
4637 }
4638 it.Next();
4639 }
4640
4641 bool skippedEndOfTextPath = false;
4642
4643 // Loop for each character in the text path.
4644 while (!it.AtEnd() && it.TextPathFrame() &&
4645 it.TextPathFrame()->GetContent() == textPath) {
4646 // The index of the cluster or ligature group's first character.
4647 uint32_t i = it.TextElementCharIndex();
4648
4649 // The index of the next character of the cluster or ligature.
4650 // We track this as we loop over the characters below so that we
4651 // can detect undisplayed characters and append entries into
4652 // partialAdvances for them.
4653 uint32_t j = i + 1;
4654
4655 MOZ_ASSERT(!mPositions[i].mClusterOrLigatureGroupMiddle)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mPositions[i].mClusterOrLigatureGroupMiddle)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!mPositions[i].mClusterOrLigatureGroupMiddle))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!mPositions[i].mClusterOrLigatureGroupMiddle"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4655); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mPositions[i].mClusterOrLigatureGroupMiddle"
")"); do { *((volatile int*)__null) = 4655; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4656
4657 gfxFloat sign = it.TextRun()->IsRightToLeft() ? -1.0 : 1.0;
4658 bool vertical = it.TextRun()->IsVertical();
4659
4660 // Compute cumulative advances for each character of the cluster or
4661 // ligature group.
4662 AutoTArray<gfxFloat, 4> partialAdvances;
4663 gfxFloat partialAdvance = it.GetAdvance(context);
4664 partialAdvances.AppendElement(partialAdvance);
4665 while (it.Next()) {
4666 // Append entries for any undisplayed characters the CharIterator
4667 // skipped over.
4668 MOZ_ASSERT(j <= it.TextElementCharIndex())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(j <= it.TextElementCharIndex())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(j <= it.TextElementCharIndex
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("j <= it.TextElementCharIndex()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4668); AnnotateMozCrashReason("MOZ_ASSERT" "(" "j <= it.TextElementCharIndex()"
")"); do { *((volatile int*)__null) = 4668; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4669 while (j < it.TextElementCharIndex()) {
4670 partialAdvances.AppendElement(partialAdvance);
4671 ++j;
4672 }
4673 // This loop may end up outside of the current text path, but
4674 // that's OK; we'll consider any complete cluster or ligature
4675 // group that begins inside the text path as being affected
4676 // by it.
4677 if (it.IsOriginalCharSkipped()) {
4678 if (!it.TextPathFrame()) {
4679 skippedEndOfTextPath = true;
4680 break;
4681 }
4682 // Leave partialAdvance unchanged.
4683 } else if (it.IsClusterAndLigatureGroupStart()) {
4684 break;
4685 } else {
4686 partialAdvance += it.GetAdvance(context);
4687 }
4688 partialAdvances.AppendElement(partialAdvance);
4689 }
4690
4691 if (!skippedEndOfTextPath) {
4692 // Any final undisplayed characters the CharIterator skipped over.
4693 MOZ_ASSERT(j <= it.TextElementCharIndex())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(j <= it.TextElementCharIndex())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(j <= it.TextElementCharIndex
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("j <= it.TextElementCharIndex()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4693); AnnotateMozCrashReason("MOZ_ASSERT" "(" "j <= it.TextElementCharIndex()"
")"); do { *((volatile int*)__null) = 4693; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4694 while (j < it.TextElementCharIndex()) {
4695 partialAdvances.AppendElement(partialAdvance);
4696 ++j;
4697 }
4698 }
4699
4700 gfxFloat halfAdvance =
4701 partialAdvances.LastElement() / mFontSizeScaleFactor / 2.0;
4702 gfxFloat midx =
4703 (vertical ? mPositions[i].mPosition.y : mPositions[i].mPosition.x) +
4704 sign * halfAdvance + offset;
4705
4706 // Hide the character if it falls off the end of the path.
4707 mPositions[i].mHidden = midx < 0 || midx > pathLength;
4708
4709 // Position the character on the path at the right angle.
4710 Point tangent; // Unit vector tangent to the point we find.
4711 Point pt;
4712 if (side == TEXTPATH_SIDETYPE_RIGHT) {
4713 pt = path->ComputePointAtLength(Float(pathLength - midx), &tangent);
4714 tangent = -tangent;
4715 } else {
4716 pt = path->ComputePointAtLength(Float(midx), &tangent);
4717 }
4718 Float rotation = vertical ? atan2f(-tangent.x, tangent.y)
4719 : atan2f(tangent.y, tangent.x);
4720 Point normal(-tangent.y, tangent.x); // Unit vector normal to the point.
4721 Point offsetFromPath = normal * (vertical ? -mPositions[i].mPosition.x
4722 : mPositions[i].mPosition.y);
4723 pt += offsetFromPath;
4724 Point direction = tangent * sign;
4725 mPositions[i].mPosition =
4726 ThebesPoint(pt) - ThebesPoint(direction) * halfAdvance;
4727 mPositions[i].mAngle += rotation;
4728
4729 // Position any characters for a partial ligature.
4730 for (uint32_t k = i + 1; k < j; k++) {
4731 gfxPoint partialAdvance = ThebesPoint(direction) *
4732 partialAdvances[k - i] / mFontSizeScaleFactor;
4733 mPositions[k].mPosition = mPositions[i].mPosition + partialAdvance;
4734 mPositions[k].mAngle = mPositions[i].mAngle;
4735 mPositions[k].mHidden = mPositions[i].mHidden;
4736 }
4737 }
4738 }
4739}
4740
4741void SVGTextFrame::DoAnchoring() {
4742 nsPresContext* presContext = PresContext();
4743
4744 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4745
4746 // Don't need to worry about skipped or trimmed characters.
4747 while (!it.AtEnd() &&
4748 (it.IsOriginalCharSkipped() || it.IsOriginalCharTrimmed())) {
4749 it.Next();
4750 }
4751
4752 bool vertical = GetWritingMode().IsVertical();
4753 for (uint32_t start = it.TextElementCharIndex(); start < mPositions.Length();
4754 start = it.TextElementCharIndex()) {
4755 it.AdvanceToCharacter(start);
4756 nsTextFrame* chunkFrame = it.TextFrame();
4757
4758 // Measure characters in this chunk to find the left-most and right-most
4759 // edges of all glyphs within the chunk.
4760 uint32_t index = it.TextElementCharIndex();
4761 uint32_t end = start;
Value stored to 'end' during its initialization is never read
4762 gfxFloat left = std::numeric_limits<gfxFloat>::infinity();
4763 gfxFloat right = -std::numeric_limits<gfxFloat>::infinity();
4764 do {
4765 if (!it.IsOriginalCharSkipped() && !it.IsOriginalCharTrimmed()) {
4766 gfxFloat advance = it.GetAdvance(presContext) / mFontSizeScaleFactor;
4767 gfxFloat pos = it.TextRun()->IsVertical()
4768 ? mPositions[index].mPosition.y
4769 : mPositions[index].mPosition.x;
4770 if (it.TextRun()->IsRightToLeft()) {
4771 left = std::min(left, pos - advance);
4772 right = std::max(right, pos);
4773 } else {
4774 left = std::min(left, pos);
4775 right = std::max(right, pos + advance);
4776 }
4777 }
4778 it.Next();
4779 index = end = it.TextElementCharIndex();
4780 } while (!it.AtEnd() && !mPositions[end].mStartOfChunk);
4781
4782 if (left != std::numeric_limits<gfxFloat>::infinity()) {
4783 bool isRTL =
4784 chunkFrame->StyleVisibility()->mDirection == StyleDirection::Rtl;
4785 TextAnchorSide anchor = ConvertLogicalTextAnchorToPhysical(
4786 chunkFrame->StyleSVG()->mTextAnchor, isRTL);
4787
4788 ShiftAnchoredChunk(mPositions, start, end, left, right, anchor, vertical);
4789 }
4790 }
4791}
4792
4793void SVGTextFrame::DoGlyphPositioning() {
4794 mPositions.Clear();
4795 RemoveStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
4796
4797 nsIFrame* kid = PrincipalChildList().FirstChild();
4798 if (kid && kid->IsSubtreeDirty()) {
4799 MOZ_ASSERT(false, "should have already reflowed the kid")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "should have already reflowed the kid"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4799); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"should have already reflowed the kid" ")"); do { *((volatile
int*)__null) = 4799; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
4800 return;
4801 }
4802
4803 // Since we can be called directly via GetBBoxContribution, our correspondence
4804 // may not be up to date.
4805 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
4806
4807 // Determine the positions of each character in app units.
4808 AutoTArray<nsPoint, 64> charPositions;
4809 DetermineCharPositions(charPositions);
4810
4811 if (charPositions.IsEmpty()) {
4812 // No characters, so nothing to do.
4813 return;
4814 }
4815
4816 // If the textLength="" attribute was specified, then we need ResolvePositions
4817 // to record that a new run starts with each glyph.
4818 SVGTextContentElement* element =
4819 static_cast<SVGTextContentElement*>(GetContent());
4820 SVGAnimatedLength* textLengthAttr =
4821 element->GetAnimatedLength(nsGkAtoms::textLength);
4822 uint16_t lengthAdjust =
4823 element->EnumAttributes()[SVGTextContentElement::LENGTHADJUST]
4824 .GetAnimValue();
4825 bool adjustingTextLength = textLengthAttr->IsExplicitlySet();
4826 float expectedTextLength = textLengthAttr->GetAnimValueWithZoom(element);
4827
4828 if (adjustingTextLength &&
4829 (expectedTextLength < 0.0f || lengthAdjust == LENGTHADJUST_UNKNOWN)) {
4830 // If textLength="" is less than zero or lengthAdjust is unknown, ignore it.
4831 adjustingTextLength = false;
4832 }
4833
4834 // Get the x, y, dx, dy, rotate values for the subtree.
4835 AutoTArray<gfxPoint, 16> deltas;
4836 if (!ResolvePositions(deltas, adjustingTextLength)) {
4837 // If ResolvePositions returned false, it means either there were some
4838 // characters in the DOM but none of them are displayed, or there was
4839 // an error in processing mPositions. Clear out mPositions so that we don't
4840 // attempt to do any painting later.
4841 mPositions.Clear();
4842 return;
4843 }
4844
4845 // XXX We might be able to do less work when there is at most a single
4846 // x/y/dx/dy position.
4847
4848 // Truncate the positioning arrays to the actual number of characters present.
4849 TruncateTo(deltas, charPositions);
4850 TruncateTo(mPositions, charPositions);
4851
4852 // Fill in an unspecified position for the first addressable character.
4853 uint32_t first = 0;
4854 while (first + 1 < mPositions.Length() && mPositions[first].mUnaddressable) {
4855 ++first;
4856 }
4857 if (!mPositions[first].IsXSpecified()) {
4858 mPositions[first].mPosition.x = 0.0;
4859 }
4860 if (!mPositions[first].IsYSpecified()) {
4861 mPositions[first].mPosition.y = 0.0;
4862 }
4863 if (!mPositions[first].IsAngleSpecified()) {
4864 mPositions[first].mAngle = 0.0;
4865 }
4866
4867 nsPresContext* presContext = PresContext();
4868 bool vertical = GetWritingMode().IsVertical();
4869
4870 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
4871 presContext->AppUnitsPerDevPixel());
4872 double factor = cssPxPerDevPx / mFontSizeScaleFactor;
4873
4874 // Determine how much to compress or expand glyph positions due to
4875 // textLength="" and lengthAdjust="".
4876 double adjustment = 0.0;
4877 mLengthAdjustScaleFactor = 1.0f;
4878 if (adjustingTextLength) {
4879 nscoord frameLength =
4880 vertical ? PrincipalChildList().FirstChild()->GetRect().height
4881 : PrincipalChildList().FirstChild()->GetRect().width;
4882 float actualTextLength = static_cast<float>(
4883 presContext->AppUnitsToGfxUnits(frameLength) * factor);
4884
4885 switch (lengthAdjust) {
4886 case LENGTHADJUST_SPACINGANDGLYPHS:
4887 // Scale the glyphs and their positions.
4888 if (actualTextLength > 0) {
4889 mLengthAdjustScaleFactor = expectedTextLength / actualTextLength;
4890 }
4891 break;
4892
4893 default:
4894 MOZ_ASSERT(lengthAdjust == LENGTHADJUST_SPACING)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(lengthAdjust == LENGTHADJUST_SPACING)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(lengthAdjust == LENGTHADJUST_SPACING
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"lengthAdjust == LENGTHADJUST_SPACING", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4894); AnnotateMozCrashReason("MOZ_ASSERT" "(" "lengthAdjust == LENGTHADJUST_SPACING"
")"); do { *((volatile int*)__null) = 4894; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4895 // Just add space between each glyph.
4896 int32_t adjustableSpaces = 0;
4897 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4898 if (!mPositions[i].mUnaddressable) {
4899 adjustableSpaces++;
4900 }
4901 }
4902 if (adjustableSpaces) {
4903 adjustment =
4904 (expectedTextLength - actualTextLength) / adjustableSpaces;
4905 }
4906 break;
4907 }
4908 }
4909
4910 // Fill in any unspecified character positions based on the positions recorded
4911 // in charPositions, and also add in the dx/dy values.
4912 if (!deltas.IsEmpty()) {
4913 mPositions[0].mPosition += deltas[0];
4914 }
4915
4916 gfxFloat xLengthAdjustFactor = vertical ? 1.0 : mLengthAdjustScaleFactor;
4917 gfxFloat yLengthAdjustFactor = vertical ? mLengthAdjustScaleFactor : 1.0;
4918 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4919 // Fill in unspecified x position.
4920 if (!mPositions[i].IsXSpecified()) {
4921 nscoord d = charPositions[i].x - charPositions[i - 1].x;
4922 mPositions[i].mPosition.x =
4923 mPositions[i - 1].mPosition.x +
4924 presContext->AppUnitsToGfxUnits(d) * factor * xLengthAdjustFactor;
4925 if (!vertical && !mPositions[i].mUnaddressable) {
4926 mPositions[i].mPosition.x += adjustment;
4927 }
4928 }
4929 // Fill in unspecified y position.
4930 if (!mPositions[i].IsYSpecified()) {
4931 nscoord d = charPositions[i].y - charPositions[i - 1].y;
4932 mPositions[i].mPosition.y =
4933 mPositions[i - 1].mPosition.y +
4934 presContext->AppUnitsToGfxUnits(d) * factor * yLengthAdjustFactor;
4935 if (vertical && !mPositions[i].mUnaddressable) {
4936 mPositions[i].mPosition.y += adjustment;
4937 }
4938 }
4939 // Add in dx/dy.
4940 if (i < deltas.Length()) {
4941 mPositions[i].mPosition += deltas[i];
4942 }
4943 // Fill in unspecified rotation values.
4944 if (!mPositions[i].IsAngleSpecified()) {
4945 mPositions[i].mAngle = 0.0f;
4946 }
4947 }
4948
4949 MOZ_ASSERT(mPositions.Length() == charPositions.Length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mPositions.Length() == charPositions.Length())>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mPositions.Length() == charPositions.Length()))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("mPositions.Length() == charPositions.Length()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 4949); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mPositions.Length() == charPositions.Length()"
")"); do { *((volatile int*)__null) = 4949; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4950
4951 AdjustChunksForLineBreaks();
4952 AdjustPositionsForClusters();
4953 DoAnchoring();
4954 DoTextPathLayout();
4955}
4956
4957bool SVGTextFrame::ShouldRenderAsPath(nsTextFrame* aFrame,
4958 bool& aShouldPaintSVGGlyphs) {
4959 // Rendering to a clip path.
4960 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
4961 aShouldPaintSVGGlyphs = false;
4962 return true;
4963 }
4964
4965 aShouldPaintSVGGlyphs = true;
4966
4967 const nsStyleSVG* style = aFrame->StyleSVG();
4968
4969 // Fill is a non-solid paint or is not opaque.
4970 if (!(style->mFill.kind.IsNone() ||
4971 (style->mFill.kind.IsColor() &&
4972 SVGUtils::GetOpacity(style->mFillOpacity, /*aContextPaint*/ nullptr) ==
4973 1.0f))) {
4974 return true;
4975 }
4976
4977 // If we're going to need to draw a non-opaque shadow.
4978 // It's possible nsTextFrame will support non-opaque shadows in the future,
4979 // in which case this test can be removed.
4980 if (style->mFill.kind.IsColor() && aFrame->StyleText()->HasTextShadow() &&
4981 NS_GET_A(style->mFill.kind.AsColor().CalcColor(*aFrame->Style()))((uint8_t)(((style->mFill.kind.AsColor().CalcColor(*aFrame
->Style())) >> 24) & 0xff))
!=
4982 0xFF) {
4983 return true;
4984 }
4985
4986 // Text has a stroke.
4987 if (style->HasStroke()) {
4988 if (style->mStrokeWidth.IsContextValue()) {
4989 return true;
4990 }
4991 if (SVGContentUtils::CoordToFloat(
4992 static_cast<SVGElement*>(GetContent()),
4993 style->mStrokeWidth.AsLengthPercentage()) > 0) {
4994 return true;
4995 }
4996 }
4997
4998 return false;
4999}
5000
5001void SVGTextFrame::ScheduleReflowSVG() {
5002 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5003 ScheduleReflowSVGNonDisplayText(
5004 IntrinsicDirty::FrameAncestorsAndDescendants);
5005 } else {
5006 SVGUtils::ScheduleReflowSVG(this);
5007 }
5008}
5009
5010void SVGTextFrame::NotifyGlyphMetricsChange(bool aUpdateTextCorrespondence) {
5011 if (aUpdateTextCorrespondence) {
5012 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
5013 }
5014 AddStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
5015 nsLayoutUtils::PostRestyleEvent(mContent->AsElement(), RestyleHint{0},
5016 nsChangeHint_InvalidateRenderingObservers);
5017 ScheduleReflowSVG();
5018}
5019
5020void SVGTextFrame::UpdateGlyphPositioning() {
5021 nsIFrame* kid = PrincipalChildList().FirstChild();
5022 if (!kid) {
5023 return;
5024 }
5025
5026 if (HasAnyStateBits(NS_STATE_SVG_POSITIONING_DIRTY)) {
5027 DoGlyphPositioning();
5028 }
5029}
5030
5031void SVGTextFrame::MaybeResolveBidiForAnonymousBlockChild() {
5032 nsIFrame* kid = PrincipalChildList().FirstChild();
5033
5034 if (kid && kid->HasAnyStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION) &&
5035 PresContext()->BidiEnabled()) {
5036 MOZ_ASSERT(static_cast<nsBlockFrame*>(do_QueryFrame(kid)),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<nsBlockFrame*>(do_QueryFrame(kid))
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<nsBlockFrame*>(do_QueryFrame(kid))
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"static_cast<nsBlockFrame*>(do_QueryFrame(kid))" " (" "Expect anonymous child to be an nsBlockFrame"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5037); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<nsBlockFrame*>(do_QueryFrame(kid))"
") (" "Expect anonymous child to be an nsBlockFrame" ")"); do
{ *((volatile int*)__null) = 5037; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
5037 "Expect anonymous child to be an nsBlockFrame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<nsBlockFrame*>(do_QueryFrame(kid))
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(static_cast<nsBlockFrame*>(do_QueryFrame(kid))
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"static_cast<nsBlockFrame*>(do_QueryFrame(kid))" " (" "Expect anonymous child to be an nsBlockFrame"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5037); AnnotateMozCrashReason("MOZ_ASSERT" "(" "static_cast<nsBlockFrame*>(do_QueryFrame(kid))"
") (" "Expect anonymous child to be an nsBlockFrame" ")"); do
{ *((volatile int*)__null) = 5037; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
5038 nsBidiPresUtils::Resolve(static_cast<nsBlockFrame*>(kid));
5039 }
5040}
5041
5042void SVGTextFrame::MaybeReflowAnonymousBlockChild() {
5043 nsIFrame* kid = PrincipalChildList().FirstChild();
5044 if (!kid) {
5045 return;
5046 }
5047
5048 NS_ASSERTION(!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW),do { if (!(!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "should not be in reflow when about to reflow again"
, "!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5049); MOZ_PretendNoReturn(); } } while (0)
5049 "should not be in reflow when about to reflow again")do { if (!(!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW))) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "should not be in reflow when about to reflow again"
, "!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5049); MOZ_PretendNoReturn(); } } while (0)
;
5050
5051 if (IsSubtreeDirty()) {
5052 if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
5053 // If we require a full reflow, ensure our kid is marked fully dirty.
5054 // (Note that our anonymous nsBlockFrame is not an ISVGDisplayableFrame,
5055 // so even when we are called via our ReflowSVG this will not be done for
5056 // us by SVGDisplayContainerFrame::ReflowSVG.)
5057 kid->MarkSubtreeDirty();
5058 }
5059
5060 // The RecordCorrespondence and DoReflow calls can result in new text frames
5061 // being created (due to bidi resolution or reflow). We set this bit to
5062 // guard against unnecessarily calling back in to
5063 // ScheduleReflowSVGNonDisplayText from nsIFrame::DidSetComputedStyle on
5064 // those new text frames.
5065 AddStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5066
5067 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
5068
5069 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "should be under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5070); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "should be under ReflowSVG" ")"); do { *((volatile int
*)__null) = 5070; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
5070 "should be under ReflowSVG")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this))>::
isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
" (" "should be under ReflowSVG" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5070); AnnotateMozCrashReason("MOZ_ASSERT" "(" "SVGUtils::AnyOuterSVGIsCallingReflowSVG(this)"
") (" "should be under ReflowSVG" ")"); do { *((volatile int
*)__null) = 5070; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
5071 nsPresContext::InterruptPreventer noInterrupts(PresContext());
5072 DoReflow();
5073
5074 RemoveStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5075 }
5076}
5077
5078void SVGTextFrame::DoReflow() {
5079 MOZ_ASSERT(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5079); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)"
")"); do { *((volatile int*)__null) = 5079; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
5080
5081 // Since we are going to reflow the anonymous block frame, we will
5082 // need to update mPositions.
5083 // We also mark our text correspondence as dirty since we can end up needing
5084 // reflow in ways that do not set NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY.
5085 // (We'd then fail the "expected a TextNodeCorrespondenceProperty" assertion
5086 // when UpdateGlyphPositioning() is called after we return.)
5087 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |
5088 NS_STATE_SVG_POSITIONING_DIRTY);
5089
5090 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5091 // Normally, these dirty flags would be cleared in ReflowSVG(), but that
5092 // doesn't get called for non-display frames. We don't want to reflow our
5093 // descendants every time SVGTextFrame::PaintSVG makes sure that we have
5094 // valid positions by calling UpdateGlyphPositioning(), so we need to clear
5095 // these dirty bits. Note that this also breaks an invalidation loop where
5096 // our descendants invalidate as they reflow, which invalidates rendering
5097 // observers, which reschedules the frame that is currently painting by
5098 // referencing us to paint again. See bug 839958 comment 7. Hopefully we
5099 // will break that loop more convincingly at some point.
5100 RemoveStateBits(NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
5101 }
5102
5103 nsPresContext* presContext = PresContext();
5104 nsIFrame* kid = PrincipalChildList().FirstChild();
5105 if (!kid) {
5106 return;
5107 }
5108
5109 UniquePtr<gfxContext> renderingContext =
5110 presContext->PresShell()->CreateReferenceRenderingContext();
5111
5112 if (UpdateFontSizeScaleFactor()) {
5113 // If the font size scale factor changed, we need the block to report
5114 // an updated preferred width.
5115 kid->MarkIntrinsicISizesDirty();
5116 }
5117
5118 const IntrinsicSizeInput input(renderingContext.get(), Nothing(), Nothing());
5119 nscoord inlineSize = kid->GetPrefISize(input);
5120 WritingMode wm = kid->GetWritingMode();
5121 ReflowInput reflowInput(presContext, kid, renderingContext.get(),
5122 LogicalSize(wm, inlineSize, NS_UNCONSTRAINEDSIZE));
5123 ReflowOutput desiredSize(reflowInput);
5124 nsReflowStatus status;
5125
5126 NS_ASSERTION(do { if (!(reflowInput.ComputedPhysicalBorderPadding() == nsMargin
(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() ==
nsMargin(0, 0, 0, 0))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "style system should ensure that :-moz-svg-text "
"does not get styled", "reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5130); MOZ_PretendNoReturn(); } } while (0)
5127 reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) &&do { if (!(reflowInput.ComputedPhysicalBorderPadding() == nsMargin
(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() ==
nsMargin(0, 0, 0, 0))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "style system should ensure that :-moz-svg-text "
"does not get styled", "reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5130); MOZ_PretendNoReturn(); } } while (0)
5128 reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0),do { if (!(reflowInput.ComputedPhysicalBorderPadding() == nsMargin
(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() ==
nsMargin(0, 0, 0, 0))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "style system should ensure that :-moz-svg-text "
"does not get styled", "reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5130); MOZ_PretendNoReturn(); } } while (0)
5129 "style system should ensure that :-moz-svg-text "do { if (!(reflowInput.ComputedPhysicalBorderPadding() == nsMargin
(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() ==
nsMargin(0, 0, 0, 0))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "style system should ensure that :-moz-svg-text "
"does not get styled", "reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5130); MOZ_PretendNoReturn(); } } while (0)
5130 "does not get styled")do { if (!(reflowInput.ComputedPhysicalBorderPadding() == nsMargin
(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() ==
nsMargin(0, 0, 0, 0))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "style system should ensure that :-moz-svg-text "
"does not get styled", "reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) && reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5130); MOZ_PretendNoReturn(); } } while (0)
;
5131
5132 kid->Reflow(presContext, desiredSize, reflowInput, status);
5133 kid->DidReflow(presContext, &reflowInput);
5134 kid->SetSize(wm, desiredSize.Size(wm));
5135}
5136
5137// Usable font size range in devpixels / user-units
5138#define CLAMP_MIN_SIZE8.0 8.0
5139#define CLAMP_MAX_SIZE200.0 200.0
5140#define PRECISE_SIZE200.0 200.0
5141
5142bool SVGTextFrame::UpdateFontSizeScaleFactor() {
5143 float contextScale = GetContextScale(this);
5144 mLastContextScale = contextScale;
5145
5146 double oldFontSizeScaleFactor = mFontSizeScaleFactor;
5147
5148 bool geometricPrecision = false;
5149 CSSCoord min = std::numeric_limits<float>::max();
5150 CSSCoord max = std::numeric_limits<float>::min();
5151 bool anyText = false;
5152
5153 // Find the minimum and maximum font sizes used over all the
5154 // nsTextFrames.
5155 TextFrameIterator it(this);
5156 nsTextFrame* f = it.Current();
5157 while (f) {
5158 if (!geometricPrecision) {
5159 // Unfortunately we can't treat text-rendering:geometricPrecision
5160 // separately for each text frame.
5161 geometricPrecision = f->StyleText()->mTextRendering ==
5162 StyleTextRendering::Geometricprecision;
5163 }
5164 const auto& fontSize = f->StyleFont()->mFont.size;
5165 if (!fontSize.IsZero()) {
5166 min = std::min(min, fontSize.ToCSSPixels());
5167 max = std::max(max, fontSize.ToCSSPixels());
5168 anyText = true;
5169 }
5170 f = it.Next();
5171 }
5172
5173 if (!anyText) {
5174 // No text, so no need for scaling.
5175 mFontSizeScaleFactor = 1.0;
5176 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5177 }
5178
5179 if (geometricPrecision) {
5180 // We want to ensure minSize is scaled to PRECISE_SIZE.
5181 mFontSizeScaleFactor = PRECISE_SIZE200.0 / min;
5182 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5183 }
5184
5185 double minTextRunSize = min * contextScale;
5186 double maxTextRunSize = max * contextScale;
5187
5188 if (minTextRunSize >= CLAMP_MIN_SIZE8.0 && maxTextRunSize <= CLAMP_MAX_SIZE200.0) {
5189 // We are already in the ideal font size range for all text frames,
5190 // so we only have to take into account the contextScale.
5191 mFontSizeScaleFactor = contextScale;
5192 } else if (max / min > CLAMP_MAX_SIZE200.0 / CLAMP_MIN_SIZE8.0) {
5193 // We can't scale the font sizes so that all of the text frames lie
5194 // within our ideal font size range.
5195 // Heuristically, if the maxTextRunSize is within the CLAMP_MAX_SIZE
5196 // as a reasonable value, it's likely to be the user's intent to
5197 // get a valid font for the maxTextRunSize one, we should honor it.
5198 // The same for minTextRunSize.
5199 if (maxTextRunSize <= CLAMP_MAX_SIZE200.0) {
5200 mFontSizeScaleFactor = CLAMP_MAX_SIZE200.0 / max;
5201 } else if (minTextRunSize >= CLAMP_MIN_SIZE8.0) {
5202 mFontSizeScaleFactor = CLAMP_MIN_SIZE8.0 / min;
5203 } else {
5204 // So maxTextRunSize is too big, minTextRunSize is too small,
5205 // we can't really do anything for this case, just leave it as is.
5206 mFontSizeScaleFactor = contextScale;
5207 }
5208 } else if (minTextRunSize < CLAMP_MIN_SIZE8.0) {
5209 mFontSizeScaleFactor = CLAMP_MIN_SIZE8.0 / min;
5210 } else {
5211 mFontSizeScaleFactor = CLAMP_MAX_SIZE200.0 / max;
5212 }
5213
5214 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5215}
5216
5217double SVGTextFrame::GetFontSizeScaleFactor() const {
5218 return mFontSizeScaleFactor;
5219}
5220
5221/**
5222 * Take aPoint, which is in the <text> element's user space, and convert
5223 * it to the appropriate frame user space of aChildFrame according to
5224 * which rendered run the point hits.
5225 */
5226Point SVGTextFrame::TransformFramePointToTextChild(
5227 const Point& aPoint, const nsIFrame* aChildFrame) {
5228 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5231); MOZ_PretendNoReturn(); } } while (0)
5229 aChildFrame->GetParent(),do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5231); MOZ_PretendNoReturn(); } } while (0)
5230 LayoutFrameType::SVGText) == this,do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5231); MOZ_PretendNoReturn(); } } while (0)
5231 "aChildFrame must be a descendant of this frame")do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5231); MOZ_PretendNoReturn(); } } while (0)
;
5232
5233 UpdateGlyphPositioning();
5234
5235 nsPresContext* presContext = PresContext();
5236
5237 // Add in the mRect offset to aPoint, as that will have been taken into
5238 // account when transforming the point from the ancestor frame down
5239 // to this one.
5240 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
5241 presContext->AppUnitsPerDevPixel());
5242 float factor = AppUnitsPerCSSPixel();
5243 Point framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5244 NSAppUnitsToFloatPixels(mRect.y, factor));
5245 Point pointInUserSpace = aPoint * cssPxPerDevPx + framePosition;
5246
5247 // Find the closest rendered run for the text frames beneath aChildFrame.
5248 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5249 aChildFrame);
5250 TextRenderedRun hit;
5251 gfxPoint pointInRun;
5252 nscoord dx = nscoord_MAX;
5253 nscoord dy = nscoord_MAX;
5254 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5255 uint32_t flags = TextRenderedRun::eIncludeFill |
5256 TextRenderedRun::eIncludeStroke |
5257 TextRenderedRun::eNoHorizontalOverflow;
5258 gfxRect runRect =
5259 run.GetRunUserSpaceRect(presContext, flags).ToThebesRect();
5260
5261 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5262 if (!m.Invert()) {
5263 return aPoint;
5264 }
5265 gfxPoint pointInRunUserSpace =
5266 m.TransformPoint(ThebesPoint(pointInUserSpace));
5267
5268 if (Inside(runRect, pointInRunUserSpace)) {
5269 // The point was inside the rendered run's rect, so we choose it.
5270 dx = 0;
5271 dy = 0;
5272 pointInRun = pointInRunUserSpace;
5273 hit = run;
5274 } else if (nsLayoutUtils::PointIsCloserToRect(pointInRunUserSpace, runRect,
5275 dx, dy)) {
5276 // The point was closer to this rendered run's rect than any others
5277 // we've seen so far.
5278 pointInRun.x =
5279 std::clamp(pointInRunUserSpace.x.value, runRect.X(), runRect.XMost());
5280 pointInRun.y =
5281 std::clamp(pointInRunUserSpace.y.value, runRect.Y(), runRect.YMost());
5282 hit = run;
5283 }
5284 }
5285
5286 if (!hit.mFrame) {
5287 // We didn't find any rendered runs for the frame.
5288 return aPoint;
5289 }
5290
5291 // Return the point in user units relative to the nsTextFrame,
5292 // but taking into account mFontSizeScaleFactor.
5293 gfxMatrix m = hit.GetTransformFromRunUserSpaceToFrameUserSpace(presContext);
5294 m.PreScale(mFontSizeScaleFactor, mFontSizeScaleFactor);
5295 return ToPoint(m.TransformPoint(pointInRun) / cssPxPerDevPx);
5296}
5297
5298/**
5299 * For each rendered run beneath aChildFrame, translate aRect from
5300 * aChildFrame to the run's text frame, transform it then into
5301 * the run's frame user space, intersect it with the run's
5302 * frame user space rect, then transform it up to user space.
5303 * The result is the union of all of these.
5304 */
5305gfxRect SVGTextFrame::TransformFrameRectFromTextChild(
5306 const nsRect& aRect, const nsIFrame* aChildFrame) {
5307 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5310); MOZ_PretendNoReturn(); } } while (0)
5308 aChildFrame->GetParent(),do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5310); MOZ_PretendNoReturn(); } } while (0)
5309 LayoutFrameType::SVGText) == this,do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5310); MOZ_PretendNoReturn(); } } while (0)
5310 "aChildFrame must be a descendant of this frame")do { if (!(aChildFrame && nsLayoutUtils::GetClosestFrameOfType
( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "aChildFrame must be a descendant of this frame"
, "aChildFrame && nsLayoutUtils::GetClosestFrameOfType( aChildFrame->GetParent(), LayoutFrameType::SVGText) == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5310); MOZ_PretendNoReturn(); } } while (0)
;
5311
5312 UpdateGlyphPositioning();
5313
5314 nsPresContext* presContext = PresContext();
5315
5316 gfxRect result;
5317 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5318 aChildFrame);
5319 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5320 // First, translate aRect from aChildFrame to this run's frame.
5321 nsRect rectInTextFrame = aRect + aChildFrame->GetOffsetTo(run.mFrame);
5322
5323 // Scale it into frame user space.
5324 gfxRect rectInFrameUserSpace = AppUnitsToFloatCSSPixels(
5325 gfxRect(rectInTextFrame.x, rectInTextFrame.y, rectInTextFrame.width,
5326 rectInTextFrame.height),
5327 presContext);
5328
5329 // Intersect it with the run.
5330 uint32_t flags =
5331 TextRenderedRun::eIncludeFill | TextRenderedRun::eIncludeStroke;
5332
5333 if (rectInFrameUserSpace.IntersectRect(
5334 rectInFrameUserSpace,
5335 run.GetFrameUserSpaceRect(presContext, flags).ToThebesRect())) {
5336 // Transform it up to user space of the <text>
5337 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5338 gfxRect rectInUserSpace = m.TransformRect(rectInFrameUserSpace);
5339
5340 // Union it into the result.
5341 result.UnionRect(result, rectInUserSpace);
5342 }
5343 }
5344
5345 // Subtract the mRect offset from the result, as our user space for
5346 // this frame is relative to the top-left of mRect.
5347 float factor = AppUnitsPerCSSPixel();
5348 gfxPoint framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5349 NSAppUnitsToFloatPixels(mRect.y, factor));
5350
5351 return result - framePosition;
5352}
5353
5354Rect SVGTextFrame::TransformFrameRectFromTextChild(
5355 const Rect& aRect, const nsIFrame* aChildFrame) {
5356 nscoord appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
5357 nsRect r = LayoutDevicePixel::ToAppUnits(
5358 LayoutDeviceRect::FromUnknownRect(aRect), appUnitsPerDevPixel);
5359 gfxRect resultCssUnits = TransformFrameRectFromTextChild(r, aChildFrame);
5360 float devPixelPerCSSPixel =
5361 float(AppUnitsPerCSSPixel()) / appUnitsPerDevPixel;
5362 resultCssUnits.Scale(devPixelPerCSSPixel);
5363 return ToRect(resultCssUnits);
5364}
5365
5366Point SVGTextFrame::TransformFramePointFromTextChild(
5367 const Point& aPoint, const nsIFrame* aChildFrame) {
5368 return TransformFrameRectFromTextChild(Rect(aPoint, Size(1, 1)), aChildFrame)
5369 .TopLeft();
5370}
5371
5372void SVGTextFrame::AppendDirectlyOwnedAnonBoxes(
5373 nsTArray<OwnedAnonBox>& aResult) {
5374 MOZ_ASSERT(PrincipalChildList().FirstChild(), "Must have our anon box")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(PrincipalChildList().FirstChild())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(PrincipalChildList().FirstChild
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("PrincipalChildList().FirstChild()" " (" "Must have our anon box"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/svg/SVGTextFrame.cpp"
, 5374); AnnotateMozCrashReason("MOZ_ASSERT" "(" "PrincipalChildList().FirstChild()"
") (" "Must have our anon box" ")"); do { *((volatile int*)__null
) = 5374; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
5375 aResult.AppendElement(OwnedAnonBox(PrincipalChildList().FirstChild()));
5376}
5377
5378} // namespace mozilla