Bug Summary

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