Bug Summary

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