Bug Summary

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