Backed out changeset 36e95068e103 (bug 1848160) for bc failures on browser_preference...
[gecko.git] / layout / svg / SVGTextFrame.cpp
blob56b3bfa4940eb3e1dc55806959c80b7b0ff9a2ce
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/. */
7 // Main header first:
8 #include "SVGTextFrame.h"
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 "nsQuickSort.h"
26 #include "SVGPaintServerFrame.h"
27 #include "nsTArray.h"
28 #include "nsTextFrame.h"
29 #include "SVGAnimatedNumberList.h"
30 #include "SVGContentUtils.h"
31 #include "SVGContextPaint.h"
32 #include "SVGLengthList.h"
33 #include "SVGNumberList.h"
34 #include "nsLayoutUtils.h"
35 #include "nsFrameSelection.h"
36 #include "nsStyleStructInlines.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>
56 using namespace mozilla::dom;
57 using namespace mozilla::dom::SVGTextContentElement_Binding;
58 using namespace mozilla::gfx;
59 using namespace mozilla::image;
61 namespace mozilla {
63 // ============================================================================
64 // Utility functions
66 /**
67 * Using the specified gfxSkipCharsIterator, converts an offset and length
68 * in original char indexes to skipped char indexes.
70 * @param aIterator The gfxSkipCharsIterator to use for the conversion.
71 * @param aOriginalOffset The original offset.
72 * @param aOriginalLength The original length.
74 static 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());
82 /**
83 * Converts an nsPoint from app units to user space units using the specified
84 * nsPresContext and returns it as a gfxPoint.
86 static gfxPoint AppUnitsToGfxUnits(const nsPoint& aPoint,
87 const nsPresContext* aContext) {
88 return gfxPoint(aContext->AppUnitsToGfxUnits(aPoint.x),
89 aContext->AppUnitsToGfxUnits(aPoint.y));
92 /**
93 * Converts a gfxRect that is in app units to CSS pixels using the specified
94 * nsPresContext and returns it as a gfxRect.
96 static 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));
105 * Returns whether a gfxPoint lies within a gfxRect.
107 static 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();
113 * Gets the measured ascent and descent of the text in the given nsTextFrame
114 * in app units.
116 * @param aFrame The text frame.
117 * @param aAscent The ascent in app units (output).
118 * @param aDescent The descent in app units (output).
120 static void GetAscentAndDescentInAppUnits(nsTextFrame* aFrame,
121 gfxFloat& aAscent,
122 gfxFloat& aDescent) {
123 gfxSkipCharsIterator it = aFrame->EnsureTextRun(nsTextFrame::eInflated);
124 gfxTextRun* textRun = aFrame->GetTextRun(nsTextFrame::eInflated);
126 gfxTextRun::Range range = ConvertOriginalToSkipped(
127 it, aFrame->GetContentOffset(), aFrame->GetContentLength());
129 textRun->GetLineHeightMetrics(range, aAscent, aDescent);
133 * Updates an interval by intersecting it with another interval.
134 * The intervals are specified using a start index and a length.
136 static 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;
141 if (aStartOther >= aEnd || aStart >= aEndOther) {
142 aLength = 0;
143 } else {
144 if (aStartOther >= aStart) aStart = aStartOther;
145 aLength = std::min(aEnd, aEndOther) - aStart;
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.
154 static void TrimOffsets(uint32_t& aStart, uint32_t& aLength,
155 const nsTextFrame::TrimmedOffsets& aTrimmedOffsets) {
156 IntersectInterval(aStart, aLength, aTrimmedOffsets.mStart,
157 aTrimmedOffsets.mLength);
161 * Returns the closest ancestor-or-self node that is not an SVG <a>
162 * element.
164 static nsIContent* GetFirstNonAAncestor(nsIContent* aContent) {
165 while (aContent && aContent->IsSVGElement(nsGkAtoms::a)) {
166 aContent = aContent->GetParent();
168 return aContent;
172 * Returns whether the given node is a text content element[1], taking into
173 * account whether it has a valid parent.
175 * For example, in:
177 * <svg xmlns="http://www.w3.org/2000/svg">
178 * <text><a/><text/></text>
179 * <tspan/>
180 * </svg>
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).
187 * Note that we don't support the <tref> element yet and this function
188 * returns false for it.
190 * [1] https://svgwg.org/svg2-draft/intro.html#TermTextContentElement
192 static bool IsTextContentElement(nsIContent* aContent) {
193 if (aContent->IsSVGElement(nsGkAtoms::text)) {
194 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
195 return !parent || !IsTextContentElement(parent);
198 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
199 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
200 return parent && parent->IsSVGElement(nsGkAtoms::text);
203 return aContent->IsAnyOfSVGElements(nsGkAtoms::a, nsGkAtoms::tspan);
207 * Returns whether the specified frame is an nsTextFrame that has some text
208 * content.
210 static bool IsNonEmptyTextFrame(nsIFrame* aFrame) {
211 nsTextFrame* textFrame = do_QueryFrame(aFrame);
212 if (!textFrame) {
213 return false;
216 return textFrame->GetContentLength() != 0;
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.
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.
228 static bool GetNonEmptyTextFrameAndNode(nsIFrame* aFrame,
229 nsTextFrame*& aTextFrame,
230 Text*& aTextNode) {
231 nsTextFrame* text = do_QueryFrame(aFrame);
232 bool isNonEmptyTextFrame = text && text->GetContentLength() != 0;
234 if (isNonEmptyTextFrame) {
235 nsIContent* content = text->GetContent();
236 NS_ASSERTION(content && content->IsText(),
237 "unexpected content type for nsTextFrame");
239 Text* node = content->AsText();
240 MOZ_ASSERT(node->TextLength() != 0,
241 "frame's GetContentLength() should be 0 if the text node "
242 "has no content");
244 aTextFrame = text;
245 aTextNode = node;
248 MOZ_ASSERT(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame,
249 "our logic should agree with IsNonEmptyTextFrame");
250 return isNonEmptyTextFrame;
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.
258 static bool IsGlyphPositioningAttribute(nsAtom* aAttribute) {
259 return aAttribute == nsGkAtoms::x || aAttribute == nsGkAtoms::y ||
260 aAttribute == nsGkAtoms::dx || aAttribute == nsGkAtoms::dy ||
261 aAttribute == nsGkAtoms::rotate;
265 * Returns the position in app units of a given baseline (using an
266 * SVG dominant-baseline property value) for a given nsTextFrame.
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.
272 static 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);
279 auto convertIfVerticalRL = [&](gfxFloat dominantBaseline) {
280 return writingMode.IsVerticalRL() ? ascent + descent - dominantBaseline
281 : dominantBaseline;
284 switch (aDominantBaseline) {
285 case StyleDominantBaseline::Hanging:
286 return convertIfVerticalRL(ascent * 0.2);
287 case StyleDominantBaseline::TextBeforeEdge:
288 return convertIfVerticalRL(0);
290 case StyleDominantBaseline::Alphabetic:
291 return writingMode.IsVerticalRL()
292 ? ascent * 0.5
293 : aFrame->GetLogicalBaseline(writingMode);
295 case StyleDominantBaseline::Auto:
296 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
298 case StyleDominantBaseline::Middle:
299 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode) -
300 SVGContentUtils::GetFontXHeight(aFrame) / 2.0 *
301 AppUnitsPerCSSPixel() *
302 aFontSizeScaleFactor);
304 case StyleDominantBaseline::TextAfterEdge:
305 case StyleDominantBaseline::Ideographic:
306 return writingMode.IsVerticalLR() ? 0 : ascent + descent;
308 case StyleDominantBaseline::Central:
309 return (ascent + descent) / 2.0;
310 case StyleDominantBaseline::Mathematical:
311 return convertIfVerticalRL(ascent / 2.0);
314 MOZ_ASSERT_UNREACHABLE("unexpected dominant-baseline value");
315 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
319 * Truncates an array to be at most the length of another array.
321 * @param aArrayToTruncate The array to truncate.
322 * @param aReferenceArray The array whose length will be used to truncate
323 * aArrayToTruncate to.
325 template <typename T, typename U>
326 static 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);
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.
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.
344 static SVGTextFrame* FrameIfAnonymousChildReflowed(SVGTextFrame* aFrame) {
345 MOZ_ASSERT(aFrame, "aFrame must not be null");
346 nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
347 if (kid->IsSubtreeDirty()) {
348 MOZ_ASSERT(false, "should have already reflowed the anonymous block child");
349 return nullptr;
351 return aFrame;
354 static 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);
363 // ============================================================================
364 // Utility classes
366 // ----------------------------------------------------------------------------
367 // TextRenderedRun
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:
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
380 * A TextRenderedRunIterator produces TextRenderedRuns required for painting a
381 * whole SVGTextFrame.
383 struct TextRenderedRun {
384 using Range = gfxTextRun::Range;
387 * Constructs a TextRenderedRun that is uninitialized except for mFrame
388 * being null.
390 TextRenderedRun() : mFrame(nullptr) {}
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.
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) {}
414 * Returns the text run for the text frame that this rendered run is part of.
416 gfxTextRun* GetTextRun() const {
417 mFrame->EnsureTextRun(nsTextFrame::eInflated);
418 return mFrame->GetTextRun(nsTextFrame::eInflated);
422 * Returns whether this rendered run is RTL.
424 bool IsRightToLeft() const { return GetTextRun()->IsRightToLeft(); }
427 * Returns whether this rendered run is vertical.
429 bool IsVertical() const { return GetTextRun()->IsVertical(); }
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.
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.
444 * Assume that we have:
446 * <text x="100" y="100" rotate="0 0 1 0 0 * 1">abcdef</text>.
448 * This would result in four text rendered runs:
450 * - one for "ab"
451 * - one for "c"
452 * - one for "de"
453 * - one for "f"
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.
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:
473 * (-leftEdge, -baseline)
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.
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:
487 * - one for "EH"
488 * - one for "B"
489 * - one for "ER"
490 * - one for "W"
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:
497 * (-frameWidth + rightEdge, -baseline)
499 * which is equivalent to:
501 * (-(leftEdge + advance("ER")), -baseline)
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.
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.
515 * @param aContext The context to use for unit conversions.
517 gfxMatrix GetTransformFromUserSpaceForPainting(
518 nsPresContext* aContext, const nscoord aVisIStartEdge,
519 const nscoord aVisIEndEdge) const;
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.
527 * @param aContext The context to use for unit conversions.
529 gfxMatrix GetTransformFromRunUserSpaceToUserSpace(
530 nsPresContext* aContext) const;
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.
536 * @param aContext The context to use for unit conversions.
538 gfxMatrix GetTransformFromRunUserSpaceToFrameUserSpace(
539 nsPresContext* aContext) const;
542 * Flag values used for the aFlags arguments of GetRunUserSpaceRect,
543 * GetFrameUserSpaceRect and GetUserSpaceRect.
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
555 * Returns a rectangle that bounds the fill and/or stroke of the rendered run
556 * in run user space.
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.
563 SVGBBox GetRunUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
566 * Returns a rectangle that covers the fill and/or stroke of the rendered run
567 * in "frame user space".
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.
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.
581 * There will be two text rendered runs, one for "a" and one for "b".
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.
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.
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.
600 SVGBBox GetFrameUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
603 * Returns a rectangle that covers the fill and/or stroke of the rendered run
604 * in the <text> element's user space.
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.
613 SVGBBox GetUserSpaceRect(
614 nsPresContext* aContext, uint32_t aFlags,
615 const gfxMatrix* aAdditionalTransform = nullptr) const;
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.
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.
626 void GetClipEdges(nscoord& aVisIStartEdge, nscoord& aVisIEndEdge) const;
629 * Returns the advance width of the whole rendered run.
631 nscoord GetAdvanceWidth() const;
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.
638 * @param aContext The context to use for unit conversions.
639 * @param aPoint The point in the user space of the <text> element.
641 int32_t GetCharNumAtPosition(nsPresContext* aContext,
642 const gfxPoint& aPoint) const;
645 * The text frame that this rendered run lies within.
647 nsTextFrame* mFrame;
650 * The point in user space that the text is positioned at.
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.
659 gfxPoint mPosition;
662 * The horizontal scale factor to apply when painting glyphs to take
663 * into account textLength="".
665 float mLengthAdjustScaleFactor;
668 * The rotation in radians in the user coordinate system that the text has.
670 float mRotate;
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.
676 double mFontSizeScaleFactor;
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.)
682 nscoord mBaseline;
685 * The offset and length in mFrame's content Text that corresponds to
686 * this text rendered run. These are original char indexes.
688 uint32_t mTextFrameContentOffset;
689 uint32_t mTextFrameContentLength;
692 * The character index in the whole SVG <text> element that this text rendered
693 * run begins at.
695 uint32_t mTextElementCharIndex;
698 gfxMatrix 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.
704 gfxMatrix m;
705 if (!mFrame) {
706 return m;
709 float cssPxPerDevPx =
710 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
712 // Glyph position in user space.
713 m.PreTranslate(mPosition / cssPxPerDevPx);
715 // Take into account any font size scaling and scaling due to textLength="".
716 m.PreScale(1.0 / mFontSizeScaleFactor, 1.0 / mFontSizeScaleFactor);
718 // Rotation due to rotate="" or a <textPath>.
719 m.PreRotate(mRotate);
721 m.PreScale(mLengthAdjustScaleFactor, 1.0);
723 // Translation to get the text frame in the right place.
724 nsPoint t;
726 if (IsVertical()) {
727 t = nsPoint(-mBaseline, IsRightToLeft()
728 ? -mFrame->GetRect().height + aVisIEndEdge
729 : -aVisIStartEdge);
730 } else {
731 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + aVisIEndEdge
732 : -aVisIStartEdge,
733 -mBaseline);
735 m.PreTranslate(AppUnitsToGfxUnits(t, aContext));
737 return m;
740 gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToUserSpace(
741 nsPresContext* aContext) const {
742 gfxMatrix m;
743 if (!mFrame) {
744 return m;
747 float cssPxPerDevPx =
748 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
750 nscoord start, end;
751 GetClipEdges(start, end);
753 // Glyph position in user space.
754 m.PreTranslate(mPosition);
756 // Rotation due to rotate="" or a <textPath>.
757 m.PreRotate(mRotate);
759 // Scale due to textLength="".
760 m.PreScale(mLengthAdjustScaleFactor, 1.0);
762 // Translation to get the text frame in the right place.
763 nsPoint t;
764 if (IsVertical()) {
765 t = nsPoint(-mBaseline,
766 IsRightToLeft() ? -mFrame->GetRect().height + start + end : 0);
767 } else {
768 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + start + end : 0,
769 -mBaseline);
771 m.PreTranslate(AppUnitsToGfxUnits(t, aContext) * cssPxPerDevPx /
772 mFontSizeScaleFactor);
774 return m;
777 gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
778 nsPresContext* aContext) const {
779 gfxMatrix m;
780 if (!mFrame) {
781 return m;
784 nscoord start, end;
785 GetClipEdges(start, end);
787 // Translate by the horizontal distance into the text frame this
788 // rendered run is.
789 gfxFloat appPerCssPx = AppUnitsPerCSSPixel();
790 gfxPoint t = IsVertical() ? gfxPoint(0, start / appPerCssPx)
791 : gfxPoint(start / appPerCssPx, 0);
792 return m.PreTranslate(t);
795 SVGBBox TextRenderedRun::GetRunUserSpaceRect(nsPresContext* aContext,
796 uint32_t aFlags) const {
797 SVGBBox r;
798 if (!mFrame) {
799 return r;
802 // Determine the amount of overflow above and below the frame's mRect.
804 // We need to call InkOverflowRectRelativeToSelf because this includes
805 // overflowing decorations, which the MeasureText call below does not. We
806 // assume here the decorations only overflow above and below the frame, never
807 // horizontally.
808 nsRect self = mFrame->InkOverflowRectRelativeToSelf();
809 nsRect rect = mFrame->GetRect();
810 bool vertical = IsVertical();
811 nscoord above = vertical ? -self.x : -self.y;
812 nscoord below =
813 vertical ? self.XMost() - rect.width : self.YMost() - rect.height;
815 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
816 gfxSkipCharsIterator start = it;
817 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
819 // Get the content range for this rendered run.
820 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
821 mTextFrameContentLength);
822 if (range.Length() == 0) {
823 return r;
826 // FIXME(heycam): We could create a single PropertyProvider for all
827 // TextRenderedRuns that correspond to the text frame, rather than recreate
828 // it each time here.
829 nsTextFrame::PropertyProvider provider(mFrame, start);
831 // Measure that range.
832 gfxTextRun::Metrics metrics = textRun->MeasureText(
833 range, gfxFont::LOOSE_INK_EXTENTS, nullptr, &provider);
834 // Make sure it includes the font-box.
835 gfxRect fontBox(0, -metrics.mAscent, metrics.mAdvanceWidth,
836 metrics.mAscent + metrics.mDescent);
837 metrics.mBoundingBox.UnionRect(metrics.mBoundingBox, fontBox);
839 // Determine the rectangle that covers the rendered run's fill,
840 // taking into account the measured vertical overflow due to
841 // 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;
852 } else {
853 x = metrics.mBoundingBox.x;
854 width = metrics.mBoundingBox.width;
856 nsRect fillInAppUnits(
857 NSToCoordRoundWithClamp(x), baseline - above,
858 NSToCoordRoundWithClamp(width),
859 NSToCoordRoundWithClamp(metrics.mBoundingBox.height) + above + below);
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);
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);
872 // Scale the rectangle up due to any mFontSizeScaleFactor.
873 fill.Scale(1.0 / mFontSizeScaleFactor);
875 // Include the fill if requested.
876 if (aFlags & eIncludeFill) {
877 r = fill;
880 // Include the stroke if requested.
881 if ((aFlags & eIncludeStroke) && !fill.IsEmpty() &&
882 SVGUtils::GetStrokeWidth(mFrame) > 0) {
883 r.UnionEdges(
884 SVGUtils::PathExtentsToMaxStrokeExtents(fill, mFrame, gfxMatrix()));
887 return r;
890 SVGBBox TextRenderedRun::GetFrameUserSpaceRect(nsPresContext* aContext,
891 uint32_t aFlags) const {
892 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
893 if (r.IsEmpty()) {
894 return r;
896 gfxMatrix m = GetTransformFromRunUserSpaceToFrameUserSpace(aContext);
897 return m.TransformBounds(r.ToThebesRect());
900 SVGBBox TextRenderedRun::GetUserSpaceRect(
901 nsPresContext* aContext, uint32_t aFlags,
902 const gfxMatrix* aAdditionalTransform) const {
903 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
904 if (r.IsEmpty()) {
905 return r;
907 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
908 if (aAdditionalTransform) {
909 m *= *aAdditionalTransform;
911 return m.TransformBounds(r.ToThebesRect());
914 void TextRenderedRun::GetClipEdges(nscoord& aVisIStartEdge,
915 nscoord& aVisIEndEdge) const {
916 uint32_t contentLength = mFrame->GetContentLength();
917 if (mTextFrameContentOffset == 0 &&
918 mTextFrameContentLength == contentLength) {
919 // If the rendered run covers the entire content, we know we don't need
920 // to clip without having to measure anything.
921 aVisIStartEdge = 0;
922 aVisIEndEdge = 0;
923 return;
926 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
927 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
928 nsTextFrame::PropertyProvider provider(mFrame, it);
930 // Get the covered content offset/length for this rendered run in skipped
931 // characters, since that is what GetAdvanceWidth expects.
932 Range runRange = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
933 mTextFrameContentLength);
935 // Get the offset/length of the whole nsTextFrame.
936 uint32_t frameOffset = mFrame->GetContentOffset();
937 uint32_t frameLength = mFrame->GetContentLength();
939 // Trim the whole-nsTextFrame offset/length to remove any leading/trailing
940 // white space, as the nsTextFrame when painting does not include them when
941 // interpreting clip edges.
942 nsTextFrame::TrimmedOffsets trimmedOffsets =
943 mFrame->GetTrimmedOffsets(mFrame->TextFragment());
944 TrimOffsets(frameOffset, frameLength, trimmedOffsets);
946 // Convert the trimmed whole-nsTextFrame offset/length into skipped
947 // characters.
948 Range frameRange = ConvertOriginalToSkipped(it, frameOffset, frameLength);
950 // Measure the advance width in the text run between the start of
951 // frame's content and the start of the rendered run's content,
952 nscoord startEdge = textRun->GetAdvanceWidth(
953 Range(frameRange.start, runRange.start), &provider);
955 // and between the end of the rendered run's content and the end
956 // of the frame's content.
957 nscoord endEdge =
958 textRun->GetAdvanceWidth(Range(runRange.end, frameRange.end), &provider);
960 if (textRun->IsRightToLeft()) {
961 aVisIStartEdge = endEdge;
962 aVisIEndEdge = startEdge;
963 } else {
964 aVisIStartEdge = startEdge;
965 aVisIEndEdge = endEdge;
969 nscoord TextRenderedRun::GetAdvanceWidth() const {
970 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
971 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
972 nsTextFrame::PropertyProvider provider(mFrame, it);
974 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
975 mTextFrameContentLength);
977 return textRun->GetAdvanceWidth(range, &provider);
980 int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext* aContext,
981 const gfxPoint& aPoint) const {
982 if (mTextFrameContentLength == 0) {
983 return -1;
986 float cssPxPerDevPx =
987 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
989 // Convert the point from user space into run user space, and take
990 // into account any mFontSizeScaleFactor.
991 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
992 if (!m.Invert()) {
993 return -1;
995 gfxPoint p = m.TransformPoint(aPoint) / cssPxPerDevPx * mFontSizeScaleFactor;
997 // First check that the point lies vertically between the top and bottom
998 // edges of the text.
999 gfxFloat ascent, descent;
1000 GetAscentAndDescentInAppUnits(mFrame, ascent, descent);
1002 WritingMode writingMode = mFrame->GetWritingMode();
1003 if (writingMode.IsVertical()) {
1004 gfxFloat leftEdge = mFrame->GetLogicalBaseline(writingMode) -
1005 (writingMode.IsVerticalRL() ? ascent : descent);
1006 gfxFloat rightEdge = leftEdge + ascent + descent;
1007 if (p.x < aContext->AppUnitsToGfxUnits(leftEdge) ||
1008 p.x > aContext->AppUnitsToGfxUnits(rightEdge)) {
1009 return -1;
1011 } else {
1012 gfxFloat topEdge = mFrame->GetLogicalBaseline(writingMode) - ascent;
1013 gfxFloat bottomEdge = topEdge + ascent + descent;
1014 if (p.y < aContext->AppUnitsToGfxUnits(topEdge) ||
1015 p.y > aContext->AppUnitsToGfxUnits(bottomEdge)) {
1016 return -1;
1020 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
1021 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
1022 nsTextFrame::PropertyProvider provider(mFrame, it);
1024 // Next check that the point lies horizontally within the left and right
1025 // edges of the text.
1026 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
1027 mTextFrameContentLength);
1028 gfxFloat runAdvance =
1029 aContext->AppUnitsToGfxUnits(textRun->GetAdvanceWidth(range, &provider));
1031 gfxFloat pos = writingMode.IsVertical() ? p.y : p.x;
1032 if (pos < 0 || pos >= runAdvance) {
1033 return -1;
1036 // Finally, measure progressively smaller portions of the rendered run to
1037 // find which glyph it lies within. This will need to change once we
1038 // support letter-spacing and word-spacing.
1039 bool rtl = textRun->IsRightToLeft();
1040 for (int32_t i = mTextFrameContentLength - 1; i >= 0; i--) {
1041 range = ConvertOriginalToSkipped(it, mTextFrameContentOffset, i);
1042 gfxFloat advance = aContext->AppUnitsToGfxUnits(
1043 textRun->GetAdvanceWidth(range, &provider));
1044 if ((rtl && pos < runAdvance - advance) || (!rtl && pos >= advance)) {
1045 return i;
1048 return -1;
1051 // ----------------------------------------------------------------------------
1052 // TextNodeIterator
1054 enum SubtreePosition { eBeforeSubtree, eWithinSubtree, eAfterSubtree };
1057 * An iterator class for Text that are descendants of a given node, the
1058 * root. Nodes are iterated in document order. An optional subtree can be
1059 * specified, in which case the iterator will track whether the current state of
1060 * the traversal over the tree is within that subtree or is past that subtree.
1062 class TextNodeIterator {
1063 public:
1065 * Constructs a TextNodeIterator with the specified root node and optional
1066 * subtree.
1068 explicit TextNodeIterator(nsIContent* aRoot, nsIContent* aSubtree = nullptr)
1069 : mRoot(aRoot),
1070 mSubtree(aSubtree == aRoot ? nullptr : aSubtree),
1071 mCurrent(aRoot),
1072 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1073 NS_ASSERTION(aRoot, "expected non-null root");
1074 if (!aRoot->IsText()) {
1075 Next();
1080 * Returns the current Text, or null if the iterator has finished.
1082 Text* Current() const { return mCurrent ? mCurrent->AsText() : nullptr; }
1085 * Advances to the next Text and returns it, or null if the end of
1086 * iteration has been reached.
1088 Text* Next();
1091 * Returns whether the iterator is currently within the subtree rooted
1092 * at mSubtree. Returns true if we are not tracking a subtree (we consider
1093 * that we're always within the subtree).
1095 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1098 * Returns whether the iterator is past the subtree rooted at mSubtree.
1099 * Returns false if we are not tracking a subtree.
1101 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1103 private:
1105 * The root under which all Text will be iterated over.
1107 nsIContent* const mRoot;
1110 * The node rooting the subtree to track.
1112 nsIContent* const mSubtree;
1115 * The current node during iteration.
1117 nsIContent* mCurrent;
1120 * The current iterator position relative to mSubtree.
1122 SubtreePosition mSubtreePosition;
1125 Text* TextNodeIterator::Next() {
1126 // Starting from mCurrent, we do a non-recursive traversal to the next
1127 // Text beneath mRoot, updating mSubtreePosition appropriately if we
1128 // encounter mSubtree.
1129 if (mCurrent) {
1130 do {
1131 nsIContent* next =
1132 IsTextContentElement(mCurrent) ? mCurrent->GetFirstChild() : nullptr;
1133 if (next) {
1134 mCurrent = next;
1135 if (mCurrent == mSubtree) {
1136 mSubtreePosition = eWithinSubtree;
1138 } else {
1139 for (;;) {
1140 if (mCurrent == mRoot) {
1141 mCurrent = nullptr;
1142 break;
1144 if (mCurrent == mSubtree) {
1145 mSubtreePosition = eAfterSubtree;
1147 next = mCurrent->GetNextSibling();
1148 if (next) {
1149 mCurrent = next;
1150 if (mCurrent == mSubtree) {
1151 mSubtreePosition = eWithinSubtree;
1153 break;
1155 if (mCurrent == mSubtree) {
1156 mSubtreePosition = eAfterSubtree;
1158 mCurrent = mCurrent->GetParent();
1161 } while (mCurrent && !mCurrent->IsText());
1164 return mCurrent ? mCurrent->AsText() : nullptr;
1167 // ----------------------------------------------------------------------------
1168 // TextNodeCorrespondenceRecorder
1171 * TextNodeCorrespondence is used as the value of a frame property that
1172 * is stored on all its descendant nsTextFrames. It stores the number of DOM
1173 * characters between it and the previous nsTextFrame that did not have an
1174 * nsTextFrame created for them, due to either not being in a correctly
1175 * parented text content element, or because they were display:none.
1176 * These are called "undisplayed characters".
1178 * See also TextNodeCorrespondenceRecorder below, which is what sets the
1179 * frame property.
1181 struct TextNodeCorrespondence {
1182 explicit TextNodeCorrespondence(uint32_t aUndisplayedCharacters)
1183 : mUndisplayedCharacters(aUndisplayedCharacters) {}
1185 uint32_t mUndisplayedCharacters;
1188 NS_DECLARE_FRAME_PROPERTY_DELETABLE(TextNodeCorrespondenceProperty,
1189 TextNodeCorrespondence)
1192 * Returns the number of undisplayed characters before the specified
1193 * nsTextFrame.
1195 static uint32_t GetUndisplayedCharactersBeforeFrame(nsTextFrame* aFrame) {
1196 void* value = aFrame->GetProperty(TextNodeCorrespondenceProperty());
1197 TextNodeCorrespondence* correspondence =
1198 static_cast<TextNodeCorrespondence*>(value);
1199 if (!correspondence) {
1200 // FIXME bug 903785
1201 NS_ERROR(
1202 "expected a TextNodeCorrespondenceProperty on nsTextFrame "
1203 "used for SVG text");
1204 return 0;
1206 return correspondence->mUndisplayedCharacters;
1210 * Traverses the nsTextFrames for an SVGTextFrame and records a
1211 * TextNodeCorrespondenceProperty on each for the number of undisplayed DOM
1212 * characters between each frame. This is done by iterating simultaneously
1213 * over the Text and nsTextFrames and noting when Text (or
1214 * parts of them) are skipped when finding the next nsTextFrame.
1216 class TextNodeCorrespondenceRecorder {
1217 public:
1219 * Entry point for the TextNodeCorrespondenceProperty recording.
1221 static void RecordCorrespondence(SVGTextFrame* aRoot);
1223 private:
1224 explicit TextNodeCorrespondenceRecorder(SVGTextFrame* aRoot)
1225 : mNodeIterator(aRoot->GetContent()),
1226 mPreviousNode(nullptr),
1227 mNodeCharIndex(0) {}
1229 void Record(SVGTextFrame* aRoot);
1230 void TraverseAndRecord(nsIFrame* aFrame);
1233 * Returns the next non-empty Text.
1235 Text* NextNode();
1238 * The iterator over the Text that we use as we simultaneously
1239 * iterate over the nsTextFrames.
1241 TextNodeIterator mNodeIterator;
1244 * The previous Text we iterated over.
1246 Text* mPreviousNode;
1249 * The index into the current Text's character content.
1251 uint32_t mNodeCharIndex;
1254 /* static */
1255 void TextNodeCorrespondenceRecorder::RecordCorrespondence(SVGTextFrame* aRoot) {
1256 if (aRoot->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)) {
1257 // Resolve bidi so that continuation frames are created if necessary:
1258 aRoot->MaybeResolveBidiForAnonymousBlockChild();
1259 TextNodeCorrespondenceRecorder recorder(aRoot);
1260 recorder.Record(aRoot);
1261 aRoot->RemoveStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
1265 void TextNodeCorrespondenceRecorder::Record(SVGTextFrame* aRoot) {
1266 if (!mNodeIterator.Current()) {
1267 // If there are no Text nodes then there is nothing to do.
1268 return;
1271 // Traverse over all the nsTextFrames and record the number of undisplayed
1272 // characters.
1273 TraverseAndRecord(aRoot);
1275 // Find how many undisplayed characters there are after the final nsTextFrame.
1276 uint32_t undisplayed = 0;
1277 if (mNodeIterator.Current()) {
1278 if (mPreviousNode && mPreviousNode->TextLength() != mNodeCharIndex) {
1279 // The last nsTextFrame ended part way through a Text node. The
1280 // remaining characters count as undisplayed.
1281 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1282 "incorrect tracking of undisplayed characters in "
1283 "text nodes");
1284 undisplayed += mPreviousNode->TextLength() - mNodeCharIndex;
1286 // All the remaining Text that we iterate must also be undisplayed.
1287 for (Text* textNode = mNodeIterator.Current(); textNode;
1288 textNode = NextNode()) {
1289 undisplayed += textNode->TextLength();
1293 // Record the trailing number of undisplayed characters on the
1294 // SVGTextFrame.
1295 aRoot->mTrailingUndisplayedCharacters = undisplayed;
1298 Text* TextNodeCorrespondenceRecorder::NextNode() {
1299 mPreviousNode = mNodeIterator.Current();
1300 Text* next;
1301 do {
1302 next = mNodeIterator.Next();
1303 } while (next && next->TextLength() == 0);
1304 return next;
1307 void TextNodeCorrespondenceRecorder::TraverseAndRecord(nsIFrame* aFrame) {
1308 // Recursively iterate over the frame tree, for frames that correspond
1309 // to text content elements.
1310 if (IsTextContentElement(aFrame->GetContent())) {
1311 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1312 TraverseAndRecord(f);
1314 return;
1317 nsTextFrame* frame; // The current text frame.
1318 Text* node; // The text node for the current text frame.
1319 if (!GetNonEmptyTextFrameAndNode(aFrame, frame, node)) {
1320 // If this isn't an nsTextFrame, or is empty, nothing to do.
1321 return;
1324 NS_ASSERTION(frame->GetContentOffset() >= 0,
1325 "don't know how to handle negative content indexes");
1327 uint32_t undisplayed = 0;
1328 if (!mPreviousNode) {
1329 // Must be the very first text frame.
1330 NS_ASSERTION(mNodeCharIndex == 0,
1331 "incorrect tracking of undisplayed "
1332 "characters in text nodes");
1333 if (!mNodeIterator.Current()) {
1334 MOZ_ASSERT_UNREACHABLE(
1335 "incorrect tracking of correspondence between "
1336 "text frames and text nodes");
1337 } else {
1338 // Each whole Text we find before we get to the text node for the
1339 // first text frame must be undisplayed.
1340 while (mNodeIterator.Current() != node) {
1341 undisplayed += mNodeIterator.Current()->TextLength();
1342 NextNode();
1344 // If the first text frame starts at a non-zero content offset, then those
1345 // earlier characters are also undisplayed.
1346 undisplayed += frame->GetContentOffset();
1347 NextNode();
1349 } else if (mPreviousNode == node) {
1350 // Same text node as last time.
1351 if (static_cast<uint32_t>(frame->GetContentOffset()) != mNodeCharIndex) {
1352 // We have some characters in the middle of the text node
1353 // that are undisplayed.
1354 NS_ASSERTION(
1355 mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset()),
1356 "incorrect tracking of undisplayed characters in "
1357 "text nodes");
1358 undisplayed = frame->GetContentOffset() - mNodeCharIndex;
1360 } else {
1361 // Different text node from last time.
1362 if (mPreviousNode->TextLength() != mNodeCharIndex) {
1363 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1364 "incorrect tracking of undisplayed characters in "
1365 "text nodes");
1366 // Any trailing characters at the end of the previous Text are
1367 // undisplayed.
1368 undisplayed = mPreviousNode->TextLength() - mNodeCharIndex;
1370 // Each whole Text we find before we get to the text node for
1371 // the current text frame must be undisplayed.
1372 while (mNodeIterator.Current() && mNodeIterator.Current() != node) {
1373 undisplayed += mNodeIterator.Current()->TextLength();
1374 NextNode();
1376 // If the current text frame starts at a non-zero content offset, then those
1377 // earlier characters are also undisplayed.
1378 undisplayed += frame->GetContentOffset();
1379 NextNode();
1382 // Set the frame property.
1383 frame->SetProperty(TextNodeCorrespondenceProperty(),
1384 new TextNodeCorrespondence(undisplayed));
1386 // Remember how far into the current Text we are.
1387 mNodeCharIndex = frame->GetContentEnd();
1390 // ----------------------------------------------------------------------------
1391 // TextFrameIterator
1394 * An iterator class for nsTextFrames that are descendants of an
1395 * SVGTextFrame. The iterator can optionally track whether the
1396 * current nsTextFrame is for a descendant of, or past, a given subtree
1397 * content node or frame. (This functionality is used for example by the SVG
1398 * DOM text methods to get only the nsTextFrames for a particular <tspan>.)
1400 * TextFrameIterator also tracks and exposes other information about the
1401 * current nsTextFrame:
1403 * * how many undisplayed characters came just before it
1404 * * its position (in app units) relative to the SVGTextFrame's anonymous
1405 * block frame
1406 * * what nsInlineFrame corresponding to a <textPath> element it is a
1407 * descendant of
1408 * * what computed dominant-baseline value applies to it
1410 * Note that any text frames that are empty -- whose ContentLength() is 0 --
1411 * will be skipped over.
1413 class MOZ_STACK_CLASS TextFrameIterator {
1414 public:
1416 * Constructs a TextFrameIterator for the specified SVGTextFrame
1417 * with an optional frame subtree to restrict iterated text frames to.
1419 explicit TextFrameIterator(SVGTextFrame* aRoot,
1420 const nsIFrame* aSubtree = nullptr)
1421 : mRootFrame(aRoot),
1422 mSubtree(aSubtree),
1423 mCurrentFrame(aRoot),
1424 mCurrentPosition(),
1425 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1426 Init();
1430 * Constructs a TextFrameIterator for the specified SVGTextFrame
1431 * with an optional frame content subtree to restrict iterated text frames to.
1433 TextFrameIterator(SVGTextFrame* aRoot, nsIContent* aSubtree)
1434 : mRootFrame(aRoot),
1435 mSubtree(aRoot && aSubtree && aSubtree != aRoot->GetContent()
1436 ? aSubtree->GetPrimaryFrame()
1437 : nullptr),
1438 mCurrentFrame(aRoot),
1439 mCurrentPosition(),
1440 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1441 Init();
1445 * Returns the root SVGTextFrame this TextFrameIterator is iterating over.
1447 SVGTextFrame* Root() const { return mRootFrame; }
1450 * Returns the current nsTextFrame.
1452 nsTextFrame* Current() const { return do_QueryFrame(mCurrentFrame); }
1455 * Returns the number of undisplayed characters in the DOM just before the
1456 * current frame.
1458 uint32_t UndisplayedCharacters() const;
1461 * Returns the current frame's position, in app units, relative to the
1462 * root SVGTextFrame's anonymous block frame.
1464 nsPoint Position() const { return mCurrentPosition; }
1467 * Advances to the next nsTextFrame and returns it.
1469 nsTextFrame* Next();
1472 * Returns whether the iterator is within the subtree.
1474 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1477 * Returns whether the iterator is past the subtree.
1479 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1482 * Returns the frame corresponding to the <textPath> element, if we
1483 * are inside one.
1485 nsIFrame* TextPathFrame() const {
1486 return mTextPathFrames.IsEmpty()
1487 ? nullptr
1488 : mTextPathFrames.ElementAt(mTextPathFrames.Length() - 1);
1492 * Returns the current frame's computed dominant-baseline value.
1494 StyleDominantBaseline DominantBaseline() const {
1495 return mBaselines.ElementAt(mBaselines.Length() - 1);
1499 * Finishes the iterator.
1501 void Close() { mCurrentFrame = nullptr; }
1503 private:
1505 * Initializes the iterator and advances to the first item.
1507 void Init() {
1508 if (!mRootFrame) {
1509 return;
1512 mBaselines.AppendElement(mRootFrame->StyleSVG()->mDominantBaseline);
1513 Next();
1517 * Pushes the specified frame's computed dominant-baseline value.
1518 * If the value of the property is "auto", then the parent frame's
1519 * computed value is used.
1521 void PushBaseline(nsIFrame* aNextFrame);
1524 * Pops the current dominant-baseline off the stack.
1526 void PopBaseline();
1529 * The root frame we are iterating through.
1531 SVGTextFrame* const mRootFrame;
1534 * The frame for the subtree we are also interested in tracking.
1536 const nsIFrame* const mSubtree;
1539 * The current value of the iterator.
1541 nsIFrame* mCurrentFrame;
1544 * The position, in app units, of the current frame relative to mRootFrame.
1546 nsPoint mCurrentPosition;
1549 * Stack of frames corresponding to <textPath> elements that are in scope
1550 * for the current frame.
1552 AutoTArray<nsIFrame*, 1> mTextPathFrames;
1555 * Stack of dominant-baseline values to record as we traverse through the
1556 * frame tree.
1558 AutoTArray<StyleDominantBaseline, 8> mBaselines;
1561 * The iterator's current position relative to mSubtree.
1563 SubtreePosition mSubtreePosition;
1566 uint32_t TextFrameIterator::UndisplayedCharacters() const {
1567 MOZ_ASSERT(
1568 !mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY),
1569 "Text correspondence must be up to date");
1571 if (!mCurrentFrame) {
1572 return mRootFrame->mTrailingUndisplayedCharacters;
1575 nsTextFrame* frame = do_QueryFrame(mCurrentFrame);
1576 return GetUndisplayedCharactersBeforeFrame(frame);
1579 nsTextFrame* TextFrameIterator::Next() {
1580 // Starting from mCurrentFrame, we do a non-recursive traversal to the next
1581 // nsTextFrame beneath mRoot, updating mSubtreePosition appropriately if we
1582 // encounter mSubtree.
1583 if (mCurrentFrame) {
1584 do {
1585 nsIFrame* next = IsTextContentElement(mCurrentFrame->GetContent())
1586 ? mCurrentFrame->PrincipalChildList().FirstChild()
1587 : nullptr;
1588 if (next) {
1589 // Descend into this frame, and accumulate its position.
1590 mCurrentPosition += next->GetPosition();
1591 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1592 // Record this <textPath> frame.
1593 mTextPathFrames.AppendElement(next);
1595 // Record the frame's baseline.
1596 PushBaseline(next);
1597 mCurrentFrame = next;
1598 if (mCurrentFrame == mSubtree) {
1599 // If the current frame is mSubtree, we have now moved into it.
1600 mSubtreePosition = eWithinSubtree;
1602 } else {
1603 for (;;) {
1604 // We want to move past the current frame.
1605 if (mCurrentFrame == mRootFrame) {
1606 // If we've reached the root frame, we're finished.
1607 mCurrentFrame = nullptr;
1608 break;
1610 // Remove the current frame's position.
1611 mCurrentPosition -= mCurrentFrame->GetPosition();
1612 if (mCurrentFrame->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1613 // Pop off the <textPath> frame if this is a <textPath>.
1614 mTextPathFrames.RemoveLastElement();
1616 // Pop off the current baseline.
1617 PopBaseline();
1618 if (mCurrentFrame == mSubtree) {
1619 // If this was mSubtree, we have now moved past it.
1620 mSubtreePosition = eAfterSubtree;
1622 next = mCurrentFrame->GetNextSibling();
1623 if (next) {
1624 // Moving to the next sibling.
1625 mCurrentPosition += next->GetPosition();
1626 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1627 // Record this <textPath> frame.
1628 mTextPathFrames.AppendElement(next);
1630 // Record the frame's baseline.
1631 PushBaseline(next);
1632 mCurrentFrame = next;
1633 if (mCurrentFrame == mSubtree) {
1634 // If the current frame is mSubtree, we have now moved into it.
1635 mSubtreePosition = eWithinSubtree;
1637 break;
1639 if (mCurrentFrame == mSubtree) {
1640 // If there is no next sibling frame, and the current frame is
1641 // mSubtree, we have now moved past it.
1642 mSubtreePosition = eAfterSubtree;
1644 // Ascend out of this frame.
1645 mCurrentFrame = mCurrentFrame->GetParent();
1648 } while (mCurrentFrame && !IsNonEmptyTextFrame(mCurrentFrame));
1651 return Current();
1654 void TextFrameIterator::PushBaseline(nsIFrame* aNextFrame) {
1655 StyleDominantBaseline baseline = aNextFrame->StyleSVG()->mDominantBaseline;
1656 mBaselines.AppendElement(baseline);
1659 void TextFrameIterator::PopBaseline() {
1660 NS_ASSERTION(!mBaselines.IsEmpty(), "popped too many baselines");
1661 mBaselines.RemoveLastElement();
1664 // -----------------------------------------------------------------------------
1665 // TextRenderedRunIterator
1668 * Iterator for TextRenderedRun objects for the SVGTextFrame.
1670 class TextRenderedRunIterator {
1671 public:
1673 * Values for the aFilter argument of the constructor, to indicate which
1674 * frames we should be limited to iterating TextRenderedRun objects for.
1676 enum RenderedRunFilter {
1677 // Iterate TextRenderedRuns for all nsTextFrames.
1678 eAllFrames,
1679 // Iterate only TextRenderedRuns for nsTextFrames that are
1680 // visibility:visible.
1681 eVisibleFrames
1685 * Constructs a TextRenderedRunIterator with an optional frame subtree to
1686 * restrict iterated rendered runs to.
1688 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1689 * through.
1690 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1691 * nsTextFrames.
1692 * @param aSubtree An optional frame subtree to restrict iterated rendered
1693 * runs to.
1695 explicit TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1696 RenderedRunFilter aFilter = eAllFrames,
1697 const nsIFrame* aSubtree = nullptr)
1698 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1699 mFilter(aFilter),
1700 mTextElementCharIndex(0),
1701 mFrameStartTextElementCharIndex(0),
1702 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1703 mCurrent(First()) {}
1706 * Constructs a TextRenderedRunIterator with a content subtree to restrict
1707 * iterated rendered runs to.
1709 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1710 * through.
1711 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1712 * nsTextFrames.
1713 * @param aSubtree A content subtree to restrict iterated rendered runs to.
1715 TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1716 RenderedRunFilter aFilter, nsIContent* aSubtree)
1717 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1718 mFilter(aFilter),
1719 mTextElementCharIndex(0),
1720 mFrameStartTextElementCharIndex(0),
1721 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1722 mCurrent(First()) {}
1725 * Returns the current TextRenderedRun.
1727 TextRenderedRun Current() const { return mCurrent; }
1730 * Advances to the next TextRenderedRun and returns it.
1732 TextRenderedRun Next();
1734 private:
1736 * Returns the root SVGTextFrame this iterator is for.
1738 SVGTextFrame* Root() const { return mFrameIterator.Root(); }
1741 * Advances to the first TextRenderedRun and returns it.
1743 TextRenderedRun First();
1746 * The frame iterator to use.
1748 TextFrameIterator mFrameIterator;
1751 * The filter indicating which TextRenderedRuns to return.
1753 RenderedRunFilter mFilter;
1756 * The character index across the entire <text> element we are currently
1757 * up to.
1759 uint32_t mTextElementCharIndex;
1762 * The character index across the entire <text> for the start of the current
1763 * frame.
1765 uint32_t mFrameStartTextElementCharIndex;
1768 * The font-size scale factor we used when constructing the nsTextFrames.
1770 double mFontSizeScaleFactor;
1773 * The current TextRenderedRun.
1775 TextRenderedRun mCurrent;
1778 TextRenderedRun TextRenderedRunIterator::Next() {
1779 if (!mFrameIterator.Current()) {
1780 // If there are no more frames, then there are no more rendered runs to
1781 // return.
1782 mCurrent = TextRenderedRun();
1783 return mCurrent;
1786 // The values we will use to initialize the TextRenderedRun with.
1787 nsTextFrame* frame;
1788 gfxPoint pt;
1789 double rotate;
1790 nscoord baseline;
1791 uint32_t offset, length;
1792 uint32_t charIndex;
1794 // We loop, because we want to skip over rendered runs that either aren't
1795 // within our subtree of interest, because they don't match the filter,
1796 // or because they are hidden due to having fallen off the end of a
1797 // <textPath>.
1798 for (;;) {
1799 if (mFrameIterator.IsAfterSubtree()) {
1800 mCurrent = TextRenderedRun();
1801 return mCurrent;
1804 frame = mFrameIterator.Current();
1806 charIndex = mTextElementCharIndex;
1808 // Find the end of the rendered run, by looking through the
1809 // SVGTextFrame's positions array until we find one that is recorded
1810 // as a run boundary.
1811 uint32_t runStart,
1812 runEnd; // XXX Replace runStart with mTextElementCharIndex.
1813 runStart = mTextElementCharIndex;
1814 runEnd = runStart + 1;
1815 while (runEnd < Root()->mPositions.Length() &&
1816 !Root()->mPositions[runEnd].mRunBoundary) {
1817 runEnd++;
1820 // Convert the global run start/end indexes into an offset/length into the
1821 // current frame's Text.
1822 offset =
1823 frame->GetContentOffset() + runStart - mFrameStartTextElementCharIndex;
1824 length = runEnd - runStart;
1826 // If the end of the frame's content comes before the run boundary we found
1827 // in SVGTextFrame's position array, we need to shorten the rendered run.
1828 uint32_t contentEnd = frame->GetContentEnd();
1829 if (offset + length > contentEnd) {
1830 length = contentEnd - offset;
1833 NS_ASSERTION(offset >= uint32_t(frame->GetContentOffset()),
1834 "invalid offset");
1835 NS_ASSERTION(offset + length <= contentEnd, "invalid offset or length");
1837 // Get the frame's baseline position.
1838 frame->EnsureTextRun(nsTextFrame::eInflated);
1839 baseline = GetBaselinePosition(
1840 frame, frame->GetTextRun(nsTextFrame::eInflated),
1841 mFrameIterator.DominantBaseline(), mFontSizeScaleFactor);
1843 // Trim the offset/length to remove any leading/trailing white space.
1844 uint32_t untrimmedOffset = offset;
1845 uint32_t untrimmedLength = length;
1846 nsTextFrame::TrimmedOffsets trimmedOffsets =
1847 frame->GetTrimmedOffsets(frame->TextFragment());
1848 TrimOffsets(offset, length, trimmedOffsets);
1849 charIndex += offset - untrimmedOffset;
1851 // Get the position and rotation of the character that begins this
1852 // rendered run.
1853 pt = Root()->mPositions[charIndex].mPosition;
1854 rotate = Root()->mPositions[charIndex].mAngle;
1856 // Determine if we should skip this rendered run.
1857 bool skip = !mFrameIterator.IsWithinSubtree() ||
1858 Root()->mPositions[mTextElementCharIndex].mHidden;
1859 if (mFilter == eVisibleFrames) {
1860 skip = skip || !frame->StyleVisibility()->IsVisible();
1863 // Update our global character index to move past the characters
1864 // corresponding to this rendered run.
1865 mTextElementCharIndex += untrimmedLength;
1867 // If we have moved past the end of the current frame's content, we need to
1868 // advance to the next frame.
1869 if (offset + untrimmedLength >= contentEnd) {
1870 mFrameIterator.Next();
1871 mTextElementCharIndex += mFrameIterator.UndisplayedCharacters();
1872 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1875 if (!mFrameIterator.Current()) {
1876 if (skip) {
1877 // That was the last frame, and we skipped this rendered run. So we
1878 // have no rendered run to return.
1879 mCurrent = TextRenderedRun();
1880 return mCurrent;
1882 break;
1885 if (length && !skip) {
1886 // Only return a rendered run if it didn't get collapsed away entirely
1887 // (due to it being all white space) and if we don't want to skip it.
1888 break;
1892 mCurrent = TextRenderedRun(frame, pt, Root()->mLengthAdjustScaleFactor,
1893 rotate, mFontSizeScaleFactor, baseline, offset,
1894 length, charIndex);
1895 return mCurrent;
1898 TextRenderedRun TextRenderedRunIterator::First() {
1899 if (!mFrameIterator.Current()) {
1900 return TextRenderedRun();
1903 if (Root()->mPositions.IsEmpty()) {
1904 mFrameIterator.Close();
1905 return TextRenderedRun();
1908 // Get the character index for the start of this rendered run, by skipping
1909 // any undisplayed characters.
1910 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
1911 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1913 return Next();
1916 // -----------------------------------------------------------------------------
1917 // CharIterator
1920 * Iterator for characters within an SVGTextFrame.
1922 class MOZ_STACK_CLASS CharIterator {
1923 using Range = gfxTextRun::Range;
1925 public:
1927 * Values for the aFilter argument of the constructor, to indicate which
1928 * characters we should be iterating over.
1930 enum CharacterFilter {
1931 // Iterate over all original characters from the DOM that are within valid
1932 // text content elements.
1933 eOriginal,
1934 // Iterate only over characters that are not skipped characters.
1935 eUnskipped,
1936 // Iterate only over characters that are addressable by the positioning
1937 // attributes x="", y="", etc. This includes all characters after
1938 // collapsing white space as required by the value of 'white-space'.
1939 eAddressable,
1943 * Constructs a CharIterator.
1945 * @param aSVGTextFrame The SVGTextFrame whose characters to iterate
1946 * through.
1947 * @param aFilter Indicates which characters to iterate over.
1948 * @param aSubtree A content subtree to track whether the current character
1949 * is within.
1951 CharIterator(SVGTextFrame* aSVGTextFrame, CharacterFilter aFilter,
1952 nsIContent* aSubtree, bool aPostReflow = true);
1955 * Returns whether the iterator is finished.
1957 bool AtEnd() const { return !mFrameIterator.Current(); }
1960 * Advances to the next matching character. Returns true if there was a
1961 * character to advance to, and false otherwise.
1963 bool Next();
1966 * Advances ahead aCount matching characters. Returns true if there were
1967 * enough characters to advance past, and false otherwise.
1969 bool Next(uint32_t aCount);
1972 * Advances ahead up to aCount matching characters.
1974 void NextWithinSubtree(uint32_t aCount);
1977 * Advances to the character with the specified index. The index is in the
1978 * space of original characters (i.e., all DOM characters under the <text>
1979 * that are within valid text content elements).
1981 bool AdvanceToCharacter(uint32_t aTextElementCharIndex);
1984 * Advances to the first matching character after the current nsTextFrame.
1986 bool AdvancePastCurrentFrame();
1989 * Advances to the first matching character after the frames within
1990 * the current <textPath>.
1992 bool AdvancePastCurrentTextPathFrame();
1995 * Advances to the first matching character of the subtree. Returns true
1996 * if we successfully advance to the subtree, or if we are already within
1997 * the subtree. Returns false if we are past the subtree.
1999 bool AdvanceToSubtree();
2002 * Returns the nsTextFrame for the current character.
2004 nsTextFrame* TextFrame() const { return mFrameIterator.Current(); }
2007 * Returns whether the iterator is within the subtree.
2009 bool IsWithinSubtree() const { return mFrameIterator.IsWithinSubtree(); }
2012 * Returns whether the iterator is past the subtree.
2014 bool IsAfterSubtree() const { return mFrameIterator.IsAfterSubtree(); }
2017 * Returns whether the current character is a skipped character.
2019 bool IsOriginalCharSkipped() const {
2020 return mSkipCharsIterator.IsOriginalCharSkipped();
2024 * Returns whether the current character is the start of a cluster and
2025 * ligature group.
2027 bool IsClusterAndLigatureGroupStart() const {
2028 return mTextRun->IsLigatureGroupStart(
2029 mSkipCharsIterator.GetSkippedOffset()) &&
2030 mTextRun->IsClusterStart(mSkipCharsIterator.GetSkippedOffset());
2034 * Returns the glyph run for the current character.
2036 const gfxTextRun::GlyphRun& GlyphRun() const {
2037 return *mTextRun->FindFirstGlyphRunContaining(
2038 mSkipCharsIterator.GetSkippedOffset());
2042 * Returns whether the current character is trimmed away when painting,
2043 * due to it being leading/trailing white space.
2045 bool IsOriginalCharTrimmed() const;
2048 * Returns whether the current character is unaddressable from the SVG glyph
2049 * positioning attributes.
2051 bool IsOriginalCharUnaddressable() const {
2052 return IsOriginalCharSkipped() || IsOriginalCharTrimmed();
2056 * Returns the text run for the current character.
2058 gfxTextRun* TextRun() const { return mTextRun; }
2061 * Returns the current character index.
2063 uint32_t TextElementCharIndex() const { return mTextElementCharIndex; }
2066 * Returns the character index for the start of the cluster/ligature group it
2067 * is part of.
2069 uint32_t GlyphStartTextElementCharIndex() const {
2070 return mGlyphStartTextElementCharIndex;
2074 * Gets the advance, in user units, of the current character. If the
2075 * character is a part of ligature, then the advance returned will be
2076 * a fraction of the ligature glyph's advance.
2078 * @param aContext The context to use for unit conversions.
2080 gfxFloat GetAdvance(nsPresContext* aContext) const;
2083 * Returns the frame corresponding to the <textPath> that the current
2084 * character is within.
2086 nsIFrame* TextPathFrame() const { return mFrameIterator.TextPathFrame(); }
2088 #ifdef DEBUG
2090 * Returns the subtree we were constructed with.
2092 nsIContent* GetSubtree() const { return mSubtree; }
2095 * Returns the CharacterFilter mode in use.
2097 CharacterFilter Filter() const { return mFilter; }
2098 #endif
2100 private:
2102 * Advances to the next character without checking it against the filter.
2103 * Returns true if there was a next character to advance to, or false
2104 * otherwise.
2106 bool NextCharacter();
2109 * Returns whether the current character matches the filter.
2111 bool MatchesFilter() const;
2114 * If this is the start of a glyph, record it.
2116 void UpdateGlyphStartTextElementCharIndex() {
2117 if (!IsOriginalCharSkipped() && IsClusterAndLigatureGroupStart()) {
2118 mGlyphStartTextElementCharIndex = mTextElementCharIndex;
2123 * The filter to use.
2125 CharacterFilter mFilter;
2128 * The iterator for text frames.
2130 TextFrameIterator mFrameIterator;
2132 #ifdef DEBUG
2134 * The subtree we were constructed with.
2136 nsIContent* const mSubtree;
2137 #endif
2140 * A gfxSkipCharsIterator for the text frame the current character is
2141 * a part of.
2143 gfxSkipCharsIterator mSkipCharsIterator;
2145 // Cache for information computed by IsOriginalCharTrimmed.
2146 mutable nsTextFrame* mFrameForTrimCheck;
2147 mutable uint32_t mTrimmedOffset;
2148 mutable uint32_t mTrimmedLength;
2151 * The text run the current character is a part of.
2153 gfxTextRun* mTextRun;
2156 * The current character's index.
2158 uint32_t mTextElementCharIndex;
2161 * The index of the character that starts the cluster/ligature group the
2162 * current character is a part of.
2164 uint32_t mGlyphStartTextElementCharIndex;
2167 * The scale factor to apply to glyph advances returned by
2168 * GetAdvance etc. to take into account textLength="".
2170 float mLengthAdjustScaleFactor;
2173 * Whether the instance of this class is being used after reflow has occurred
2174 * or not.
2176 bool mPostReflow;
2179 CharIterator::CharIterator(SVGTextFrame* aSVGTextFrame,
2180 CharIterator::CharacterFilter aFilter,
2181 nsIContent* aSubtree, bool aPostReflow)
2182 : mFilter(aFilter),
2183 mFrameIterator(aSVGTextFrame, aSubtree),
2184 #ifdef DEBUG
2185 mSubtree(aSubtree),
2186 #endif
2187 mFrameForTrimCheck(nullptr),
2188 mTrimmedOffset(0),
2189 mTrimmedLength(0),
2190 mTextRun(nullptr),
2191 mTextElementCharIndex(0),
2192 mGlyphStartTextElementCharIndex(0),
2193 mLengthAdjustScaleFactor(aSVGTextFrame->mLengthAdjustScaleFactor),
2194 mPostReflow(aPostReflow) {
2195 if (!AtEnd()) {
2196 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2197 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2198 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
2199 UpdateGlyphStartTextElementCharIndex();
2200 if (!MatchesFilter()) {
2201 Next();
2206 bool CharIterator::Next() {
2207 while (NextCharacter()) {
2208 if (MatchesFilter()) {
2209 return true;
2212 return false;
2215 bool CharIterator::Next(uint32_t aCount) {
2216 if (aCount == 0 && AtEnd()) {
2217 return false;
2219 while (aCount) {
2220 if (!Next()) {
2221 return false;
2223 aCount--;
2225 return true;
2228 void CharIterator::NextWithinSubtree(uint32_t aCount) {
2229 while (IsWithinSubtree() && aCount) {
2230 --aCount;
2231 if (!Next()) {
2232 return;
2237 bool CharIterator::AdvanceToCharacter(uint32_t aTextElementCharIndex) {
2238 while (mTextElementCharIndex < aTextElementCharIndex) {
2239 if (!Next()) {
2240 return false;
2243 return true;
2246 bool CharIterator::AdvancePastCurrentFrame() {
2247 // XXX Can do this better than one character at a time if it matters.
2248 nsTextFrame* currentFrame = TextFrame();
2249 do {
2250 if (!Next()) {
2251 return false;
2253 } while (TextFrame() == currentFrame);
2254 return true;
2257 bool CharIterator::AdvancePastCurrentTextPathFrame() {
2258 nsIFrame* currentTextPathFrame = TextPathFrame();
2259 NS_ASSERTION(currentTextPathFrame,
2260 "expected AdvancePastCurrentTextPathFrame to be called only "
2261 "within a text path frame");
2262 do {
2263 if (!AdvancePastCurrentFrame()) {
2264 return false;
2266 } while (TextPathFrame() == currentTextPathFrame);
2267 return true;
2270 bool CharIterator::AdvanceToSubtree() {
2271 while (!IsWithinSubtree()) {
2272 if (IsAfterSubtree()) {
2273 return false;
2275 if (!AdvancePastCurrentFrame()) {
2276 return false;
2279 return true;
2282 bool CharIterator::IsOriginalCharTrimmed() const {
2283 if (mFrameForTrimCheck != TextFrame()) {
2284 // Since we do a lot of trim checking, we cache the trimmed offsets and
2285 // lengths while we are in the same frame.
2286 mFrameForTrimCheck = TextFrame();
2287 uint32_t offset = mFrameForTrimCheck->GetContentOffset();
2288 uint32_t length = mFrameForTrimCheck->GetContentLength();
2289 nsTextFrame::TrimmedOffsets trim = mFrameForTrimCheck->GetTrimmedOffsets(
2290 mFrameForTrimCheck->TextFragment(),
2291 (mPostReflow ? nsTextFrame::TrimmedOffsetFlags::Default
2292 : nsTextFrame::TrimmedOffsetFlags::NotPostReflow));
2293 TrimOffsets(offset, length, trim);
2294 mTrimmedOffset = offset;
2295 mTrimmedLength = length;
2298 // A character is trimmed if it is outside the mTrimmedOffset/mTrimmedLength
2299 // range and it is not a significant newline character.
2300 uint32_t index = mSkipCharsIterator.GetOriginalOffset();
2301 return !(
2302 (index >= mTrimmedOffset && index < mTrimmedOffset + mTrimmedLength) ||
2303 (index >= mTrimmedOffset + mTrimmedLength &&
2304 mFrameForTrimCheck->StyleText()->NewlineIsSignificant(
2305 mFrameForTrimCheck) &&
2306 mFrameForTrimCheck->TextFragment()->CharAt(index) == '\n'));
2309 gfxFloat CharIterator::GetAdvance(nsPresContext* aContext) const {
2310 float cssPxPerDevPx =
2311 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
2313 gfxSkipCharsIterator start =
2314 TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2315 nsTextFrame::PropertyProvider provider(TextFrame(), start);
2317 uint32_t offset = mSkipCharsIterator.GetSkippedOffset();
2318 gfxFloat advance =
2319 mTextRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
2320 return aContext->AppUnitsToGfxUnits(advance) * mLengthAdjustScaleFactor *
2321 cssPxPerDevPx;
2324 bool CharIterator::NextCharacter() {
2325 if (AtEnd()) {
2326 return false;
2329 mTextElementCharIndex++;
2331 // Advance within the current text run.
2332 mSkipCharsIterator.AdvanceOriginal(1);
2333 if (mSkipCharsIterator.GetOriginalOffset() < TextFrame()->GetContentEnd()) {
2334 // We're still within the part of the text run for the current text frame.
2335 UpdateGlyphStartTextElementCharIndex();
2336 return true;
2339 // Advance to the next frame.
2340 mFrameIterator.Next();
2342 // Skip any undisplayed characters.
2343 uint32_t undisplayed = mFrameIterator.UndisplayedCharacters();
2344 mTextElementCharIndex += undisplayed;
2345 if (!TextFrame()) {
2346 // We're at the end.
2347 mSkipCharsIterator = gfxSkipCharsIterator();
2348 return false;
2351 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2352 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2353 UpdateGlyphStartTextElementCharIndex();
2354 return true;
2357 bool CharIterator::MatchesFilter() const {
2358 switch (mFilter) {
2359 case eOriginal:
2360 return true;
2361 case eUnskipped:
2362 return !IsOriginalCharSkipped();
2363 case eAddressable:
2364 return !IsOriginalCharSkipped() && !IsOriginalCharUnaddressable();
2366 MOZ_ASSERT_UNREACHABLE("Invalid mFilter value");
2367 return true;
2370 // -----------------------------------------------------------------------------
2371 // SVGTextDrawPathCallbacks
2374 * Text frame draw callback class that paints the text and text decoration parts
2375 * of an nsTextFrame using SVG painting properties, and selection backgrounds
2376 * and decorations as they would normally.
2378 * An instance of this class is passed to nsTextFrame::PaintText if painting
2379 * cannot be done directly (e.g. if we are using an SVG pattern fill, stroking
2380 * the text, etc.).
2382 class SVGTextDrawPathCallbacks final : public nsTextFrame::DrawPathCallbacks {
2383 using imgDrawingParams = image::imgDrawingParams;
2385 public:
2387 * Constructs an SVGTextDrawPathCallbacks.
2389 * @param aSVGTextFrame The ancestor text frame.
2390 * @param aContext The context to use for painting.
2391 * @param aFrame The nsTextFrame to paint.
2392 * @param aCanvasTM The transformation matrix to set when painting; this
2393 * should be the FOR_OUTERSVG_TM canvas TM of the text, so that
2394 * paint servers are painted correctly.
2395 * @param aImgParams Whether we need to synchronously decode images.
2396 * @param aShouldPaintSVGGlyphs Whether SVG glyphs should be painted.
2398 SVGTextDrawPathCallbacks(SVGTextFrame* aSVGTextFrame, gfxContext& aContext,
2399 nsTextFrame* aFrame, const gfxMatrix& aCanvasTM,
2400 imgDrawingParams& aImgParams,
2401 bool aShouldPaintSVGGlyphs)
2402 : DrawPathCallbacks(aShouldPaintSVGGlyphs),
2403 mSVGTextFrame(aSVGTextFrame),
2404 mContext(aContext),
2405 mFrame(aFrame),
2406 mCanvasTM(aCanvasTM),
2407 mImgParams(aImgParams),
2408 mColor(0) {}
2410 void NotifySelectionBackgroundNeedsFill(const Rect& aBackgroundRect,
2411 nscolor aColor,
2412 DrawTarget& aDrawTarget) override;
2413 void PaintDecorationLine(Rect aPath, nscolor aColor) override;
2414 void PaintSelectionDecorationLine(Rect aPath, nscolor aColor) override;
2415 void NotifyBeforeText(nscolor aColor) override;
2416 void NotifyGlyphPathEmitted() override;
2417 void NotifyAfterText() override;
2419 private:
2420 void SetupContext();
2422 bool IsClipPathChild() const {
2423 return mSVGTextFrame->HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD);
2427 * Paints a piece of text geometry. This is called when glyphs
2428 * or text decorations have been emitted to the gfxContext.
2430 void HandleTextGeometry();
2433 * Sets the gfxContext paint to the appropriate color or pattern
2434 * for filling text geometry.
2436 void MakeFillPattern(GeneralPattern* aOutPattern);
2439 * Fills and strokes a piece of text geometry, using group opacity
2440 * if the selection style requires it.
2442 void FillAndStrokeGeometry();
2445 * Fills a piece of text geometry.
2447 void FillGeometry();
2450 * Strokes a piece of text geometry.
2452 void StrokeGeometry();
2454 SVGTextFrame* const mSVGTextFrame;
2455 gfxContext& mContext;
2456 nsTextFrame* const mFrame;
2457 const gfxMatrix& mCanvasTM;
2458 imgDrawingParams& mImgParams;
2461 * The color that we were last told from one of the path callback functions.
2462 * This color can be the special NS_SAME_AS_FOREGROUND_COLOR,
2463 * NS_40PERCENT_FOREGROUND_COLOR and NS_TRANSPARENT colors when we are
2464 * painting selections or IME decorations.
2466 nscolor mColor;
2469 void SVGTextDrawPathCallbacks::NotifySelectionBackgroundNeedsFill(
2470 const Rect& aBackgroundRect, nscolor aColor, DrawTarget& aDrawTarget) {
2471 if (IsClipPathChild()) {
2472 // Don't paint selection backgrounds when in a clip path.
2473 return;
2476 mColor = aColor; // currently needed by MakeFillPattern
2478 GeneralPattern fillPattern;
2479 MakeFillPattern(&fillPattern);
2480 if (fillPattern.GetPattern()) {
2481 DrawOptions drawOptions(aColor == NS_40PERCENT_FOREGROUND_COLOR ? 0.4
2482 : 1.0);
2483 aDrawTarget.FillRect(aBackgroundRect, fillPattern, drawOptions);
2487 void SVGTextDrawPathCallbacks::NotifyBeforeText(nscolor aColor) {
2488 mColor = aColor;
2489 SetupContext();
2490 mContext.NewPath();
2493 void SVGTextDrawPathCallbacks::NotifyGlyphPathEmitted() {
2494 HandleTextGeometry();
2495 mContext.NewPath();
2498 void SVGTextDrawPathCallbacks::NotifyAfterText() { mContext.Restore(); }
2500 void SVGTextDrawPathCallbacks::PaintDecorationLine(Rect aPath, nscolor aColor) {
2501 mColor = aColor;
2502 AntialiasMode aaMode =
2503 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2505 mContext.Save();
2506 mContext.NewPath();
2507 mContext.SetAntialiasMode(aaMode);
2508 mContext.Rectangle(ThebesRect(aPath));
2509 HandleTextGeometry();
2510 mContext.NewPath();
2511 mContext.Restore();
2514 void SVGTextDrawPathCallbacks::PaintSelectionDecorationLine(Rect aPath,
2515 nscolor aColor) {
2516 if (IsClipPathChild()) {
2517 // Don't paint selection decorations when in a clip path.
2518 return;
2521 mColor = aColor;
2523 mContext.Save();
2524 mContext.NewPath();
2525 mContext.Rectangle(ThebesRect(aPath));
2526 FillAndStrokeGeometry();
2527 mContext.Restore();
2530 void SVGTextDrawPathCallbacks::SetupContext() {
2531 mContext.Save();
2533 // XXX This is copied from nsSVGGlyphFrame::Render, but cairo doesn't actually
2534 // seem to do anything with the antialias mode. So we can perhaps remove it,
2535 // or make SetAntialiasMode set cairo text antialiasing too.
2536 switch (mFrame->StyleText()->mTextRendering) {
2537 case StyleTextRendering::Optimizespeed:
2538 mContext.SetAntialiasMode(AntialiasMode::NONE);
2539 break;
2540 default:
2541 mContext.SetAntialiasMode(AntialiasMode::SUBPIXEL);
2542 break;
2546 void SVGTextDrawPathCallbacks::HandleTextGeometry() {
2547 if (IsClipPathChild()) {
2548 RefPtr<Path> path = mContext.GetPath();
2549 ColorPattern white(
2550 DeviceColor(1.f, 1.f, 1.f, 1.f)); // for masking, so no ToDeviceColor
2551 mContext.GetDrawTarget()->Fill(path, white);
2552 } else {
2553 // Normal painting.
2554 gfxContextMatrixAutoSaveRestore saveMatrix(&mContext);
2555 mContext.SetMatrixDouble(mCanvasTM);
2557 FillAndStrokeGeometry();
2561 void SVGTextDrawPathCallbacks::MakeFillPattern(GeneralPattern* aOutPattern) {
2562 if (mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2563 mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2564 SVGUtils::MakeFillPatternFor(mFrame, &mContext, aOutPattern, mImgParams);
2565 return;
2568 if (mColor == NS_TRANSPARENT) {
2569 return;
2572 aOutPattern->InitColorPattern(ToDeviceColor(mColor));
2575 void SVGTextDrawPathCallbacks::FillAndStrokeGeometry() {
2576 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&mContext);
2577 if (mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2578 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 0.4f);
2581 uint32_t paintOrder = mFrame->StyleSVG()->mPaintOrder;
2582 if (!paintOrder) {
2583 FillGeometry();
2584 StrokeGeometry();
2585 } else {
2586 while (paintOrder) {
2587 auto component = StylePaintOrder(paintOrder & kPaintOrderMask);
2588 switch (component) {
2589 case StylePaintOrder::Fill:
2590 FillGeometry();
2591 break;
2592 case StylePaintOrder::Stroke:
2593 StrokeGeometry();
2594 break;
2595 default:
2596 MOZ_FALLTHROUGH_ASSERT("Unknown paint-order value");
2597 case StylePaintOrder::Markers:
2598 case StylePaintOrder::Normal:
2599 break;
2601 paintOrder >>= kPaintOrderShift;
2606 void SVGTextDrawPathCallbacks::FillGeometry() {
2607 GeneralPattern fillPattern;
2608 MakeFillPattern(&fillPattern);
2609 if (fillPattern.GetPattern()) {
2610 RefPtr<Path> path = mContext.GetPath();
2611 FillRule fillRule = SVGUtils::ToFillRule(mFrame->StyleSVG()->mFillRule);
2612 if (fillRule != path->GetFillRule()) {
2613 RefPtr<PathBuilder> builder = path->CopyToBuilder(fillRule);
2614 path = builder->Finish();
2616 mContext.GetDrawTarget()->Fill(path, fillPattern);
2620 void SVGTextDrawPathCallbacks::StrokeGeometry() {
2621 // We don't paint the stroke when we are filling with a selection color.
2622 if (mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2623 mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2624 if (SVGUtils::HasStroke(mFrame, /*aContextPaint*/ nullptr)) {
2625 GeneralPattern strokePattern;
2626 SVGUtils::MakeStrokePatternFor(mFrame, &mContext, &strokePattern,
2627 mImgParams, /*aContextPaint*/ nullptr);
2628 if (strokePattern.GetPattern()) {
2629 if (!mFrame->GetParent()->GetContent()->IsSVGElement()) {
2630 // The cast that follows would be unsafe
2631 MOZ_ASSERT(false, "Our nsTextFrame's parent's content should be SVG");
2632 return;
2634 SVGElement* svgOwner =
2635 static_cast<SVGElement*>(mFrame->GetParent()->GetContent());
2637 // Apply any stroke-specific transform
2638 gfxMatrix outerSVGToUser;
2639 if (SVGUtils::GetNonScalingStrokeTransform(mFrame, &outerSVGToUser) &&
2640 outerSVGToUser.Invert()) {
2641 mContext.Multiply(outerSVGToUser);
2644 RefPtr<Path> path = mContext.GetPath();
2645 SVGContentUtils::AutoStrokeOptions strokeOptions;
2646 SVGContentUtils::GetStrokeOptions(&strokeOptions, svgOwner,
2647 mFrame->Style(),
2648 /*aContextPaint*/ nullptr);
2649 DrawOptions drawOptions;
2650 drawOptions.mAntialiasMode =
2651 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2652 mContext.GetDrawTarget()->Stroke(path, strokePattern, strokeOptions);
2658 // ============================================================================
2659 // SVGTextFrame
2661 // ----------------------------------------------------------------------------
2662 // Display list item
2664 class DisplaySVGText final : public DisplaySVGItem {
2665 public:
2666 DisplaySVGText(nsDisplayListBuilder* aBuilder, SVGTextFrame* aFrame)
2667 : DisplaySVGItem(aBuilder, aFrame) {
2668 MOZ_COUNT_CTOR(DisplaySVGText);
2671 MOZ_COUNTED_DTOR_OVERRIDE(DisplaySVGText)
2673 NS_DISPLAY_DECL_NAME("DisplaySVGText", TYPE_SVG_TEXT)
2675 nsDisplayItemGeometry* AllocateGeometry(
2676 nsDisplayListBuilder* aBuilder) override {
2677 return new nsDisplayItemGenericGeometry(this, aBuilder);
2680 nsRect GetComponentAlphaBounds(
2681 nsDisplayListBuilder* aBuilder) const override {
2682 bool snap;
2683 return GetBounds(aBuilder, &snap);
2687 // ---------------------------------------------------------------------
2688 // nsQueryFrame methods
2690 NS_QUERYFRAME_HEAD(SVGTextFrame)
2691 NS_QUERYFRAME_ENTRY(SVGTextFrame)
2692 NS_QUERYFRAME_TAIL_INHERITING(SVGDisplayContainerFrame)
2694 } // namespace mozilla
2696 // ---------------------------------------------------------------------
2697 // Implementation
2699 nsIFrame* NS_NewSVGTextFrame(mozilla::PresShell* aPresShell,
2700 mozilla::ComputedStyle* aStyle) {
2701 return new (aPresShell)
2702 mozilla::SVGTextFrame(aStyle, aPresShell->GetPresContext());
2705 namespace mozilla {
2707 NS_IMPL_FRAMEARENA_HELPERS(SVGTextFrame)
2709 // ---------------------------------------------------------------------
2710 // nsIFrame methods
2712 void SVGTextFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
2713 nsIFrame* aPrevInFlow) {
2714 NS_ASSERTION(aContent->IsSVGElement(nsGkAtoms::text),
2715 "Content is not an SVG text");
2717 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
2718 AddStateBits(aParent->GetStateBits() & NS_STATE_SVG_CLIPPATH_CHILD);
2720 mMutationObserver = new MutationObserver(this);
2722 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2723 // We're inserting a new <text> element into a non-display context.
2724 // Ensure that we get reflowed.
2725 ScheduleReflowSVGNonDisplayText(
2726 IntrinsicDirty::FrameAncestorsAndDescendants);
2730 void SVGTextFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
2731 const nsDisplayListSet& aLists) {
2732 if (IsSubtreeDirty()) {
2733 // We can sometimes be asked to paint before reflow happens and we
2734 // have updated mPositions, etc. In this case, we just avoid
2735 // painting.
2736 return;
2738 if (!IsVisibleForPainting() && aBuilder->IsForPainting()) {
2739 return;
2741 DisplayOutline(aBuilder, aLists);
2742 aLists.Content()->AppendNewToTop<DisplaySVGText>(aBuilder, this);
2745 nsresult SVGTextFrame::AttributeChanged(int32_t aNameSpaceID,
2746 nsAtom* aAttribute, int32_t aModType) {
2747 if (aNameSpaceID != kNameSpaceID_None) {
2748 return NS_OK;
2751 if (aAttribute == nsGkAtoms::transform) {
2752 // We don't invalidate for transform changes (the layers code does that).
2753 // Also note that SVGTransformableElement::GetAttributeChangeHint will
2754 // return nsChangeHint_UpdateOverflow for "transform" attribute changes
2755 // and cause DoApplyRenderingChangeToTree to make the SchedulePaint call.
2757 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && mCanvasTM &&
2758 mCanvasTM->IsSingular()) {
2759 // We won't have calculated the glyph positions correctly.
2760 NotifyGlyphMetricsChange(false);
2762 mCanvasTM = nullptr;
2763 } else if (IsGlyphPositioningAttribute(aAttribute) ||
2764 aAttribute == nsGkAtoms::textLength ||
2765 aAttribute == nsGkAtoms::lengthAdjust) {
2766 NotifyGlyphMetricsChange(false);
2769 return NS_OK;
2772 void SVGTextFrame::ReflowSVGNonDisplayText() {
2773 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
2774 "only call ReflowSVGNonDisplayText when an outer SVG frame is "
2775 "under ReflowSVG");
2776 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),
2777 "only call ReflowSVGNonDisplayText if the frame is "
2778 "NS_FRAME_IS_NONDISPLAY");
2780 // We had a style change, so we mark this frame as dirty so that the next
2781 // time it is painted, we reflow the anonymous block frame.
2782 this->MarkSubtreeDirty();
2784 // Finally, we need to actually reflow the anonymous block frame and update
2785 // mPositions, in case we are being reflowed immediately after a DOM
2786 // mutation that needs frame reconstruction.
2787 MaybeReflowAnonymousBlockChild();
2788 UpdateGlyphPositioning();
2791 void SVGTextFrame::ScheduleReflowSVGNonDisplayText(IntrinsicDirty aReason) {
2792 MOZ_ASSERT(!SVGUtils::OuterSVGIsCallingReflowSVG(this),
2793 "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
2794 "frame is under ReflowSVG");
2795 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW),
2796 "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
2797 "anonymous block child");
2799 // We need to find an ancestor frame that we can call FrameNeedsReflow
2800 // on that will cause the document to be marked as needing relayout,
2801 // and for that ancestor (or some further ancestor) to be marked as
2802 // a root to reflow. We choose the closest ancestor frame that is not
2803 // NS_FRAME_IS_NONDISPLAY and which is either an outer SVG frame or a
2804 // non-SVG frame. (We don't consider displayed SVG frame ancestors other
2805 // than SVGOuterSVGFrame, since calling FrameNeedsReflow on those other
2806 // SVG frames would do a bunch of unnecessary work on the SVG frames up to
2807 // the SVGOuterSVGFrame.)
2809 nsIFrame* f = this;
2810 while (f) {
2811 if (!f->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2812 if (f->IsSubtreeDirty()) {
2813 // This is a displayed frame, so if it is already dirty, we will be
2814 // reflowed soon anyway. No need to call FrameNeedsReflow again, then.
2815 return;
2817 if (!f->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
2818 break;
2820 f->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
2822 f = f->GetParent();
2825 MOZ_ASSERT(f, "should have found an ancestor frame to reflow");
2827 PresShell()->FrameNeedsReflow(f, aReason, NS_FRAME_IS_DIRTY);
2830 NS_IMPL_ISUPPORTS(SVGTextFrame::MutationObserver, nsIMutationObserver)
2832 void SVGTextFrame::MutationObserver::ContentAppended(
2833 nsIContent* aFirstNewContent) {
2834 mFrame->NotifyGlyphMetricsChange(true);
2837 void SVGTextFrame::MutationObserver::ContentInserted(nsIContent* aChild) {
2838 mFrame->NotifyGlyphMetricsChange(true);
2841 void SVGTextFrame::MutationObserver::ContentRemoved(
2842 nsIContent* aChild, nsIContent* aPreviousSibling) {
2843 mFrame->NotifyGlyphMetricsChange(true);
2846 void SVGTextFrame::MutationObserver::CharacterDataChanged(
2847 nsIContent* aContent, const CharacterDataChangeInfo&) {
2848 mFrame->NotifyGlyphMetricsChange(true);
2851 void SVGTextFrame::MutationObserver::AttributeChanged(
2852 Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
2853 int32_t aModType, const nsAttrValue* aOldValue) {
2854 if (!aElement->IsSVGElement()) {
2855 return;
2858 // Attribute changes on this element will be handled by
2859 // SVGTextFrame::AttributeChanged.
2860 if (aElement == mFrame->GetContent()) {
2861 return;
2864 mFrame->HandleAttributeChangeInDescendant(aElement, aNameSpaceID, aAttribute);
2867 void SVGTextFrame::HandleAttributeChangeInDescendant(Element* aElement,
2868 int32_t aNameSpaceID,
2869 nsAtom* aAttribute) {
2870 if (aElement->IsSVGElement(nsGkAtoms::textPath)) {
2871 if (aNameSpaceID == kNameSpaceID_None &&
2872 (aAttribute == nsGkAtoms::startOffset ||
2873 aAttribute == nsGkAtoms::path || aAttribute == nsGkAtoms::side_)) {
2874 NotifyGlyphMetricsChange(false);
2875 } else if ((aNameSpaceID == kNameSpaceID_XLink ||
2876 aNameSpaceID == kNameSpaceID_None) &&
2877 aAttribute == nsGkAtoms::href) {
2878 // Blow away our reference, if any
2879 nsIFrame* childElementFrame = aElement->GetPrimaryFrame();
2880 if (childElementFrame) {
2881 SVGObserverUtils::RemoveTextPathObserver(childElementFrame);
2882 NotifyGlyphMetricsChange(false);
2885 } else {
2886 if (aNameSpaceID == kNameSpaceID_None &&
2887 IsGlyphPositioningAttribute(aAttribute)) {
2888 NotifyGlyphMetricsChange(false);
2893 void SVGTextFrame::FindCloserFrameForSelection(
2894 const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
2895 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2896 return;
2899 UpdateGlyphPositioning();
2901 nsPresContext* presContext = PresContext();
2903 // Find the frame that has the closest rendered run rect to aPoint.
2904 TextRenderedRunIterator it(this);
2905 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
2906 uint32_t flags = TextRenderedRun::eIncludeFill |
2907 TextRenderedRun::eIncludeStroke |
2908 TextRenderedRun::eNoHorizontalOverflow;
2909 SVGBBox userRect = run.GetUserSpaceRect(presContext, flags);
2910 float devPxPerCSSPx = presContext->CSSPixelsToDevPixels(1.f);
2911 userRect.Scale(devPxPerCSSPx);
2913 if (!userRect.IsEmpty()) {
2914 gfxMatrix m;
2915 nsRect rect =
2916 SVGUtils::ToCanvasBounds(userRect.ToThebesRect(), m, presContext);
2918 if (nsLayoutUtils::PointIsCloserToRect(aPoint, rect,
2919 aCurrentBestFrame->mXDistance,
2920 aCurrentBestFrame->mYDistance)) {
2921 aCurrentBestFrame->mFrame = run.mFrame;
2927 //----------------------------------------------------------------------
2928 // ISVGDisplayableFrame methods
2930 void SVGTextFrame::NotifySVGChanged(uint32_t aFlags) {
2931 MOZ_ASSERT(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED),
2932 "Invalidation logic may need adjusting");
2934 bool needNewBounds = false;
2935 bool needGlyphMetricsUpdate = false;
2936 bool needNewCanvasTM = false;
2938 if ((aFlags & COORD_CONTEXT_CHANGED) &&
2939 HasAnyStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES)) {
2940 needGlyphMetricsUpdate = true;
2943 if (aFlags & TRANSFORM_CHANGED) {
2944 needNewCanvasTM = true;
2945 if (mCanvasTM && mCanvasTM->IsSingular()) {
2946 // We won't have calculated the glyph positions correctly.
2947 needNewBounds = true;
2948 needGlyphMetricsUpdate = true;
2950 if (StyleSVGReset()->HasNonScalingStroke()) {
2951 // Stroke currently contributes to our mRect, and our stroke depends on
2952 // the transform to our outer-<svg> if |vector-effect:non-scaling-stroke|.
2953 needNewBounds = true;
2957 // If the scale at which we computed our mFontSizeScaleFactor has changed by
2958 // at least a factor of two, reflow the text. This avoids reflowing text
2959 // at every tick of a transform animation, but ensures our glyph metrics
2960 // do not get too far out of sync with the final font size on the screen.
2961 if (needNewCanvasTM && mLastContextScale != 0.0f) {
2962 mCanvasTM = nullptr;
2963 // If we are a non-display frame, then we don't want to call
2964 // GetCanvasTM(), since the context scale does not use it.
2965 gfxMatrix newTM =
2966 HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) ? gfxMatrix() : GetCanvasTM();
2967 // Compare the old and new context scales.
2968 float scale = GetContextScale(newTM);
2969 float change = scale / mLastContextScale;
2970 if (change >= 2.0f || change <= 0.5f) {
2971 needNewBounds = true;
2972 needGlyphMetricsUpdate = true;
2976 if (needNewBounds) {
2977 // Ancestor changes can't affect how we render from the perspective of
2978 // any rendering observers that we may have, so we don't need to
2979 // invalidate them. We also don't need to invalidate ourself, since our
2980 // changed ancestor will have invalidated its entire area, which includes
2981 // our area.
2982 ScheduleReflowSVG();
2985 if (needGlyphMetricsUpdate) {
2986 // If we are positioned using percentage values we need to update our
2987 // position whenever our viewport's dimensions change. But only do this if
2988 // we have been reflowed once, otherwise the glyph positioning will be
2989 // wrong. (We need to wait until bidi reordering has been done.)
2990 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
2991 NotifyGlyphMetricsChange(false);
2997 * Gets the offset into a DOM node that the specified caret is positioned at.
2999 static int32_t GetCaretOffset(nsCaret* aCaret) {
3000 RefPtr<Selection> selection = aCaret->GetSelection();
3001 if (!selection) {
3002 return -1;
3005 return selection->AnchorOffset();
3009 * Returns whether the caret should be painted for a given TextRenderedRun
3010 * by checking whether the caret is in the range covered by the rendered run.
3012 * @param aThisRun The TextRenderedRun to be painted.
3013 * @param aCaret The caret.
3015 static bool ShouldPaintCaret(const TextRenderedRun& aThisRun, nsCaret* aCaret) {
3016 int32_t caretOffset = GetCaretOffset(aCaret);
3018 if (caretOffset < 0) {
3019 return false;
3022 return uint32_t(caretOffset) >= aThisRun.mTextFrameContentOffset &&
3023 uint32_t(caretOffset) < aThisRun.mTextFrameContentOffset +
3024 aThisRun.mTextFrameContentLength;
3027 void SVGTextFrame::PaintSVG(gfxContext& aContext, const gfxMatrix& aTransform,
3028 imgDrawingParams& aImgParams) {
3029 DrawTarget& aDrawTarget = *aContext.GetDrawTarget();
3030 nsIFrame* kid = PrincipalChildList().FirstChild();
3031 if (!kid) {
3032 return;
3035 nsPresContext* presContext = PresContext();
3037 gfxMatrix initialMatrix = aContext.CurrentMatrixDouble();
3039 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3040 // If we are in a canvas DrawWindow call that used the
3041 // DRAWWINDOW_DO_NOT_FLUSH flag, then we may still have out
3042 // of date frames. Just don't paint anything if they are
3043 // dirty.
3044 if (presContext->PresShell()->InDrawWindowNotFlushing() &&
3045 IsSubtreeDirty()) {
3046 return;
3048 // Text frames inside <clipPath>, <mask>, etc. will never have had
3049 // ReflowSVG called on them, so call UpdateGlyphPositioning to do this now.
3050 UpdateGlyphPositioning();
3051 } else if (IsSubtreeDirty()) {
3052 // If we are asked to paint before reflow has recomputed mPositions etc.
3053 // directly via PaintSVG, rather than via a display list, then we need
3054 // to bail out here too.
3055 return;
3058 const float epsilon = 0.0001;
3059 if (abs(mLengthAdjustScaleFactor) < epsilon) {
3060 // A zero scale factor can be caused by having forced the text length to
3061 // zero. In this situation there is nothing to show.
3062 return;
3065 if (aTransform.IsSingular()) {
3066 NS_WARNING("Can't render text element!");
3067 return;
3070 gfxMatrix matrixForPaintServers = aTransform * initialMatrix;
3072 // SVG frames' PaintSVG methods paint in CSS px, but normally frames paint in
3073 // dev pixels. Here we multiply a CSS-px-to-dev-pixel factor onto aTransform
3074 // so our non-SVG nsTextFrame children paint correctly.
3075 auto auPerDevPx = presContext->AppUnitsPerDevPixel();
3076 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(auPerDevPx);
3077 gfxMatrix canvasTMForChildren = aTransform;
3078 canvasTMForChildren.PreScale(cssPxPerDevPx, cssPxPerDevPx);
3079 initialMatrix.PreScale(1 / cssPxPerDevPx, 1 / cssPxPerDevPx);
3081 gfxContextMatrixAutoSaveRestore matSR(&aContext);
3082 aContext.NewPath();
3083 aContext.Multiply(canvasTMForChildren);
3084 gfxMatrix currentMatrix = aContext.CurrentMatrixDouble();
3086 RefPtr<nsCaret> caret = presContext->PresShell()->GetCaret();
3087 nsRect caretRect;
3088 nsIFrame* caretFrame = caret->GetPaintGeometry(&caretRect);
3090 gfxContextAutoSaveRestore ctxSR;
3091 TextRenderedRunIterator it(this, TextRenderedRunIterator::eVisibleFrames);
3092 TextRenderedRun run = it.Current();
3094 SVGContextPaint* outerContextPaint =
3095 SVGContextPaint::GetContextPaint(GetContent());
3097 while (run.mFrame) {
3098 nsTextFrame* frame = run.mFrame;
3100 RefPtr<SVGContextPaintImpl> contextPaint = new SVGContextPaintImpl();
3101 DrawMode drawMode = contextPaint->Init(&aDrawTarget, initialMatrix, frame,
3102 outerContextPaint, aImgParams);
3103 if (drawMode & DrawMode::GLYPH_STROKE) {
3104 ctxSR.EnsureSaved(&aContext);
3105 // This may change the gfxContext's transform (for non-scaling stroke),
3106 // in which case this needs to happen before we call SetMatrix() below.
3107 SVGUtils::SetupStrokeGeometry(frame->GetParent(), &aContext,
3108 outerContextPaint);
3111 nscoord startEdge, endEdge;
3112 run.GetClipEdges(startEdge, endEdge);
3114 // Set up the transform for painting the text frame for the substring
3115 // indicated by the run.
3116 gfxMatrix runTransform = run.GetTransformFromUserSpaceForPainting(
3117 presContext, startEdge, endEdge) *
3118 currentMatrix;
3119 aContext.SetMatrixDouble(runTransform);
3121 if (drawMode != DrawMode(0)) {
3122 bool paintSVGGlyphs;
3123 nsTextFrame::PaintTextParams params(&aContext);
3124 params.framePt = Point();
3125 params.dirtyRect =
3126 LayoutDevicePixel::FromAppUnits(frame->InkOverflowRect(), auPerDevPx);
3127 params.contextPaint = contextPaint;
3128 bool isSelected;
3129 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
3130 params.state = nsTextFrame::PaintTextParams::GenerateTextMask;
3131 isSelected = false;
3132 } else {
3133 isSelected = frame->IsSelected();
3135 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&aContext);
3136 float opacity = 1.0f;
3137 nsIFrame* ancestor = frame->GetParent();
3138 while (ancestor != this) {
3139 opacity *= ancestor->StyleEffects()->mOpacity;
3140 ancestor = ancestor->GetParent();
3142 if (opacity < 1.0f) {
3143 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA,
3144 opacity);
3147 if (ShouldRenderAsPath(frame, paintSVGGlyphs)) {
3148 SVGTextDrawPathCallbacks callbacks(this, aContext, frame,
3149 matrixForPaintServers, aImgParams,
3150 paintSVGGlyphs);
3151 params.callbacks = &callbacks;
3152 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3153 } else {
3154 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3158 if (frame == caretFrame && ShouldPaintCaret(run, caret)) {
3159 // XXX Should we be looking at the fill/stroke colours to paint the
3160 // caret with, rather than using the color property?
3161 caret->PaintCaret(aDrawTarget, frame, nsPoint());
3162 aContext.NewPath();
3165 run = it.Next();
3169 nsIFrame* SVGTextFrame::GetFrameForPoint(const gfxPoint& aPoint) {
3170 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3172 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3173 // Text frames inside <clipPath> will never have had ReflowSVG called on
3174 // them, so call UpdateGlyphPositioning to do this now. (Text frames
3175 // inside <mask> and other non-display containers will never need to
3176 // be hit tested.)
3177 UpdateGlyphPositioning();
3178 } else {
3179 NS_ASSERTION(!IsSubtreeDirty(), "reflow should have happened");
3182 // Hit-testing any clip-path will typically be a lot quicker than the
3183 // hit-testing of our text frames in the loop below, so we do the former up
3184 // front to avoid unnecessarily wasting cycles on the latter.
3185 if (!SVGUtils::HitTestClip(this, aPoint)) {
3186 return nullptr;
3189 nsPresContext* presContext = PresContext();
3191 // Ideally we'd iterate backwards so that we can just return the first frame
3192 // that is under aPoint. In practice this will rarely matter though since it
3193 // is rare for text in/under an SVG <text> element to overlap (i.e. the first
3194 // text frame that is hit will likely be the only text frame that is hit).
3196 TextRenderedRunIterator it(this);
3197 nsIFrame* hit = nullptr;
3198 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3199 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3200 if (!hitTestFlags) {
3201 continue;
3204 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
3205 if (!m.Invert()) {
3206 return nullptr;
3209 gfxPoint pointInRunUserSpace = m.TransformPoint(aPoint);
3210 gfxRect frameRect = run.GetRunUserSpaceRect(
3211 presContext, TextRenderedRun::eIncludeFill |
3212 TextRenderedRun::eIncludeStroke)
3213 .ToThebesRect();
3215 if (Inside(frameRect, pointInRunUserSpace)) {
3216 hit = run.mFrame;
3219 return hit;
3222 void SVGTextFrame::ReflowSVG() {
3223 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
3224 "This call is probaby a wasteful mistake");
3226 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),
3227 "ReflowSVG mechanism not designed for this");
3229 if (!SVGUtils::NeedsReflowSVG(this)) {
3230 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |
3231 NS_STATE_SVG_POSITIONING_DIRTY),
3232 "How did this happen?");
3233 return;
3236 MaybeReflowAnonymousBlockChild();
3237 UpdateGlyphPositioning();
3239 nsPresContext* presContext = PresContext();
3241 SVGBBox r;
3242 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames);
3243 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3244 uint32_t runFlags = 0;
3245 if (!run.mFrame->StyleSVG()->mFill.kind.IsNone()) {
3246 runFlags |= TextRenderedRun::eIncludeFill;
3248 if (SVGUtils::HasStroke(run.mFrame)) {
3249 runFlags |= TextRenderedRun::eIncludeStroke;
3251 // Our "visual" overflow rect needs to be valid for building display lists
3252 // for hit testing, which means that for certain values of 'pointer-events'
3253 // it needs to include the geometry of the fill or stroke even when the
3254 // fill/ stroke don't actually render (e.g. when stroke="none" or
3255 // stroke-opacity="0"). GetGeometryHitTestFlags accounts for
3256 // 'pointer-events'. The text-shadow is not part of the hit-test area.
3257 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3258 if (hitTestFlags & SVG_HIT_TEST_FILL) {
3259 runFlags |= TextRenderedRun::eIncludeFill;
3261 if (hitTestFlags & SVG_HIT_TEST_STROKE) {
3262 runFlags |= TextRenderedRun::eIncludeStroke;
3265 if (runFlags) {
3266 r.UnionEdges(run.GetUserSpaceRect(presContext, runFlags));
3270 if (r.IsEmpty()) {
3271 mRect.SetEmpty();
3272 } else {
3273 mRect = nsLayoutUtils::RoundGfxRectToAppRect(r.ToThebesRect(),
3274 AppUnitsPerCSSPixel());
3276 // Due to rounding issues when we have a transform applied, we sometimes
3277 // don't include an additional row of pixels. For now, just inflate our
3278 // covered region.
3279 mRect.Inflate(ceil(presContext->AppUnitsPerDevPixel() / mLastContextScale));
3282 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
3283 // Make sure we have our filter property (if any) before calling
3284 // FinishAndStoreOverflow (subsequent filter changes are handled off
3285 // nsChangeHint_UpdateEffects):
3286 SVGObserverUtils::UpdateEffects(this);
3289 // Now unset the various reflow bits. Do this before calling
3290 // FinishAndStoreOverflow since FinishAndStoreOverflow can require glyph
3291 // positions (to resolve transform-origin).
3292 RemoveStateBits(NS_FRAME_FIRST_REFLOW | NS_FRAME_IS_DIRTY |
3293 NS_FRAME_HAS_DIRTY_CHILDREN);
3295 nsRect overflow = nsRect(nsPoint(0, 0), mRect.Size());
3296 OverflowAreas overflowAreas(overflow, overflow);
3297 FinishAndStoreOverflow(overflowAreas, mRect.Size());
3301 * Converts SVGUtils::eBBox* flags into TextRenderedRun flags appropriate
3302 * for the specified rendered run.
3304 static uint32_t TextRenderedRunFlagsForBBoxContribution(
3305 const TextRenderedRun& aRun, uint32_t aBBoxFlags) {
3306 uint32_t flags = 0;
3307 if ((aBBoxFlags & SVGUtils::eBBoxIncludeFillGeometry) ||
3308 ((aBBoxFlags & SVGUtils::eBBoxIncludeFill) &&
3309 !aRun.mFrame->StyleSVG()->mFill.kind.IsNone())) {
3310 flags |= TextRenderedRun::eIncludeFill;
3312 if ((aBBoxFlags & SVGUtils::eBBoxIncludeStrokeGeometry) ||
3313 ((aBBoxFlags & SVGUtils::eBBoxIncludeStroke) &&
3314 SVGUtils::HasStroke(aRun.mFrame))) {
3315 flags |= TextRenderedRun::eIncludeStroke;
3317 return flags;
3320 SVGBBox SVGTextFrame::GetBBoxContribution(const Matrix& aToBBoxUserspace,
3321 uint32_t aFlags) {
3322 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3323 SVGBBox bbox;
3325 if (aFlags & SVGUtils::eForGetClientRects) {
3326 Rect rect = NSRectToRect(mRect, AppUnitsPerCSSPixel());
3327 if (!rect.IsEmpty()) {
3328 bbox = aToBBoxUserspace.TransformBounds(rect);
3330 return bbox;
3333 nsIFrame* kid = PrincipalChildList().FirstChild();
3334 if (kid && kid->IsSubtreeDirty()) {
3335 // Return an empty bbox if our kid's subtree is dirty. This may be called
3336 // in that situation, e.g. when we're building a display list after an
3337 // interrupted reflow. This can also be called during reflow before we've
3338 // been reflowed, e.g. if an earlier sibling is calling
3339 // FinishAndStoreOverflow and needs our parent's perspective matrix, which
3340 // depends on the SVG bbox contribution of this frame. In the latter
3341 // situation, when all siblings have been reflowed, the parent will compute
3342 // its perspective and rerun FinishAndStoreOverflow for all its children.
3343 return bbox;
3346 UpdateGlyphPositioning();
3348 nsPresContext* presContext = PresContext();
3350 TextRenderedRunIterator it(this);
3351 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3352 uint32_t flags = TextRenderedRunFlagsForBBoxContribution(run, aFlags);
3353 gfxMatrix m = ThebesMatrix(aToBBoxUserspace);
3354 SVGBBox bboxForRun = run.GetUserSpaceRect(presContext, flags, &m);
3355 bbox.UnionEdges(bboxForRun);
3358 return bbox;
3361 //----------------------------------------------------------------------
3362 // SVGTextFrame SVG DOM methods
3365 * Returns whether the specified node has any non-empty Text
3366 * beneath it.
3368 static bool HasTextContent(nsIContent* aContent) {
3369 NS_ASSERTION(aContent, "expected non-null aContent");
3371 TextNodeIterator it(aContent);
3372 for (Text* text = it.Current(); text; text = it.Next()) {
3373 if (text->TextLength() != 0) {
3374 return true;
3377 return false;
3381 * Returns the number of DOM characters beneath the specified node.
3383 static uint32_t GetTextContentLength(nsIContent* aContent) {
3384 NS_ASSERTION(aContent, "expected non-null aContent");
3386 uint32_t length = 0;
3387 TextNodeIterator it(aContent);
3388 for (Text* text = it.Current(); text; text = it.Next()) {
3389 length += text->TextLength();
3391 return length;
3394 int32_t SVGTextFrame::ConvertTextElementCharIndexToAddressableIndex(
3395 int32_t aIndex, nsIContent* aContent) {
3396 CharIterator it(this, CharIterator::eOriginal, aContent);
3397 if (!it.AdvanceToSubtree()) {
3398 return -1;
3400 int32_t result = 0;
3401 int32_t textElementCharIndex;
3402 while (!it.AtEnd() && it.IsWithinSubtree()) {
3403 bool addressable = !it.IsOriginalCharUnaddressable();
3404 textElementCharIndex = it.TextElementCharIndex();
3405 it.Next();
3406 uint32_t delta = it.TextElementCharIndex() - textElementCharIndex;
3407 aIndex -= delta;
3408 if (addressable) {
3409 if (aIndex < 0) {
3410 return result;
3412 result += delta;
3415 return -1;
3419 * Implements the SVG DOM GetNumberOfChars method for the specified
3420 * text content element.
3422 uint32_t SVGTextFrame::GetNumberOfChars(nsIContent* aContent) {
3423 nsIFrame* kid = PrincipalChildList().FirstChild();
3424 if (kid->IsSubtreeDirty()) {
3425 // We're never reflowed if we're under a non-SVG element that is
3426 // never reflowed (such as the HTML 'caption' element).
3427 return 0;
3430 UpdateGlyphPositioning();
3432 uint32_t n = 0;
3433 CharIterator it(this, CharIterator::eAddressable, aContent);
3434 if (it.AdvanceToSubtree()) {
3435 while (!it.AtEnd() && it.IsWithinSubtree()) {
3436 n++;
3437 it.Next();
3440 return n;
3444 * Implements the SVG DOM GetComputedTextLength method for the specified
3445 * text child element.
3447 float SVGTextFrame::GetComputedTextLength(nsIContent* aContent) {
3448 nsIFrame* kid = PrincipalChildList().FirstChild();
3449 if (kid->IsSubtreeDirty()) {
3450 // We're never reflowed if we're under a non-SVG element that is
3451 // never reflowed (such as the HTML 'caption' element).
3453 // If we ever decide that we need to return accurate values here,
3454 // we could do similar work to GetSubStringLength.
3455 return 0;
3458 UpdateGlyphPositioning();
3460 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3461 PresContext()->AppUnitsPerDevPixel());
3463 nscoord length = 0;
3464 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3465 aContent);
3466 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3467 length += run.GetAdvanceWidth();
3470 return PresContext()->AppUnitsToGfxUnits(length) * cssPxPerDevPx *
3471 mLengthAdjustScaleFactor / mFontSizeScaleFactor;
3475 * Implements the SVG DOM SelectSubString method for the specified
3476 * text content element.
3478 void SVGTextFrame::SelectSubString(nsIContent* aContent, uint32_t charnum,
3479 uint32_t nchars, ErrorResult& aRv) {
3480 nsIFrame* kid = PrincipalChildList().FirstChild();
3481 if (kid->IsSubtreeDirty()) {
3482 // We're never reflowed if we're under a non-SVG element that is
3483 // never reflowed (such as the HTML 'caption' element).
3484 // XXXbz Should this just return without throwing like the no-frame case?
3485 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3486 return;
3489 UpdateGlyphPositioning();
3491 // Convert charnum/nchars from addressable characters relative to
3492 // aContent to global character indices.
3493 CharIterator chit(this, CharIterator::eAddressable, aContent);
3494 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3495 chit.IsAfterSubtree()) {
3496 aRv.ThrowIndexSizeError("Character index out of range");
3497 return;
3499 charnum = chit.TextElementCharIndex();
3500 const RefPtr<nsIContent> content = chit.TextFrame()->GetContent();
3501 chit.NextWithinSubtree(nchars);
3502 nchars = chit.TextElementCharIndex() - charnum;
3504 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
3506 frameSelection->HandleClick(content, charnum, charnum + nchars,
3507 nsFrameSelection::FocusMode::kCollapseToNewPoint,
3508 CARET_ASSOCIATE_BEFORE);
3512 * For some content we cannot (or currently cannot) compute the length
3513 * without reflowing. In those cases we need to fall back to using
3514 * GetSubStringLengthSlowFallback.
3516 * We fall back for textPath since we need glyph positioning in order to
3517 * tell if any characters should be ignored due to having fallen off the
3518 * end of the textPath.
3520 * We fall back for bidi because GetTrimmedOffsets does not produce the
3521 * correct results for bidi continuations when passed aPostReflow = false.
3522 * XXX It may be possible to determine which continuations to trim from (and
3523 * which sides), but currently we don't do that. It would require us to
3524 * identify the visual (rather than logical) start and end of the line, to
3525 * avoid trimming at line-internal frame boundaries. Maybe nsBidiPresUtils
3526 * methods like GetFrameToRightOf and GetFrameToLeftOf would help?
3529 bool SVGTextFrame::RequiresSlowFallbackForSubStringLength() {
3530 TextFrameIterator frameIter(this);
3531 for (nsTextFrame* frame = frameIter.Current(); frame;
3532 frame = frameIter.Next()) {
3533 if (frameIter.TextPathFrame() || frame->GetNextContinuation()) {
3534 return true;
3537 return false;
3541 * Implements the SVG DOM GetSubStringLength method for the specified
3542 * text content element.
3544 float SVGTextFrame::GetSubStringLengthFastPath(nsIContent* aContent,
3545 uint32_t charnum,
3546 uint32_t nchars,
3547 ErrorResult& aRv) {
3548 MOZ_ASSERT(!RequiresSlowFallbackForSubStringLength());
3550 // We only need our text correspondence to be up to date (no need to call
3551 // UpdateGlyphPositioning).
3552 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
3554 // Convert charnum/nchars from addressable characters relative to
3555 // aContent to global character indices.
3556 CharIterator chit(this, CharIterator::eAddressable, aContent,
3557 /* aPostReflow */ false);
3558 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3559 chit.IsAfterSubtree()) {
3560 aRv.ThrowIndexSizeError("Character index out of range");
3561 return 0;
3564 // We do this after the ThrowIndexSizeError() bit so JS calls correctly throw
3565 // when necessary.
3566 if (nchars == 0) {
3567 return 0.0f;
3570 charnum = chit.TextElementCharIndex();
3571 chit.NextWithinSubtree(nchars);
3572 nchars = chit.TextElementCharIndex() - charnum;
3574 // Sum of the substring advances.
3575 nscoord textLength = 0;
3577 TextFrameIterator frit(this); // aSubtree = nullptr
3579 // Index of the first non-skipped char in the frame, and of a subsequent char
3580 // that we're interested in. Both are relative to the index of the first
3581 // non-skipped char in the ancestor <text> element.
3582 uint32_t frameStartTextElementCharIndex = 0;
3583 uint32_t textElementCharIndex;
3585 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
3586 frameStartTextElementCharIndex += frit.UndisplayedCharacters();
3587 textElementCharIndex = frameStartTextElementCharIndex;
3589 // Offset into frame's Text:
3590 const uint32_t untrimmedOffset = frame->GetContentOffset();
3591 const uint32_t untrimmedLength = frame->GetContentEnd() - untrimmedOffset;
3593 // Trim the offset/length to remove any leading/trailing white space.
3594 uint32_t trimmedOffset = untrimmedOffset;
3595 uint32_t trimmedLength = untrimmedLength;
3596 nsTextFrame::TrimmedOffsets trimmedOffsets = frame->GetTrimmedOffsets(
3597 frame->TextFragment(), nsTextFrame::TrimmedOffsetFlags::NotPostReflow);
3598 TrimOffsets(trimmedOffset, trimmedLength, trimmedOffsets);
3600 textElementCharIndex += trimmedOffset - untrimmedOffset;
3602 if (textElementCharIndex >= charnum + nchars) {
3603 break; // we're past the end of the substring
3606 uint32_t offset = textElementCharIndex;
3608 // Intersect the substring we are interested in with the range covered by
3609 // the nsTextFrame.
3610 IntersectInterval(offset, trimmedLength, charnum, nchars);
3612 if (trimmedLength != 0) {
3613 // Convert offset into an index into the frame.
3614 offset += trimmedOffset - textElementCharIndex;
3616 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
3617 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
3618 nsTextFrame::PropertyProvider provider(frame, it);
3620 Range range = ConvertOriginalToSkipped(it, offset, trimmedLength);
3622 // Accumulate the advance.
3623 textLength += textRun->GetAdvanceWidth(range, &provider);
3626 // Advance, ready for next call:
3627 frameStartTextElementCharIndex += untrimmedLength;
3630 nsPresContext* presContext = PresContext();
3631 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3632 presContext->AppUnitsPerDevPixel());
3634 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3635 mFontSizeScaleFactor;
3638 float SVGTextFrame::GetSubStringLengthSlowFallback(nsIContent* aContent,
3639 uint32_t charnum,
3640 uint32_t nchars,
3641 ErrorResult& aRv) {
3642 UpdateGlyphPositioning();
3644 // Convert charnum/nchars from addressable characters relative to
3645 // aContent to global character indices.
3646 CharIterator chit(this, CharIterator::eAddressable, aContent);
3647 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3648 chit.IsAfterSubtree()) {
3649 aRv.ThrowIndexSizeError("Character index out of range");
3650 return 0;
3653 if (nchars == 0) {
3654 return 0.0f;
3657 charnum = chit.TextElementCharIndex();
3658 chit.NextWithinSubtree(nchars);
3659 nchars = chit.TextElementCharIndex() - charnum;
3661 // Find each rendered run that intersects with the range defined
3662 // by charnum/nchars.
3663 nscoord textLength = 0;
3664 TextRenderedRunIterator runIter(this, TextRenderedRunIterator::eAllFrames);
3665 TextRenderedRun run = runIter.Current();
3666 while (run.mFrame) {
3667 // If this rendered run is past the substring we are interested in, we
3668 // are done.
3669 uint32_t offset = run.mTextElementCharIndex;
3670 if (offset >= charnum + nchars) {
3671 break;
3674 // Intersect the substring we are interested in with the range covered by
3675 // the rendered run.
3676 uint32_t length = run.mTextFrameContentLength;
3677 IntersectInterval(offset, length, charnum, nchars);
3679 if (length != 0) {
3680 // Convert offset into an index into the frame.
3681 offset += run.mTextFrameContentOffset - run.mTextElementCharIndex;
3683 gfxSkipCharsIterator it =
3684 run.mFrame->EnsureTextRun(nsTextFrame::eInflated);
3685 gfxTextRun* textRun = run.mFrame->GetTextRun(nsTextFrame::eInflated);
3686 nsTextFrame::PropertyProvider provider(run.mFrame, it);
3688 Range range = ConvertOriginalToSkipped(it, offset, length);
3690 // Accumulate the advance.
3691 textLength += textRun->GetAdvanceWidth(range, &provider);
3694 run = runIter.Next();
3697 nsPresContext* presContext = PresContext();
3698 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3699 presContext->AppUnitsPerDevPixel());
3701 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3702 mFontSizeScaleFactor;
3706 * Implements the SVG DOM GetCharNumAtPosition method for the specified
3707 * text content element.
3709 int32_t SVGTextFrame::GetCharNumAtPosition(nsIContent* aContent,
3710 const DOMPointInit& aPoint) {
3711 nsIFrame* kid = PrincipalChildList().FirstChild();
3712 if (kid->IsSubtreeDirty()) {
3713 // We're never reflowed if we're under a non-SVG element that is
3714 // never reflowed (such as the HTML 'caption' element).
3715 return -1;
3718 UpdateGlyphPositioning();
3720 nsPresContext* context = PresContext();
3722 gfxPoint p(aPoint.mX, aPoint.mY);
3724 int32_t result = -1;
3726 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3727 aContent);
3728 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3729 // Hit test this rendered run. Later runs will override earlier ones.
3730 int32_t index = run.GetCharNumAtPosition(context, p);
3731 if (index != -1) {
3732 result = index + run.mTextElementCharIndex;
3736 if (result == -1) {
3737 return result;
3740 return ConvertTextElementCharIndexToAddressableIndex(result, aContent);
3744 * Implements the SVG DOM GetStartPositionOfChar method for the specified
3745 * text content element.
3747 already_AddRefed<DOMSVGPoint> SVGTextFrame::GetStartPositionOfChar(
3748 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3749 nsIFrame* kid = PrincipalChildList().FirstChild();
3750 if (kid->IsSubtreeDirty()) {
3751 // We're never reflowed if we're under a non-SVG element that is
3752 // never reflowed (such as the HTML 'caption' element).
3753 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3754 return nullptr;
3757 UpdateGlyphPositioning();
3759 CharIterator it(this, CharIterator::eAddressable, aContent);
3760 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3761 aRv.ThrowIndexSizeError("Character index out of range");
3762 return nullptr;
3765 // We need to return the start position of the whole glyph.
3766 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3768 RefPtr<DOMSVGPoint> point =
3769 new DOMSVGPoint(ToPoint(mPositions[startIndex].mPosition));
3770 return point.forget();
3774 * Returns the advance of the entire glyph whose starting character is at
3775 * aTextElementCharIndex.
3777 * aIterator, if provided, must be a CharIterator that already points to
3778 * aTextElementCharIndex that is restricted to aContent and is using
3779 * filter mode eAddressable.
3781 static gfxFloat GetGlyphAdvance(SVGTextFrame* aFrame, nsIContent* aContent,
3782 uint32_t aTextElementCharIndex,
3783 CharIterator* aIterator) {
3784 MOZ_ASSERT(!aIterator || (aIterator->Filter() == CharIterator::eAddressable &&
3785 aIterator->GetSubtree() == aContent &&
3786 aIterator->GlyphStartTextElementCharIndex() ==
3787 aTextElementCharIndex),
3788 "Invalid aIterator");
3790 Maybe<CharIterator> newIterator;
3791 CharIterator* it = aIterator;
3792 if (!it) {
3793 newIterator.emplace(aFrame, CharIterator::eAddressable, aContent);
3794 if (!newIterator->AdvanceToSubtree()) {
3795 MOZ_ASSERT_UNREACHABLE("Invalid aContent");
3796 return 0.0;
3798 it = newIterator.ptr();
3801 while (it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3802 if (!it->Next()) {
3803 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3804 return 0.0;
3808 if (it->AtEnd()) {
3809 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3810 return 0.0;
3813 nsPresContext* presContext = aFrame->PresContext();
3814 gfxFloat advance = 0.0;
3816 for (;;) {
3817 advance += it->GetAdvance(presContext);
3818 if (!it->Next() ||
3819 it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3820 break;
3824 return advance;
3828 * Implements the SVG DOM GetEndPositionOfChar method for the specified
3829 * text content element.
3831 already_AddRefed<DOMSVGPoint> SVGTextFrame::GetEndPositionOfChar(
3832 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3833 nsIFrame* kid = PrincipalChildList().FirstChild();
3834 if (kid->IsSubtreeDirty()) {
3835 // We're never reflowed if we're under a non-SVG element that is
3836 // never reflowed (such as the HTML 'caption' element).
3837 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3838 return nullptr;
3841 UpdateGlyphPositioning();
3843 CharIterator it(this, CharIterator::eAddressable, aContent);
3844 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3845 aRv.ThrowIndexSizeError("Character index out of range");
3846 return nullptr;
3849 // We need to return the end position of the whole glyph.
3850 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3852 // Get the advance of the glyph.
3853 gfxFloat advance =
3854 GetGlyphAdvance(this, aContent, startIndex,
3855 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3856 if (it.TextRun()->IsRightToLeft()) {
3857 advance = -advance;
3860 // The end position is the start position plus the advance in the direction
3861 // of the glyph's rotation.
3862 Matrix m = Matrix::Rotation(mPositions[startIndex].mAngle) *
3863 Matrix::Translation(ToPoint(mPositions[startIndex].mPosition));
3864 Point p = m.TransformPoint(Point(advance / mFontSizeScaleFactor, 0));
3866 RefPtr<DOMSVGPoint> point = new DOMSVGPoint(p);
3867 return point.forget();
3871 * Implements the SVG DOM GetExtentOfChar method for the specified
3872 * text content element.
3874 already_AddRefed<SVGRect> SVGTextFrame::GetExtentOfChar(nsIContent* aContent,
3875 uint32_t aCharNum,
3876 ErrorResult& aRv) {
3877 nsIFrame* kid = PrincipalChildList().FirstChild();
3878 if (kid->IsSubtreeDirty()) {
3879 // We're never reflowed if we're under a non-SVG element that is
3880 // never reflowed (such as the HTML 'caption' element).
3881 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3882 return nullptr;
3885 UpdateGlyphPositioning();
3887 // Search for the character whose addressable index is aCharNum.
3888 CharIterator it(this, CharIterator::eAddressable, aContent);
3889 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3890 aRv.ThrowIndexSizeError("Character index out of range");
3891 return nullptr;
3894 nsPresContext* presContext = PresContext();
3895 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3896 presContext->AppUnitsPerDevPixel());
3898 nsTextFrame* textFrame = it.TextFrame();
3899 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3900 bool isRTL = it.TextRun()->IsRightToLeft();
3901 bool isVertical = it.TextRun()->IsVertical();
3903 // Get the glyph advance.
3904 gfxFloat advance =
3905 GetGlyphAdvance(this, aContent, startIndex,
3906 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3907 gfxFloat x = isRTL ? -advance : 0.0;
3909 // The ascent and descent gives the height of the glyph.
3910 gfxFloat ascent, descent;
3911 GetAscentAndDescentInAppUnits(textFrame, ascent, descent);
3913 // The horizontal extent is the origin of the glyph plus the advance
3914 // in the direction of the glyph's rotation.
3915 gfxMatrix m;
3916 m.PreTranslate(mPositions[startIndex].mPosition);
3917 m.PreRotate(mPositions[startIndex].mAngle);
3918 m.PreScale(1 / mFontSizeScaleFactor, 1 / mFontSizeScaleFactor);
3920 gfxRect glyphRect;
3921 if (isVertical) {
3922 glyphRect = gfxRect(
3923 -presContext->AppUnitsToGfxUnits(descent) * cssPxPerDevPx, x,
3924 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx,
3925 advance);
3926 } else {
3927 glyphRect = gfxRect(
3928 x, -presContext->AppUnitsToGfxUnits(ascent) * cssPxPerDevPx, advance,
3929 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx);
3932 // Transform the glyph's rect into user space.
3933 gfxRect r = m.TransformBounds(glyphRect);
3935 RefPtr<SVGRect> rect = new SVGRect(aContent, ToRect(r));
3936 return rect.forget();
3940 * Implements the SVG DOM GetRotationOfChar method for the specified
3941 * text content element.
3943 float SVGTextFrame::GetRotationOfChar(nsIContent* aContent, uint32_t aCharNum,
3944 ErrorResult& aRv) {
3945 nsIFrame* kid = PrincipalChildList().FirstChild();
3946 if (kid->IsSubtreeDirty()) {
3947 // We're never reflowed if we're under a non-SVG element that is
3948 // never reflowed (such as the HTML 'caption' element).
3949 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3950 return 0;
3953 UpdateGlyphPositioning();
3955 CharIterator it(this, CharIterator::eAddressable, aContent);
3956 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3957 aRv.ThrowIndexSizeError("Character index out of range");
3958 return 0;
3961 // we need to account for the glyph's underlying orientation
3962 const gfxTextRun::GlyphRun& glyphRun = it.GlyphRun();
3963 int32_t glyphOrientation =
3964 90 * (glyphRun.IsSidewaysRight() - glyphRun.IsSidewaysLeft());
3966 return mPositions[it.TextElementCharIndex()].mAngle * 180.0 / M_PI +
3967 glyphOrientation;
3970 //----------------------------------------------------------------------
3971 // SVGTextFrame text layout methods
3974 * Given the character position array before values have been filled in
3975 * to any unspecified positions, and an array of dx/dy values, returns whether
3976 * a character at a given index should start a new rendered run.
3978 * @param aPositions The array of character positions before unspecified
3979 * positions have been filled in and dx/dy values have been added to them.
3980 * @param aDeltas The array of dx/dy values.
3981 * @param aIndex The character index in question.
3983 static bool ShouldStartRunAtIndex(const nsTArray<CharPosition>& aPositions,
3984 const nsTArray<gfxPoint>& aDeltas,
3985 uint32_t aIndex) {
3986 if (aIndex == 0) {
3987 return true;
3990 if (aIndex < aPositions.Length()) {
3991 // If an explicit x or y value was given, start a new run.
3992 if (aPositions[aIndex].IsXSpecified() ||
3993 aPositions[aIndex].IsYSpecified()) {
3994 return true;
3997 // If a non-zero rotation was given, or the previous character had a non-
3998 // zero rotation, start a new run.
3999 if ((aPositions[aIndex].IsAngleSpecified() &&
4000 aPositions[aIndex].mAngle != 0.0f) ||
4001 (aPositions[aIndex - 1].IsAngleSpecified() &&
4002 (aPositions[aIndex - 1].mAngle != 0.0f))) {
4003 return true;
4007 if (aIndex < aDeltas.Length()) {
4008 // If a non-zero dx or dy value was given, start a new run.
4009 if (aDeltas[aIndex].x != 0.0 || aDeltas[aIndex].y != 0.0) {
4010 return true;
4014 return false;
4017 bool SVGTextFrame::ResolvePositionsForNode(nsIContent* aContent,
4018 uint32_t& aIndex, bool aInTextPath,
4019 bool& aForceStartOfChunk,
4020 nsTArray<gfxPoint>& aDeltas) {
4021 if (aContent->IsText()) {
4022 // We found a text node.
4023 uint32_t length = aContent->AsText()->TextLength();
4024 if (length) {
4025 uint32_t end = aIndex + length;
4026 if (MOZ_UNLIKELY(end > mPositions.Length())) {
4027 MOZ_ASSERT_UNREACHABLE(
4028 "length of mPositions does not match characters "
4029 "found by iterating content");
4030 return false;
4032 if (aForceStartOfChunk) {
4033 // Note this character as starting a new anchored chunk.
4034 mPositions[aIndex].mStartOfChunk = true;
4035 aForceStartOfChunk = false;
4037 while (aIndex < end) {
4038 // Record whether each of these characters should start a new rendered
4039 // run. That is always the case for characters on a text path.
4041 // Run boundaries due to rotate="" values are handled in
4042 // DoGlyphPositioning.
4043 if (aInTextPath || ShouldStartRunAtIndex(mPositions, aDeltas, aIndex)) {
4044 mPositions[aIndex].mRunBoundary = true;
4046 aIndex++;
4049 return true;
4052 // Skip past elements that aren't text content elements.
4053 if (!IsTextContentElement(aContent)) {
4054 return true;
4057 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4058 // Any ‘y’ attributes on horizontal <textPath> elements are ignored.
4059 // Similarly, for vertical <texPath>s x attributes are ignored.
4060 // <textPath> elements behave as if they have x="0" y="0" on them, but only
4061 // if there is not a value for the non-ignored coordinate that got inherited
4062 // from a parent. We skip this if there is no text content, so that empty
4063 // <textPath>s don't interrupt the layout of text in the parent element.
4064 if (HasTextContent(aContent)) {
4065 if (MOZ_UNLIKELY(aIndex >= mPositions.Length())) {
4066 MOZ_ASSERT_UNREACHABLE(
4067 "length of mPositions does not match characters "
4068 "found by iterating content");
4069 return false;
4071 bool vertical = GetWritingMode().IsVertical();
4072 if (vertical || !mPositions[aIndex].IsXSpecified()) {
4073 mPositions[aIndex].mPosition.x = 0.0;
4075 if (!vertical || !mPositions[aIndex].IsYSpecified()) {
4076 mPositions[aIndex].mPosition.y = 0.0;
4078 mPositions[aIndex].mStartOfChunk = true;
4080 } else if (!aContent->IsSVGElement(nsGkAtoms::a)) {
4081 MOZ_ASSERT(aContent->IsSVGElement());
4083 // We have a text content element that can have x/y/dx/dy/rotate attributes.
4084 SVGElement* element = static_cast<SVGElement*>(aContent);
4086 // Get x, y, dx, dy.
4087 SVGUserUnitList x, y, dx, dy;
4088 element->GetAnimatedLengthListValues(&x, &y, &dx, &dy, nullptr);
4090 // Get rotate.
4091 const SVGNumberList* rotate = nullptr;
4092 SVGAnimatedNumberList* animatedRotate =
4093 element->GetAnimatedNumberList(nsGkAtoms::rotate);
4094 if (animatedRotate) {
4095 rotate = &animatedRotate->GetAnimValue();
4098 bool percentages = false;
4099 uint32_t count = GetTextContentLength(aContent);
4101 if (MOZ_UNLIKELY(aIndex + count > mPositions.Length())) {
4102 MOZ_ASSERT_UNREACHABLE(
4103 "length of mPositions does not match characters "
4104 "found by iterating content");
4105 return false;
4108 // New text anchoring chunks start at each character assigned a position
4109 // with x="" or y="", or if we forced one with aForceStartOfChunk due to
4110 // being just after a <textPath>.
4111 uint32_t newChunkCount = std::max(x.Length(), y.Length());
4112 if (!newChunkCount && aForceStartOfChunk) {
4113 newChunkCount = 1;
4115 for (uint32_t i = 0, j = 0; i < newChunkCount && j < count; j++) {
4116 if (!mPositions[aIndex + j].mUnaddressable) {
4117 mPositions[aIndex + j].mStartOfChunk = true;
4118 i++;
4122 // Copy dx="" and dy="" values into aDeltas.
4123 if (!dx.IsEmpty() || !dy.IsEmpty()) {
4124 // Any unspecified deltas when we grow the array just get left as 0s.
4125 aDeltas.EnsureLengthAtLeast(aIndex + count);
4126 for (uint32_t i = 0, j = 0; i < dx.Length() && j < count; j++) {
4127 if (!mPositions[aIndex + j].mUnaddressable) {
4128 aDeltas[aIndex + j].x = dx[i];
4129 percentages = percentages || dx.HasPercentageValueAt(i);
4130 i++;
4133 for (uint32_t i = 0, j = 0; i < dy.Length() && j < count; j++) {
4134 if (!mPositions[aIndex + j].mUnaddressable) {
4135 aDeltas[aIndex + j].y = dy[i];
4136 percentages = percentages || dy.HasPercentageValueAt(i);
4137 i++;
4142 // Copy x="" and y="" values.
4143 for (uint32_t i = 0, j = 0; i < x.Length() && j < count; j++) {
4144 if (!mPositions[aIndex + j].mUnaddressable) {
4145 mPositions[aIndex + j].mPosition.x = x[i];
4146 percentages = percentages || x.HasPercentageValueAt(i);
4147 i++;
4150 for (uint32_t i = 0, j = 0; i < y.Length() && j < count; j++) {
4151 if (!mPositions[aIndex + j].mUnaddressable) {
4152 mPositions[aIndex + j].mPosition.y = y[i];
4153 percentages = percentages || y.HasPercentageValueAt(i);
4154 i++;
4158 // Copy rotate="" values.
4159 if (rotate && !rotate->IsEmpty()) {
4160 uint32_t i = 0, j = 0;
4161 while (i < rotate->Length() && j < count) {
4162 if (!mPositions[aIndex + j].mUnaddressable) {
4163 mPositions[aIndex + j].mAngle = M_PI * (*rotate)[i] / 180.0;
4164 i++;
4166 j++;
4168 // Propagate final rotate="" value to the end of this element.
4169 while (j < count) {
4170 mPositions[aIndex + j].mAngle = mPositions[aIndex + j - 1].mAngle;
4171 j++;
4175 if (percentages) {
4176 AddStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4180 // Recurse to children.
4181 bool inTextPath = aInTextPath || aContent->IsSVGElement(nsGkAtoms::textPath);
4182 for (nsIContent* child = aContent->GetFirstChild(); child;
4183 child = child->GetNextSibling()) {
4184 bool ok = ResolvePositionsForNode(child, aIndex, inTextPath,
4185 aForceStartOfChunk, aDeltas);
4186 if (!ok) {
4187 return false;
4191 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4192 // Force a new anchored chunk just after a <textPath>.
4193 aForceStartOfChunk = true;
4196 return true;
4199 bool SVGTextFrame::ResolvePositions(nsTArray<gfxPoint>& aDeltas,
4200 bool aRunPerGlyph) {
4201 NS_ASSERTION(mPositions.IsEmpty(), "expected mPositions to be empty");
4202 RemoveStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4204 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4205 if (it.AtEnd()) {
4206 return false;
4209 // We assume the first character position is (0,0) unless we later see
4210 // otherwise, and note it as unaddressable if it is.
4211 bool firstCharUnaddressable = it.IsOriginalCharUnaddressable();
4212 mPositions.AppendElement(CharPosition::Unspecified(firstCharUnaddressable));
4214 // Fill in unspecified positions for all remaining characters, noting
4215 // them as unaddressable if they are.
4216 uint32_t index = 0;
4217 while (it.Next()) {
4218 while (++index < it.TextElementCharIndex()) {
4219 mPositions.AppendElement(CharPosition::Unspecified(false));
4221 mPositions.AppendElement(
4222 CharPosition::Unspecified(it.IsOriginalCharUnaddressable()));
4224 while (++index < it.TextElementCharIndex()) {
4225 mPositions.AppendElement(CharPosition::Unspecified(false));
4228 // Recurse over the content and fill in character positions as we go.
4229 bool forceStartOfChunk = false;
4230 index = 0;
4231 bool ok = ResolvePositionsForNode(mContent, index, aRunPerGlyph,
4232 forceStartOfChunk, aDeltas);
4233 return ok && index > 0;
4236 void SVGTextFrame::DetermineCharPositions(nsTArray<nsPoint>& aPositions) {
4237 NS_ASSERTION(aPositions.IsEmpty(), "expected aPositions to be empty");
4239 nsPoint position;
4241 TextFrameIterator frit(this);
4242 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
4243 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
4244 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
4245 nsTextFrame::PropertyProvider provider(frame, it);
4247 // Reset the position to the new frame's position.
4248 position = frit.Position();
4249 if (textRun->IsVertical()) {
4250 if (textRun->IsRightToLeft()) {
4251 position.y += frame->GetRect().height;
4253 position.x += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4254 mFontSizeScaleFactor);
4255 } else {
4256 if (textRun->IsRightToLeft()) {
4257 position.x += frame->GetRect().width;
4259 position.y += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4260 mFontSizeScaleFactor);
4263 // Any characters not in a frame, e.g. when display:none.
4264 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4265 aPositions.AppendElement(position);
4268 // Any white space characters trimmed at the start of the line of text.
4269 nsTextFrame::TrimmedOffsets trimmedOffsets =
4270 frame->GetTrimmedOffsets(frame->TextFragment());
4271 while (it.GetOriginalOffset() < trimmedOffsets.mStart) {
4272 aPositions.AppendElement(position);
4273 it.AdvanceOriginal(1);
4276 // Visible characters in the text frame.
4277 while (it.GetOriginalOffset() < frame->GetContentEnd()) {
4278 aPositions.AppendElement(position);
4279 if (!it.IsOriginalCharSkipped()) {
4280 // Accumulate partial ligature advance into position. (We must get
4281 // partial advances rather than get the advance of the whole ligature
4282 // group / cluster at once, since the group may span text frames, and
4283 // the PropertyProvider only has spacing information for the current
4284 // text frame.)
4285 uint32_t offset = it.GetSkippedOffset();
4286 nscoord advance =
4287 textRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
4288 (textRun->IsVertical() ? position.y : position.x) +=
4289 textRun->IsRightToLeft() ? -advance : advance;
4291 it.AdvanceOriginal(1);
4295 // Finally any characters at the end that are not in a frame.
4296 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4297 aPositions.AppendElement(position);
4302 * Physical text-anchor values.
4304 enum TextAnchorSide { eAnchorLeft, eAnchorMiddle, eAnchorRight };
4307 * Converts a logical text-anchor value to its physical value, based on whether
4308 * it is for an RTL frame.
4310 static TextAnchorSide ConvertLogicalTextAnchorToPhysical(
4311 StyleTextAnchor aTextAnchor, bool aIsRightToLeft) {
4312 NS_ASSERTION(uint8_t(aTextAnchor) <= 3, "unexpected value for aTextAnchor");
4313 if (!aIsRightToLeft) {
4314 return TextAnchorSide(uint8_t(aTextAnchor));
4316 return TextAnchorSide(2 - uint8_t(aTextAnchor));
4320 * Shifts the recorded character positions for an anchored chunk.
4322 * @param aCharPositions The recorded character positions.
4323 * @param aChunkStart The character index the starts the anchored chunk. This
4324 * character's initial position is the anchor point.
4325 * @param aChunkEnd The character index just after the end of the anchored
4326 * chunk.
4327 * @param aVisIStartEdge The left/top-most edge of any of the glyphs within the
4328 * anchored chunk.
4329 * @param aVisIEndEdge The right/bottom-most edge of any of the glyphs within
4330 * the anchored chunk.
4331 * @param aAnchorSide The direction to anchor.
4333 static void ShiftAnchoredChunk(nsTArray<CharPosition>& aCharPositions,
4334 uint32_t aChunkStart, uint32_t aChunkEnd,
4335 gfxFloat aVisIStartEdge, gfxFloat aVisIEndEdge,
4336 TextAnchorSide aAnchorSide, bool aVertical) {
4337 NS_ASSERTION(aVisIStartEdge <= aVisIEndEdge,
4338 "unexpected anchored chunk edges");
4339 NS_ASSERTION(aChunkStart < aChunkEnd,
4340 "unexpected values for aChunkStart and aChunkEnd");
4342 gfxFloat shift = aVertical ? aCharPositions[aChunkStart].mPosition.y
4343 : aCharPositions[aChunkStart].mPosition.x;
4344 switch (aAnchorSide) {
4345 case eAnchorLeft:
4346 shift -= aVisIStartEdge;
4347 break;
4348 case eAnchorMiddle:
4349 shift -= (aVisIStartEdge + aVisIEndEdge) / 2;
4350 break;
4351 case eAnchorRight:
4352 shift -= aVisIEndEdge;
4353 break;
4354 default:
4355 MOZ_ASSERT_UNREACHABLE("unexpected value for aAnchorSide");
4358 if (shift != 0.0) {
4359 if (aVertical) {
4360 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4361 aCharPositions[i].mPosition.y += shift;
4363 } else {
4364 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4365 aCharPositions[i].mPosition.x += shift;
4371 void SVGTextFrame::AdjustChunksForLineBreaks() {
4372 nsBlockFrame* block = do_QueryFrame(PrincipalChildList().FirstChild());
4373 NS_ASSERTION(block, "expected block frame");
4375 nsBlockFrame::LineIterator line = block->LinesBegin();
4377 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4378 while (!it.AtEnd() && line != block->LinesEnd()) {
4379 if (it.TextFrame() == line->mFirstChild) {
4380 mPositions[it.TextElementCharIndex()].mStartOfChunk = true;
4381 line++;
4383 it.AdvancePastCurrentFrame();
4387 void SVGTextFrame::AdjustPositionsForClusters() {
4388 nsPresContext* presContext = PresContext();
4390 // Find all of the characters that are in the middle of a cluster or
4391 // ligature group, and adjust their positions and rotations to match
4392 // the first character of the cluster/group.
4394 // Also move the boundaries of text rendered runs and anchored chunks to
4395 // not lie in the middle of cluster/group.
4397 // The partial advance of the current cluster or ligature group that we
4398 // have accumulated.
4399 gfxFloat partialAdvance = 0.0;
4401 CharIterator it(this, CharIterator::eUnskipped, /* aSubtree */ nullptr);
4402 bool isFirst = true;
4403 while (!it.AtEnd()) {
4404 if (it.IsClusterAndLigatureGroupStart() || isFirst) {
4405 // If we're at the start of a new cluster or ligature group, reset our
4406 // accumulated partial advance. Also treat the beginning of the text as
4407 // an anchor, even if it is a combining character and therefore was
4408 // marked as being a Unicode cluster continuation.
4409 partialAdvance = 0.0;
4410 isFirst = false;
4411 } else {
4412 // Otherwise, we're in the middle of a cluster or ligature group, and
4413 // we need to use the currently accumulated partial advance to adjust
4414 // the character's position and rotation.
4416 // Find the start of the cluster/ligature group.
4417 uint32_t charIndex = it.TextElementCharIndex();
4418 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
4419 MOZ_ASSERT(charIndex != startIndex,
4420 "If the current character is in the middle of a cluster or "
4421 "ligature group, then charIndex must be different from "
4422 "startIndex");
4424 mPositions[charIndex].mClusterOrLigatureGroupMiddle = true;
4426 // Don't allow different rotations on ligature parts.
4427 bool rotationAdjusted = false;
4428 double angle = mPositions[startIndex].mAngle;
4429 if (mPositions[charIndex].mAngle != angle) {
4430 mPositions[charIndex].mAngle = angle;
4431 rotationAdjusted = true;
4434 // Update the character position.
4435 gfxFloat advance = partialAdvance / mFontSizeScaleFactor;
4436 gfxPoint direction = gfxPoint(cos(angle), sin(angle)) *
4437 (it.TextRun()->IsRightToLeft() ? -1.0 : 1.0);
4438 if (it.TextRun()->IsVertical()) {
4439 std::swap(direction.x, direction.y);
4441 mPositions[charIndex].mPosition =
4442 mPositions[startIndex].mPosition + direction * advance;
4444 // Ensure any runs that would end in the middle of a ligature now end just
4445 // after the ligature.
4446 if (mPositions[charIndex].mRunBoundary) {
4447 mPositions[charIndex].mRunBoundary = false;
4448 if (charIndex + 1 < mPositions.Length()) {
4449 mPositions[charIndex + 1].mRunBoundary = true;
4451 } else if (rotationAdjusted) {
4452 if (charIndex + 1 < mPositions.Length()) {
4453 mPositions[charIndex + 1].mRunBoundary = true;
4457 // Ensure any anchored chunks that would begin in the middle of a ligature
4458 // now begin just after the ligature.
4459 if (mPositions[charIndex].mStartOfChunk) {
4460 mPositions[charIndex].mStartOfChunk = false;
4461 if (charIndex + 1 < mPositions.Length()) {
4462 mPositions[charIndex + 1].mStartOfChunk = true;
4467 // Accumulate the current character's partial advance.
4468 partialAdvance += it.GetAdvance(presContext);
4470 it.Next();
4474 already_AddRefed<Path> SVGTextFrame::GetTextPath(nsIFrame* aTextPathFrame) {
4475 nsIContent* content = aTextPathFrame->GetContent();
4476 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4477 if (tp->mPath.IsRendered()) {
4478 // This is just an attribute so there's no transform that can apply
4479 // so we can just return the path directly.
4480 return tp->mPath.GetAnimValue().BuildPathForMeasuring();
4483 SVGGeometryElement* geomElement =
4484 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4485 if (!geomElement) {
4486 return nullptr;
4489 RefPtr<Path> path = geomElement->GetOrBuildPathForMeasuring();
4490 if (!path) {
4491 return nullptr;
4494 gfxMatrix matrix = geomElement->PrependLocalTransformsTo(gfxMatrix());
4495 if (!matrix.IsIdentity()) {
4496 // Apply the geometry element's transform
4497 RefPtr<PathBuilder> builder =
4498 path->TransformedCopyToBuilder(ToMatrix(matrix));
4499 path = builder->Finish();
4502 return path.forget();
4505 gfxFloat SVGTextFrame::GetOffsetScale(nsIFrame* aTextPathFrame) {
4506 nsIContent* content = aTextPathFrame->GetContent();
4507 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4508 if (tp->mPath.IsRendered()) {
4509 // A path attribute has no pathLength or transform
4510 // so we return a unit scale.
4511 return 1.0;
4514 SVGGeometryElement* geomElement =
4515 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4516 if (!geomElement) {
4517 return 1.0;
4519 return geomElement->GetPathLengthScale(SVGGeometryElement::eForTextPath);
4522 gfxFloat SVGTextFrame::GetStartOffset(nsIFrame* aTextPathFrame) {
4523 SVGTextPathElement* tp =
4524 static_cast<SVGTextPathElement*>(aTextPathFrame->GetContent());
4525 SVGAnimatedLength* length =
4526 &tp->mLengthAttributes[SVGTextPathElement::STARTOFFSET];
4528 if (length->IsPercentage()) {
4529 if (!std::isfinite(GetOffsetScale(aTextPathFrame))) {
4530 // Either pathLength="0" for this path or the path has 0 length.
4531 return 0.0;
4533 RefPtr<Path> data = GetTextPath(aTextPathFrame);
4534 return data ? length->GetAnimValInSpecifiedUnits() * data->ComputeLength() /
4535 100.0
4536 : 0.0;
4538 float lengthValue = length->GetAnimValue(tp);
4539 // If offsetScale is infinity we want to return 0 not NaN
4540 return lengthValue == 0 ? 0.0 : lengthValue * GetOffsetScale(aTextPathFrame);
4543 void SVGTextFrame::DoTextPathLayout() {
4544 nsPresContext* context = PresContext();
4546 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4547 while (!it.AtEnd()) {
4548 nsIFrame* textPathFrame = it.TextPathFrame();
4549 if (!textPathFrame) {
4550 // Skip past this frame if we're not in a text path.
4551 it.AdvancePastCurrentFrame();
4552 continue;
4555 // Get the path itself.
4556 RefPtr<Path> path = GetTextPath(textPathFrame);
4557 if (!path) {
4558 uint32_t start = it.TextElementCharIndex();
4559 it.AdvancePastCurrentTextPathFrame();
4560 uint32_t end = it.TextElementCharIndex();
4561 for (uint32_t i = start; i < end; i++) {
4562 mPositions[i].mHidden = true;
4564 continue;
4567 SVGTextPathElement* textPath =
4568 static_cast<SVGTextPathElement*>(textPathFrame->GetContent());
4569 uint16_t side =
4570 textPath->EnumAttributes()[SVGTextPathElement::SIDE].GetAnimValue();
4572 gfxFloat offset = GetStartOffset(textPathFrame);
4573 Float pathLength = path->ComputeLength();
4575 // If the first character within the text path is in the middle of a
4576 // cluster or ligature group, just skip it and don't apply text path
4577 // positioning.
4578 while (!it.AtEnd()) {
4579 if (it.IsOriginalCharSkipped()) {
4580 it.Next();
4581 continue;
4583 if (it.IsClusterAndLigatureGroupStart()) {
4584 break;
4586 it.Next();
4589 bool skippedEndOfTextPath = false;
4591 // Loop for each character in the text path.
4592 while (!it.AtEnd() && it.TextPathFrame() &&
4593 it.TextPathFrame()->GetContent() == textPath) {
4594 // The index of the cluster or ligature group's first character.
4595 uint32_t i = it.TextElementCharIndex();
4597 // The index of the next character of the cluster or ligature.
4598 // We track this as we loop over the characters below so that we
4599 // can detect undisplayed characters and append entries into
4600 // partialAdvances for them.
4601 uint32_t j = i + 1;
4603 MOZ_ASSERT(!mPositions[i].mClusterOrLigatureGroupMiddle);
4605 gfxFloat sign = it.TextRun()->IsRightToLeft() ? -1.0 : 1.0;
4606 bool vertical = it.TextRun()->IsVertical();
4608 // Compute cumulative advances for each character of the cluster or
4609 // ligature group.
4610 AutoTArray<gfxFloat, 4> partialAdvances;
4611 gfxFloat partialAdvance = it.GetAdvance(context);
4612 partialAdvances.AppendElement(partialAdvance);
4613 while (it.Next()) {
4614 // Append entries for any undisplayed characters the CharIterator
4615 // skipped over.
4616 MOZ_ASSERT(j <= it.TextElementCharIndex());
4617 while (j < it.TextElementCharIndex()) {
4618 partialAdvances.AppendElement(partialAdvance);
4619 ++j;
4621 // This loop may end up outside of the current text path, but
4622 // that's OK; we'll consider any complete cluster or ligature
4623 // group that begins inside the text path as being affected
4624 // by it.
4625 if (it.IsOriginalCharSkipped()) {
4626 if (!it.TextPathFrame()) {
4627 skippedEndOfTextPath = true;
4628 break;
4630 // Leave partialAdvance unchanged.
4631 } else if (it.IsClusterAndLigatureGroupStart()) {
4632 break;
4633 } else {
4634 partialAdvance += it.GetAdvance(context);
4636 partialAdvances.AppendElement(partialAdvance);
4639 if (!skippedEndOfTextPath) {
4640 // Any final undisplayed characters the CharIterator skipped over.
4641 MOZ_ASSERT(j <= it.TextElementCharIndex());
4642 while (j < it.TextElementCharIndex()) {
4643 partialAdvances.AppendElement(partialAdvance);
4644 ++j;
4648 gfxFloat halfAdvance =
4649 partialAdvances.LastElement() / mFontSizeScaleFactor / 2.0;
4650 gfxFloat midx =
4651 (vertical ? mPositions[i].mPosition.y : mPositions[i].mPosition.x) +
4652 sign * halfAdvance + offset;
4654 // Hide the character if it falls off the end of the path.
4655 mPositions[i].mHidden = midx < 0 || midx > pathLength;
4657 // Position the character on the path at the right angle.
4658 Point tangent; // Unit vector tangent to the point we find.
4659 Point pt;
4660 if (side == TEXTPATH_SIDETYPE_RIGHT) {
4661 pt = path->ComputePointAtLength(Float(pathLength - midx), &tangent);
4662 tangent = -tangent;
4663 } else {
4664 pt = path->ComputePointAtLength(Float(midx), &tangent);
4666 Float rotation = vertical ? atan2f(-tangent.x, tangent.y)
4667 : atan2f(tangent.y, tangent.x);
4668 Point normal(-tangent.y, tangent.x); // Unit vector normal to the point.
4669 Point offsetFromPath = normal * (vertical ? -mPositions[i].mPosition.x
4670 : mPositions[i].mPosition.y);
4671 pt += offsetFromPath;
4672 Point direction = tangent * sign;
4673 mPositions[i].mPosition =
4674 ThebesPoint(pt) - ThebesPoint(direction) * halfAdvance;
4675 mPositions[i].mAngle += rotation;
4677 // Position any characters for a partial ligature.
4678 for (uint32_t k = i + 1; k < j; k++) {
4679 gfxPoint partialAdvance = ThebesPoint(direction) *
4680 partialAdvances[k - i] / mFontSizeScaleFactor;
4681 mPositions[k].mPosition = mPositions[i].mPosition + partialAdvance;
4682 mPositions[k].mAngle = mPositions[i].mAngle;
4683 mPositions[k].mHidden = mPositions[i].mHidden;
4689 void SVGTextFrame::DoAnchoring() {
4690 nsPresContext* presContext = PresContext();
4692 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4694 // Don't need to worry about skipped or trimmed characters.
4695 while (!it.AtEnd() &&
4696 (it.IsOriginalCharSkipped() || it.IsOriginalCharTrimmed())) {
4697 it.Next();
4700 bool vertical = GetWritingMode().IsVertical();
4701 uint32_t start = it.TextElementCharIndex();
4702 while (start < mPositions.Length()) {
4703 it.AdvanceToCharacter(start);
4704 nsTextFrame* chunkFrame = it.TextFrame();
4706 // Measure characters in this chunk to find the left-most and right-most
4707 // edges of all glyphs within the chunk.
4708 uint32_t index = it.TextElementCharIndex();
4709 uint32_t end = start;
4710 gfxFloat left = std::numeric_limits<gfxFloat>::infinity();
4711 gfxFloat right = -std::numeric_limits<gfxFloat>::infinity();
4712 do {
4713 if (!it.IsOriginalCharSkipped() && !it.IsOriginalCharTrimmed()) {
4714 gfxFloat advance = it.GetAdvance(presContext) / mFontSizeScaleFactor;
4715 gfxFloat pos = it.TextRun()->IsVertical()
4716 ? mPositions[index].mPosition.y
4717 : mPositions[index].mPosition.x;
4718 if (it.TextRun()->IsRightToLeft()) {
4719 left = std::min(left, pos - advance);
4720 right = std::max(right, pos);
4721 } else {
4722 left = std::min(left, pos);
4723 right = std::max(right, pos + advance);
4726 it.Next();
4727 index = end = it.TextElementCharIndex();
4728 } while (!it.AtEnd() && !mPositions[end].mStartOfChunk);
4730 if (left != std::numeric_limits<gfxFloat>::infinity()) {
4731 bool isRTL =
4732 chunkFrame->StyleVisibility()->mDirection == StyleDirection::Rtl;
4733 TextAnchorSide anchor = ConvertLogicalTextAnchorToPhysical(
4734 chunkFrame->StyleSVG()->mTextAnchor, isRTL);
4736 ShiftAnchoredChunk(mPositions, start, end, left, right, anchor, vertical);
4739 start = it.TextElementCharIndex();
4743 void SVGTextFrame::DoGlyphPositioning() {
4744 mPositions.Clear();
4745 RemoveStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
4747 nsIFrame* kid = PrincipalChildList().FirstChild();
4748 if (kid && kid->IsSubtreeDirty()) {
4749 MOZ_ASSERT(false, "should have already reflowed the kid");
4750 return;
4753 // Since we can be called directly via GetBBoxContribution, our correspondence
4754 // may not be up to date.
4755 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
4757 // Determine the positions of each character in app units.
4758 AutoTArray<nsPoint, 64> charPositions;
4759 DetermineCharPositions(charPositions);
4761 if (charPositions.IsEmpty()) {
4762 // No characters, so nothing to do.
4763 return;
4766 // If the textLength="" attribute was specified, then we need ResolvePositions
4767 // to record that a new run starts with each glyph.
4768 SVGTextContentElement* element =
4769 static_cast<SVGTextContentElement*>(GetContent());
4770 SVGAnimatedLength* textLengthAttr =
4771 element->GetAnimatedLength(nsGkAtoms::textLength);
4772 uint16_t lengthAdjust =
4773 element->EnumAttributes()[SVGTextContentElement::LENGTHADJUST]
4774 .GetAnimValue();
4775 bool adjustingTextLength = textLengthAttr->IsExplicitlySet();
4776 float expectedTextLength = textLengthAttr->GetAnimValue(element);
4778 if (adjustingTextLength &&
4779 (expectedTextLength < 0.0f || lengthAdjust == LENGTHADJUST_UNKNOWN)) {
4780 // If textLength="" is less than zero or lengthAdjust is unknown, ignore it.
4781 adjustingTextLength = false;
4784 // Get the x, y, dx, dy, rotate values for the subtree.
4785 AutoTArray<gfxPoint, 16> deltas;
4786 if (!ResolvePositions(deltas, adjustingTextLength)) {
4787 // If ResolvePositions returned false, it means either there were some
4788 // characters in the DOM but none of them are displayed, or there was
4789 // an error in processing mPositions. Clear out mPositions so that we don't
4790 // attempt to do any painting later.
4791 mPositions.Clear();
4792 return;
4795 // XXX We might be able to do less work when there is at most a single
4796 // x/y/dx/dy position.
4798 // Truncate the positioning arrays to the actual number of characters present.
4799 TruncateTo(deltas, charPositions);
4800 TruncateTo(mPositions, charPositions);
4802 // Fill in an unspecified character position at index 0.
4803 if (!mPositions[0].IsXSpecified()) {
4804 mPositions[0].mPosition.x = 0.0;
4806 if (!mPositions[0].IsYSpecified()) {
4807 mPositions[0].mPosition.y = 0.0;
4809 if (!mPositions[0].IsAngleSpecified()) {
4810 mPositions[0].mAngle = 0.0;
4813 nsPresContext* presContext = PresContext();
4814 bool vertical = GetWritingMode().IsVertical();
4816 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
4817 presContext->AppUnitsPerDevPixel());
4818 double factor = cssPxPerDevPx / mFontSizeScaleFactor;
4820 // Determine how much to compress or expand glyph positions due to
4821 // textLength="" and lengthAdjust="".
4822 double adjustment = 0.0;
4823 mLengthAdjustScaleFactor = 1.0f;
4824 if (adjustingTextLength) {
4825 nscoord frameLength =
4826 vertical ? PrincipalChildList().FirstChild()->GetRect().height
4827 : PrincipalChildList().FirstChild()->GetRect().width;
4828 float actualTextLength = static_cast<float>(
4829 presContext->AppUnitsToGfxUnits(frameLength) * factor);
4831 switch (lengthAdjust) {
4832 case LENGTHADJUST_SPACINGANDGLYPHS:
4833 // Scale the glyphs and their positions.
4834 if (actualTextLength > 0) {
4835 mLengthAdjustScaleFactor = expectedTextLength / actualTextLength;
4837 break;
4839 default:
4840 MOZ_ASSERT(lengthAdjust == LENGTHADJUST_SPACING);
4841 // Just add space between each glyph.
4842 int32_t adjustableSpaces = 0;
4843 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4844 if (!mPositions[i].mUnaddressable) {
4845 adjustableSpaces++;
4848 if (adjustableSpaces) {
4849 adjustment =
4850 (expectedTextLength - actualTextLength) / adjustableSpaces;
4852 break;
4856 // Fill in any unspecified character positions based on the positions recorded
4857 // in charPositions, and also add in the dx/dy values.
4858 if (!deltas.IsEmpty()) {
4859 mPositions[0].mPosition += deltas[0];
4862 gfxFloat xLengthAdjustFactor = vertical ? 1.0 : mLengthAdjustScaleFactor;
4863 gfxFloat yLengthAdjustFactor = vertical ? mLengthAdjustScaleFactor : 1.0;
4864 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4865 // Fill in unspecified x position.
4866 if (!mPositions[i].IsXSpecified()) {
4867 nscoord d = charPositions[i].x - charPositions[i - 1].x;
4868 mPositions[i].mPosition.x =
4869 mPositions[i - 1].mPosition.x +
4870 presContext->AppUnitsToGfxUnits(d) * factor * xLengthAdjustFactor;
4871 if (!vertical && !mPositions[i].mUnaddressable) {
4872 mPositions[i].mPosition.x += adjustment;
4875 // Fill in unspecified y position.
4876 if (!mPositions[i].IsYSpecified()) {
4877 nscoord d = charPositions[i].y - charPositions[i - 1].y;
4878 mPositions[i].mPosition.y =
4879 mPositions[i - 1].mPosition.y +
4880 presContext->AppUnitsToGfxUnits(d) * factor * yLengthAdjustFactor;
4881 if (vertical && !mPositions[i].mUnaddressable) {
4882 mPositions[i].mPosition.y += adjustment;
4885 // Add in dx/dy.
4886 if (i < deltas.Length()) {
4887 mPositions[i].mPosition += deltas[i];
4889 // Fill in unspecified rotation values.
4890 if (!mPositions[i].IsAngleSpecified()) {
4891 mPositions[i].mAngle = 0.0f;
4895 MOZ_ASSERT(mPositions.Length() == charPositions.Length());
4897 AdjustChunksForLineBreaks();
4898 AdjustPositionsForClusters();
4899 DoAnchoring();
4900 DoTextPathLayout();
4903 bool SVGTextFrame::ShouldRenderAsPath(nsTextFrame* aFrame,
4904 bool& aShouldPaintSVGGlyphs) {
4905 // Rendering to a clip path.
4906 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
4907 aShouldPaintSVGGlyphs = false;
4908 return true;
4911 aShouldPaintSVGGlyphs = true;
4913 const nsStyleSVG* style = aFrame->StyleSVG();
4915 // Fill is a non-solid paint, has a non-default fill-rule or has
4916 // non-1 opacity.
4917 if (!(style->mFill.kind.IsNone() ||
4918 (style->mFill.kind.IsColor() && style->mFillOpacity.IsOpacity() &&
4919 style->mFillOpacity.AsOpacity() == 1))) {
4920 return true;
4923 // Text has a stroke.
4924 if (style->HasStroke()) {
4925 if (style->mStrokeWidth.IsContextValue()) {
4926 return true;
4928 if (SVGContentUtils::CoordToFloat(
4929 static_cast<SVGElement*>(GetContent()),
4930 style->mStrokeWidth.AsLengthPercentage()) > 0) {
4931 return true;
4935 return false;
4938 void SVGTextFrame::ScheduleReflowSVG() {
4939 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
4940 ScheduleReflowSVGNonDisplayText(
4941 IntrinsicDirty::FrameAncestorsAndDescendants);
4942 } else {
4943 SVGUtils::ScheduleReflowSVG(this);
4947 void SVGTextFrame::NotifyGlyphMetricsChange(bool aUpdateTextCorrespondence) {
4948 if (aUpdateTextCorrespondence) {
4949 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
4951 AddStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
4952 nsLayoutUtils::PostRestyleEvent(mContent->AsElement(), RestyleHint{0},
4953 nsChangeHint_InvalidateRenderingObservers);
4954 ScheduleReflowSVG();
4957 void SVGTextFrame::UpdateGlyphPositioning() {
4958 nsIFrame* kid = PrincipalChildList().FirstChild();
4959 if (!kid) {
4960 return;
4963 if (HasAnyStateBits(NS_STATE_SVG_POSITIONING_DIRTY)) {
4964 DoGlyphPositioning();
4968 void SVGTextFrame::MaybeResolveBidiForAnonymousBlockChild() {
4969 nsIFrame* kid = PrincipalChildList().FirstChild();
4971 if (kid && kid->HasAnyStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION) &&
4972 PresContext()->BidiEnabled()) {
4973 MOZ_ASSERT(static_cast<nsBlockFrame*>(do_QueryFrame(kid)),
4974 "Expect anonymous child to be an nsBlockFrame");
4975 nsBidiPresUtils::Resolve(static_cast<nsBlockFrame*>(kid));
4979 void SVGTextFrame::MaybeReflowAnonymousBlockChild() {
4980 nsIFrame* kid = PrincipalChildList().FirstChild();
4981 if (!kid) {
4982 return;
4985 NS_ASSERTION(!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW),
4986 "should not be in reflow when about to reflow again");
4988 if (IsSubtreeDirty()) {
4989 if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
4990 // If we require a full reflow, ensure our kid is marked fully dirty.
4991 // (Note that our anonymous nsBlockFrame is not an ISVGDisplayableFrame,
4992 // so even when we are called via our ReflowSVG this will not be done for
4993 // us by SVGDisplayContainerFrame::ReflowSVG.)
4994 kid->MarkSubtreeDirty();
4997 // The RecordCorrespondence and DoReflow calls can result in new text frames
4998 // being created (due to bidi resolution or reflow). We set this bit to
4999 // guard against unnecessarily calling back in to
5000 // ScheduleReflowSVGNonDisplayText from nsIFrame::DidSetComputedStyle on
5001 // those new text frames.
5002 AddStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5004 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
5006 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
5007 "should be under ReflowSVG");
5008 nsPresContext::InterruptPreventer noInterrupts(PresContext());
5009 DoReflow();
5011 RemoveStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5015 void SVGTextFrame::DoReflow() {
5016 MOZ_ASSERT(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW));
5018 // Since we are going to reflow the anonymous block frame, we will
5019 // need to update mPositions.
5020 // We also mark our text correspondence as dirty since we can end up needing
5021 // reflow in ways that do not set NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY.
5022 // (We'd then fail the "expected a TextNodeCorrespondenceProperty" assertion
5023 // when UpdateGlyphPositioning() is called after we return.)
5024 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |
5025 NS_STATE_SVG_POSITIONING_DIRTY);
5027 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5028 // Normally, these dirty flags would be cleared in ReflowSVG(), but that
5029 // doesn't get called for non-display frames. We don't want to reflow our
5030 // descendants every time SVGTextFrame::PaintSVG makes sure that we have
5031 // valid positions by calling UpdateGlyphPositioning(), so we need to clear
5032 // these dirty bits. Note that this also breaks an invalidation loop where
5033 // our descendants invalidate as they reflow, which invalidates rendering
5034 // observers, which reschedules the frame that is currently painting by
5035 // referencing us to paint again. See bug 839958 comment 7. Hopefully we
5036 // will break that loop more convincingly at some point.
5037 RemoveStateBits(NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
5040 nsPresContext* presContext = PresContext();
5041 nsIFrame* kid = PrincipalChildList().FirstChild();
5042 if (!kid) {
5043 return;
5046 UniquePtr<gfxContext> renderingContext =
5047 presContext->PresShell()->CreateReferenceRenderingContext();
5049 if (UpdateFontSizeScaleFactor()) {
5050 // If the font size scale factor changed, we need the block to report
5051 // an updated preferred width.
5052 kid->MarkIntrinsicISizesDirty();
5055 nscoord inlineSize = kid->GetPrefISize(renderingContext.get());
5056 WritingMode wm = kid->GetWritingMode();
5057 ReflowInput reflowInput(presContext, kid, renderingContext.get(),
5058 LogicalSize(wm, inlineSize, NS_UNCONSTRAINEDSIZE));
5059 ReflowOutput desiredSize(reflowInput);
5060 nsReflowStatus status;
5062 NS_ASSERTION(
5063 reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) &&
5064 reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0),
5065 "style system should ensure that :-moz-svg-text "
5066 "does not get styled");
5068 kid->Reflow(presContext, desiredSize, reflowInput, status);
5069 kid->DidReflow(presContext, &reflowInput);
5070 kid->SetSize(wm, desiredSize.Size(wm));
5073 // Usable font size range in devpixels / user-units
5074 #define CLAMP_MIN_SIZE 8.0
5075 #define CLAMP_MAX_SIZE 200.0
5076 #define PRECISE_SIZE 200.0
5078 bool SVGTextFrame::UpdateFontSizeScaleFactor() {
5079 double oldFontSizeScaleFactor = mFontSizeScaleFactor;
5081 nsPresContext* presContext = PresContext();
5083 bool geometricPrecision = false;
5084 CSSCoord min = std::numeric_limits<float>::max();
5085 CSSCoord max = std::numeric_limits<float>::min();
5086 bool anyText = false;
5088 // Find the minimum and maximum font sizes used over all the
5089 // nsTextFrames.
5090 TextFrameIterator it(this);
5091 nsTextFrame* f = it.Current();
5092 while (f) {
5093 if (!geometricPrecision) {
5094 // Unfortunately we can't treat text-rendering:geometricPrecision
5095 // separately for each text frame.
5096 geometricPrecision = f->StyleText()->mTextRendering ==
5097 StyleTextRendering::Geometricprecision;
5099 const auto& fontSize = f->StyleFont()->mFont.size;
5100 if (!fontSize.IsZero()) {
5101 min = std::min(min, fontSize.ToCSSPixels());
5102 max = std::max(max, fontSize.ToCSSPixels());
5103 anyText = true;
5105 f = it.Next();
5108 if (!anyText) {
5109 // No text, so no need for scaling.
5110 mFontSizeScaleFactor = 1.0;
5111 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5114 if (geometricPrecision) {
5115 // We want to ensure minSize is scaled to PRECISE_SIZE.
5116 mFontSizeScaleFactor = PRECISE_SIZE / min;
5117 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5120 // When we are non-display, we could be painted in different coordinate
5121 // spaces, and we don't want to have to reflow for each of these. We
5122 // just assume that the context scale is 1.0 for them all, so we don't
5123 // get stuck with a font size scale factor based on whichever referencing
5124 // frame happens to reflow first.
5125 double contextScale = 1.0;
5126 if (!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5127 gfxMatrix m(GetCanvasTM());
5128 if (!m.IsSingular()) {
5129 contextScale = GetContextScale(m);
5130 if (!std::isfinite(contextScale)) {
5131 contextScale = 1.0f;
5135 mLastContextScale = contextScale;
5137 // But we want to ignore any scaling required due to HiDPI displays, since
5138 // regular CSS text frames will still create text runs using the font size
5139 // in CSS pixels, and we want SVG text to have the same rendering as HTML
5140 // text for regular font sizes.
5141 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
5142 presContext->AppUnitsPerDevPixel());
5143 contextScale *= cssPxPerDevPx;
5145 double minTextRunSize = min * contextScale;
5146 double maxTextRunSize = max * contextScale;
5148 if (minTextRunSize >= CLAMP_MIN_SIZE && maxTextRunSize <= CLAMP_MAX_SIZE) {
5149 // We are already in the ideal font size range for all text frames,
5150 // so we only have to take into account the contextScale.
5151 mFontSizeScaleFactor = contextScale;
5152 } else if (max / min > CLAMP_MAX_SIZE / CLAMP_MIN_SIZE) {
5153 // We can't scale the font sizes so that all of the text frames lie
5154 // within our ideal font size range.
5155 // Heuristically, if the maxTextRunSize is within the CLAMP_MAX_SIZE
5156 // as a reasonable value, it's likely to be the user's intent to
5157 // get a valid font for the maxTextRunSize one, we should honor it.
5158 // The same for minTextRunSize.
5159 if (maxTextRunSize <= CLAMP_MAX_SIZE) {
5160 mFontSizeScaleFactor = CLAMP_MAX_SIZE / max;
5161 } else if (minTextRunSize >= CLAMP_MIN_SIZE) {
5162 mFontSizeScaleFactor = CLAMP_MIN_SIZE / min;
5163 } else {
5164 // So maxTextRunSize is too big, minTextRunSize is too small,
5165 // we can't really do anything for this case, just leave it as is.
5166 mFontSizeScaleFactor = contextScale;
5168 } else if (minTextRunSize < CLAMP_MIN_SIZE) {
5169 mFontSizeScaleFactor = CLAMP_MIN_SIZE / min;
5170 } else {
5171 mFontSizeScaleFactor = CLAMP_MAX_SIZE / max;
5174 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5177 double SVGTextFrame::GetFontSizeScaleFactor() const {
5178 return mFontSizeScaleFactor;
5182 * Take aPoint, which is in the <text> element's user space, and convert
5183 * it to the appropriate frame user space of aChildFrame according to
5184 * which rendered run the point hits.
5186 Point SVGTextFrame::TransformFramePointToTextChild(
5187 const Point& aPoint, const nsIFrame* aChildFrame) {
5188 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(
5189 aChildFrame->GetParent(),
5190 LayoutFrameType::SVGText) == this,
5191 "aChildFrame must be a descendant of this frame");
5193 UpdateGlyphPositioning();
5195 nsPresContext* presContext = PresContext();
5197 // Add in the mRect offset to aPoint, as that will have been taken into
5198 // account when transforming the point from the ancestor frame down
5199 // to this one.
5200 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
5201 presContext->AppUnitsPerDevPixel());
5202 float factor = AppUnitsPerCSSPixel();
5203 Point framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5204 NSAppUnitsToFloatPixels(mRect.y, factor));
5205 Point pointInUserSpace = aPoint * cssPxPerDevPx + framePosition;
5207 // Find the closest rendered run for the text frames beneath aChildFrame.
5208 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5209 aChildFrame);
5210 TextRenderedRun hit;
5211 gfxPoint pointInRun;
5212 nscoord dx = nscoord_MAX;
5213 nscoord dy = nscoord_MAX;
5214 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5215 uint32_t flags = TextRenderedRun::eIncludeFill |
5216 TextRenderedRun::eIncludeStroke |
5217 TextRenderedRun::eNoHorizontalOverflow;
5218 gfxRect runRect =
5219 run.GetRunUserSpaceRect(presContext, flags).ToThebesRect();
5221 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5222 if (!m.Invert()) {
5223 return aPoint;
5225 gfxPoint pointInRunUserSpace =
5226 m.TransformPoint(ThebesPoint(pointInUserSpace));
5228 if (Inside(runRect, pointInRunUserSpace)) {
5229 // The point was inside the rendered run's rect, so we choose it.
5230 dx = 0;
5231 dy = 0;
5232 pointInRun = pointInRunUserSpace;
5233 hit = run;
5234 } else if (nsLayoutUtils::PointIsCloserToRect(pointInRunUserSpace, runRect,
5235 dx, dy)) {
5236 // The point was closer to this rendered run's rect than any others
5237 // we've seen so far.
5238 pointInRun.x =
5239 clamped(pointInRunUserSpace.x.value, runRect.X(), runRect.XMost());
5240 pointInRun.y =
5241 clamped(pointInRunUserSpace.y.value, runRect.Y(), runRect.YMost());
5242 hit = run;
5246 if (!hit.mFrame) {
5247 // We didn't find any rendered runs for the frame.
5248 return aPoint;
5251 // Return the point in user units relative to the nsTextFrame,
5252 // but taking into account mFontSizeScaleFactor.
5253 gfxMatrix m = hit.GetTransformFromRunUserSpaceToFrameUserSpace(presContext);
5254 m.PreScale(mFontSizeScaleFactor, mFontSizeScaleFactor);
5255 return ToPoint(m.TransformPoint(pointInRun) / cssPxPerDevPx);
5259 * For each rendered run beneath aChildFrame, translate aRect from
5260 * aChildFrame to the run's text frame, transform it then into
5261 * the run's frame user space, intersect it with the run's
5262 * frame user space rect, then transform it up to user space.
5263 * The result is the union of all of these.
5265 gfxRect SVGTextFrame::TransformFrameRectFromTextChild(
5266 const nsRect& aRect, const nsIFrame* aChildFrame) {
5267 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(
5268 aChildFrame->GetParent(),
5269 LayoutFrameType::SVGText) == this,
5270 "aChildFrame must be a descendant of this frame");
5272 UpdateGlyphPositioning();
5274 nsPresContext* presContext = PresContext();
5276 gfxRect result;
5277 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5278 aChildFrame);
5279 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5280 // First, translate aRect from aChildFrame to this run's frame.
5281 nsRect rectInTextFrame = aRect + aChildFrame->GetOffsetTo(run.mFrame);
5283 // Scale it into frame user space.
5284 gfxRect rectInFrameUserSpace = AppUnitsToFloatCSSPixels(
5285 gfxRect(rectInTextFrame.x, rectInTextFrame.y, rectInTextFrame.width,
5286 rectInTextFrame.height),
5287 presContext);
5289 // Intersect it with the run.
5290 uint32_t flags =
5291 TextRenderedRun::eIncludeFill | TextRenderedRun::eIncludeStroke;
5293 if (rectInFrameUserSpace.IntersectRect(
5294 rectInFrameUserSpace,
5295 run.GetFrameUserSpaceRect(presContext, flags).ToThebesRect())) {
5296 // Transform it up to user space of the <text>
5297 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5298 gfxRect rectInUserSpace = m.TransformRect(rectInFrameUserSpace);
5300 // Union it into the result.
5301 result.UnionRect(result, rectInUserSpace);
5305 // Subtract the mRect offset from the result, as our user space for
5306 // this frame is relative to the top-left of mRect.
5307 float factor = AppUnitsPerCSSPixel();
5308 gfxPoint framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5309 NSAppUnitsToFloatPixels(mRect.y, factor));
5311 return result - framePosition;
5314 Rect SVGTextFrame::TransformFrameRectFromTextChild(
5315 const Rect& aRect, const nsIFrame* aChildFrame) {
5316 nscoord appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
5317 nsRect r = LayoutDevicePixel::ToAppUnits(
5318 LayoutDeviceRect::FromUnknownRect(aRect), appUnitsPerDevPixel);
5319 gfxRect resultCssUnits = TransformFrameRectFromTextChild(r, aChildFrame);
5320 float devPixelPerCSSPixel =
5321 float(AppUnitsPerCSSPixel()) / appUnitsPerDevPixel;
5322 resultCssUnits.Scale(devPixelPerCSSPixel);
5323 return ToRect(resultCssUnits);
5326 Point SVGTextFrame::TransformFramePointFromTextChild(
5327 const Point& aPoint, const nsIFrame* aChildFrame) {
5328 return TransformFrameRectFromTextChild(Rect(aPoint, Size(1, 1)), aChildFrame)
5329 .TopLeft();
5332 void SVGTextFrame::AppendDirectlyOwnedAnonBoxes(
5333 nsTArray<OwnedAnonBox>& aResult) {
5334 MOZ_ASSERT(PrincipalChildList().FirstChild(), "Must have our anon box");
5335 aResult.AppendElement(OwnedAnonBox(PrincipalChildList().FirstChild()));
5338 } // namespace mozilla