no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / layout / svg / SVGTextFrame.cpp
blobd53637af0ab95678e6c6a5a654d7829790b3b352
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 "SVGPaintServerFrame.h"
26 #include "nsTArray.h"
27 #include "nsTextFrame.h"
28 #include "SVGAnimatedNumberList.h"
29 #include "SVGContentUtils.h"
30 #include "SVGContextPaint.h"
31 #include "SVGLengthList.h"
32 #include "SVGNumberList.h"
33 #include "nsLayoutUtils.h"
34 #include "nsFrameSelection.h"
35 #include "nsStyleStructInlines.h"
36 #include "mozilla/CaretAssociationHint.h"
37 #include "mozilla/DisplaySVGItem.h"
38 #include "mozilla/Likely.h"
39 #include "mozilla/PresShell.h"
40 #include "mozilla/SVGObserverUtils.h"
41 #include "mozilla/SVGOuterSVGFrame.h"
42 #include "mozilla/SVGUtils.h"
43 #include "mozilla/dom/DOMPointBinding.h"
44 #include "mozilla/dom/Selection.h"
45 #include "mozilla/dom/SVGGeometryElement.h"
46 #include "mozilla/dom/SVGRect.h"
47 #include "mozilla/dom/SVGTextContentElementBinding.h"
48 #include "mozilla/dom/SVGTextPathElement.h"
49 #include "mozilla/dom/Text.h"
50 #include "mozilla/gfx/2D.h"
51 #include "mozilla/gfx/PatternHelpers.h"
52 #include <algorithm>
53 #include <cmath>
54 #include <limits>
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 // Scale for textLength="" and translate to get the text frame
722 // to the right place.
723 nsPoint t;
724 if (IsVertical()) {
725 m.PreScale(1.0, mLengthAdjustScaleFactor);
726 t = nsPoint(-mBaseline, IsRightToLeft()
727 ? -mFrame->GetRect().height + aVisIEndEdge
728 : -aVisIStartEdge);
729 } else {
730 m.PreScale(mLengthAdjustScaleFactor, 1.0);
731 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + aVisIEndEdge
732 : -aVisIStartEdge,
733 -mBaseline);
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 for textLength="" and translate to get the text frame
760 // to the right place.
762 nsPoint t;
763 if (IsVertical()) {
764 m.PreScale(1.0, mLengthAdjustScaleFactor);
765 t = nsPoint(-mBaseline,
766 IsRightToLeft() ? -mFrame->GetRect().height + start + end : 0);
767 } else {
768 m.PreScale(mLengthAdjustScaleFactor, 1.0);
769 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + start + end : 0,
770 -mBaseline);
772 m.PreTranslate(AppUnitsToGfxUnits(t, aContext) * cssPxPerDevPx /
773 mFontSizeScaleFactor);
775 return m;
778 gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
779 nsPresContext* aContext) const {
780 gfxMatrix m;
781 if (!mFrame) {
782 return m;
785 nscoord start, end;
786 GetClipEdges(start, end);
788 // Translate by the horizontal distance into the text frame this
789 // rendered run is.
790 gfxFloat appPerCssPx = AppUnitsPerCSSPixel();
791 gfxPoint t = IsVertical() ? gfxPoint(0, start / appPerCssPx)
792 : gfxPoint(start / appPerCssPx, 0);
793 return m.PreTranslate(t);
796 SVGBBox TextRenderedRun::GetRunUserSpaceRect(nsPresContext* aContext,
797 uint32_t aFlags) const {
798 SVGBBox r;
799 if (!mFrame) {
800 return r;
803 // Determine the amount of overflow around frame's mRect.
805 // We need to call InkOverflowRectRelativeToSelf because this includes
806 // overflowing decorations, which the MeasureText call below does not.
807 nsRect self = mFrame->InkOverflowRectRelativeToSelf();
808 nsRect rect = mFrame->GetRect();
809 bool vertical = IsVertical();
810 nsMargin inkOverflow(
811 vertical ? -self.x : -self.y,
812 vertical ? self.YMost() - rect.height : self.XMost() - rect.width,
813 vertical ? self.XMost() - rect.width : self.YMost() - rect.height,
814 vertical ? -self.y : -self.x);
816 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
817 gfxSkipCharsIterator start = it;
818 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
820 // Get the content range for this rendered run.
821 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
822 mTextFrameContentLength);
823 if (range.Length() == 0) {
824 return r;
827 // FIXME(heycam): We could create a single PropertyProvider for all
828 // TextRenderedRuns that correspond to the text frame, rather than recreate
829 // it each time here.
830 nsTextFrame::PropertyProvider provider(mFrame, start);
832 // Measure that range.
833 gfxTextRun::Metrics metrics = textRun->MeasureText(
834 range, gfxFont::LOOSE_INK_EXTENTS, nullptr, &provider);
835 // Make sure it includes the font-box.
836 gfxRect fontBox(0, -metrics.mAscent, metrics.mAdvanceWidth,
837 metrics.mAscent + metrics.mDescent);
838 metrics.mBoundingBox.UnionRect(metrics.mBoundingBox, fontBox);
840 // Determine the rectangle that covers the rendered run's fill,
841 // taking into account the measured overflow due to decorations.
842 nscoord baseline =
843 NSToCoordRoundWithClamp(metrics.mBoundingBox.y + metrics.mAscent);
844 gfxFloat x, width;
845 if (aFlags & eNoHorizontalOverflow) {
846 x = 0.0;
847 width = textRun->GetAdvanceWidth(range, &provider);
848 if (width < 0.0) {
849 x = width;
850 width = -width;
852 } else {
853 x = metrics.mBoundingBox.x;
854 width = metrics.mBoundingBox.width;
856 nsRect fillInAppUnits(NSToCoordRoundWithClamp(x), baseline,
857 NSToCoordRoundWithClamp(width),
858 NSToCoordRoundWithClamp(metrics.mBoundingBox.height));
859 fillInAppUnits.Inflate(inkOverflow);
860 if (textRun->IsVertical()) {
861 // Swap line-relative textMetrics dimensions to physical coordinates.
862 std::swap(fillInAppUnits.x, fillInAppUnits.y);
863 std::swap(fillInAppUnits.width, fillInAppUnits.height);
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 if (vertical) {
873 fill.Scale(1.0, mLengthAdjustScaleFactor);
874 } else {
875 fill.Scale(mLengthAdjustScaleFactor, 1.0);
878 // Scale the rectangle up due to any mFontSizeScaleFactor.
879 fill.Scale(1.0 / mFontSizeScaleFactor);
881 // Include the fill if requested.
882 if (aFlags & eIncludeFill) {
883 r = fill;
886 // Include the stroke if requested.
887 if ((aFlags & eIncludeStroke) && !fill.IsEmpty() &&
888 SVGUtils::GetStrokeWidth(mFrame) > 0) {
889 r.UnionEdges(
890 SVGUtils::PathExtentsToMaxStrokeExtents(fill, mFrame, gfxMatrix()));
893 return r;
896 SVGBBox TextRenderedRun::GetFrameUserSpaceRect(nsPresContext* aContext,
897 uint32_t aFlags) const {
898 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
899 if (r.IsEmpty()) {
900 return r;
902 gfxMatrix m = GetTransformFromRunUserSpaceToFrameUserSpace(aContext);
903 return m.TransformBounds(r.ToThebesRect());
906 SVGBBox TextRenderedRun::GetUserSpaceRect(
907 nsPresContext* aContext, uint32_t aFlags,
908 const gfxMatrix* aAdditionalTransform) const {
909 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
910 if (r.IsEmpty()) {
911 return r;
913 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
914 if (aAdditionalTransform) {
915 m *= *aAdditionalTransform;
917 return m.TransformBounds(r.ToThebesRect());
920 void TextRenderedRun::GetClipEdges(nscoord& aVisIStartEdge,
921 nscoord& aVisIEndEdge) const {
922 uint32_t contentLength = mFrame->GetContentLength();
923 if (mTextFrameContentOffset == 0 &&
924 mTextFrameContentLength == contentLength) {
925 // If the rendered run covers the entire content, we know we don't need
926 // to clip without having to measure anything.
927 aVisIStartEdge = 0;
928 aVisIEndEdge = 0;
929 return;
932 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
933 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
934 nsTextFrame::PropertyProvider provider(mFrame, it);
936 // Get the covered content offset/length for this rendered run in skipped
937 // characters, since that is what GetAdvanceWidth expects.
938 Range runRange = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
939 mTextFrameContentLength);
941 // Get the offset/length of the whole nsTextFrame.
942 uint32_t frameOffset = mFrame->GetContentOffset();
943 uint32_t frameLength = mFrame->GetContentLength();
945 // Trim the whole-nsTextFrame offset/length to remove any leading/trailing
946 // white space, as the nsTextFrame when painting does not include them when
947 // interpreting clip edges.
948 nsTextFrame::TrimmedOffsets trimmedOffsets =
949 mFrame->GetTrimmedOffsets(mFrame->TextFragment());
950 TrimOffsets(frameOffset, frameLength, trimmedOffsets);
952 // Convert the trimmed whole-nsTextFrame offset/length into skipped
953 // characters.
954 Range frameRange = ConvertOriginalToSkipped(it, frameOffset, frameLength);
956 // Measure the advance width in the text run between the start of
957 // frame's content and the start of the rendered run's content,
958 nscoord startEdge = textRun->GetAdvanceWidth(
959 Range(frameRange.start, runRange.start), &provider);
961 // and between the end of the rendered run's content and the end
962 // of the frame's content.
963 nscoord endEdge =
964 textRun->GetAdvanceWidth(Range(runRange.end, frameRange.end), &provider);
966 if (textRun->IsRightToLeft()) {
967 aVisIStartEdge = endEdge;
968 aVisIEndEdge = startEdge;
969 } else {
970 aVisIStartEdge = startEdge;
971 aVisIEndEdge = endEdge;
975 nscoord TextRenderedRun::GetAdvanceWidth() const {
976 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
977 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
978 nsTextFrame::PropertyProvider provider(mFrame, it);
980 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
981 mTextFrameContentLength);
983 return textRun->GetAdvanceWidth(range, &provider);
986 int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext* aContext,
987 const gfxPoint& aPoint) const {
988 if (mTextFrameContentLength == 0) {
989 return -1;
992 float cssPxPerDevPx =
993 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
995 // Convert the point from user space into run user space, and take
996 // into account any mFontSizeScaleFactor.
997 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
998 if (!m.Invert()) {
999 return -1;
1001 gfxPoint p = m.TransformPoint(aPoint) / cssPxPerDevPx * mFontSizeScaleFactor;
1003 // First check that the point lies vertically between the top and bottom
1004 // edges of the text.
1005 gfxFloat ascent, descent;
1006 GetAscentAndDescentInAppUnits(mFrame, ascent, descent);
1008 WritingMode writingMode = mFrame->GetWritingMode();
1009 if (writingMode.IsVertical()) {
1010 gfxFloat leftEdge = mFrame->GetLogicalBaseline(writingMode) -
1011 (writingMode.IsVerticalRL() ? ascent : descent);
1012 gfxFloat rightEdge = leftEdge + ascent + descent;
1013 if (p.x < aContext->AppUnitsToGfxUnits(leftEdge) ||
1014 p.x > aContext->AppUnitsToGfxUnits(rightEdge)) {
1015 return -1;
1017 } else {
1018 gfxFloat topEdge = mFrame->GetLogicalBaseline(writingMode) - ascent;
1019 gfxFloat bottomEdge = topEdge + ascent + descent;
1020 if (p.y < aContext->AppUnitsToGfxUnits(topEdge) ||
1021 p.y > aContext->AppUnitsToGfxUnits(bottomEdge)) {
1022 return -1;
1026 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
1027 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
1028 nsTextFrame::PropertyProvider provider(mFrame, it);
1030 // Next check that the point lies horizontally within the left and right
1031 // edges of the text.
1032 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
1033 mTextFrameContentLength);
1034 gfxFloat runAdvance =
1035 aContext->AppUnitsToGfxUnits(textRun->GetAdvanceWidth(range, &provider));
1037 gfxFloat pos = writingMode.IsVertical() ? p.y : p.x;
1038 if (pos < 0 || pos >= runAdvance) {
1039 return -1;
1042 // Finally, measure progressively smaller portions of the rendered run to
1043 // find which glyph it lies within. This will need to change once we
1044 // support letter-spacing and word-spacing.
1045 bool rtl = textRun->IsRightToLeft();
1046 for (int32_t i = mTextFrameContentLength - 1; i >= 0; i--) {
1047 range = ConvertOriginalToSkipped(it, mTextFrameContentOffset, i);
1048 gfxFloat advance = aContext->AppUnitsToGfxUnits(
1049 textRun->GetAdvanceWidth(range, &provider));
1050 if ((rtl && pos < runAdvance - advance) || (!rtl && pos >= advance)) {
1051 return i;
1054 return -1;
1057 // ----------------------------------------------------------------------------
1058 // TextNodeIterator
1060 enum SubtreePosition { eBeforeSubtree, eWithinSubtree, eAfterSubtree };
1063 * An iterator class for Text that are descendants of a given node, the
1064 * root. Nodes are iterated in document order. An optional subtree can be
1065 * specified, in which case the iterator will track whether the current state of
1066 * the traversal over the tree is within that subtree or is past that subtree.
1068 class TextNodeIterator {
1069 public:
1071 * Constructs a TextNodeIterator with the specified root node and optional
1072 * subtree.
1074 explicit TextNodeIterator(nsIContent* aRoot, nsIContent* aSubtree = nullptr)
1075 : mRoot(aRoot),
1076 mSubtree(aSubtree == aRoot ? nullptr : aSubtree),
1077 mCurrent(aRoot),
1078 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1079 NS_ASSERTION(aRoot, "expected non-null root");
1080 if (!aRoot->IsText()) {
1081 Next();
1086 * Returns the current Text, or null if the iterator has finished.
1088 Text* Current() const { return mCurrent ? mCurrent->AsText() : nullptr; }
1091 * Advances to the next Text and returns it, or null if the end of
1092 * iteration has been reached.
1094 Text* Next();
1097 * Returns whether the iterator is currently within the subtree rooted
1098 * at mSubtree. Returns true if we are not tracking a subtree (we consider
1099 * that we're always within the subtree).
1101 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1104 * Returns whether the iterator is past the subtree rooted at mSubtree.
1105 * Returns false if we are not tracking a subtree.
1107 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1109 private:
1111 * The root under which all Text will be iterated over.
1113 nsIContent* const mRoot;
1116 * The node rooting the subtree to track.
1118 nsIContent* const mSubtree;
1121 * The current node during iteration.
1123 nsIContent* mCurrent;
1126 * The current iterator position relative to mSubtree.
1128 SubtreePosition mSubtreePosition;
1131 Text* TextNodeIterator::Next() {
1132 // Starting from mCurrent, we do a non-recursive traversal to the next
1133 // Text beneath mRoot, updating mSubtreePosition appropriately if we
1134 // encounter mSubtree.
1135 if (mCurrent) {
1136 do {
1137 nsIContent* next =
1138 IsTextContentElement(mCurrent) ? mCurrent->GetFirstChild() : nullptr;
1139 if (next) {
1140 mCurrent = next;
1141 if (mCurrent == mSubtree) {
1142 mSubtreePosition = eWithinSubtree;
1144 } else {
1145 for (;;) {
1146 if (mCurrent == mRoot) {
1147 mCurrent = nullptr;
1148 break;
1150 if (mCurrent == mSubtree) {
1151 mSubtreePosition = eAfterSubtree;
1153 next = mCurrent->GetNextSibling();
1154 if (next) {
1155 mCurrent = next;
1156 if (mCurrent == mSubtree) {
1157 mSubtreePosition = eWithinSubtree;
1159 break;
1161 if (mCurrent == mSubtree) {
1162 mSubtreePosition = eAfterSubtree;
1164 mCurrent = mCurrent->GetParent();
1167 } while (mCurrent && !mCurrent->IsText());
1170 return mCurrent ? mCurrent->AsText() : nullptr;
1173 // ----------------------------------------------------------------------------
1174 // TextNodeCorrespondenceRecorder
1177 * TextNodeCorrespondence is used as the value of a frame property that
1178 * is stored on all its descendant nsTextFrames. It stores the number of DOM
1179 * characters between it and the previous nsTextFrame that did not have an
1180 * nsTextFrame created for them, due to either not being in a correctly
1181 * parented text content element, or because they were display:none.
1182 * These are called "undisplayed characters".
1184 * See also TextNodeCorrespondenceRecorder below, which is what sets the
1185 * frame property.
1187 struct TextNodeCorrespondence {
1188 explicit TextNodeCorrespondence(uint32_t aUndisplayedCharacters)
1189 : mUndisplayedCharacters(aUndisplayedCharacters) {}
1191 uint32_t mUndisplayedCharacters;
1194 NS_DECLARE_FRAME_PROPERTY_DELETABLE(TextNodeCorrespondenceProperty,
1195 TextNodeCorrespondence)
1198 * Returns the number of undisplayed characters before the specified
1199 * nsTextFrame.
1201 static uint32_t GetUndisplayedCharactersBeforeFrame(nsTextFrame* aFrame) {
1202 void* value = aFrame->GetProperty(TextNodeCorrespondenceProperty());
1203 TextNodeCorrespondence* correspondence =
1204 static_cast<TextNodeCorrespondence*>(value);
1205 if (!correspondence) {
1206 // FIXME bug 903785
1207 NS_ERROR(
1208 "expected a TextNodeCorrespondenceProperty on nsTextFrame "
1209 "used for SVG text");
1210 return 0;
1212 return correspondence->mUndisplayedCharacters;
1216 * Traverses the nsTextFrames for an SVGTextFrame and records a
1217 * TextNodeCorrespondenceProperty on each for the number of undisplayed DOM
1218 * characters between each frame. This is done by iterating simultaneously
1219 * over the Text and nsTextFrames and noting when Text (or
1220 * parts of them) are skipped when finding the next nsTextFrame.
1222 class TextNodeCorrespondenceRecorder {
1223 public:
1225 * Entry point for the TextNodeCorrespondenceProperty recording.
1227 static void RecordCorrespondence(SVGTextFrame* aRoot);
1229 private:
1230 explicit TextNodeCorrespondenceRecorder(SVGTextFrame* aRoot)
1231 : mNodeIterator(aRoot->GetContent()),
1232 mPreviousNode(nullptr),
1233 mNodeCharIndex(0) {}
1235 void Record(SVGTextFrame* aRoot);
1236 void TraverseAndRecord(nsIFrame* aFrame);
1239 * Returns the next non-empty Text.
1241 Text* NextNode();
1244 * The iterator over the Text that we use as we simultaneously
1245 * iterate over the nsTextFrames.
1247 TextNodeIterator mNodeIterator;
1250 * The previous Text we iterated over.
1252 Text* mPreviousNode;
1255 * The index into the current Text's character content.
1257 uint32_t mNodeCharIndex;
1260 /* static */
1261 void TextNodeCorrespondenceRecorder::RecordCorrespondence(SVGTextFrame* aRoot) {
1262 if (aRoot->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)) {
1263 // Resolve bidi so that continuation frames are created if necessary:
1264 aRoot->MaybeResolveBidiForAnonymousBlockChild();
1265 TextNodeCorrespondenceRecorder recorder(aRoot);
1266 recorder.Record(aRoot);
1267 aRoot->RemoveStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
1271 void TextNodeCorrespondenceRecorder::Record(SVGTextFrame* aRoot) {
1272 if (!mNodeIterator.Current()) {
1273 // If there are no Text nodes then there is nothing to do.
1274 return;
1277 // Traverse over all the nsTextFrames and record the number of undisplayed
1278 // characters.
1279 TraverseAndRecord(aRoot);
1281 // Find how many undisplayed characters there are after the final nsTextFrame.
1282 uint32_t undisplayed = 0;
1283 if (mNodeIterator.Current()) {
1284 if (mPreviousNode && mPreviousNode->TextLength() != mNodeCharIndex) {
1285 // The last nsTextFrame ended part way through a Text node. The
1286 // remaining characters count as undisplayed.
1287 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1288 "incorrect tracking of undisplayed characters in "
1289 "text nodes");
1290 undisplayed += mPreviousNode->TextLength() - mNodeCharIndex;
1292 // All the remaining Text that we iterate must also be undisplayed.
1293 for (Text* textNode = mNodeIterator.Current(); textNode;
1294 textNode = NextNode()) {
1295 undisplayed += textNode->TextLength();
1299 // Record the trailing number of undisplayed characters on the
1300 // SVGTextFrame.
1301 aRoot->mTrailingUndisplayedCharacters = undisplayed;
1304 Text* TextNodeCorrespondenceRecorder::NextNode() {
1305 mPreviousNode = mNodeIterator.Current();
1306 Text* next;
1307 do {
1308 next = mNodeIterator.Next();
1309 } while (next && next->TextLength() == 0);
1310 return next;
1313 void TextNodeCorrespondenceRecorder::TraverseAndRecord(nsIFrame* aFrame) {
1314 // Recursively iterate over the frame tree, for frames that correspond
1315 // to text content elements.
1316 if (IsTextContentElement(aFrame->GetContent())) {
1317 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1318 TraverseAndRecord(f);
1320 return;
1323 nsTextFrame* frame; // The current text frame.
1324 Text* node; // The text node for the current text frame.
1325 if (!GetNonEmptyTextFrameAndNode(aFrame, frame, node)) {
1326 // If this isn't an nsTextFrame, or is empty, nothing to do.
1327 return;
1330 NS_ASSERTION(frame->GetContentOffset() >= 0,
1331 "don't know how to handle negative content indexes");
1333 uint32_t undisplayed = 0;
1334 if (!mPreviousNode) {
1335 // Must be the very first text frame.
1336 NS_ASSERTION(mNodeCharIndex == 0,
1337 "incorrect tracking of undisplayed "
1338 "characters in text nodes");
1339 if (!mNodeIterator.Current()) {
1340 MOZ_ASSERT_UNREACHABLE(
1341 "incorrect tracking of correspondence between "
1342 "text frames and text nodes");
1343 } else {
1344 // Each whole Text we find before we get to the text node for the
1345 // first text frame must be undisplayed.
1346 while (mNodeIterator.Current() != node) {
1347 undisplayed += mNodeIterator.Current()->TextLength();
1348 NextNode();
1350 // If the first text frame starts at a non-zero content offset, then those
1351 // earlier characters are also undisplayed.
1352 undisplayed += frame->GetContentOffset();
1353 NextNode();
1355 } else if (mPreviousNode == node) {
1356 // Same text node as last time.
1357 if (static_cast<uint32_t>(frame->GetContentOffset()) != mNodeCharIndex) {
1358 // We have some characters in the middle of the text node
1359 // that are undisplayed.
1360 NS_ASSERTION(
1361 mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset()),
1362 "incorrect tracking of undisplayed characters in "
1363 "text nodes");
1364 undisplayed = frame->GetContentOffset() - mNodeCharIndex;
1366 } else {
1367 // Different text node from last time.
1368 if (mPreviousNode->TextLength() != mNodeCharIndex) {
1369 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1370 "incorrect tracking of undisplayed characters in "
1371 "text nodes");
1372 // Any trailing characters at the end of the previous Text are
1373 // undisplayed.
1374 undisplayed = mPreviousNode->TextLength() - mNodeCharIndex;
1376 // Each whole Text we find before we get to the text node for
1377 // the current text frame must be undisplayed.
1378 while (mNodeIterator.Current() && mNodeIterator.Current() != node) {
1379 undisplayed += mNodeIterator.Current()->TextLength();
1380 NextNode();
1382 // If the current text frame starts at a non-zero content offset, then those
1383 // earlier characters are also undisplayed.
1384 undisplayed += frame->GetContentOffset();
1385 NextNode();
1388 // Set the frame property.
1389 frame->SetProperty(TextNodeCorrespondenceProperty(),
1390 new TextNodeCorrespondence(undisplayed));
1392 // Remember how far into the current Text we are.
1393 mNodeCharIndex = frame->GetContentEnd();
1396 // ----------------------------------------------------------------------------
1397 // TextFrameIterator
1400 * An iterator class for nsTextFrames that are descendants of an
1401 * SVGTextFrame. The iterator can optionally track whether the
1402 * current nsTextFrame is for a descendant of, or past, a given subtree
1403 * content node or frame. (This functionality is used for example by the SVG
1404 * DOM text methods to get only the nsTextFrames for a particular <tspan>.)
1406 * TextFrameIterator also tracks and exposes other information about the
1407 * current nsTextFrame:
1409 * * how many undisplayed characters came just before it
1410 * * its position (in app units) relative to the SVGTextFrame's anonymous
1411 * block frame
1412 * * what nsInlineFrame corresponding to a <textPath> element it is a
1413 * descendant of
1414 * * what computed dominant-baseline value applies to it
1416 * Note that any text frames that are empty -- whose ContentLength() is 0 --
1417 * will be skipped over.
1419 class MOZ_STACK_CLASS TextFrameIterator {
1420 public:
1422 * Constructs a TextFrameIterator for the specified SVGTextFrame
1423 * with an optional frame subtree to restrict iterated text frames to.
1425 explicit TextFrameIterator(SVGTextFrame* aRoot,
1426 const nsIFrame* aSubtree = nullptr)
1427 : mRootFrame(aRoot),
1428 mSubtree(aSubtree),
1429 mCurrentFrame(aRoot),
1430 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1431 Init();
1435 * Constructs a TextFrameIterator for the specified SVGTextFrame
1436 * with an optional frame content subtree to restrict iterated text frames to.
1438 TextFrameIterator(SVGTextFrame* aRoot, nsIContent* aSubtree)
1439 : mRootFrame(aRoot),
1440 mSubtree(aRoot && aSubtree && aSubtree != aRoot->GetContent()
1441 ? aSubtree->GetPrimaryFrame()
1442 : nullptr),
1443 mCurrentFrame(aRoot),
1444 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1445 Init();
1449 * Returns the root SVGTextFrame this TextFrameIterator is iterating over.
1451 SVGTextFrame* Root() const { return mRootFrame; }
1454 * Returns the current nsTextFrame.
1456 nsTextFrame* Current() const { return do_QueryFrame(mCurrentFrame); }
1459 * Returns the number of undisplayed characters in the DOM just before the
1460 * current frame.
1462 uint32_t UndisplayedCharacters() const;
1465 * Returns the current frame's position, in app units, relative to the
1466 * root SVGTextFrame's anonymous block frame.
1468 nsPoint Position() const { return mCurrentPosition; }
1471 * Advances to the next nsTextFrame and returns it.
1473 nsTextFrame* Next();
1476 * Returns whether the iterator is within the subtree.
1478 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1481 * Returns whether the iterator is past the subtree.
1483 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1486 * Returns the frame corresponding to the <textPath> element, if we
1487 * are inside one.
1489 nsIFrame* TextPathFrame() const {
1490 return mTextPathFrames.IsEmpty() ? nullptr : mTextPathFrames.LastElement();
1494 * Returns the current frame's computed dominant-baseline value.
1496 StyleDominantBaseline DominantBaseline() const {
1497 return mBaselines.LastElement();
1501 * Finishes the iterator.
1503 void Close() { mCurrentFrame = nullptr; }
1505 private:
1507 * Initializes the iterator and advances to the first item.
1509 void Init() {
1510 if (!mRootFrame) {
1511 return;
1514 mBaselines.AppendElement(mRootFrame->StyleSVG()->mDominantBaseline);
1515 Next();
1519 * Pushes the specified frame's computed dominant-baseline value.
1520 * If the value of the property is "auto", then the parent frame's
1521 * computed value is used.
1523 void PushBaseline(nsIFrame* aNextFrame);
1526 * Pops the current dominant-baseline off the stack.
1528 void PopBaseline();
1531 * The root frame we are iterating through.
1533 SVGTextFrame* const mRootFrame;
1536 * The frame for the subtree we are also interested in tracking.
1538 const nsIFrame* const mSubtree;
1541 * The current value of the iterator.
1543 nsIFrame* mCurrentFrame;
1546 * The position, in app units, of the current frame relative to mRootFrame.
1548 nsPoint mCurrentPosition;
1551 * Stack of frames corresponding to <textPath> elements that are in scope
1552 * for the current frame.
1554 AutoTArray<nsIFrame*, 1> mTextPathFrames;
1557 * Stack of dominant-baseline values to record as we traverse through the
1558 * frame tree.
1560 AutoTArray<StyleDominantBaseline, 8> mBaselines;
1563 * The iterator's current position relative to mSubtree.
1565 SubtreePosition mSubtreePosition;
1568 uint32_t TextFrameIterator::UndisplayedCharacters() const {
1569 MOZ_ASSERT(
1570 !mRootFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY),
1571 "Text correspondence must be up to date");
1573 if (!mCurrentFrame) {
1574 return mRootFrame->mTrailingUndisplayedCharacters;
1577 nsTextFrame* frame = do_QueryFrame(mCurrentFrame);
1578 return GetUndisplayedCharactersBeforeFrame(frame);
1581 nsTextFrame* TextFrameIterator::Next() {
1582 // Starting from mCurrentFrame, we do a non-recursive traversal to the next
1583 // nsTextFrame beneath mRoot, updating mSubtreePosition appropriately if we
1584 // encounter mSubtree.
1585 if (mCurrentFrame) {
1586 do {
1587 nsIFrame* next = IsTextContentElement(mCurrentFrame->GetContent())
1588 ? mCurrentFrame->PrincipalChildList().FirstChild()
1589 : nullptr;
1590 if (next) {
1591 // Descend into this frame, and accumulate its position.
1592 mCurrentPosition += next->GetPosition();
1593 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1594 // Record this <textPath> frame.
1595 mTextPathFrames.AppendElement(next);
1597 // Record the frame's baseline.
1598 PushBaseline(next);
1599 mCurrentFrame = next;
1600 if (mCurrentFrame == mSubtree) {
1601 // If the current frame is mSubtree, we have now moved into it.
1602 mSubtreePosition = eWithinSubtree;
1604 } else {
1605 for (;;) {
1606 // We want to move past the current frame.
1607 if (mCurrentFrame == mRootFrame) {
1608 // If we've reached the root frame, we're finished.
1609 mCurrentFrame = nullptr;
1610 break;
1612 // Remove the current frame's position.
1613 mCurrentPosition -= mCurrentFrame->GetPosition();
1614 if (mCurrentFrame->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1615 // Pop off the <textPath> frame if this is a <textPath>.
1616 mTextPathFrames.RemoveLastElement();
1618 // Pop off the current baseline.
1619 PopBaseline();
1620 if (mCurrentFrame == mSubtree) {
1621 // If this was mSubtree, we have now moved past it.
1622 mSubtreePosition = eAfterSubtree;
1624 next = mCurrentFrame->GetNextSibling();
1625 if (next) {
1626 // Moving to the next sibling.
1627 mCurrentPosition += next->GetPosition();
1628 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1629 // Record this <textPath> frame.
1630 mTextPathFrames.AppendElement(next);
1632 // Record the frame's baseline.
1633 PushBaseline(next);
1634 mCurrentFrame = next;
1635 if (mCurrentFrame == mSubtree) {
1636 // If the current frame is mSubtree, we have now moved into it.
1637 mSubtreePosition = eWithinSubtree;
1639 break;
1641 if (mCurrentFrame == mSubtree) {
1642 // If there is no next sibling frame, and the current frame is
1643 // mSubtree, we have now moved past it.
1644 mSubtreePosition = eAfterSubtree;
1646 // Ascend out of this frame.
1647 mCurrentFrame = mCurrentFrame->GetParent();
1650 } while (mCurrentFrame && !IsNonEmptyTextFrame(mCurrentFrame));
1653 return Current();
1656 void TextFrameIterator::PushBaseline(nsIFrame* aNextFrame) {
1657 StyleDominantBaseline baseline = aNextFrame->StyleSVG()->mDominantBaseline;
1658 mBaselines.AppendElement(baseline);
1661 void TextFrameIterator::PopBaseline() {
1662 NS_ASSERTION(!mBaselines.IsEmpty(), "popped too many baselines");
1663 mBaselines.RemoveLastElement();
1666 // -----------------------------------------------------------------------------
1667 // TextRenderedRunIterator
1670 * Iterator for TextRenderedRun objects for the SVGTextFrame.
1672 class TextRenderedRunIterator {
1673 public:
1675 * Values for the aFilter argument of the constructor, to indicate which
1676 * frames we should be limited to iterating TextRenderedRun objects for.
1678 enum RenderedRunFilter {
1679 // Iterate TextRenderedRuns for all nsTextFrames.
1680 eAllFrames,
1681 // Iterate only TextRenderedRuns for nsTextFrames that are
1682 // visibility:visible.
1683 eVisibleFrames
1687 * Constructs a TextRenderedRunIterator with an optional frame subtree to
1688 * restrict iterated rendered runs to.
1690 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1691 * through.
1692 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1693 * nsTextFrames.
1694 * @param aSubtree An optional frame subtree to restrict iterated rendered
1695 * runs to.
1697 explicit TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1698 RenderedRunFilter aFilter = eAllFrames,
1699 const nsIFrame* aSubtree = nullptr)
1700 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1701 mFilter(aFilter),
1702 mTextElementCharIndex(0),
1703 mFrameStartTextElementCharIndex(0),
1704 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1705 mCurrent(First()) {}
1708 * Constructs a TextRenderedRunIterator with a content subtree to restrict
1709 * iterated rendered runs to.
1711 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1712 * through.
1713 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1714 * nsTextFrames.
1715 * @param aSubtree A content subtree to restrict iterated rendered runs to.
1717 TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1718 RenderedRunFilter aFilter, nsIContent* aSubtree)
1719 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1720 mFilter(aFilter),
1721 mTextElementCharIndex(0),
1722 mFrameStartTextElementCharIndex(0),
1723 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1724 mCurrent(First()) {}
1727 * Returns the current TextRenderedRun.
1729 TextRenderedRun Current() const { return mCurrent; }
1732 * Advances to the next TextRenderedRun and returns it.
1734 TextRenderedRun Next();
1736 private:
1738 * Returns the root SVGTextFrame this iterator is for.
1740 SVGTextFrame* Root() const { return mFrameIterator.Root(); }
1743 * Advances to the first TextRenderedRun and returns it.
1745 TextRenderedRun First();
1748 * The frame iterator to use.
1750 TextFrameIterator mFrameIterator;
1753 * The filter indicating which TextRenderedRuns to return.
1755 RenderedRunFilter mFilter;
1758 * The character index across the entire <text> element we are currently
1759 * up to.
1761 uint32_t mTextElementCharIndex;
1764 * The character index across the entire <text> for the start of the current
1765 * frame.
1767 uint32_t mFrameStartTextElementCharIndex;
1770 * The font-size scale factor we used when constructing the nsTextFrames.
1772 double mFontSizeScaleFactor;
1775 * The current TextRenderedRun.
1777 TextRenderedRun mCurrent;
1780 TextRenderedRun TextRenderedRunIterator::Next() {
1781 if (!mFrameIterator.Current()) {
1782 // If there are no more frames, then there are no more rendered runs to
1783 // return.
1784 mCurrent = TextRenderedRun();
1785 return mCurrent;
1788 // The values we will use to initialize the TextRenderedRun with.
1789 nsTextFrame* frame;
1790 gfxPoint pt;
1791 double rotate;
1792 nscoord baseline;
1793 uint32_t offset, length;
1794 uint32_t charIndex;
1796 // We loop, because we want to skip over rendered runs that either aren't
1797 // within our subtree of interest, because they don't match the filter,
1798 // or because they are hidden due to having fallen off the end of a
1799 // <textPath>.
1800 for (;;) {
1801 if (mFrameIterator.IsAfterSubtree()) {
1802 mCurrent = TextRenderedRun();
1803 return mCurrent;
1806 frame = mFrameIterator.Current();
1808 charIndex = mTextElementCharIndex;
1810 // Find the end of the rendered run, by looking through the
1811 // SVGTextFrame's positions array until we find one that is recorded
1812 // as a run boundary.
1813 uint32_t runStart,
1814 runEnd; // XXX Replace runStart with mTextElementCharIndex.
1815 runStart = mTextElementCharIndex;
1816 runEnd = runStart + 1;
1817 while (runEnd < Root()->mPositions.Length() &&
1818 !Root()->mPositions[runEnd].mRunBoundary) {
1819 runEnd++;
1822 // Convert the global run start/end indexes into an offset/length into the
1823 // current frame's Text.
1824 offset =
1825 frame->GetContentOffset() + runStart - mFrameStartTextElementCharIndex;
1826 length = runEnd - runStart;
1828 // If the end of the frame's content comes before the run boundary we found
1829 // in SVGTextFrame's position array, we need to shorten the rendered run.
1830 uint32_t contentEnd = frame->GetContentEnd();
1831 if (offset + length > contentEnd) {
1832 length = contentEnd - offset;
1835 NS_ASSERTION(offset >= uint32_t(frame->GetContentOffset()),
1836 "invalid offset");
1837 NS_ASSERTION(offset + length <= contentEnd, "invalid offset or length");
1839 // Get the frame's baseline position.
1840 frame->EnsureTextRun(nsTextFrame::eInflated);
1841 baseline = GetBaselinePosition(
1842 frame, frame->GetTextRun(nsTextFrame::eInflated),
1843 mFrameIterator.DominantBaseline(), mFontSizeScaleFactor);
1845 // Trim the offset/length to remove any leading/trailing white space.
1846 uint32_t untrimmedOffset = offset;
1847 uint32_t untrimmedLength = length;
1848 nsTextFrame::TrimmedOffsets trimmedOffsets =
1849 frame->GetTrimmedOffsets(frame->TextFragment());
1850 TrimOffsets(offset, length, trimmedOffsets);
1851 charIndex += offset - untrimmedOffset;
1853 // Get the position and rotation of the character that begins this
1854 // rendered run.
1855 pt = Root()->mPositions[charIndex].mPosition;
1856 rotate = Root()->mPositions[charIndex].mAngle;
1858 // Determine if we should skip this rendered run.
1859 bool skip = !mFrameIterator.IsWithinSubtree() ||
1860 Root()->mPositions[mTextElementCharIndex].mHidden;
1861 if (mFilter == eVisibleFrames) {
1862 skip = skip || !frame->StyleVisibility()->IsVisible();
1865 // Update our global character index to move past the characters
1866 // corresponding to this rendered run.
1867 mTextElementCharIndex += untrimmedLength;
1869 // If we have moved past the end of the current frame's content, we need to
1870 // advance to the next frame.
1871 if (offset + untrimmedLength >= contentEnd) {
1872 mFrameIterator.Next();
1873 mTextElementCharIndex += mFrameIterator.UndisplayedCharacters();
1874 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1877 if (!mFrameIterator.Current()) {
1878 if (skip) {
1879 // That was the last frame, and we skipped this rendered run. So we
1880 // have no rendered run to return.
1881 mCurrent = TextRenderedRun();
1882 return mCurrent;
1884 break;
1887 if (length && !skip) {
1888 // Only return a rendered run if it didn't get collapsed away entirely
1889 // (due to it being all white space) and if we don't want to skip it.
1890 break;
1894 mCurrent = TextRenderedRun(frame, pt, Root()->mLengthAdjustScaleFactor,
1895 rotate, mFontSizeScaleFactor, baseline, offset,
1896 length, charIndex);
1897 return mCurrent;
1900 TextRenderedRun TextRenderedRunIterator::First() {
1901 if (!mFrameIterator.Current()) {
1902 return TextRenderedRun();
1905 if (Root()->mPositions.IsEmpty()) {
1906 mFrameIterator.Close();
1907 return TextRenderedRun();
1910 // Get the character index for the start of this rendered run, by skipping
1911 // any undisplayed characters.
1912 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
1913 mFrameStartTextElementCharIndex = mTextElementCharIndex;
1915 return Next();
1918 // -----------------------------------------------------------------------------
1919 // CharIterator
1922 * Iterator for characters within an SVGTextFrame.
1924 class MOZ_STACK_CLASS CharIterator {
1925 using Range = gfxTextRun::Range;
1927 public:
1929 * Values for the aFilter argument of the constructor, to indicate which
1930 * characters we should be iterating over.
1932 enum CharacterFilter {
1933 // Iterate over all original characters from the DOM that are within valid
1934 // text content elements.
1935 eOriginal,
1936 // Iterate only over characters that are not skipped characters.
1937 eUnskipped,
1938 // Iterate only over characters that are addressable by the positioning
1939 // attributes x="", y="", etc. This includes all characters after
1940 // collapsing white space as required by the value of 'white-space'.
1941 eAddressable,
1945 * Constructs a CharIterator.
1947 * @param aSVGTextFrame The SVGTextFrame whose characters to iterate
1948 * through.
1949 * @param aFilter Indicates which characters to iterate over.
1950 * @param aSubtree A content subtree to track whether the current character
1951 * is within.
1953 CharIterator(SVGTextFrame* aSVGTextFrame, CharacterFilter aFilter,
1954 nsIContent* aSubtree, bool aPostReflow = true);
1957 * Returns whether the iterator is finished.
1959 bool AtEnd() const { return !mFrameIterator.Current(); }
1962 * Advances to the next matching character. Returns true if there was a
1963 * character to advance to, and false otherwise.
1965 bool Next();
1968 * Advances ahead aCount matching characters. Returns true if there were
1969 * enough characters to advance past, and false otherwise.
1971 bool Next(uint32_t aCount);
1974 * Advances ahead up to aCount matching characters.
1976 void NextWithinSubtree(uint32_t aCount);
1979 * Advances to the character with the specified index. The index is in the
1980 * space of original characters (i.e., all DOM characters under the <text>
1981 * that are within valid text content elements).
1983 bool AdvanceToCharacter(uint32_t aTextElementCharIndex);
1986 * Advances to the first matching character after the current nsTextFrame.
1988 bool AdvancePastCurrentFrame();
1991 * Advances to the first matching character after the frames within
1992 * the current <textPath>.
1994 bool AdvancePastCurrentTextPathFrame();
1997 * Advances to the first matching character of the subtree. Returns true
1998 * if we successfully advance to the subtree, or if we are already within
1999 * the subtree. Returns false if we are past the subtree.
2001 bool AdvanceToSubtree();
2004 * Returns the nsTextFrame for the current character.
2006 nsTextFrame* TextFrame() const { return mFrameIterator.Current(); }
2009 * Returns whether the iterator is within the subtree.
2011 bool IsWithinSubtree() const { return mFrameIterator.IsWithinSubtree(); }
2014 * Returns whether the iterator is past the subtree.
2016 bool IsAfterSubtree() const { return mFrameIterator.IsAfterSubtree(); }
2019 * Returns whether the current character is a skipped character.
2021 bool IsOriginalCharSkipped() const {
2022 return mSkipCharsIterator.IsOriginalCharSkipped();
2026 * Returns whether the current character is the start of a cluster and
2027 * ligature group.
2029 bool IsClusterAndLigatureGroupStart() const {
2030 return mTextRun->IsLigatureGroupStart(
2031 mSkipCharsIterator.GetSkippedOffset()) &&
2032 mTextRun->IsClusterStart(mSkipCharsIterator.GetSkippedOffset());
2036 * Returns the glyph run for the current character.
2038 const gfxTextRun::GlyphRun& GlyphRun() const {
2039 return *mTextRun->FindFirstGlyphRunContaining(
2040 mSkipCharsIterator.GetSkippedOffset());
2044 * Returns whether the current character is trimmed away when painting,
2045 * due to it being leading/trailing white space.
2047 bool IsOriginalCharTrimmed() const;
2050 * Returns whether the current character is unaddressable from the SVG glyph
2051 * positioning attributes.
2053 bool IsOriginalCharUnaddressable() const {
2054 return IsOriginalCharSkipped() || IsOriginalCharTrimmed();
2058 * Returns the text run for the current character.
2060 gfxTextRun* TextRun() const { return mTextRun; }
2063 * Returns the current character index.
2065 uint32_t TextElementCharIndex() const { return mTextElementCharIndex; }
2068 * Returns the character index for the start of the cluster/ligature group it
2069 * is part of.
2071 uint32_t GlyphStartTextElementCharIndex() const {
2072 return mGlyphStartTextElementCharIndex;
2076 * Gets the advance, in user units, of the current character. If the
2077 * character is a part of ligature, then the advance returned will be
2078 * a fraction of the ligature glyph's advance.
2080 * @param aContext The context to use for unit conversions.
2082 gfxFloat GetAdvance(nsPresContext* aContext) const;
2085 * Returns the frame corresponding to the <textPath> that the current
2086 * character is within.
2088 nsIFrame* TextPathFrame() const { return mFrameIterator.TextPathFrame(); }
2090 #ifdef DEBUG
2092 * Returns the subtree we were constructed with.
2094 nsIContent* GetSubtree() const { return mSubtree; }
2097 * Returns the CharacterFilter mode in use.
2099 CharacterFilter Filter() const { return mFilter; }
2100 #endif
2102 private:
2104 * Advances to the next character without checking it against the filter.
2105 * Returns true if there was a next character to advance to, or false
2106 * otherwise.
2108 bool NextCharacter();
2111 * Returns whether the current character matches the filter.
2113 bool MatchesFilter() const;
2116 * If this is the start of a glyph, record it.
2118 void UpdateGlyphStartTextElementCharIndex() {
2119 if (!IsOriginalCharSkipped() && IsClusterAndLigatureGroupStart()) {
2120 mGlyphStartTextElementCharIndex = mTextElementCharIndex;
2125 * The filter to use.
2127 CharacterFilter mFilter;
2130 * The iterator for text frames.
2132 TextFrameIterator mFrameIterator;
2134 #ifdef DEBUG
2136 * The subtree we were constructed with.
2138 nsIContent* const mSubtree;
2139 #endif
2142 * A gfxSkipCharsIterator for the text frame the current character is
2143 * a part of.
2145 gfxSkipCharsIterator mSkipCharsIterator;
2147 // Cache for information computed by IsOriginalCharTrimmed.
2148 mutable nsTextFrame* mFrameForTrimCheck;
2149 mutable uint32_t mTrimmedOffset;
2150 mutable uint32_t mTrimmedLength;
2153 * The text run the current character is a part of.
2155 gfxTextRun* mTextRun;
2158 * The current character's index.
2160 uint32_t mTextElementCharIndex;
2163 * The index of the character that starts the cluster/ligature group the
2164 * current character is a part of.
2166 uint32_t mGlyphStartTextElementCharIndex;
2169 * The scale factor to apply to glyph advances returned by
2170 * GetAdvance etc. to take into account textLength="".
2172 float mLengthAdjustScaleFactor;
2175 * Whether the instance of this class is being used after reflow has occurred
2176 * or not.
2178 bool mPostReflow;
2181 CharIterator::CharIterator(SVGTextFrame* aSVGTextFrame,
2182 CharIterator::CharacterFilter aFilter,
2183 nsIContent* aSubtree, bool aPostReflow)
2184 : mFilter(aFilter),
2185 mFrameIterator(aSVGTextFrame, aSubtree),
2186 #ifdef DEBUG
2187 mSubtree(aSubtree),
2188 #endif
2189 mFrameForTrimCheck(nullptr),
2190 mTrimmedOffset(0),
2191 mTrimmedLength(0),
2192 mTextRun(nullptr),
2193 mTextElementCharIndex(0),
2194 mGlyphStartTextElementCharIndex(0),
2195 mLengthAdjustScaleFactor(aSVGTextFrame->mLengthAdjustScaleFactor),
2196 mPostReflow(aPostReflow) {
2197 if (!AtEnd()) {
2198 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2199 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2200 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
2201 UpdateGlyphStartTextElementCharIndex();
2202 if (!MatchesFilter()) {
2203 Next();
2208 bool CharIterator::Next() {
2209 while (NextCharacter()) {
2210 if (MatchesFilter()) {
2211 return true;
2214 return false;
2217 bool CharIterator::Next(uint32_t aCount) {
2218 if (aCount == 0 && AtEnd()) {
2219 return false;
2221 while (aCount) {
2222 if (!Next()) {
2223 return false;
2225 aCount--;
2227 return true;
2230 void CharIterator::NextWithinSubtree(uint32_t aCount) {
2231 while (IsWithinSubtree() && aCount) {
2232 --aCount;
2233 if (!Next()) {
2234 return;
2239 bool CharIterator::AdvanceToCharacter(uint32_t aTextElementCharIndex) {
2240 while (mTextElementCharIndex < aTextElementCharIndex) {
2241 if (!Next()) {
2242 return false;
2245 return true;
2248 bool CharIterator::AdvancePastCurrentFrame() {
2249 // XXX Can do this better than one character at a time if it matters.
2250 nsTextFrame* currentFrame = TextFrame();
2251 do {
2252 if (!Next()) {
2253 return false;
2255 } while (TextFrame() == currentFrame);
2256 return true;
2259 bool CharIterator::AdvancePastCurrentTextPathFrame() {
2260 nsIFrame* currentTextPathFrame = TextPathFrame();
2261 NS_ASSERTION(currentTextPathFrame,
2262 "expected AdvancePastCurrentTextPathFrame to be called only "
2263 "within a text path frame");
2264 do {
2265 if (!AdvancePastCurrentFrame()) {
2266 return false;
2268 } while (TextPathFrame() == currentTextPathFrame);
2269 return true;
2272 bool CharIterator::AdvanceToSubtree() {
2273 while (!IsWithinSubtree()) {
2274 if (IsAfterSubtree()) {
2275 return false;
2277 if (!AdvancePastCurrentFrame()) {
2278 return false;
2281 return true;
2284 bool CharIterator::IsOriginalCharTrimmed() const {
2285 if (mFrameForTrimCheck != TextFrame()) {
2286 // Since we do a lot of trim checking, we cache the trimmed offsets and
2287 // lengths while we are in the same frame.
2288 mFrameForTrimCheck = TextFrame();
2289 uint32_t offset = mFrameForTrimCheck->GetContentOffset();
2290 uint32_t length = mFrameForTrimCheck->GetContentLength();
2291 nsTextFrame::TrimmedOffsets trim = mFrameForTrimCheck->GetTrimmedOffsets(
2292 mFrameForTrimCheck->TextFragment(),
2293 (mPostReflow ? nsTextFrame::TrimmedOffsetFlags::Default
2294 : nsTextFrame::TrimmedOffsetFlags::NotPostReflow));
2295 TrimOffsets(offset, length, trim);
2296 mTrimmedOffset = offset;
2297 mTrimmedLength = length;
2300 // A character is trimmed if it is outside the mTrimmedOffset/mTrimmedLength
2301 // range and it is not a significant newline character.
2302 uint32_t index = mSkipCharsIterator.GetOriginalOffset();
2303 return !(
2304 (index >= mTrimmedOffset && index < mTrimmedOffset + mTrimmedLength) ||
2305 (index >= mTrimmedOffset + mTrimmedLength &&
2306 mFrameForTrimCheck->StyleText()->NewlineIsSignificant(
2307 mFrameForTrimCheck) &&
2308 mFrameForTrimCheck->TextFragment()->CharAt(index) == '\n'));
2311 gfxFloat CharIterator::GetAdvance(nsPresContext* aContext) const {
2312 float cssPxPerDevPx =
2313 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
2315 gfxSkipCharsIterator start =
2316 TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2317 nsTextFrame::PropertyProvider provider(TextFrame(), start);
2319 uint32_t offset = mSkipCharsIterator.GetSkippedOffset();
2320 gfxFloat advance =
2321 mTextRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
2322 return aContext->AppUnitsToGfxUnits(advance) * mLengthAdjustScaleFactor *
2323 cssPxPerDevPx;
2326 bool CharIterator::NextCharacter() {
2327 if (AtEnd()) {
2328 return false;
2331 mTextElementCharIndex++;
2333 // Advance within the current text run.
2334 mSkipCharsIterator.AdvanceOriginal(1);
2335 if (mSkipCharsIterator.GetOriginalOffset() < TextFrame()->GetContentEnd()) {
2336 // We're still within the part of the text run for the current text frame.
2337 UpdateGlyphStartTextElementCharIndex();
2338 return true;
2341 // Advance to the next frame.
2342 mFrameIterator.Next();
2344 // Skip any undisplayed characters.
2345 uint32_t undisplayed = mFrameIterator.UndisplayedCharacters();
2346 mTextElementCharIndex += undisplayed;
2347 if (!TextFrame()) {
2348 // We're at the end.
2349 mSkipCharsIterator = gfxSkipCharsIterator();
2350 return false;
2353 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2354 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2355 UpdateGlyphStartTextElementCharIndex();
2356 return true;
2359 bool CharIterator::MatchesFilter() const {
2360 switch (mFilter) {
2361 case eOriginal:
2362 return true;
2363 case eUnskipped:
2364 return !IsOriginalCharSkipped();
2365 case eAddressable:
2366 return !IsOriginalCharSkipped() && !IsOriginalCharUnaddressable();
2368 MOZ_ASSERT_UNREACHABLE("Invalid mFilter value");
2369 return true;
2372 // -----------------------------------------------------------------------------
2373 // SVGTextDrawPathCallbacks
2376 * Text frame draw callback class that paints the text and text decoration parts
2377 * of an nsTextFrame using SVG painting properties, and selection backgrounds
2378 * and decorations as they would normally.
2380 * An instance of this class is passed to nsTextFrame::PaintText if painting
2381 * cannot be done directly (e.g. if we are using an SVG pattern fill, stroking
2382 * the text, etc.).
2384 class SVGTextDrawPathCallbacks final : public nsTextFrame::DrawPathCallbacks {
2385 using imgDrawingParams = image::imgDrawingParams;
2387 public:
2389 * Constructs an SVGTextDrawPathCallbacks.
2391 * @param aSVGTextFrame The ancestor text frame.
2392 * @param aContext The context to use for painting.
2393 * @param aFrame The nsTextFrame to paint.
2394 * @param aCanvasTM The transformation matrix to set when painting; this
2395 * should be the FOR_OUTERSVG_TM canvas TM of the text, so that
2396 * paint servers are painted correctly.
2397 * @param aImgParams Whether we need to synchronously decode images.
2398 * @param aShouldPaintSVGGlyphs Whether SVG glyphs should be painted.
2400 SVGTextDrawPathCallbacks(SVGTextFrame* aSVGTextFrame, gfxContext& aContext,
2401 nsTextFrame* aFrame, const gfxMatrix& aCanvasTM,
2402 imgDrawingParams& aImgParams,
2403 bool aShouldPaintSVGGlyphs)
2404 : DrawPathCallbacks(aShouldPaintSVGGlyphs),
2405 mSVGTextFrame(aSVGTextFrame),
2406 mContext(aContext),
2407 mFrame(aFrame),
2408 mCanvasTM(aCanvasTM),
2409 mImgParams(aImgParams) {}
2411 void NotifySelectionBackgroundNeedsFill(const Rect& aBackgroundRect,
2412 nscolor aColor,
2413 DrawTarget& aDrawTarget) override;
2414 void PaintDecorationLine(Rect aPath, bool aPaintingShadows,
2415 nscolor aColor) override;
2416 void PaintSelectionDecorationLine(Rect aPath, bool aPaintingShadows,
2417 nscolor aColor) override;
2418 void NotifyBeforeText(bool aPaintingShadows, nscolor aColor) override;
2419 void NotifyGlyphPathEmitted() override;
2420 void NotifyAfterText() override;
2422 private:
2423 void SetupContext();
2425 bool IsClipPathChild() const {
2426 return mSVGTextFrame->HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD);
2430 * Paints a piece of text geometry. This is called when glyphs
2431 * or text decorations have been emitted to the gfxContext.
2433 void HandleTextGeometry();
2436 * Sets the gfxContext paint to the appropriate color or pattern
2437 * for filling text geometry.
2439 void MakeFillPattern(GeneralPattern* aOutPattern);
2442 * Fills and strokes a piece of text geometry, using group opacity
2443 * if the selection style requires it.
2445 void FillAndStrokeGeometry();
2448 * Fills a piece of text geometry.
2450 void FillGeometry();
2453 * Strokes a piece of text geometry.
2455 void StrokeGeometry();
2458 * Takes a colour and modifies it to account for opacity properties.
2460 void ApplyOpacity(sRGBColor& aColor, const StyleSVGPaint& aPaint,
2461 const StyleSVGOpacity& aOpacity) const;
2463 SVGTextFrame* const mSVGTextFrame;
2464 gfxContext& mContext;
2465 nsTextFrame* const mFrame;
2466 const gfxMatrix& mCanvasTM;
2467 imgDrawingParams& mImgParams;
2470 * The color that we were last told from one of the path callback functions.
2471 * This color can be the special NS_SAME_AS_FOREGROUND_COLOR,
2472 * NS_40PERCENT_FOREGROUND_COLOR and NS_TRANSPARENT colors when we are
2473 * painting selections or IME decorations.
2475 nscolor mColor = NS_RGBA(0, 0, 0, 0);
2478 * Whether we're painting text shadows.
2480 bool mPaintingShadows = false;
2483 void SVGTextDrawPathCallbacks::NotifySelectionBackgroundNeedsFill(
2484 const Rect& aBackgroundRect, nscolor aColor, DrawTarget& aDrawTarget) {
2485 if (IsClipPathChild()) {
2486 // Don't paint selection backgrounds when in a clip path.
2487 return;
2490 mColor = aColor; // currently needed by MakeFillPattern
2491 mPaintingShadows = false;
2493 GeneralPattern fillPattern;
2494 MakeFillPattern(&fillPattern);
2495 if (fillPattern.GetPattern()) {
2496 DrawOptions drawOptions(aColor == NS_40PERCENT_FOREGROUND_COLOR ? 0.4
2497 : 1.0);
2498 aDrawTarget.FillRect(aBackgroundRect, fillPattern, drawOptions);
2502 void SVGTextDrawPathCallbacks::NotifyBeforeText(bool aPaintingShadows,
2503 nscolor aColor) {
2504 mColor = aColor;
2505 mPaintingShadows = aPaintingShadows;
2506 SetupContext();
2507 mContext.NewPath();
2510 void SVGTextDrawPathCallbacks::NotifyGlyphPathEmitted() {
2511 HandleTextGeometry();
2512 mContext.NewPath();
2515 void SVGTextDrawPathCallbacks::NotifyAfterText() { mContext.Restore(); }
2517 void SVGTextDrawPathCallbacks::PaintDecorationLine(Rect aPath,
2518 bool aPaintingShadows,
2519 nscolor aColor) {
2520 mColor = aColor;
2521 mPaintingShadows = aPaintingShadows;
2522 AntialiasMode aaMode =
2523 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2525 mContext.Save();
2526 mContext.NewPath();
2527 mContext.SetAntialiasMode(aaMode);
2528 mContext.Rectangle(ThebesRect(aPath));
2529 HandleTextGeometry();
2530 mContext.NewPath();
2531 mContext.Restore();
2534 void SVGTextDrawPathCallbacks::PaintSelectionDecorationLine(
2535 Rect aPath, bool aPaintingShadows, nscolor aColor) {
2536 if (IsClipPathChild()) {
2537 // Don't paint selection decorations when in a clip path.
2538 return;
2541 mColor = aColor;
2542 mPaintingShadows = aPaintingShadows;
2544 mContext.Save();
2545 mContext.NewPath();
2546 mContext.Rectangle(ThebesRect(aPath));
2547 FillAndStrokeGeometry();
2548 mContext.Restore();
2551 void SVGTextDrawPathCallbacks::SetupContext() {
2552 mContext.Save();
2554 // XXX This is copied from nsSVGGlyphFrame::Render, but cairo doesn't actually
2555 // seem to do anything with the antialias mode. So we can perhaps remove it,
2556 // or make SetAntialiasMode set cairo text antialiasing too.
2557 switch (mFrame->StyleText()->mTextRendering) {
2558 case StyleTextRendering::Optimizespeed:
2559 mContext.SetAntialiasMode(AntialiasMode::NONE);
2560 break;
2561 default:
2562 mContext.SetAntialiasMode(AntialiasMode::SUBPIXEL);
2563 break;
2567 void SVGTextDrawPathCallbacks::HandleTextGeometry() {
2568 if (IsClipPathChild()) {
2569 RefPtr<Path> path = mContext.GetPath();
2570 ColorPattern white(
2571 DeviceColor(1.f, 1.f, 1.f, 1.f)); // for masking, so no ToDeviceColor
2572 mContext.GetDrawTarget()->Fill(path, white);
2573 } else {
2574 // Normal painting.
2575 gfxContextMatrixAutoSaveRestore saveMatrix(&mContext);
2576 mContext.SetMatrixDouble(mCanvasTM);
2578 FillAndStrokeGeometry();
2582 void SVGTextDrawPathCallbacks::ApplyOpacity(
2583 sRGBColor& aColor, const StyleSVGPaint& aPaint,
2584 const StyleSVGOpacity& aOpacity) const {
2585 if (aPaint.kind.tag == StyleSVGPaintKind::Tag::Color) {
2586 aColor.a *=
2587 sRGBColor::FromABGR(aPaint.kind.AsColor().CalcColor(*mFrame->Style()))
2590 aColor.a *= SVGUtils::GetOpacity(aOpacity, /*aContextPaint*/ nullptr);
2593 void SVGTextDrawPathCallbacks::MakeFillPattern(GeneralPattern* aOutPattern) {
2594 if (mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2595 mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2596 SVGUtils::MakeFillPatternFor(mFrame, &mContext, aOutPattern, mImgParams);
2597 return;
2600 if (mColor == NS_TRANSPARENT) {
2601 return;
2604 sRGBColor color(sRGBColor::FromABGR(mColor));
2605 if (mPaintingShadows) {
2606 ApplyOpacity(color, mFrame->StyleSVG()->mFill,
2607 mFrame->StyleSVG()->mFillOpacity);
2609 aOutPattern->InitColorPattern(ToDeviceColor(color));
2612 void SVGTextDrawPathCallbacks::FillAndStrokeGeometry() {
2613 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&mContext);
2614 if (mColor == NS_40PERCENT_FOREGROUND_COLOR) {
2615 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 0.4f);
2618 uint32_t paintOrder = mFrame->StyleSVG()->mPaintOrder;
2619 if (!paintOrder) {
2620 FillGeometry();
2621 StrokeGeometry();
2622 } else {
2623 while (paintOrder) {
2624 auto component = StylePaintOrder(paintOrder & kPaintOrderMask);
2625 switch (component) {
2626 case StylePaintOrder::Fill:
2627 FillGeometry();
2628 break;
2629 case StylePaintOrder::Stroke:
2630 StrokeGeometry();
2631 break;
2632 default:
2633 MOZ_FALLTHROUGH_ASSERT("Unknown paint-order value");
2634 case StylePaintOrder::Markers:
2635 case StylePaintOrder::Normal:
2636 break;
2638 paintOrder >>= kPaintOrderShift;
2643 void SVGTextDrawPathCallbacks::FillGeometry() {
2644 if (mFrame->StyleSVG()->mFill.kind.IsNone()) {
2645 return;
2647 GeneralPattern fillPattern;
2648 MakeFillPattern(&fillPattern);
2649 if (fillPattern.GetPattern()) {
2650 RefPtr<Path> path = mContext.GetPath();
2651 FillRule fillRule = SVGUtils::ToFillRule(mFrame->StyleSVG()->mFillRule);
2652 if (fillRule != path->GetFillRule()) {
2653 RefPtr<PathBuilder> builder = path->CopyToBuilder(fillRule);
2654 path = builder->Finish();
2656 mContext.GetDrawTarget()->Fill(path, fillPattern);
2660 void SVGTextDrawPathCallbacks::StrokeGeometry() {
2661 // We don't paint the stroke when we are filling with a selection color.
2662 if (!(mColor == NS_SAME_AS_FOREGROUND_COLOR ||
2663 mColor == NS_40PERCENT_FOREGROUND_COLOR || mPaintingShadows)) {
2664 return;
2667 if (!SVGUtils::HasStroke(mFrame, /*aContextPaint*/ nullptr)) {
2668 return;
2671 GeneralPattern strokePattern;
2672 if (mPaintingShadows) {
2673 sRGBColor color(sRGBColor::FromABGR(mColor));
2674 ApplyOpacity(color, mFrame->StyleSVG()->mStroke,
2675 mFrame->StyleSVG()->mStrokeOpacity);
2676 strokePattern.InitColorPattern(ToDeviceColor(color));
2677 } else {
2678 SVGUtils::MakeStrokePatternFor(mFrame, &mContext, &strokePattern,
2679 mImgParams, /*aContextPaint*/ nullptr);
2681 if (strokePattern.GetPattern()) {
2682 SVGElement* svgOwner =
2683 SVGElement::FromNode(mFrame->GetParent()->GetContent());
2685 // Apply any stroke-specific transform
2686 gfxMatrix outerSVGToUser;
2687 if (SVGUtils::GetNonScalingStrokeTransform(mFrame, &outerSVGToUser) &&
2688 outerSVGToUser.Invert()) {
2689 mContext.Multiply(outerSVGToUser);
2692 RefPtr<Path> path = mContext.GetPath();
2693 SVGContentUtils::AutoStrokeOptions strokeOptions;
2694 SVGContentUtils::GetStrokeOptions(&strokeOptions, svgOwner, mFrame->Style(),
2695 /*aContextPaint*/ nullptr);
2696 DrawOptions drawOptions;
2697 drawOptions.mAntialiasMode =
2698 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2699 mContext.GetDrawTarget()->Stroke(path, strokePattern, strokeOptions);
2703 // ============================================================================
2704 // SVGTextFrame
2706 // ----------------------------------------------------------------------------
2707 // Display list item
2709 class DisplaySVGText final : public DisplaySVGItem {
2710 public:
2711 DisplaySVGText(nsDisplayListBuilder* aBuilder, SVGTextFrame* aFrame)
2712 : DisplaySVGItem(aBuilder, aFrame) {
2713 MOZ_COUNT_CTOR(DisplaySVGText);
2716 MOZ_COUNTED_DTOR_OVERRIDE(DisplaySVGText)
2718 NS_DISPLAY_DECL_NAME("DisplaySVGText", TYPE_SVG_TEXT)
2720 nsDisplayItemGeometry* AllocateGeometry(
2721 nsDisplayListBuilder* aBuilder) override {
2722 return new nsDisplayItemGenericGeometry(this, aBuilder);
2725 nsRect GetComponentAlphaBounds(
2726 nsDisplayListBuilder* aBuilder) const override {
2727 bool snap;
2728 return GetBounds(aBuilder, &snap);
2732 // ---------------------------------------------------------------------
2733 // nsQueryFrame methods
2735 NS_QUERYFRAME_HEAD(SVGTextFrame)
2736 NS_QUERYFRAME_ENTRY(SVGTextFrame)
2737 NS_QUERYFRAME_TAIL_INHERITING(SVGDisplayContainerFrame)
2739 } // namespace mozilla
2741 // ---------------------------------------------------------------------
2742 // Implementation
2744 nsIFrame* NS_NewSVGTextFrame(mozilla::PresShell* aPresShell,
2745 mozilla::ComputedStyle* aStyle) {
2746 return new (aPresShell)
2747 mozilla::SVGTextFrame(aStyle, aPresShell->GetPresContext());
2750 namespace mozilla {
2752 NS_IMPL_FRAMEARENA_HELPERS(SVGTextFrame)
2754 // ---------------------------------------------------------------------
2755 // nsIFrame methods
2757 void SVGTextFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
2758 nsIFrame* aPrevInFlow) {
2759 NS_ASSERTION(aContent->IsSVGElement(nsGkAtoms::text),
2760 "Content is not an SVG text");
2762 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
2763 AddStateBits(aParent->GetStateBits() & NS_STATE_SVG_CLIPPATH_CHILD);
2765 mMutationObserver = new MutationObserver(this);
2767 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2768 // We're inserting a new <text> element into a non-display context.
2769 // Ensure that we get reflowed.
2770 ScheduleReflowSVGNonDisplayText(
2771 IntrinsicDirty::FrameAncestorsAndDescendants);
2775 void SVGTextFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
2776 const nsDisplayListSet& aLists) {
2777 if (IsSubtreeDirty()) {
2778 // We can sometimes be asked to paint before reflow happens and we
2779 // have updated mPositions, etc. In this case, we just avoid
2780 // painting.
2781 return;
2783 if (!IsVisibleForPainting() && aBuilder->IsForPainting()) {
2784 return;
2786 DisplayOutline(aBuilder, aLists);
2787 aLists.Content()->AppendNewToTop<DisplaySVGText>(aBuilder, this);
2790 nsresult SVGTextFrame::AttributeChanged(int32_t aNameSpaceID,
2791 nsAtom* aAttribute, int32_t aModType) {
2792 if (aNameSpaceID != kNameSpaceID_None) {
2793 return NS_OK;
2796 if (aAttribute == nsGkAtoms::transform) {
2797 // We don't invalidate for transform changes (the layers code does that).
2798 // Also note that SVGTransformableElement::GetAttributeChangeHint will
2799 // return nsChangeHint_UpdateOverflow for "transform" attribute changes
2800 // and cause DoApplyRenderingChangeToTree to make the SchedulePaint call.
2802 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && mCanvasTM &&
2803 mCanvasTM->IsSingular()) {
2804 // We won't have calculated the glyph positions correctly.
2805 NotifyGlyphMetricsChange(false);
2807 mCanvasTM = nullptr;
2808 } else if (IsGlyphPositioningAttribute(aAttribute) ||
2809 aAttribute == nsGkAtoms::textLength ||
2810 aAttribute == nsGkAtoms::lengthAdjust) {
2811 NotifyGlyphMetricsChange(false);
2814 return NS_OK;
2817 void SVGTextFrame::ReflowSVGNonDisplayText() {
2818 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
2819 "only call ReflowSVGNonDisplayText when an outer SVG frame is "
2820 "under ReflowSVG");
2821 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),
2822 "only call ReflowSVGNonDisplayText if the frame is "
2823 "NS_FRAME_IS_NONDISPLAY");
2825 // We had a style change, so we mark this frame as dirty so that the next
2826 // time it is painted, we reflow the anonymous block frame.
2827 this->MarkSubtreeDirty();
2829 // Finally, we need to actually reflow the anonymous block frame and update
2830 // mPositions, in case we are being reflowed immediately after a DOM
2831 // mutation that needs frame reconstruction.
2832 MaybeReflowAnonymousBlockChild();
2833 UpdateGlyphPositioning();
2836 void SVGTextFrame::ScheduleReflowSVGNonDisplayText(IntrinsicDirty aReason) {
2837 MOZ_ASSERT(!SVGUtils::OuterSVGIsCallingReflowSVG(this),
2838 "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
2839 "frame is under ReflowSVG");
2840 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW),
2841 "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
2842 "anonymous block child");
2844 // We need to find an ancestor frame that we can call FrameNeedsReflow
2845 // on that will cause the document to be marked as needing relayout,
2846 // and for that ancestor (or some further ancestor) to be marked as
2847 // a root to reflow. We choose the closest ancestor frame that is not
2848 // NS_FRAME_IS_NONDISPLAY and which is either an outer SVG frame or a
2849 // non-SVG frame. (We don't consider displayed SVG frame ancestors other
2850 // than SVGOuterSVGFrame, since calling FrameNeedsReflow on those other
2851 // SVG frames would do a bunch of unnecessary work on the SVG frames up to
2852 // the SVGOuterSVGFrame.)
2854 nsIFrame* f = this;
2855 while (f) {
2856 if (!f->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2857 if (f->IsSubtreeDirty()) {
2858 // This is a displayed frame, so if it is already dirty, we will be
2859 // reflowed soon anyway. No need to call FrameNeedsReflow again, then.
2860 return;
2862 if (!f->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
2863 break;
2865 f->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
2867 f = f->GetParent();
2870 MOZ_ASSERT(f, "should have found an ancestor frame to reflow");
2872 PresShell()->FrameNeedsReflow(f, aReason, NS_FRAME_IS_DIRTY);
2875 NS_IMPL_ISUPPORTS(SVGTextFrame::MutationObserver, nsIMutationObserver)
2877 void SVGTextFrame::MutationObserver::ContentAppended(
2878 nsIContent* aFirstNewContent) {
2879 mFrame->NotifyGlyphMetricsChange(true);
2882 void SVGTextFrame::MutationObserver::ContentInserted(nsIContent* aChild) {
2883 mFrame->NotifyGlyphMetricsChange(true);
2886 void SVGTextFrame::MutationObserver::ContentRemoved(
2887 nsIContent* aChild, nsIContent* aPreviousSibling) {
2888 mFrame->NotifyGlyphMetricsChange(true);
2891 void SVGTextFrame::MutationObserver::CharacterDataChanged(
2892 nsIContent* aContent, const CharacterDataChangeInfo&) {
2893 mFrame->NotifyGlyphMetricsChange(true);
2896 void SVGTextFrame::MutationObserver::AttributeChanged(
2897 Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
2898 int32_t aModType, const nsAttrValue* aOldValue) {
2899 if (!aElement->IsSVGElement()) {
2900 return;
2903 // Attribute changes on this element will be handled by
2904 // SVGTextFrame::AttributeChanged.
2905 if (aElement == mFrame->GetContent()) {
2906 return;
2909 mFrame->HandleAttributeChangeInDescendant(aElement, aNameSpaceID, aAttribute);
2912 void SVGTextFrame::HandleAttributeChangeInDescendant(Element* aElement,
2913 int32_t aNameSpaceID,
2914 nsAtom* aAttribute) {
2915 if (aElement->IsSVGElement(nsGkAtoms::textPath)) {
2916 if (aNameSpaceID == kNameSpaceID_None &&
2917 (aAttribute == nsGkAtoms::startOffset ||
2918 aAttribute == nsGkAtoms::path || aAttribute == nsGkAtoms::side_)) {
2919 NotifyGlyphMetricsChange(false);
2920 } else if ((aNameSpaceID == kNameSpaceID_XLink ||
2921 aNameSpaceID == kNameSpaceID_None) &&
2922 aAttribute == nsGkAtoms::href) {
2923 // Blow away our reference, if any
2924 nsIFrame* childElementFrame = aElement->GetPrimaryFrame();
2925 if (childElementFrame) {
2926 SVGObserverUtils::RemoveTextPathObserver(childElementFrame);
2927 NotifyGlyphMetricsChange(false);
2930 } else {
2931 if (aNameSpaceID == kNameSpaceID_None &&
2932 IsGlyphPositioningAttribute(aAttribute)) {
2933 NotifyGlyphMetricsChange(false);
2938 void SVGTextFrame::FindCloserFrameForSelection(
2939 const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
2940 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
2941 return;
2944 UpdateGlyphPositioning();
2946 nsPresContext* presContext = PresContext();
2948 // Find the frame that has the closest rendered run rect to aPoint.
2949 TextRenderedRunIterator it(this);
2950 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
2951 uint32_t flags = TextRenderedRun::eIncludeFill |
2952 TextRenderedRun::eIncludeStroke |
2953 TextRenderedRun::eNoHorizontalOverflow;
2954 SVGBBox userRect = run.GetUserSpaceRect(presContext, flags);
2955 float devPxPerCSSPx = presContext->CSSPixelsToDevPixels(1.f);
2956 userRect.Scale(devPxPerCSSPx);
2958 if (!userRect.IsEmpty()) {
2959 gfxMatrix m;
2960 nsRect rect =
2961 SVGUtils::ToCanvasBounds(userRect.ToThebesRect(), m, presContext);
2963 if (nsLayoutUtils::PointIsCloserToRect(aPoint, rect,
2964 aCurrentBestFrame->mXDistance,
2965 aCurrentBestFrame->mYDistance)) {
2966 aCurrentBestFrame->mFrame = run.mFrame;
2972 //----------------------------------------------------------------------
2973 // ISVGDisplayableFrame methods
2975 void SVGTextFrame::NotifySVGChanged(uint32_t aFlags) {
2976 MOZ_ASSERT(aFlags & (TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED),
2977 "Invalidation logic may need adjusting");
2979 bool needNewBounds = false;
2980 bool needGlyphMetricsUpdate = false;
2981 bool needNewCanvasTM = false;
2983 if ((aFlags & COORD_CONTEXT_CHANGED) &&
2984 HasAnyStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES)) {
2985 needGlyphMetricsUpdate = true;
2988 if (aFlags & TRANSFORM_CHANGED) {
2989 needNewCanvasTM = true;
2990 if (mCanvasTM && mCanvasTM->IsSingular()) {
2991 // We won't have calculated the glyph positions correctly.
2992 needNewBounds = true;
2993 needGlyphMetricsUpdate = true;
2995 if (StyleSVGReset()->HasNonScalingStroke()) {
2996 // Stroke currently contributes to our mRect, and our stroke depends on
2997 // the transform to our outer-<svg> if |vector-effect:non-scaling-stroke|.
2998 needNewBounds = true;
3002 // If the scale at which we computed our mFontSizeScaleFactor has changed by
3003 // at least a factor of two, reflow the text. This avoids reflowing text
3004 // at every tick of a transform animation, but ensures our glyph metrics
3005 // do not get too far out of sync with the final font size on the screen.
3006 if (needNewCanvasTM && mLastContextScale != 0.0f) {
3007 mCanvasTM = nullptr;
3008 // If we are a non-display frame, then we don't want to call
3009 // GetCanvasTM(), since the context scale does not use it.
3010 gfxMatrix newTM =
3011 HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) ? gfxMatrix() : GetCanvasTM();
3012 // Compare the old and new context scales.
3013 float scale = GetContextScale(newTM);
3014 float change = scale / mLastContextScale;
3015 if (change >= 2.0f || change <= 0.5f) {
3016 needNewBounds = true;
3017 needGlyphMetricsUpdate = true;
3021 if (needNewBounds) {
3022 // Ancestor changes can't affect how we render from the perspective of
3023 // any rendering observers that we may have, so we don't need to
3024 // invalidate them. We also don't need to invalidate ourself, since our
3025 // changed ancestor will have invalidated its entire area, which includes
3026 // our area.
3027 ScheduleReflowSVG();
3030 if (needGlyphMetricsUpdate) {
3031 // If we are positioned using percentage values we need to update our
3032 // position whenever our viewport's dimensions change. But only do this if
3033 // we have been reflowed once, otherwise the glyph positioning will be
3034 // wrong. (We need to wait until bidi reordering has been done.)
3035 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
3036 NotifyGlyphMetricsChange(false);
3042 * Gets the offset into a DOM node that the specified caret is positioned at.
3044 static int32_t GetCaretOffset(nsCaret* aCaret) {
3045 RefPtr<Selection> selection = aCaret->GetSelection();
3046 if (!selection) {
3047 return -1;
3050 return selection->AnchorOffset();
3054 * Returns whether the caret should be painted for a given TextRenderedRun
3055 * by checking whether the caret is in the range covered by the rendered run.
3057 * @param aThisRun The TextRenderedRun to be painted.
3058 * @param aCaret The caret.
3060 static bool ShouldPaintCaret(const TextRenderedRun& aThisRun, nsCaret* aCaret) {
3061 int32_t caretOffset = GetCaretOffset(aCaret);
3063 if (caretOffset < 0) {
3064 return false;
3067 return uint32_t(caretOffset) >= aThisRun.mTextFrameContentOffset &&
3068 uint32_t(caretOffset) < aThisRun.mTextFrameContentOffset +
3069 aThisRun.mTextFrameContentLength;
3072 void SVGTextFrame::PaintSVG(gfxContext& aContext, const gfxMatrix& aTransform,
3073 imgDrawingParams& aImgParams) {
3074 DrawTarget& aDrawTarget = *aContext.GetDrawTarget();
3075 nsIFrame* kid = PrincipalChildList().FirstChild();
3076 if (!kid) {
3077 return;
3080 nsPresContext* presContext = PresContext();
3082 gfxMatrix initialMatrix = aContext.CurrentMatrixDouble();
3084 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3085 // If we are in a canvas DrawWindow call that used the
3086 // DRAWWINDOW_DO_NOT_FLUSH flag, then we may still have out
3087 // of date frames. Just don't paint anything if they are
3088 // dirty.
3089 if (presContext->PresShell()->InDrawWindowNotFlushing() &&
3090 IsSubtreeDirty()) {
3091 return;
3093 // Text frames inside <clipPath>, <mask>, etc. will never have had
3094 // ReflowSVG called on them, so call UpdateGlyphPositioning to do this now.
3095 UpdateGlyphPositioning();
3096 } else if (IsSubtreeDirty()) {
3097 // If we are asked to paint before reflow has recomputed mPositions etc.
3098 // directly via PaintSVG, rather than via a display list, then we need
3099 // to bail out here too.
3100 return;
3103 const float epsilon = 0.0001;
3104 if (abs(mLengthAdjustScaleFactor) < epsilon) {
3105 // A zero scale factor can be caused by having forced the text length to
3106 // zero. In this situation there is nothing to show.
3107 return;
3110 if (aTransform.IsSingular()) {
3111 NS_WARNING("Can't render text element!");
3112 return;
3115 gfxMatrix matrixForPaintServers = aTransform * initialMatrix;
3117 // SVG frames' PaintSVG methods paint in CSS px, but normally frames paint in
3118 // dev pixels. Here we multiply a CSS-px-to-dev-pixel factor onto aTransform
3119 // so our non-SVG nsTextFrame children paint correctly.
3120 auto auPerDevPx = presContext->AppUnitsPerDevPixel();
3121 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(auPerDevPx);
3122 gfxMatrix canvasTMForChildren = aTransform;
3123 canvasTMForChildren.PreScale(cssPxPerDevPx, cssPxPerDevPx);
3124 initialMatrix.PreScale(1 / cssPxPerDevPx, 1 / cssPxPerDevPx);
3126 gfxContextMatrixAutoSaveRestore matSR(&aContext);
3127 aContext.NewPath();
3128 aContext.Multiply(canvasTMForChildren);
3129 gfxMatrix currentMatrix = aContext.CurrentMatrixDouble();
3131 RefPtr<nsCaret> caret = presContext->PresShell()->GetCaret();
3132 nsRect caretRect;
3133 nsIFrame* caretFrame = caret->GetPaintGeometry(&caretRect);
3135 gfxContextAutoSaveRestore ctxSR;
3136 TextRenderedRunIterator it(this, TextRenderedRunIterator::eVisibleFrames);
3137 TextRenderedRun run = it.Current();
3139 SVGContextPaint* outerContextPaint =
3140 SVGContextPaint::GetContextPaint(GetContent());
3142 while (run.mFrame) {
3143 nsTextFrame* frame = run.mFrame;
3145 RefPtr<SVGContextPaintImpl> contextPaint = new SVGContextPaintImpl();
3146 DrawMode drawMode = contextPaint->Init(&aDrawTarget, initialMatrix, frame,
3147 outerContextPaint, aImgParams);
3148 if (drawMode & DrawMode::GLYPH_STROKE) {
3149 ctxSR.EnsureSaved(&aContext);
3150 // This may change the gfxContext's transform (for non-scaling stroke),
3151 // in which case this needs to happen before we call SetMatrix() below.
3152 SVGUtils::SetupStrokeGeometry(frame->GetParent(), &aContext,
3153 outerContextPaint);
3156 nscoord startEdge, endEdge;
3157 run.GetClipEdges(startEdge, endEdge);
3159 // Set up the transform for painting the text frame for the substring
3160 // indicated by the run.
3161 gfxMatrix runTransform = run.GetTransformFromUserSpaceForPainting(
3162 presContext, startEdge, endEdge) *
3163 currentMatrix;
3164 aContext.SetMatrixDouble(runTransform);
3166 if (drawMode != DrawMode(0)) {
3167 bool paintSVGGlyphs;
3168 nsTextFrame::PaintTextParams params(&aContext);
3169 params.framePt = Point();
3170 params.dirtyRect =
3171 LayoutDevicePixel::FromAppUnits(frame->InkOverflowRect(), auPerDevPx);
3172 params.contextPaint = contextPaint;
3173 bool isSelected;
3174 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
3175 params.state = nsTextFrame::PaintTextParams::GenerateTextMask;
3176 isSelected = false;
3177 } else {
3178 isSelected = frame->IsSelected();
3180 gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&aContext);
3181 float opacity = 1.0f;
3182 nsIFrame* ancestor = frame->GetParent();
3183 while (ancestor != this) {
3184 opacity *= ancestor->StyleEffects()->mOpacity;
3185 ancestor = ancestor->GetParent();
3187 if (opacity < 1.0f) {
3188 autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA,
3189 opacity);
3192 if (ShouldRenderAsPath(frame, paintSVGGlyphs)) {
3193 SVGTextDrawPathCallbacks callbacks(this, aContext, frame,
3194 matrixForPaintServers, aImgParams,
3195 paintSVGGlyphs);
3196 params.callbacks = &callbacks;
3197 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3198 } else {
3199 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3203 if (frame == caretFrame && ShouldPaintCaret(run, caret)) {
3204 // XXX Should we be looking at the fill/stroke colours to paint the
3205 // caret with, rather than using the color property?
3206 caret->PaintCaret(aDrawTarget, frame, nsPoint());
3207 aContext.NewPath();
3210 run = it.Next();
3214 nsIFrame* SVGTextFrame::GetFrameForPoint(const gfxPoint& aPoint) {
3215 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3217 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
3218 // Text frames inside <clipPath> will never have had ReflowSVG called on
3219 // them, so call UpdateGlyphPositioning to do this now. (Text frames
3220 // inside <mask> and other non-display containers will never need to
3221 // be hit tested.)
3222 UpdateGlyphPositioning();
3223 } else {
3224 NS_ASSERTION(!IsSubtreeDirty(), "reflow should have happened");
3227 // Hit-testing any clip-path will typically be a lot quicker than the
3228 // hit-testing of our text frames in the loop below, so we do the former up
3229 // front to avoid unnecessarily wasting cycles on the latter.
3230 if (!SVGUtils::HitTestClip(this, aPoint)) {
3231 return nullptr;
3234 nsPresContext* presContext = PresContext();
3236 // Ideally we'd iterate backwards so that we can just return the first frame
3237 // that is under aPoint. In practice this will rarely matter though since it
3238 // is rare for text in/under an SVG <text> element to overlap (i.e. the first
3239 // text frame that is hit will likely be the only text frame that is hit).
3241 TextRenderedRunIterator it(this);
3242 nsIFrame* hit = nullptr;
3243 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3244 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3245 if (!hitTestFlags) {
3246 continue;
3249 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
3250 if (!m.Invert()) {
3251 return nullptr;
3254 gfxPoint pointInRunUserSpace = m.TransformPoint(aPoint);
3255 gfxRect frameRect = run.GetRunUserSpaceRect(
3256 presContext, TextRenderedRun::eIncludeFill |
3257 TextRenderedRun::eIncludeStroke)
3258 .ToThebesRect();
3260 if (Inside(frameRect, pointInRunUserSpace)) {
3261 hit = run.mFrame;
3264 return hit;
3267 void SVGTextFrame::ReflowSVG() {
3268 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
3269 "This call is probaby a wasteful mistake");
3271 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY),
3272 "ReflowSVG mechanism not designed for this");
3274 if (!SVGUtils::NeedsReflowSVG(this)) {
3275 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |
3276 NS_STATE_SVG_POSITIONING_DIRTY),
3277 "How did this happen?");
3278 return;
3281 MaybeReflowAnonymousBlockChild();
3282 UpdateGlyphPositioning();
3284 nsPresContext* presContext = PresContext();
3286 SVGBBox r;
3287 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames);
3288 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3289 uint32_t runFlags = 0;
3290 if (!run.mFrame->StyleSVG()->mFill.kind.IsNone()) {
3291 runFlags |= TextRenderedRun::eIncludeFill;
3293 if (SVGUtils::HasStroke(run.mFrame)) {
3294 runFlags |= TextRenderedRun::eIncludeStroke;
3296 // Our "visual" overflow rect needs to be valid for building display lists
3297 // for hit testing, which means that for certain values of 'pointer-events'
3298 // it needs to include the geometry of the fill or stroke even when the
3299 // fill/ stroke don't actually render (e.g. when stroke="none" or
3300 // stroke-opacity="0"). GetGeometryHitTestFlags accounts for
3301 // 'pointer-events'. The text-shadow is not part of the hit-test area.
3302 uint16_t hitTestFlags = SVGUtils::GetGeometryHitTestFlags(run.mFrame);
3303 if (hitTestFlags & SVG_HIT_TEST_FILL) {
3304 runFlags |= TextRenderedRun::eIncludeFill;
3306 if (hitTestFlags & SVG_HIT_TEST_STROKE) {
3307 runFlags |= TextRenderedRun::eIncludeStroke;
3310 if (runFlags) {
3311 r.UnionEdges(run.GetUserSpaceRect(presContext, runFlags));
3315 if (r.IsEmpty()) {
3316 mRect.SetEmpty();
3317 } else {
3318 mRect = nsLayoutUtils::RoundGfxRectToAppRect(r.ToThebesRect(),
3319 AppUnitsPerCSSPixel());
3321 // Due to rounding issues when we have a transform applied, we sometimes
3322 // don't include an additional row of pixels. For now, just inflate our
3323 // covered region.
3324 mRect.Inflate(ceil(presContext->AppUnitsPerDevPixel() / mLastContextScale));
3327 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
3328 // Make sure we have our filter property (if any) before calling
3329 // FinishAndStoreOverflow (subsequent filter changes are handled off
3330 // nsChangeHint_UpdateEffects):
3331 SVGObserverUtils::UpdateEffects(this);
3334 // Now unset the various reflow bits. Do this before calling
3335 // FinishAndStoreOverflow since FinishAndStoreOverflow can require glyph
3336 // positions (to resolve transform-origin).
3337 RemoveStateBits(NS_FRAME_FIRST_REFLOW | NS_FRAME_IS_DIRTY |
3338 NS_FRAME_HAS_DIRTY_CHILDREN);
3340 nsRect overflow = nsRect(nsPoint(0, 0), mRect.Size());
3341 OverflowAreas overflowAreas(overflow, overflow);
3342 FinishAndStoreOverflow(overflowAreas, mRect.Size());
3346 * Converts SVGUtils::eBBox* flags into TextRenderedRun flags appropriate
3347 * for the specified rendered run.
3349 static uint32_t TextRenderedRunFlagsForBBoxContribution(
3350 const TextRenderedRun& aRun, uint32_t aBBoxFlags) {
3351 uint32_t flags = 0;
3352 if ((aBBoxFlags & SVGUtils::eBBoxIncludeFillGeometry) ||
3353 ((aBBoxFlags & SVGUtils::eBBoxIncludeFill) &&
3354 !aRun.mFrame->StyleSVG()->mFill.kind.IsNone())) {
3355 flags |= TextRenderedRun::eIncludeFill;
3357 if ((aBBoxFlags & SVGUtils::eBBoxIncludeStrokeGeometry) ||
3358 ((aBBoxFlags & SVGUtils::eBBoxIncludeStroke) &&
3359 SVGUtils::HasStroke(aRun.mFrame))) {
3360 flags |= TextRenderedRun::eIncludeStroke;
3362 return flags;
3365 SVGBBox SVGTextFrame::GetBBoxContribution(const Matrix& aToBBoxUserspace,
3366 uint32_t aFlags) {
3367 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3368 SVGBBox bbox;
3370 if (aFlags & SVGUtils::eForGetClientRects) {
3371 Rect rect = NSRectToRect(mRect, AppUnitsPerCSSPixel());
3372 if (!rect.IsEmpty()) {
3373 bbox = aToBBoxUserspace.TransformBounds(rect);
3375 return bbox;
3378 nsIFrame* kid = PrincipalChildList().FirstChild();
3379 if (kid && kid->IsSubtreeDirty()) {
3380 // Return an empty bbox if our kid's subtree is dirty. This may be called
3381 // in that situation, e.g. when we're building a display list after an
3382 // interrupted reflow. This can also be called during reflow before we've
3383 // been reflowed, e.g. if an earlier sibling is calling
3384 // FinishAndStoreOverflow and needs our parent's perspective matrix, which
3385 // depends on the SVG bbox contribution of this frame. In the latter
3386 // situation, when all siblings have been reflowed, the parent will compute
3387 // its perspective and rerun FinishAndStoreOverflow for all its children.
3388 return bbox;
3391 UpdateGlyphPositioning();
3393 nsPresContext* presContext = PresContext();
3395 TextRenderedRunIterator it(this);
3396 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3397 uint32_t flags = TextRenderedRunFlagsForBBoxContribution(run, aFlags);
3398 gfxMatrix m = ThebesMatrix(aToBBoxUserspace);
3399 SVGBBox bboxForRun = run.GetUserSpaceRect(presContext, flags, &m);
3400 bbox.UnionEdges(bboxForRun);
3403 return bbox;
3406 //----------------------------------------------------------------------
3407 // SVGTextFrame SVG DOM methods
3410 * Returns whether the specified node has any non-empty Text
3411 * beneath it.
3413 static bool HasTextContent(nsIContent* aContent) {
3414 NS_ASSERTION(aContent, "expected non-null aContent");
3416 TextNodeIterator it(aContent);
3417 for (Text* text = it.Current(); text; text = it.Next()) {
3418 if (text->TextLength() != 0) {
3419 return true;
3422 return false;
3426 * Returns the number of DOM characters beneath the specified node.
3428 static uint32_t GetTextContentLength(nsIContent* aContent) {
3429 NS_ASSERTION(aContent, "expected non-null aContent");
3431 uint32_t length = 0;
3432 TextNodeIterator it(aContent);
3433 for (Text* text = it.Current(); text; text = it.Next()) {
3434 length += text->TextLength();
3436 return length;
3439 int32_t SVGTextFrame::ConvertTextElementCharIndexToAddressableIndex(
3440 int32_t aIndex, nsIContent* aContent) {
3441 CharIterator it(this, CharIterator::eOriginal, aContent);
3442 if (!it.AdvanceToSubtree()) {
3443 return -1;
3445 int32_t result = 0;
3446 int32_t textElementCharIndex;
3447 while (!it.AtEnd() && it.IsWithinSubtree()) {
3448 bool addressable = !it.IsOriginalCharUnaddressable();
3449 textElementCharIndex = it.TextElementCharIndex();
3450 it.Next();
3451 uint32_t delta = it.TextElementCharIndex() - textElementCharIndex;
3452 aIndex -= delta;
3453 if (addressable) {
3454 if (aIndex < 0) {
3455 return result;
3457 result += delta;
3460 return -1;
3464 * Implements the SVG DOM GetNumberOfChars method for the specified
3465 * text content element.
3467 uint32_t SVGTextFrame::GetNumberOfChars(nsIContent* aContent) {
3468 nsIFrame* kid = PrincipalChildList().FirstChild();
3469 if (kid->IsSubtreeDirty()) {
3470 // We're never reflowed if we're under a non-SVG element that is
3471 // never reflowed (such as the HTML 'caption' element).
3472 return 0;
3475 UpdateGlyphPositioning();
3477 uint32_t n = 0;
3478 CharIterator it(this, CharIterator::eAddressable, aContent);
3479 if (it.AdvanceToSubtree()) {
3480 while (!it.AtEnd() && it.IsWithinSubtree()) {
3481 n++;
3482 it.Next();
3485 return n;
3489 * Implements the SVG DOM GetComputedTextLength method for the specified
3490 * text child element.
3492 float SVGTextFrame::GetComputedTextLength(nsIContent* aContent) {
3493 nsIFrame* kid = PrincipalChildList().FirstChild();
3494 if (kid->IsSubtreeDirty()) {
3495 // We're never reflowed if we're under a non-SVG element that is
3496 // never reflowed (such as the HTML 'caption' element).
3498 // If we ever decide that we need to return accurate values here,
3499 // we could do similar work to GetSubStringLength.
3500 return 0;
3503 UpdateGlyphPositioning();
3505 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3506 PresContext()->AppUnitsPerDevPixel());
3508 nscoord length = 0;
3509 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3510 aContent);
3511 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3512 length += run.GetAdvanceWidth();
3515 return PresContext()->AppUnitsToGfxUnits(length) * cssPxPerDevPx *
3516 mLengthAdjustScaleFactor / mFontSizeScaleFactor;
3520 * Implements the SVG DOM SelectSubString method for the specified
3521 * text content element.
3523 void SVGTextFrame::SelectSubString(nsIContent* aContent, uint32_t charnum,
3524 uint32_t nchars, ErrorResult& aRv) {
3525 nsIFrame* kid = PrincipalChildList().FirstChild();
3526 if (kid->IsSubtreeDirty()) {
3527 // We're never reflowed if we're under a non-SVG element that is
3528 // never reflowed (such as the HTML 'caption' element).
3529 // XXXbz Should this just return without throwing like the no-frame case?
3530 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3531 return;
3534 UpdateGlyphPositioning();
3536 // Convert charnum/nchars from addressable characters relative to
3537 // aContent to global character indices.
3538 CharIterator chit(this, CharIterator::eAddressable, aContent);
3539 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3540 chit.IsAfterSubtree()) {
3541 aRv.ThrowIndexSizeError("Character index out of range");
3542 return;
3544 charnum = chit.TextElementCharIndex();
3545 const RefPtr<nsIContent> content = chit.TextFrame()->GetContent();
3546 chit.NextWithinSubtree(nchars);
3547 nchars = chit.TextElementCharIndex() - charnum;
3549 RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
3551 frameSelection->HandleClick(content, charnum, charnum + nchars,
3552 nsFrameSelection::FocusMode::kCollapseToNewPoint,
3553 CaretAssociationHint::Before);
3557 * For some content we cannot (or currently cannot) compute the length
3558 * without reflowing. In those cases we need to fall back to using
3559 * GetSubStringLengthSlowFallback.
3561 * We fall back for textPath since we need glyph positioning in order to
3562 * tell if any characters should be ignored due to having fallen off the
3563 * end of the textPath.
3565 * We fall back for bidi because GetTrimmedOffsets does not produce the
3566 * correct results for bidi continuations when passed aPostReflow = false.
3567 * XXX It may be possible to determine which continuations to trim from (and
3568 * which sides), but currently we don't do that. It would require us to
3569 * identify the visual (rather than logical) start and end of the line, to
3570 * avoid trimming at line-internal frame boundaries. Maybe nsBidiPresUtils
3571 * methods like GetFrameToRightOf and GetFrameToLeftOf would help?
3574 bool SVGTextFrame::RequiresSlowFallbackForSubStringLength() {
3575 TextFrameIterator frameIter(this);
3576 for (nsTextFrame* frame = frameIter.Current(); frame;
3577 frame = frameIter.Next()) {
3578 if (frameIter.TextPathFrame() || frame->GetNextContinuation()) {
3579 return true;
3582 return false;
3586 * Implements the SVG DOM GetSubStringLength method for the specified
3587 * text content element.
3589 float SVGTextFrame::GetSubStringLengthFastPath(nsIContent* aContent,
3590 uint32_t charnum,
3591 uint32_t nchars,
3592 ErrorResult& aRv) {
3593 MOZ_ASSERT(!RequiresSlowFallbackForSubStringLength());
3595 // We only need our text correspondence to be up to date (no need to call
3596 // UpdateGlyphPositioning).
3597 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
3599 // Convert charnum/nchars from addressable characters relative to
3600 // aContent to global character indices.
3601 CharIterator chit(this, CharIterator::eAddressable, aContent,
3602 /* aPostReflow */ false);
3603 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3604 chit.IsAfterSubtree()) {
3605 aRv.ThrowIndexSizeError("Character index out of range");
3606 return 0;
3609 // We do this after the ThrowIndexSizeError() bit so JS calls correctly throw
3610 // when necessary.
3611 if (nchars == 0) {
3612 return 0.0f;
3615 charnum = chit.TextElementCharIndex();
3616 chit.NextWithinSubtree(nchars);
3617 nchars = chit.TextElementCharIndex() - charnum;
3619 // Sum of the substring advances.
3620 nscoord textLength = 0;
3622 TextFrameIterator frit(this); // aSubtree = nullptr
3624 // Index of the first non-skipped char in the frame, and of a subsequent char
3625 // that we're interested in. Both are relative to the index of the first
3626 // non-skipped char in the ancestor <text> element.
3627 uint32_t frameStartTextElementCharIndex = 0;
3628 uint32_t textElementCharIndex;
3630 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
3631 frameStartTextElementCharIndex += frit.UndisplayedCharacters();
3632 textElementCharIndex = frameStartTextElementCharIndex;
3634 // Offset into frame's Text:
3635 const uint32_t untrimmedOffset = frame->GetContentOffset();
3636 const uint32_t untrimmedLength = frame->GetContentEnd() - untrimmedOffset;
3638 // Trim the offset/length to remove any leading/trailing white space.
3639 uint32_t trimmedOffset = untrimmedOffset;
3640 uint32_t trimmedLength = untrimmedLength;
3641 nsTextFrame::TrimmedOffsets trimmedOffsets = frame->GetTrimmedOffsets(
3642 frame->TextFragment(), nsTextFrame::TrimmedOffsetFlags::NotPostReflow);
3643 TrimOffsets(trimmedOffset, trimmedLength, trimmedOffsets);
3645 textElementCharIndex += trimmedOffset - untrimmedOffset;
3647 if (textElementCharIndex >= charnum + nchars) {
3648 break; // we're past the end of the substring
3651 uint32_t offset = textElementCharIndex;
3653 // Intersect the substring we are interested in with the range covered by
3654 // the nsTextFrame.
3655 IntersectInterval(offset, trimmedLength, charnum, nchars);
3657 if (trimmedLength != 0) {
3658 // Convert offset into an index into the frame.
3659 offset += trimmedOffset - textElementCharIndex;
3661 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
3662 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
3663 nsTextFrame::PropertyProvider provider(frame, it);
3665 Range range = ConvertOriginalToSkipped(it, offset, trimmedLength);
3667 // Accumulate the advance.
3668 textLength += textRun->GetAdvanceWidth(range, &provider);
3671 // Advance, ready for next call:
3672 frameStartTextElementCharIndex += untrimmedLength;
3675 nsPresContext* presContext = PresContext();
3676 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3677 presContext->AppUnitsPerDevPixel());
3679 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3680 mFontSizeScaleFactor;
3683 float SVGTextFrame::GetSubStringLengthSlowFallback(nsIContent* aContent,
3684 uint32_t charnum,
3685 uint32_t nchars,
3686 ErrorResult& aRv) {
3687 UpdateGlyphPositioning();
3689 // Convert charnum/nchars from addressable characters relative to
3690 // aContent to global character indices.
3691 CharIterator chit(this, CharIterator::eAddressable, aContent);
3692 if (!chit.AdvanceToSubtree() || !chit.Next(charnum) ||
3693 chit.IsAfterSubtree()) {
3694 aRv.ThrowIndexSizeError("Character index out of range");
3695 return 0;
3698 if (nchars == 0) {
3699 return 0.0f;
3702 charnum = chit.TextElementCharIndex();
3703 chit.NextWithinSubtree(nchars);
3704 nchars = chit.TextElementCharIndex() - charnum;
3706 // Find each rendered run that intersects with the range defined
3707 // by charnum/nchars.
3708 nscoord textLength = 0;
3709 TextRenderedRunIterator runIter(this, TextRenderedRunIterator::eAllFrames);
3710 TextRenderedRun run = runIter.Current();
3711 while (run.mFrame) {
3712 // If this rendered run is past the substring we are interested in, we
3713 // are done.
3714 uint32_t offset = run.mTextElementCharIndex;
3715 if (offset >= charnum + nchars) {
3716 break;
3719 // Intersect the substring we are interested in with the range covered by
3720 // the rendered run.
3721 uint32_t length = run.mTextFrameContentLength;
3722 IntersectInterval(offset, length, charnum, nchars);
3724 if (length != 0) {
3725 // Convert offset into an index into the frame.
3726 offset += run.mTextFrameContentOffset - run.mTextElementCharIndex;
3728 gfxSkipCharsIterator it =
3729 run.mFrame->EnsureTextRun(nsTextFrame::eInflated);
3730 gfxTextRun* textRun = run.mFrame->GetTextRun(nsTextFrame::eInflated);
3731 nsTextFrame::PropertyProvider provider(run.mFrame, it);
3733 Range range = ConvertOriginalToSkipped(it, offset, length);
3735 // Accumulate the advance.
3736 textLength += textRun->GetAdvanceWidth(range, &provider);
3739 run = runIter.Next();
3742 nsPresContext* presContext = PresContext();
3743 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3744 presContext->AppUnitsPerDevPixel());
3746 return presContext->AppUnitsToGfxUnits(textLength) * cssPxPerDevPx /
3747 mFontSizeScaleFactor;
3751 * Implements the SVG DOM GetCharNumAtPosition method for the specified
3752 * text content element.
3754 int32_t SVGTextFrame::GetCharNumAtPosition(nsIContent* aContent,
3755 const DOMPointInit& aPoint) {
3756 nsIFrame* kid = PrincipalChildList().FirstChild();
3757 if (kid->IsSubtreeDirty()) {
3758 // We're never reflowed if we're under a non-SVG element that is
3759 // never reflowed (such as the HTML 'caption' element).
3760 return -1;
3763 UpdateGlyphPositioning();
3765 nsPresContext* context = PresContext();
3767 gfxPoint p(aPoint.mX, aPoint.mY);
3769 int32_t result = -1;
3771 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3772 aContent);
3773 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
3774 // Hit test this rendered run. Later runs will override earlier ones.
3775 int32_t index = run.GetCharNumAtPosition(context, p);
3776 if (index != -1) {
3777 result = index + run.mTextElementCharIndex;
3781 if (result == -1) {
3782 return result;
3785 return ConvertTextElementCharIndexToAddressableIndex(result, aContent);
3789 * Implements the SVG DOM GetStartPositionOfChar method for the specified
3790 * text content element.
3792 already_AddRefed<DOMSVGPoint> SVGTextFrame::GetStartPositionOfChar(
3793 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3794 nsIFrame* kid = PrincipalChildList().FirstChild();
3795 if (kid->IsSubtreeDirty()) {
3796 // We're never reflowed if we're under a non-SVG element that is
3797 // never reflowed (such as the HTML 'caption' element).
3798 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3799 return nullptr;
3802 UpdateGlyphPositioning();
3804 CharIterator it(this, CharIterator::eAddressable, aContent);
3805 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3806 aRv.ThrowIndexSizeError("Character index out of range");
3807 return nullptr;
3810 // We need to return the start position of the whole glyph.
3811 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3813 return do_AddRef(new DOMSVGPoint(ToPoint(mPositions[startIndex].mPosition)));
3817 * Returns the advance of the entire glyph whose starting character is at
3818 * aTextElementCharIndex.
3820 * aIterator, if provided, must be a CharIterator that already points to
3821 * aTextElementCharIndex that is restricted to aContent and is using
3822 * filter mode eAddressable.
3824 static gfxFloat GetGlyphAdvance(SVGTextFrame* aFrame, nsIContent* aContent,
3825 uint32_t aTextElementCharIndex,
3826 CharIterator* aIterator) {
3827 MOZ_ASSERT(!aIterator || (aIterator->Filter() == CharIterator::eAddressable &&
3828 aIterator->GetSubtree() == aContent &&
3829 aIterator->GlyphStartTextElementCharIndex() ==
3830 aTextElementCharIndex),
3831 "Invalid aIterator");
3833 Maybe<CharIterator> newIterator;
3834 CharIterator* it = aIterator;
3835 if (!it) {
3836 newIterator.emplace(aFrame, CharIterator::eAddressable, aContent);
3837 if (!newIterator->AdvanceToSubtree()) {
3838 MOZ_ASSERT_UNREACHABLE("Invalid aContent");
3839 return 0.0;
3841 it = newIterator.ptr();
3844 while (it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3845 if (!it->Next()) {
3846 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3847 return 0.0;
3851 if (it->AtEnd()) {
3852 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3853 return 0.0;
3856 nsPresContext* presContext = aFrame->PresContext();
3857 gfxFloat advance = 0.0;
3859 for (;;) {
3860 advance += it->GetAdvance(presContext);
3861 if (!it->Next() ||
3862 it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3863 break;
3867 return advance;
3871 * Implements the SVG DOM GetEndPositionOfChar method for the specified
3872 * text content element.
3874 already_AddRefed<DOMSVGPoint> SVGTextFrame::GetEndPositionOfChar(
3875 nsIContent* aContent, uint32_t aCharNum, ErrorResult& aRv) {
3876 nsIFrame* kid = PrincipalChildList().FirstChild();
3877 if (kid->IsSubtreeDirty()) {
3878 // We're never reflowed if we're under a non-SVG element that is
3879 // never reflowed (such as the HTML 'caption' element).
3880 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3881 return nullptr;
3884 UpdateGlyphPositioning();
3886 CharIterator it(this, CharIterator::eAddressable, aContent);
3887 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3888 aRv.ThrowIndexSizeError("Character index out of range");
3889 return nullptr;
3892 // We need to return the end position of the whole glyph.
3893 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3895 // Get the advance of the glyph.
3896 gfxFloat advance =
3897 GetGlyphAdvance(this, aContent, startIndex,
3898 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3899 if (it.TextRun()->IsRightToLeft()) {
3900 advance = -advance;
3903 // The end position is the start position plus the advance in the direction
3904 // of the glyph's rotation.
3905 Matrix m = Matrix::Rotation(mPositions[startIndex].mAngle) *
3906 Matrix::Translation(ToPoint(mPositions[startIndex].mPosition));
3907 Point p = m.TransformPoint(Point(advance / mFontSizeScaleFactor, 0));
3909 return do_AddRef(new DOMSVGPoint(p));
3913 * Implements the SVG DOM GetExtentOfChar method for the specified
3914 * text content element.
3916 already_AddRefed<SVGRect> SVGTextFrame::GetExtentOfChar(nsIContent* aContent,
3917 uint32_t aCharNum,
3918 ErrorResult& aRv) {
3919 nsIFrame* kid = PrincipalChildList().FirstChild();
3920 if (kid->IsSubtreeDirty()) {
3921 // We're never reflowed if we're under a non-SVG element that is
3922 // never reflowed (such as the HTML 'caption' element).
3923 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3924 return nullptr;
3927 UpdateGlyphPositioning();
3929 // Search for the character whose addressable index is aCharNum.
3930 CharIterator it(this, CharIterator::eAddressable, aContent);
3931 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3932 aRv.ThrowIndexSizeError("Character index out of range");
3933 return nullptr;
3936 nsPresContext* presContext = PresContext();
3937 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3938 presContext->AppUnitsPerDevPixel());
3940 nsTextFrame* textFrame = it.TextFrame();
3941 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
3942 bool isRTL = it.TextRun()->IsRightToLeft();
3943 bool isVertical = it.TextRun()->IsVertical();
3945 // Get the glyph advance.
3946 gfxFloat advance =
3947 GetGlyphAdvance(this, aContent, startIndex,
3948 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3949 gfxFloat x = isRTL ? -advance : 0.0;
3951 // The ascent and descent gives the height of the glyph.
3952 gfxFloat ascent, descent;
3953 GetAscentAndDescentInAppUnits(textFrame, ascent, descent);
3955 // The horizontal extent is the origin of the glyph plus the advance
3956 // in the direction of the glyph's rotation.
3957 gfxMatrix m;
3958 m.PreTranslate(mPositions[startIndex].mPosition);
3959 m.PreRotate(mPositions[startIndex].mAngle);
3960 m.PreScale(1 / mFontSizeScaleFactor, 1 / mFontSizeScaleFactor);
3962 gfxRect glyphRect;
3963 if (isVertical) {
3964 glyphRect = gfxRect(
3965 -presContext->AppUnitsToGfxUnits(descent) * cssPxPerDevPx, x,
3966 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx,
3967 advance);
3968 } else {
3969 glyphRect = gfxRect(
3970 x, -presContext->AppUnitsToGfxUnits(ascent) * cssPxPerDevPx, advance,
3971 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx);
3974 // Transform the glyph's rect into user space.
3975 gfxRect r = m.TransformBounds(glyphRect);
3977 return do_AddRef(new SVGRect(aContent, ToRect(r)));
3981 * Implements the SVG DOM GetRotationOfChar method for the specified
3982 * text content element.
3984 float SVGTextFrame::GetRotationOfChar(nsIContent* aContent, uint32_t aCharNum,
3985 ErrorResult& aRv) {
3986 nsIFrame* kid = PrincipalChildList().FirstChild();
3987 if (kid->IsSubtreeDirty()) {
3988 // We're never reflowed if we're under a non-SVG element that is
3989 // never reflowed (such as the HTML 'caption' element).
3990 aRv.ThrowInvalidStateError("No layout information available for SVG text");
3991 return 0;
3994 UpdateGlyphPositioning();
3996 CharIterator it(this, CharIterator::eAddressable, aContent);
3997 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3998 aRv.ThrowIndexSizeError("Character index out of range");
3999 return 0;
4002 // we need to account for the glyph's underlying orientation
4003 const gfxTextRun::GlyphRun& glyphRun = it.GlyphRun();
4004 int32_t glyphOrientation =
4005 90 * (glyphRun.IsSidewaysRight() - glyphRun.IsSidewaysLeft());
4007 return mPositions[it.TextElementCharIndex()].mAngle * 180.0 / M_PI +
4008 glyphOrientation;
4011 //----------------------------------------------------------------------
4012 // SVGTextFrame text layout methods
4015 * Given the character position array before values have been filled in
4016 * to any unspecified positions, and an array of dx/dy values, returns whether
4017 * a character at a given index should start a new rendered run.
4019 * @param aPositions The array of character positions before unspecified
4020 * positions have been filled in and dx/dy values have been added to them.
4021 * @param aDeltas The array of dx/dy values.
4022 * @param aIndex The character index in question.
4024 static bool ShouldStartRunAtIndex(const nsTArray<CharPosition>& aPositions,
4025 const nsTArray<gfxPoint>& aDeltas,
4026 uint32_t aIndex) {
4027 if (aIndex == 0) {
4028 return true;
4031 if (aIndex < aPositions.Length()) {
4032 // If an explicit x or y value was given, start a new run.
4033 if (aPositions[aIndex].IsXSpecified() ||
4034 aPositions[aIndex].IsYSpecified()) {
4035 return true;
4038 // If a non-zero rotation was given, or the previous character had a non-
4039 // zero rotation, start a new run.
4040 if ((aPositions[aIndex].IsAngleSpecified() &&
4041 aPositions[aIndex].mAngle != 0.0f) ||
4042 (aPositions[aIndex - 1].IsAngleSpecified() &&
4043 (aPositions[aIndex - 1].mAngle != 0.0f))) {
4044 return true;
4048 if (aIndex < aDeltas.Length()) {
4049 // If a non-zero dx or dy value was given, start a new run.
4050 if (aDeltas[aIndex].x != 0.0 || aDeltas[aIndex].y != 0.0) {
4051 return true;
4055 return false;
4058 bool SVGTextFrame::ResolvePositionsForNode(nsIContent* aContent,
4059 uint32_t& aIndex, bool aInTextPath,
4060 bool& aForceStartOfChunk,
4061 nsTArray<gfxPoint>& aDeltas) {
4062 if (aContent->IsText()) {
4063 // We found a text node.
4064 uint32_t length = aContent->AsText()->TextLength();
4065 if (length) {
4066 uint32_t end = aIndex + length;
4067 if (MOZ_UNLIKELY(end > mPositions.Length())) {
4068 MOZ_ASSERT_UNREACHABLE(
4069 "length of mPositions does not match characters "
4070 "found by iterating content");
4071 return false;
4073 if (aForceStartOfChunk) {
4074 // Note this character as starting a new anchored chunk.
4075 mPositions[aIndex].mStartOfChunk = true;
4076 aForceStartOfChunk = false;
4078 while (aIndex < end) {
4079 // Record whether each of these characters should start a new rendered
4080 // run. That is always the case for characters on a text path.
4082 // Run boundaries due to rotate="" values are handled in
4083 // DoGlyphPositioning.
4084 if (aInTextPath || ShouldStartRunAtIndex(mPositions, aDeltas, aIndex)) {
4085 mPositions[aIndex].mRunBoundary = true;
4087 aIndex++;
4090 return true;
4093 // Skip past elements that aren't text content elements.
4094 if (!IsTextContentElement(aContent)) {
4095 return true;
4098 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4099 // Any ‘y’ attributes on horizontal <textPath> elements are ignored.
4100 // Similarly, for vertical <texPath>s x attributes are ignored.
4101 // <textPath> elements behave as if they have x="0" y="0" on them, but only
4102 // if there is not a value for the non-ignored coordinate that got inherited
4103 // from a parent. We skip this if there is no text content, so that empty
4104 // <textPath>s don't interrupt the layout of text in the parent element.
4105 if (HasTextContent(aContent)) {
4106 if (MOZ_UNLIKELY(aIndex >= mPositions.Length())) {
4107 MOZ_ASSERT_UNREACHABLE(
4108 "length of mPositions does not match characters "
4109 "found by iterating content");
4110 return false;
4112 bool vertical = GetWritingMode().IsVertical();
4113 if (vertical || !mPositions[aIndex].IsXSpecified()) {
4114 mPositions[aIndex].mPosition.x = 0.0;
4116 if (!vertical || !mPositions[aIndex].IsYSpecified()) {
4117 mPositions[aIndex].mPosition.y = 0.0;
4119 mPositions[aIndex].mStartOfChunk = true;
4121 } else if (!aContent->IsSVGElement(nsGkAtoms::a)) {
4122 MOZ_ASSERT(aContent->IsSVGElement());
4124 // We have a text content element that can have x/y/dx/dy/rotate attributes.
4125 SVGElement* element = static_cast<SVGElement*>(aContent);
4127 // Get x, y, dx, dy.
4128 SVGUserUnitList x, y, dx, dy;
4129 element->GetAnimatedLengthListValues(&x, &y, &dx, &dy, nullptr);
4131 // Get rotate.
4132 const SVGNumberList* rotate = nullptr;
4133 SVGAnimatedNumberList* animatedRotate =
4134 element->GetAnimatedNumberList(nsGkAtoms::rotate);
4135 if (animatedRotate) {
4136 rotate = &animatedRotate->GetAnimValue();
4139 bool percentages = false;
4140 uint32_t count = GetTextContentLength(aContent);
4142 if (MOZ_UNLIKELY(aIndex + count > mPositions.Length())) {
4143 MOZ_ASSERT_UNREACHABLE(
4144 "length of mPositions does not match characters "
4145 "found by iterating content");
4146 return false;
4149 // New text anchoring chunks start at each character assigned a position
4150 // with x="" or y="", or if we forced one with aForceStartOfChunk due to
4151 // being just after a <textPath>.
4152 uint32_t newChunkCount = std::max(x.Length(), y.Length());
4153 if (!newChunkCount && aForceStartOfChunk) {
4154 newChunkCount = 1;
4156 for (uint32_t i = 0, j = 0; i < newChunkCount && j < count; j++) {
4157 if (!mPositions[aIndex + j].mUnaddressable) {
4158 mPositions[aIndex + j].mStartOfChunk = true;
4159 i++;
4163 // Copy dx="" and dy="" values into aDeltas.
4164 if (!dx.IsEmpty() || !dy.IsEmpty()) {
4165 // Any unspecified deltas when we grow the array just get left as 0s.
4166 aDeltas.EnsureLengthAtLeast(aIndex + count);
4167 for (uint32_t i = 0, j = 0; i < dx.Length() && j < count; j++) {
4168 if (!mPositions[aIndex + j].mUnaddressable) {
4169 aDeltas[aIndex + j].x = dx[i];
4170 percentages = percentages || dx.HasPercentageValueAt(i);
4171 i++;
4174 for (uint32_t i = 0, j = 0; i < dy.Length() && j < count; j++) {
4175 if (!mPositions[aIndex + j].mUnaddressable) {
4176 aDeltas[aIndex + j].y = dy[i];
4177 percentages = percentages || dy.HasPercentageValueAt(i);
4178 i++;
4183 // Copy x="" and y="" values.
4184 for (uint32_t i = 0, j = 0; i < x.Length() && j < count; j++) {
4185 if (!mPositions[aIndex + j].mUnaddressable) {
4186 mPositions[aIndex + j].mPosition.x = x[i];
4187 percentages = percentages || x.HasPercentageValueAt(i);
4188 i++;
4191 for (uint32_t i = 0, j = 0; i < y.Length() && j < count; j++) {
4192 if (!mPositions[aIndex + j].mUnaddressable) {
4193 mPositions[aIndex + j].mPosition.y = y[i];
4194 percentages = percentages || y.HasPercentageValueAt(i);
4195 i++;
4199 // Copy rotate="" values.
4200 if (rotate && !rotate->IsEmpty()) {
4201 uint32_t i = 0, j = 0;
4202 while (i < rotate->Length() && j < count) {
4203 if (!mPositions[aIndex + j].mUnaddressable) {
4204 mPositions[aIndex + j].mAngle = M_PI * (*rotate)[i] / 180.0;
4205 i++;
4207 j++;
4209 // Propagate final rotate="" value to the end of this element.
4210 while (j < count) {
4211 mPositions[aIndex + j].mAngle = mPositions[aIndex + j - 1].mAngle;
4212 j++;
4216 if (percentages) {
4217 AddStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4221 // Recurse to children.
4222 bool inTextPath = aInTextPath || aContent->IsSVGElement(nsGkAtoms::textPath);
4223 for (nsIContent* child = aContent->GetFirstChild(); child;
4224 child = child->GetNextSibling()) {
4225 bool ok = ResolvePositionsForNode(child, aIndex, inTextPath,
4226 aForceStartOfChunk, aDeltas);
4227 if (!ok) {
4228 return false;
4232 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4233 // Force a new anchored chunk just after a <textPath>.
4234 aForceStartOfChunk = true;
4237 return true;
4240 bool SVGTextFrame::ResolvePositions(nsTArray<gfxPoint>& aDeltas,
4241 bool aRunPerGlyph) {
4242 NS_ASSERTION(mPositions.IsEmpty(), "expected mPositions to be empty");
4243 RemoveStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES);
4245 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4246 if (it.AtEnd()) {
4247 return false;
4250 // We assume the first character position is (0,0) unless we later see
4251 // otherwise, and note it as unaddressable if it is.
4252 bool firstCharUnaddressable = it.IsOriginalCharUnaddressable();
4253 mPositions.AppendElement(CharPosition::Unspecified(firstCharUnaddressable));
4255 // Fill in unspecified positions for all remaining characters, noting
4256 // them as unaddressable if they are.
4257 uint32_t index = 0;
4258 while (it.Next()) {
4259 while (++index < it.TextElementCharIndex()) {
4260 mPositions.AppendElement(CharPosition::Unspecified(false));
4262 mPositions.AppendElement(
4263 CharPosition::Unspecified(it.IsOriginalCharUnaddressable()));
4265 while (++index < it.TextElementCharIndex()) {
4266 mPositions.AppendElement(CharPosition::Unspecified(false));
4269 // Recurse over the content and fill in character positions as we go.
4270 bool forceStartOfChunk = false;
4271 index = 0;
4272 bool ok = ResolvePositionsForNode(mContent, index, aRunPerGlyph,
4273 forceStartOfChunk, aDeltas);
4274 return ok && index > 0;
4277 void SVGTextFrame::DetermineCharPositions(nsTArray<nsPoint>& aPositions) {
4278 NS_ASSERTION(aPositions.IsEmpty(), "expected aPositions to be empty");
4280 nsPoint position;
4282 TextFrameIterator frit(this);
4283 for (nsTextFrame* frame = frit.Current(); frame; frame = frit.Next()) {
4284 gfxSkipCharsIterator it = frame->EnsureTextRun(nsTextFrame::eInflated);
4285 gfxTextRun* textRun = frame->GetTextRun(nsTextFrame::eInflated);
4286 nsTextFrame::PropertyProvider provider(frame, it);
4288 // Reset the position to the new frame's position.
4289 position = frit.Position();
4290 if (textRun->IsVertical()) {
4291 if (textRun->IsRightToLeft()) {
4292 position.y += frame->GetRect().height;
4294 position.x += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4295 mFontSizeScaleFactor);
4296 } else {
4297 if (textRun->IsRightToLeft()) {
4298 position.x += frame->GetRect().width;
4300 position.y += GetBaselinePosition(frame, textRun, frit.DominantBaseline(),
4301 mFontSizeScaleFactor);
4304 // Any characters not in a frame, e.g. when display:none.
4305 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4306 aPositions.AppendElement(position);
4309 // Any white space characters trimmed at the start of the line of text.
4310 nsTextFrame::TrimmedOffsets trimmedOffsets =
4311 frame->GetTrimmedOffsets(frame->TextFragment());
4312 while (it.GetOriginalOffset() < trimmedOffsets.mStart) {
4313 aPositions.AppendElement(position);
4314 it.AdvanceOriginal(1);
4317 // Visible characters in the text frame.
4318 while (it.GetOriginalOffset() < frame->GetContentEnd()) {
4319 aPositions.AppendElement(position);
4320 if (!it.IsOriginalCharSkipped()) {
4321 // Accumulate partial ligature advance into position. (We must get
4322 // partial advances rather than get the advance of the whole ligature
4323 // group / cluster at once, since the group may span text frames, and
4324 // the PropertyProvider only has spacing information for the current
4325 // text frame.)
4326 uint32_t offset = it.GetSkippedOffset();
4327 nscoord advance =
4328 textRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
4329 (textRun->IsVertical() ? position.y : position.x) +=
4330 textRun->IsRightToLeft() ? -advance : advance;
4332 it.AdvanceOriginal(1);
4336 // Finally any characters at the end that are not in a frame.
4337 for (uint32_t i = 0; i < frit.UndisplayedCharacters(); i++) {
4338 aPositions.AppendElement(position);
4343 * Physical text-anchor values.
4345 enum TextAnchorSide { eAnchorLeft, eAnchorMiddle, eAnchorRight };
4348 * Converts a logical text-anchor value to its physical value, based on whether
4349 * it is for an RTL frame.
4351 static TextAnchorSide ConvertLogicalTextAnchorToPhysical(
4352 StyleTextAnchor aTextAnchor, bool aIsRightToLeft) {
4353 NS_ASSERTION(uint8_t(aTextAnchor) <= 3, "unexpected value for aTextAnchor");
4354 if (!aIsRightToLeft) {
4355 return TextAnchorSide(uint8_t(aTextAnchor));
4357 return TextAnchorSide(2 - uint8_t(aTextAnchor));
4361 * Shifts the recorded character positions for an anchored chunk.
4363 * @param aCharPositions The recorded character positions.
4364 * @param aChunkStart The character index the starts the anchored chunk. This
4365 * character's initial position is the anchor point.
4366 * @param aChunkEnd The character index just after the end of the anchored
4367 * chunk.
4368 * @param aVisIStartEdge The left/top-most edge of any of the glyphs within the
4369 * anchored chunk.
4370 * @param aVisIEndEdge The right/bottom-most edge of any of the glyphs within
4371 * the anchored chunk.
4372 * @param aAnchorSide The direction to anchor.
4374 static void ShiftAnchoredChunk(nsTArray<CharPosition>& aCharPositions,
4375 uint32_t aChunkStart, uint32_t aChunkEnd,
4376 gfxFloat aVisIStartEdge, gfxFloat aVisIEndEdge,
4377 TextAnchorSide aAnchorSide, bool aVertical) {
4378 NS_ASSERTION(aVisIStartEdge <= aVisIEndEdge,
4379 "unexpected anchored chunk edges");
4380 NS_ASSERTION(aChunkStart < aChunkEnd,
4381 "unexpected values for aChunkStart and aChunkEnd");
4383 gfxFloat shift = aVertical ? aCharPositions[aChunkStart].mPosition.y
4384 : aCharPositions[aChunkStart].mPosition.x;
4385 switch (aAnchorSide) {
4386 case eAnchorLeft:
4387 shift -= aVisIStartEdge;
4388 break;
4389 case eAnchorMiddle:
4390 shift -= (aVisIStartEdge + aVisIEndEdge) / 2;
4391 break;
4392 case eAnchorRight:
4393 shift -= aVisIEndEdge;
4394 break;
4395 default:
4396 MOZ_ASSERT_UNREACHABLE("unexpected value for aAnchorSide");
4399 if (shift != 0.0) {
4400 if (aVertical) {
4401 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4402 aCharPositions[i].mPosition.y += shift;
4404 } else {
4405 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4406 aCharPositions[i].mPosition.x += shift;
4412 void SVGTextFrame::AdjustChunksForLineBreaks() {
4413 nsBlockFrame* block = do_QueryFrame(PrincipalChildList().FirstChild());
4414 NS_ASSERTION(block, "expected block frame");
4416 nsBlockFrame::LineIterator line = block->LinesBegin();
4418 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4419 while (!it.AtEnd() && line != block->LinesEnd()) {
4420 if (it.TextFrame() == line->mFirstChild) {
4421 mPositions[it.TextElementCharIndex()].mStartOfChunk = true;
4422 line++;
4424 it.AdvancePastCurrentFrame();
4428 void SVGTextFrame::AdjustPositionsForClusters() {
4429 nsPresContext* presContext = PresContext();
4431 // Find all of the characters that are in the middle of a cluster or
4432 // ligature group, and adjust their positions and rotations to match
4433 // the first character of the cluster/group.
4435 // Also move the boundaries of text rendered runs and anchored chunks to
4436 // not lie in the middle of cluster/group.
4438 // The partial advance of the current cluster or ligature group that we
4439 // have accumulated.
4440 gfxFloat partialAdvance = 0.0;
4442 CharIterator it(this, CharIterator::eUnskipped, /* aSubtree */ nullptr);
4443 bool isFirst = true;
4444 while (!it.AtEnd()) {
4445 if (it.IsClusterAndLigatureGroupStart() || isFirst) {
4446 // If we're at the start of a new cluster or ligature group, reset our
4447 // accumulated partial advance. Also treat the beginning of the text as
4448 // an anchor, even if it is a combining character and therefore was
4449 // marked as being a Unicode cluster continuation.
4450 partialAdvance = 0.0;
4451 isFirst = false;
4452 } else {
4453 // Otherwise, we're in the middle of a cluster or ligature group, and
4454 // we need to use the currently accumulated partial advance to adjust
4455 // the character's position and rotation.
4457 // Find the start of the cluster/ligature group.
4458 uint32_t charIndex = it.TextElementCharIndex();
4459 uint32_t startIndex = it.GlyphStartTextElementCharIndex();
4460 MOZ_ASSERT(charIndex != startIndex,
4461 "If the current character is in the middle of a cluster or "
4462 "ligature group, then charIndex must be different from "
4463 "startIndex");
4465 mPositions[charIndex].mClusterOrLigatureGroupMiddle = true;
4467 // Don't allow different rotations on ligature parts.
4468 bool rotationAdjusted = false;
4469 double angle = mPositions[startIndex].mAngle;
4470 if (mPositions[charIndex].mAngle != angle) {
4471 mPositions[charIndex].mAngle = angle;
4472 rotationAdjusted = true;
4475 // Update the character position.
4476 gfxFloat advance = partialAdvance / mFontSizeScaleFactor;
4477 gfxPoint direction = gfxPoint(cos(angle), sin(angle)) *
4478 (it.TextRun()->IsRightToLeft() ? -1.0 : 1.0);
4479 if (it.TextRun()->IsVertical()) {
4480 std::swap(direction.x, direction.y);
4482 mPositions[charIndex].mPosition =
4483 mPositions[startIndex].mPosition + direction * advance;
4485 // Ensure any runs that would end in the middle of a ligature now end just
4486 // after the ligature.
4487 if (mPositions[charIndex].mRunBoundary) {
4488 mPositions[charIndex].mRunBoundary = false;
4489 if (charIndex + 1 < mPositions.Length()) {
4490 mPositions[charIndex + 1].mRunBoundary = true;
4492 } else if (rotationAdjusted) {
4493 if (charIndex + 1 < mPositions.Length()) {
4494 mPositions[charIndex + 1].mRunBoundary = true;
4498 // Ensure any anchored chunks that would begin in the middle of a ligature
4499 // now begin just after the ligature.
4500 if (mPositions[charIndex].mStartOfChunk) {
4501 mPositions[charIndex].mStartOfChunk = false;
4502 if (charIndex + 1 < mPositions.Length()) {
4503 mPositions[charIndex + 1].mStartOfChunk = true;
4508 // Accumulate the current character's partial advance.
4509 partialAdvance += it.GetAdvance(presContext);
4511 it.Next();
4515 already_AddRefed<Path> SVGTextFrame::GetTextPath(nsIFrame* aTextPathFrame) {
4516 nsIContent* content = aTextPathFrame->GetContent();
4517 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4518 if (tp->mPath.IsRendered()) {
4519 // This is just an attribute so there's no transform that can apply
4520 // so we can just return the path directly.
4521 return tp->mPath.GetAnimValue().BuildPathForMeasuring();
4524 SVGGeometryElement* geomElement =
4525 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4526 if (!geomElement) {
4527 return nullptr;
4530 RefPtr<Path> path = geomElement->GetOrBuildPathForMeasuring();
4531 if (!path) {
4532 return nullptr;
4535 gfxMatrix matrix = geomElement->PrependLocalTransformsTo(gfxMatrix());
4536 if (!matrix.IsIdentity()) {
4537 // Apply the geometry element's transform
4538 RefPtr<PathBuilder> builder =
4539 path->TransformedCopyToBuilder(ToMatrix(matrix));
4540 path = builder->Finish();
4543 return path.forget();
4546 gfxFloat SVGTextFrame::GetOffsetScale(nsIFrame* aTextPathFrame) {
4547 nsIContent* content = aTextPathFrame->GetContent();
4548 SVGTextPathElement* tp = static_cast<SVGTextPathElement*>(content);
4549 if (tp->mPath.IsRendered()) {
4550 // A path attribute has no pathLength or transform
4551 // so we return a unit scale.
4552 return 1.0;
4555 SVGGeometryElement* geomElement =
4556 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4557 if (!geomElement) {
4558 return 1.0;
4560 return geomElement->GetPathLengthScale(SVGGeometryElement::eForTextPath);
4563 gfxFloat SVGTextFrame::GetStartOffset(nsIFrame* aTextPathFrame) {
4564 SVGTextPathElement* tp =
4565 static_cast<SVGTextPathElement*>(aTextPathFrame->GetContent());
4566 SVGAnimatedLength* length =
4567 &tp->mLengthAttributes[SVGTextPathElement::STARTOFFSET];
4569 if (length->IsPercentage()) {
4570 if (!std::isfinite(GetOffsetScale(aTextPathFrame))) {
4571 // Either pathLength="0" for this path or the path has 0 length.
4572 return 0.0;
4574 RefPtr<Path> data = GetTextPath(aTextPathFrame);
4575 return data ? length->GetAnimValInSpecifiedUnits() * data->ComputeLength() /
4576 100.0
4577 : 0.0;
4579 float lengthValue = length->GetAnimValue(tp);
4580 // If offsetScale is infinity we want to return 0 not NaN
4581 return lengthValue == 0 ? 0.0 : lengthValue * GetOffsetScale(aTextPathFrame);
4584 void SVGTextFrame::DoTextPathLayout() {
4585 nsPresContext* context = PresContext();
4587 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4588 while (!it.AtEnd()) {
4589 nsIFrame* textPathFrame = it.TextPathFrame();
4590 if (!textPathFrame) {
4591 // Skip past this frame if we're not in a text path.
4592 it.AdvancePastCurrentFrame();
4593 continue;
4596 // Get the path itself.
4597 RefPtr<Path> path = GetTextPath(textPathFrame);
4598 if (!path) {
4599 uint32_t start = it.TextElementCharIndex();
4600 it.AdvancePastCurrentTextPathFrame();
4601 uint32_t end = it.TextElementCharIndex();
4602 for (uint32_t i = start; i < end; i++) {
4603 mPositions[i].mHidden = true;
4605 continue;
4608 SVGTextPathElement* textPath =
4609 static_cast<SVGTextPathElement*>(textPathFrame->GetContent());
4610 uint16_t side =
4611 textPath->EnumAttributes()[SVGTextPathElement::SIDE].GetAnimValue();
4613 gfxFloat offset = GetStartOffset(textPathFrame);
4614 Float pathLength = path->ComputeLength();
4616 // If the first character within the text path is in the middle of a
4617 // cluster or ligature group, just skip it and don't apply text path
4618 // positioning.
4619 while (!it.AtEnd()) {
4620 if (it.IsOriginalCharSkipped()) {
4621 it.Next();
4622 continue;
4624 if (it.IsClusterAndLigatureGroupStart()) {
4625 break;
4627 it.Next();
4630 bool skippedEndOfTextPath = false;
4632 // Loop for each character in the text path.
4633 while (!it.AtEnd() && it.TextPathFrame() &&
4634 it.TextPathFrame()->GetContent() == textPath) {
4635 // The index of the cluster or ligature group's first character.
4636 uint32_t i = it.TextElementCharIndex();
4638 // The index of the next character of the cluster or ligature.
4639 // We track this as we loop over the characters below so that we
4640 // can detect undisplayed characters and append entries into
4641 // partialAdvances for them.
4642 uint32_t j = i + 1;
4644 MOZ_ASSERT(!mPositions[i].mClusterOrLigatureGroupMiddle);
4646 gfxFloat sign = it.TextRun()->IsRightToLeft() ? -1.0 : 1.0;
4647 bool vertical = it.TextRun()->IsVertical();
4649 // Compute cumulative advances for each character of the cluster or
4650 // ligature group.
4651 AutoTArray<gfxFloat, 4> partialAdvances;
4652 gfxFloat partialAdvance = it.GetAdvance(context);
4653 partialAdvances.AppendElement(partialAdvance);
4654 while (it.Next()) {
4655 // Append entries for any undisplayed characters the CharIterator
4656 // skipped over.
4657 MOZ_ASSERT(j <= it.TextElementCharIndex());
4658 while (j < it.TextElementCharIndex()) {
4659 partialAdvances.AppendElement(partialAdvance);
4660 ++j;
4662 // This loop may end up outside of the current text path, but
4663 // that's OK; we'll consider any complete cluster or ligature
4664 // group that begins inside the text path as being affected
4665 // by it.
4666 if (it.IsOriginalCharSkipped()) {
4667 if (!it.TextPathFrame()) {
4668 skippedEndOfTextPath = true;
4669 break;
4671 // Leave partialAdvance unchanged.
4672 } else if (it.IsClusterAndLigatureGroupStart()) {
4673 break;
4674 } else {
4675 partialAdvance += it.GetAdvance(context);
4677 partialAdvances.AppendElement(partialAdvance);
4680 if (!skippedEndOfTextPath) {
4681 // Any final undisplayed characters the CharIterator skipped over.
4682 MOZ_ASSERT(j <= it.TextElementCharIndex());
4683 while (j < it.TextElementCharIndex()) {
4684 partialAdvances.AppendElement(partialAdvance);
4685 ++j;
4689 gfxFloat halfAdvance =
4690 partialAdvances.LastElement() / mFontSizeScaleFactor / 2.0;
4691 gfxFloat midx =
4692 (vertical ? mPositions[i].mPosition.y : mPositions[i].mPosition.x) +
4693 sign * halfAdvance + offset;
4695 // Hide the character if it falls off the end of the path.
4696 mPositions[i].mHidden = midx < 0 || midx > pathLength;
4698 // Position the character on the path at the right angle.
4699 Point tangent; // Unit vector tangent to the point we find.
4700 Point pt;
4701 if (side == TEXTPATH_SIDETYPE_RIGHT) {
4702 pt = path->ComputePointAtLength(Float(pathLength - midx), &tangent);
4703 tangent = -tangent;
4704 } else {
4705 pt = path->ComputePointAtLength(Float(midx), &tangent);
4707 Float rotation = vertical ? atan2f(-tangent.x, tangent.y)
4708 : atan2f(tangent.y, tangent.x);
4709 Point normal(-tangent.y, tangent.x); // Unit vector normal to the point.
4710 Point offsetFromPath = normal * (vertical ? -mPositions[i].mPosition.x
4711 : mPositions[i].mPosition.y);
4712 pt += offsetFromPath;
4713 Point direction = tangent * sign;
4714 mPositions[i].mPosition =
4715 ThebesPoint(pt) - ThebesPoint(direction) * halfAdvance;
4716 mPositions[i].mAngle += rotation;
4718 // Position any characters for a partial ligature.
4719 for (uint32_t k = i + 1; k < j; k++) {
4720 gfxPoint partialAdvance = ThebesPoint(direction) *
4721 partialAdvances[k - i] / mFontSizeScaleFactor;
4722 mPositions[k].mPosition = mPositions[i].mPosition + partialAdvance;
4723 mPositions[k].mAngle = mPositions[i].mAngle;
4724 mPositions[k].mHidden = mPositions[i].mHidden;
4730 void SVGTextFrame::DoAnchoring() {
4731 nsPresContext* presContext = PresContext();
4733 CharIterator it(this, CharIterator::eOriginal, /* aSubtree */ nullptr);
4735 // Don't need to worry about skipped or trimmed characters.
4736 while (!it.AtEnd() &&
4737 (it.IsOriginalCharSkipped() || it.IsOriginalCharTrimmed())) {
4738 it.Next();
4741 bool vertical = GetWritingMode().IsVertical();
4742 uint32_t start = it.TextElementCharIndex();
4743 while (start < mPositions.Length()) {
4744 it.AdvanceToCharacter(start);
4745 nsTextFrame* chunkFrame = it.TextFrame();
4747 // Measure characters in this chunk to find the left-most and right-most
4748 // edges of all glyphs within the chunk.
4749 uint32_t index = it.TextElementCharIndex();
4750 uint32_t end = start;
4751 gfxFloat left = std::numeric_limits<gfxFloat>::infinity();
4752 gfxFloat right = -std::numeric_limits<gfxFloat>::infinity();
4753 do {
4754 if (!it.IsOriginalCharSkipped() && !it.IsOriginalCharTrimmed()) {
4755 gfxFloat advance = it.GetAdvance(presContext) / mFontSizeScaleFactor;
4756 gfxFloat pos = it.TextRun()->IsVertical()
4757 ? mPositions[index].mPosition.y
4758 : mPositions[index].mPosition.x;
4759 if (it.TextRun()->IsRightToLeft()) {
4760 left = std::min(left, pos - advance);
4761 right = std::max(right, pos);
4762 } else {
4763 left = std::min(left, pos);
4764 right = std::max(right, pos + advance);
4767 it.Next();
4768 index = end = it.TextElementCharIndex();
4769 } while (!it.AtEnd() && !mPositions[end].mStartOfChunk);
4771 if (left != std::numeric_limits<gfxFloat>::infinity()) {
4772 bool isRTL =
4773 chunkFrame->StyleVisibility()->mDirection == StyleDirection::Rtl;
4774 TextAnchorSide anchor = ConvertLogicalTextAnchorToPhysical(
4775 chunkFrame->StyleSVG()->mTextAnchor, isRTL);
4777 ShiftAnchoredChunk(mPositions, start, end, left, right, anchor, vertical);
4780 start = it.TextElementCharIndex();
4784 void SVGTextFrame::DoGlyphPositioning() {
4785 mPositions.Clear();
4786 RemoveStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
4788 nsIFrame* kid = PrincipalChildList().FirstChild();
4789 if (kid && kid->IsSubtreeDirty()) {
4790 MOZ_ASSERT(false, "should have already reflowed the kid");
4791 return;
4794 // Since we can be called directly via GetBBoxContribution, our correspondence
4795 // may not be up to date.
4796 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
4798 // Determine the positions of each character in app units.
4799 AutoTArray<nsPoint, 64> charPositions;
4800 DetermineCharPositions(charPositions);
4802 if (charPositions.IsEmpty()) {
4803 // No characters, so nothing to do.
4804 return;
4807 // If the textLength="" attribute was specified, then we need ResolvePositions
4808 // to record that a new run starts with each glyph.
4809 SVGTextContentElement* element =
4810 static_cast<SVGTextContentElement*>(GetContent());
4811 SVGAnimatedLength* textLengthAttr =
4812 element->GetAnimatedLength(nsGkAtoms::textLength);
4813 uint16_t lengthAdjust =
4814 element->EnumAttributes()[SVGTextContentElement::LENGTHADJUST]
4815 .GetAnimValue();
4816 bool adjustingTextLength = textLengthAttr->IsExplicitlySet();
4817 float expectedTextLength = textLengthAttr->GetAnimValue(element);
4819 if (adjustingTextLength &&
4820 (expectedTextLength < 0.0f || lengthAdjust == LENGTHADJUST_UNKNOWN)) {
4821 // If textLength="" is less than zero or lengthAdjust is unknown, ignore it.
4822 adjustingTextLength = false;
4825 // Get the x, y, dx, dy, rotate values for the subtree.
4826 AutoTArray<gfxPoint, 16> deltas;
4827 if (!ResolvePositions(deltas, adjustingTextLength)) {
4828 // If ResolvePositions returned false, it means either there were some
4829 // characters in the DOM but none of them are displayed, or there was
4830 // an error in processing mPositions. Clear out mPositions so that we don't
4831 // attempt to do any painting later.
4832 mPositions.Clear();
4833 return;
4836 // XXX We might be able to do less work when there is at most a single
4837 // x/y/dx/dy position.
4839 // Truncate the positioning arrays to the actual number of characters present.
4840 TruncateTo(deltas, charPositions);
4841 TruncateTo(mPositions, charPositions);
4843 // Fill in an unspecified character position at index 0.
4844 if (!mPositions[0].IsXSpecified()) {
4845 mPositions[0].mPosition.x = 0.0;
4847 if (!mPositions[0].IsYSpecified()) {
4848 mPositions[0].mPosition.y = 0.0;
4850 if (!mPositions[0].IsAngleSpecified()) {
4851 mPositions[0].mAngle = 0.0;
4854 nsPresContext* presContext = PresContext();
4855 bool vertical = GetWritingMode().IsVertical();
4857 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
4858 presContext->AppUnitsPerDevPixel());
4859 double factor = cssPxPerDevPx / mFontSizeScaleFactor;
4861 // Determine how much to compress or expand glyph positions due to
4862 // textLength="" and lengthAdjust="".
4863 double adjustment = 0.0;
4864 mLengthAdjustScaleFactor = 1.0f;
4865 if (adjustingTextLength) {
4866 nscoord frameLength =
4867 vertical ? PrincipalChildList().FirstChild()->GetRect().height
4868 : PrincipalChildList().FirstChild()->GetRect().width;
4869 float actualTextLength = static_cast<float>(
4870 presContext->AppUnitsToGfxUnits(frameLength) * factor);
4872 switch (lengthAdjust) {
4873 case LENGTHADJUST_SPACINGANDGLYPHS:
4874 // Scale the glyphs and their positions.
4875 if (actualTextLength > 0) {
4876 mLengthAdjustScaleFactor = expectedTextLength / actualTextLength;
4878 break;
4880 default:
4881 MOZ_ASSERT(lengthAdjust == LENGTHADJUST_SPACING);
4882 // Just add space between each glyph.
4883 int32_t adjustableSpaces = 0;
4884 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4885 if (!mPositions[i].mUnaddressable) {
4886 adjustableSpaces++;
4889 if (adjustableSpaces) {
4890 adjustment =
4891 (expectedTextLength - actualTextLength) / adjustableSpaces;
4893 break;
4897 // Fill in any unspecified character positions based on the positions recorded
4898 // in charPositions, and also add in the dx/dy values.
4899 if (!deltas.IsEmpty()) {
4900 mPositions[0].mPosition += deltas[0];
4903 gfxFloat xLengthAdjustFactor = vertical ? 1.0 : mLengthAdjustScaleFactor;
4904 gfxFloat yLengthAdjustFactor = vertical ? mLengthAdjustScaleFactor : 1.0;
4905 for (uint32_t i = 1; i < mPositions.Length(); i++) {
4906 // Fill in unspecified x position.
4907 if (!mPositions[i].IsXSpecified()) {
4908 nscoord d = charPositions[i].x - charPositions[i - 1].x;
4909 mPositions[i].mPosition.x =
4910 mPositions[i - 1].mPosition.x +
4911 presContext->AppUnitsToGfxUnits(d) * factor * xLengthAdjustFactor;
4912 if (!vertical && !mPositions[i].mUnaddressable) {
4913 mPositions[i].mPosition.x += adjustment;
4916 // Fill in unspecified y position.
4917 if (!mPositions[i].IsYSpecified()) {
4918 nscoord d = charPositions[i].y - charPositions[i - 1].y;
4919 mPositions[i].mPosition.y =
4920 mPositions[i - 1].mPosition.y +
4921 presContext->AppUnitsToGfxUnits(d) * factor * yLengthAdjustFactor;
4922 if (vertical && !mPositions[i].mUnaddressable) {
4923 mPositions[i].mPosition.y += adjustment;
4926 // Add in dx/dy.
4927 if (i < deltas.Length()) {
4928 mPositions[i].mPosition += deltas[i];
4930 // Fill in unspecified rotation values.
4931 if (!mPositions[i].IsAngleSpecified()) {
4932 mPositions[i].mAngle = 0.0f;
4936 MOZ_ASSERT(mPositions.Length() == charPositions.Length());
4938 AdjustChunksForLineBreaks();
4939 AdjustPositionsForClusters();
4940 DoAnchoring();
4941 DoTextPathLayout();
4944 bool SVGTextFrame::ShouldRenderAsPath(nsTextFrame* aFrame,
4945 bool& aShouldPaintSVGGlyphs) {
4946 // Rendering to a clip path.
4947 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
4948 aShouldPaintSVGGlyphs = false;
4949 return true;
4952 aShouldPaintSVGGlyphs = true;
4954 const nsStyleSVG* style = aFrame->StyleSVG();
4956 // Fill is a non-solid paint or is not opaque.
4957 if (!(style->mFill.kind.IsNone() ||
4958 (style->mFill.kind.IsColor() &&
4959 SVGUtils::GetOpacity(style->mFillOpacity, /*aContextPaint*/ nullptr) ==
4960 1.0f))) {
4961 return true;
4964 // If we're going to need to draw a non-opaque shadow.
4965 // It's possible nsTextFrame will support non-opaque shadows in the future,
4966 // in which case this test can be removed.
4967 if (style->mFill.kind.IsColor() && aFrame->StyleText()->HasTextShadow() &&
4968 NS_GET_A(style->mFill.kind.AsColor().CalcColor(*aFrame->Style())) !=
4969 0xFF) {
4970 return true;
4973 // Text has a stroke.
4974 if (style->HasStroke()) {
4975 if (style->mStrokeWidth.IsContextValue()) {
4976 return true;
4978 if (SVGContentUtils::CoordToFloat(
4979 static_cast<SVGElement*>(GetContent()),
4980 style->mStrokeWidth.AsLengthPercentage()) > 0) {
4981 return true;
4985 return false;
4988 void SVGTextFrame::ScheduleReflowSVG() {
4989 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
4990 ScheduleReflowSVGNonDisplayText(
4991 IntrinsicDirty::FrameAncestorsAndDescendants);
4992 } else {
4993 SVGUtils::ScheduleReflowSVG(this);
4997 void SVGTextFrame::NotifyGlyphMetricsChange(bool aUpdateTextCorrespondence) {
4998 if (aUpdateTextCorrespondence) {
4999 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
5001 AddStateBits(NS_STATE_SVG_POSITIONING_DIRTY);
5002 nsLayoutUtils::PostRestyleEvent(mContent->AsElement(), RestyleHint{0},
5003 nsChangeHint_InvalidateRenderingObservers);
5004 ScheduleReflowSVG();
5007 void SVGTextFrame::UpdateGlyphPositioning() {
5008 nsIFrame* kid = PrincipalChildList().FirstChild();
5009 if (!kid) {
5010 return;
5013 if (HasAnyStateBits(NS_STATE_SVG_POSITIONING_DIRTY)) {
5014 DoGlyphPositioning();
5018 void SVGTextFrame::MaybeResolveBidiForAnonymousBlockChild() {
5019 nsIFrame* kid = PrincipalChildList().FirstChild();
5021 if (kid && kid->HasAnyStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION) &&
5022 PresContext()->BidiEnabled()) {
5023 MOZ_ASSERT(static_cast<nsBlockFrame*>(do_QueryFrame(kid)),
5024 "Expect anonymous child to be an nsBlockFrame");
5025 nsBidiPresUtils::Resolve(static_cast<nsBlockFrame*>(kid));
5029 void SVGTextFrame::MaybeReflowAnonymousBlockChild() {
5030 nsIFrame* kid = PrincipalChildList().FirstChild();
5031 if (!kid) {
5032 return;
5035 NS_ASSERTION(!kid->HasAnyStateBits(NS_FRAME_IN_REFLOW),
5036 "should not be in reflow when about to reflow again");
5038 if (IsSubtreeDirty()) {
5039 if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
5040 // If we require a full reflow, ensure our kid is marked fully dirty.
5041 // (Note that our anonymous nsBlockFrame is not an ISVGDisplayableFrame,
5042 // so even when we are called via our ReflowSVG this will not be done for
5043 // us by SVGDisplayContainerFrame::ReflowSVG.)
5044 kid->MarkSubtreeDirty();
5047 // The RecordCorrespondence and DoReflow calls can result in new text frames
5048 // being created (due to bidi resolution or reflow). We set this bit to
5049 // guard against unnecessarily calling back in to
5050 // ScheduleReflowSVGNonDisplayText from nsIFrame::DidSetComputedStyle on
5051 // those new text frames.
5052 AddStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5054 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
5056 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
5057 "should be under ReflowSVG");
5058 nsPresContext::InterruptPreventer noInterrupts(PresContext());
5059 DoReflow();
5061 RemoveStateBits(NS_STATE_SVG_TEXT_IN_REFLOW);
5065 void SVGTextFrame::DoReflow() {
5066 MOZ_ASSERT(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW));
5068 // Since we are going to reflow the anonymous block frame, we will
5069 // need to update mPositions.
5070 // We also mark our text correspondence as dirty since we can end up needing
5071 // reflow in ways that do not set NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY.
5072 // (We'd then fail the "expected a TextNodeCorrespondenceProperty" assertion
5073 // when UpdateGlyphPositioning() is called after we return.)
5074 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY |
5075 NS_STATE_SVG_POSITIONING_DIRTY);
5077 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5078 // Normally, these dirty flags would be cleared in ReflowSVG(), but that
5079 // doesn't get called for non-display frames. We don't want to reflow our
5080 // descendants every time SVGTextFrame::PaintSVG makes sure that we have
5081 // valid positions by calling UpdateGlyphPositioning(), so we need to clear
5082 // these dirty bits. Note that this also breaks an invalidation loop where
5083 // our descendants invalidate as they reflow, which invalidates rendering
5084 // observers, which reschedules the frame that is currently painting by
5085 // referencing us to paint again. See bug 839958 comment 7. Hopefully we
5086 // will break that loop more convincingly at some point.
5087 RemoveStateBits(NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
5090 nsPresContext* presContext = PresContext();
5091 nsIFrame* kid = PrincipalChildList().FirstChild();
5092 if (!kid) {
5093 return;
5096 UniquePtr<gfxContext> renderingContext =
5097 presContext->PresShell()->CreateReferenceRenderingContext();
5099 if (UpdateFontSizeScaleFactor()) {
5100 // If the font size scale factor changed, we need the block to report
5101 // an updated preferred width.
5102 kid->MarkIntrinsicISizesDirty();
5105 nscoord inlineSize = kid->GetPrefISize(renderingContext.get());
5106 WritingMode wm = kid->GetWritingMode();
5107 ReflowInput reflowInput(presContext, kid, renderingContext.get(),
5108 LogicalSize(wm, inlineSize, NS_UNCONSTRAINEDSIZE));
5109 ReflowOutput desiredSize(reflowInput);
5110 nsReflowStatus status;
5112 NS_ASSERTION(
5113 reflowInput.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) &&
5114 reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0),
5115 "style system should ensure that :-moz-svg-text "
5116 "does not get styled");
5118 kid->Reflow(presContext, desiredSize, reflowInput, status);
5119 kid->DidReflow(presContext, &reflowInput);
5120 kid->SetSize(wm, desiredSize.Size(wm));
5123 // Usable font size range in devpixels / user-units
5124 #define CLAMP_MIN_SIZE 8.0
5125 #define CLAMP_MAX_SIZE 200.0
5126 #define PRECISE_SIZE 200.0
5128 bool SVGTextFrame::UpdateFontSizeScaleFactor() {
5129 double oldFontSizeScaleFactor = mFontSizeScaleFactor;
5131 nsPresContext* presContext = PresContext();
5133 bool geometricPrecision = false;
5134 CSSCoord min = std::numeric_limits<float>::max();
5135 CSSCoord max = std::numeric_limits<float>::min();
5136 bool anyText = false;
5138 // Find the minimum and maximum font sizes used over all the
5139 // nsTextFrames.
5140 TextFrameIterator it(this);
5141 nsTextFrame* f = it.Current();
5142 while (f) {
5143 if (!geometricPrecision) {
5144 // Unfortunately we can't treat text-rendering:geometricPrecision
5145 // separately for each text frame.
5146 geometricPrecision = f->StyleText()->mTextRendering ==
5147 StyleTextRendering::Geometricprecision;
5149 const auto& fontSize = f->StyleFont()->mFont.size;
5150 if (!fontSize.IsZero()) {
5151 min = std::min(min, fontSize.ToCSSPixels());
5152 max = std::max(max, fontSize.ToCSSPixels());
5153 anyText = true;
5155 f = it.Next();
5158 if (!anyText) {
5159 // No text, so no need for scaling.
5160 mFontSizeScaleFactor = 1.0;
5161 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5164 if (geometricPrecision) {
5165 // We want to ensure minSize is scaled to PRECISE_SIZE.
5166 mFontSizeScaleFactor = PRECISE_SIZE / min;
5167 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5170 // When we are non-display, we could be painted in different coordinate
5171 // spaces, and we don't want to have to reflow for each of these. We
5172 // just assume that the context scale is 1.0 for them all, so we don't
5173 // get stuck with a font size scale factor based on whichever referencing
5174 // frame happens to reflow first.
5175 double contextScale = 1.0;
5176 if (!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
5177 gfxMatrix m(GetCanvasTM());
5178 if (!m.IsSingular()) {
5179 contextScale = GetContextScale(m);
5180 if (!std::isfinite(contextScale)) {
5181 contextScale = 1.0f;
5185 mLastContextScale = contextScale;
5187 // But we want to ignore any scaling required due to HiDPI displays, since
5188 // regular CSS text frames will still create text runs using the font size
5189 // in CSS pixels, and we want SVG text to have the same rendering as HTML
5190 // text for regular font sizes.
5191 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
5192 presContext->AppUnitsPerDevPixel());
5193 contextScale *= cssPxPerDevPx;
5195 double minTextRunSize = min * contextScale;
5196 double maxTextRunSize = max * contextScale;
5198 if (minTextRunSize >= CLAMP_MIN_SIZE && maxTextRunSize <= CLAMP_MAX_SIZE) {
5199 // We are already in the ideal font size range for all text frames,
5200 // so we only have to take into account the contextScale.
5201 mFontSizeScaleFactor = contextScale;
5202 } else if (max / min > CLAMP_MAX_SIZE / CLAMP_MIN_SIZE) {
5203 // We can't scale the font sizes so that all of the text frames lie
5204 // within our ideal font size range.
5205 // Heuristically, if the maxTextRunSize is within the CLAMP_MAX_SIZE
5206 // as a reasonable value, it's likely to be the user's intent to
5207 // get a valid font for the maxTextRunSize one, we should honor it.
5208 // The same for minTextRunSize.
5209 if (maxTextRunSize <= CLAMP_MAX_SIZE) {
5210 mFontSizeScaleFactor = CLAMP_MAX_SIZE / max;
5211 } else if (minTextRunSize >= CLAMP_MIN_SIZE) {
5212 mFontSizeScaleFactor = CLAMP_MIN_SIZE / min;
5213 } else {
5214 // So maxTextRunSize is too big, minTextRunSize is too small,
5215 // we can't really do anything for this case, just leave it as is.
5216 mFontSizeScaleFactor = contextScale;
5218 } else if (minTextRunSize < CLAMP_MIN_SIZE) {
5219 mFontSizeScaleFactor = CLAMP_MIN_SIZE / min;
5220 } else {
5221 mFontSizeScaleFactor = CLAMP_MAX_SIZE / max;
5224 return mFontSizeScaleFactor != oldFontSizeScaleFactor;
5227 double SVGTextFrame::GetFontSizeScaleFactor() const {
5228 return mFontSizeScaleFactor;
5232 * Take aPoint, which is in the <text> element's user space, and convert
5233 * it to the appropriate frame user space of aChildFrame according to
5234 * which rendered run the point hits.
5236 Point SVGTextFrame::TransformFramePointToTextChild(
5237 const Point& aPoint, const nsIFrame* aChildFrame) {
5238 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(
5239 aChildFrame->GetParent(),
5240 LayoutFrameType::SVGText) == this,
5241 "aChildFrame must be a descendant of this frame");
5243 UpdateGlyphPositioning();
5245 nsPresContext* presContext = PresContext();
5247 // Add in the mRect offset to aPoint, as that will have been taken into
5248 // account when transforming the point from the ancestor frame down
5249 // to this one.
5250 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
5251 presContext->AppUnitsPerDevPixel());
5252 float factor = AppUnitsPerCSSPixel();
5253 Point framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5254 NSAppUnitsToFloatPixels(mRect.y, factor));
5255 Point pointInUserSpace = aPoint * cssPxPerDevPx + framePosition;
5257 // Find the closest rendered run for the text frames beneath aChildFrame.
5258 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5259 aChildFrame);
5260 TextRenderedRun hit;
5261 gfxPoint pointInRun;
5262 nscoord dx = nscoord_MAX;
5263 nscoord dy = nscoord_MAX;
5264 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5265 uint32_t flags = TextRenderedRun::eIncludeFill |
5266 TextRenderedRun::eIncludeStroke |
5267 TextRenderedRun::eNoHorizontalOverflow;
5268 gfxRect runRect =
5269 run.GetRunUserSpaceRect(presContext, flags).ToThebesRect();
5271 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5272 if (!m.Invert()) {
5273 return aPoint;
5275 gfxPoint pointInRunUserSpace =
5276 m.TransformPoint(ThebesPoint(pointInUserSpace));
5278 if (Inside(runRect, pointInRunUserSpace)) {
5279 // The point was inside the rendered run's rect, so we choose it.
5280 dx = 0;
5281 dy = 0;
5282 pointInRun = pointInRunUserSpace;
5283 hit = run;
5284 } else if (nsLayoutUtils::PointIsCloserToRect(pointInRunUserSpace, runRect,
5285 dx, dy)) {
5286 // The point was closer to this rendered run's rect than any others
5287 // we've seen so far.
5288 pointInRun.x =
5289 clamped(pointInRunUserSpace.x.value, runRect.X(), runRect.XMost());
5290 pointInRun.y =
5291 clamped(pointInRunUserSpace.y.value, runRect.Y(), runRect.YMost());
5292 hit = run;
5296 if (!hit.mFrame) {
5297 // We didn't find any rendered runs for the frame.
5298 return aPoint;
5301 // Return the point in user units relative to the nsTextFrame,
5302 // but taking into account mFontSizeScaleFactor.
5303 gfxMatrix m = hit.GetTransformFromRunUserSpaceToFrameUserSpace(presContext);
5304 m.PreScale(mFontSizeScaleFactor, mFontSizeScaleFactor);
5305 return ToPoint(m.TransformPoint(pointInRun) / cssPxPerDevPx);
5309 * For each rendered run beneath aChildFrame, translate aRect from
5310 * aChildFrame to the run's text frame, transform it then into
5311 * the run's frame user space, intersect it with the run's
5312 * frame user space rect, then transform it up to user space.
5313 * The result is the union of all of these.
5315 gfxRect SVGTextFrame::TransformFrameRectFromTextChild(
5316 const nsRect& aRect, const nsIFrame* aChildFrame) {
5317 NS_ASSERTION(aChildFrame && nsLayoutUtils::GetClosestFrameOfType(
5318 aChildFrame->GetParent(),
5319 LayoutFrameType::SVGText) == this,
5320 "aChildFrame must be a descendant of this frame");
5322 UpdateGlyphPositioning();
5324 nsPresContext* presContext = PresContext();
5326 gfxRect result;
5327 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5328 aChildFrame);
5329 for (TextRenderedRun run = it.Current(); run.mFrame; run = it.Next()) {
5330 // First, translate aRect from aChildFrame to this run's frame.
5331 nsRect rectInTextFrame = aRect + aChildFrame->GetOffsetTo(run.mFrame);
5333 // Scale it into frame user space.
5334 gfxRect rectInFrameUserSpace = AppUnitsToFloatCSSPixels(
5335 gfxRect(rectInTextFrame.x, rectInTextFrame.y, rectInTextFrame.width,
5336 rectInTextFrame.height),
5337 presContext);
5339 // Intersect it with the run.
5340 uint32_t flags =
5341 TextRenderedRun::eIncludeFill | TextRenderedRun::eIncludeStroke;
5343 if (rectInFrameUserSpace.IntersectRect(
5344 rectInFrameUserSpace,
5345 run.GetFrameUserSpaceRect(presContext, flags).ToThebesRect())) {
5346 // Transform it up to user space of the <text>
5347 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5348 gfxRect rectInUserSpace = m.TransformRect(rectInFrameUserSpace);
5350 // Union it into the result.
5351 result.UnionRect(result, rectInUserSpace);
5355 // Subtract the mRect offset from the result, as our user space for
5356 // this frame is relative to the top-left of mRect.
5357 float factor = AppUnitsPerCSSPixel();
5358 gfxPoint framePosition(NSAppUnitsToFloatPixels(mRect.x, factor),
5359 NSAppUnitsToFloatPixels(mRect.y, factor));
5361 return result - framePosition;
5364 Rect SVGTextFrame::TransformFrameRectFromTextChild(
5365 const Rect& aRect, const nsIFrame* aChildFrame) {
5366 nscoord appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
5367 nsRect r = LayoutDevicePixel::ToAppUnits(
5368 LayoutDeviceRect::FromUnknownRect(aRect), appUnitsPerDevPixel);
5369 gfxRect resultCssUnits = TransformFrameRectFromTextChild(r, aChildFrame);
5370 float devPixelPerCSSPixel =
5371 float(AppUnitsPerCSSPixel()) / appUnitsPerDevPixel;
5372 resultCssUnits.Scale(devPixelPerCSSPixel);
5373 return ToRect(resultCssUnits);
5376 Point SVGTextFrame::TransformFramePointFromTextChild(
5377 const Point& aPoint, const nsIFrame* aChildFrame) {
5378 return TransformFrameRectFromTextChild(Rect(aPoint, Size(1, 1)), aChildFrame)
5379 .TopLeft();
5382 void SVGTextFrame::AppendDirectlyOwnedAnonBoxes(
5383 nsTArray<OwnedAnonBox>& aResult) {
5384 MOZ_ASSERT(PrincipalChildList().FirstChild(), "Must have our anon box");
5385 aResult.AppendElement(OwnedAnonBox(PrincipalChildList().FirstChild()));
5388 } // namespace mozilla