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/. */
8 #include "SVGTextFrame.h"
10 // Keep others in (case-insensitive) order:
11 #include "DOMSVGPoint.h"
12 #include "gfx2DGlue.h"
13 #include "gfxContext.h"
15 #include "gfxSkipChars.h"
18 #include "LookAndFeel.h"
19 #include "nsAlgorithm.h"
20 #include "nsBidiPresUtils.h"
21 #include "nsBlockFrame.h"
23 #include "nsContentUtils.h"
24 #include "nsGkAtoms.h"
25 #include "nsQuickSort.h"
26 #include "SVGPaintServerFrame.h"
28 #include "nsTextFrame.h"
29 #include "SVGAnimatedNumberList.h"
30 #include "SVGContentUtils.h"
31 #include "SVGContextPaint.h"
32 #include "SVGLengthList.h"
33 #include "SVGNumberList.h"
34 #include "nsLayoutUtils.h"
35 #include "nsFrameSelection.h"
36 #include "nsStyleStructInlines.h"
37 #include "mozilla/DisplaySVGItem.h"
38 #include "mozilla/Likely.h"
39 #include "mozilla/PresShell.h"
40 #include "mozilla/SVGObserverUtils.h"
41 #include "mozilla/SVGOuterSVGFrame.h"
42 #include "mozilla/SVGUtils.h"
43 #include "mozilla/dom/DOMPointBinding.h"
44 #include "mozilla/dom/Selection.h"
45 #include "mozilla/dom/SVGGeometryElement.h"
46 #include "mozilla/dom/SVGRect.h"
47 #include "mozilla/dom/SVGTextContentElementBinding.h"
48 #include "mozilla/dom/SVGTextPathElement.h"
49 #include "mozilla/dom/Text.h"
50 #include "mozilla/gfx/2D.h"
51 #include "mozilla/gfx/PatternHelpers.h"
56 using namespace mozilla::dom
;
57 using namespace mozilla::dom::SVGTextContentElement_Binding
;
58 using namespace mozilla::gfx
;
59 using namespace mozilla::image
;
63 // ============================================================================
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());
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
));
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
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
,
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
) {
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>
164 static nsIContent
* GetFirstNonAAncestor(nsIContent
* aContent
) {
165 while (aContent
&& aContent
->IsSVGElement(nsGkAtoms::a
)) {
166 aContent
= aContent
->GetParent();
172 * Returns whether the given node is a text content element[1], taking into
173 * account whether it has a valid parent.
177 * <svg xmlns="http://www.w3.org/2000/svg">
178 * <text><a/><text/></text>
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
210 static bool IsNonEmptyTextFrame(nsIFrame
* aFrame
) {
211 nsTextFrame
* textFrame
= do_QueryFrame(aFrame
);
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
,
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 "
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
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()
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
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");
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 // ============================================================================
366 // ----------------------------------------------------------------------------
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
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
)
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
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:
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:
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.
546 // Includes the fill geometry of the text in the returned rectangle.
548 // Includes the stroke geometry of the text in the returned rectangle.
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
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
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
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
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.
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.
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.
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.)
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
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.
709 float cssPxPerDevPx
=
710 nsPresContext::AppUnitsToFloatCSSPixels(aContext
->AppUnitsPerDevPixel());
712 // Glyph position in user space.
713 m
.PreTranslate(mPosition
/ cssPxPerDevPx
);
715 // Take into account any font size scaling and scaling due to textLength="".
716 m
.PreScale(1.0 / mFontSizeScaleFactor
, 1.0 / mFontSizeScaleFactor
);
718 // Rotation due to rotate="" or a <textPath>.
719 m
.PreRotate(mRotate
);
721 m
.PreScale(mLengthAdjustScaleFactor
, 1.0);
723 // Translation to get the text frame in the right place.
727 t
= nsPoint(-mBaseline
, IsRightToLeft()
728 ? -mFrame
->GetRect().height
+ aVisIEndEdge
731 t
= nsPoint(IsRightToLeft() ? -mFrame
->GetRect().width
+ aVisIEndEdge
735 m
.PreTranslate(AppUnitsToGfxUnits(t
, aContext
));
740 gfxMatrix
TextRenderedRun::GetTransformFromRunUserSpaceToUserSpace(
741 nsPresContext
* aContext
) const {
747 float cssPxPerDevPx
=
748 nsPresContext::AppUnitsToFloatCSSPixels(aContext
->AppUnitsPerDevPixel());
751 GetClipEdges(start
, end
);
753 // Glyph position in user space.
754 m
.PreTranslate(mPosition
);
756 // Rotation due to rotate="" or a <textPath>.
757 m
.PreRotate(mRotate
);
759 // Scale due to textLength="".
760 m
.PreScale(mLengthAdjustScaleFactor
, 1.0);
762 // Translation to get the text frame in the right place.
765 t
= nsPoint(-mBaseline
,
766 IsRightToLeft() ? -mFrame
->GetRect().height
+ start
+ end
: 0);
768 t
= nsPoint(IsRightToLeft() ? -mFrame
->GetRect().width
+ start
+ end
: 0,
771 m
.PreTranslate(AppUnitsToGfxUnits(t
, aContext
) * cssPxPerDevPx
/
772 mFontSizeScaleFactor
);
777 gfxMatrix
TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
778 nsPresContext
* aContext
) const {
785 GetClipEdges(start
, end
);
787 // Translate by the horizontal distance into the text frame this
789 gfxFloat appPerCssPx
= AppUnitsPerCSSPixel();
790 gfxPoint t
= IsVertical() ? gfxPoint(0, start
/ appPerCssPx
)
791 : gfxPoint(start
/ appPerCssPx
, 0);
792 return m
.PreTranslate(t
);
795 SVGBBox
TextRenderedRun::GetRunUserSpaceRect(nsPresContext
* aContext
,
796 uint32_t aFlags
) const {
802 // Determine the amount of overflow above and below the frame's mRect.
804 // We need to call InkOverflowRectRelativeToSelf because this includes
805 // overflowing decorations, which the MeasureText call below does not. We
806 // assume here the decorations only overflow above and below the frame, never
808 nsRect self
= mFrame
->InkOverflowRectRelativeToSelf();
809 nsRect rect
= mFrame
->GetRect();
810 bool vertical
= IsVertical();
811 nscoord above
= vertical
? -self
.x
: -self
.y
;
813 vertical
? self
.XMost() - rect
.width
: self
.YMost() - rect
.height
;
815 gfxSkipCharsIterator it
= mFrame
->EnsureTextRun(nsTextFrame::eInflated
);
816 gfxSkipCharsIterator start
= it
;
817 gfxTextRun
* textRun
= mFrame
->GetTextRun(nsTextFrame::eInflated
);
819 // Get the content range for this rendered run.
820 Range range
= ConvertOriginalToSkipped(it
, mTextFrameContentOffset
,
821 mTextFrameContentLength
);
822 if (range
.Length() == 0) {
826 // FIXME(heycam): We could create a single PropertyProvider for all
827 // TextRenderedRuns that correspond to the text frame, rather than recreate
828 // it each time here.
829 nsTextFrame::PropertyProvider
provider(mFrame
, start
);
831 // Measure that range.
832 gfxTextRun::Metrics metrics
= textRun
->MeasureText(
833 range
, gfxFont::LOOSE_INK_EXTENTS
, nullptr, &provider
);
834 // Make sure it includes the font-box.
835 gfxRect
fontBox(0, -metrics
.mAscent
, metrics
.mAdvanceWidth
,
836 metrics
.mAscent
+ metrics
.mDescent
);
837 metrics
.mBoundingBox
.UnionRect(metrics
.mBoundingBox
, fontBox
);
839 // Determine the rectangle that covers the rendered run's fill,
840 // taking into account the measured vertical overflow due to
843 NSToCoordRoundWithClamp(metrics
.mBoundingBox
.y
+ metrics
.mAscent
);
845 if (aFlags
& eNoHorizontalOverflow
) {
847 width
= textRun
->GetAdvanceWidth(range
, &provider
);
853 x
= metrics
.mBoundingBox
.x
;
854 width
= metrics
.mBoundingBox
.width
;
856 nsRect
fillInAppUnits(
857 NSToCoordRoundWithClamp(x
), baseline
- above
,
858 NSToCoordRoundWithClamp(width
),
859 NSToCoordRoundWithClamp(metrics
.mBoundingBox
.height
) + above
+ below
);
860 if (textRun
->IsVertical()) {
861 // Swap line-relative textMetrics dimensions to physical coordinates.
862 std::swap(fillInAppUnits
.x
, fillInAppUnits
.y
);
863 std::swap(fillInAppUnits
.width
, fillInAppUnits
.height
);
866 // Convert the app units rectangle to user units.
867 gfxRect fill
= AppUnitsToFloatCSSPixels(
868 gfxRect(fillInAppUnits
.x
, fillInAppUnits
.y
, fillInAppUnits
.width
,
869 fillInAppUnits
.height
),
872 // Scale the rectangle up due to any mFontSizeScaleFactor.
873 fill
.Scale(1.0 / mFontSizeScaleFactor
);
875 // Include the fill if requested.
876 if (aFlags
& eIncludeFill
) {
880 // Include the stroke if requested.
881 if ((aFlags
& eIncludeStroke
) && !fill
.IsEmpty() &&
882 SVGUtils::GetStrokeWidth(mFrame
) > 0) {
884 SVGUtils::PathExtentsToMaxStrokeExtents(fill
, mFrame
, gfxMatrix()));
890 SVGBBox
TextRenderedRun::GetFrameUserSpaceRect(nsPresContext
* aContext
,
891 uint32_t aFlags
) const {
892 SVGBBox r
= GetRunUserSpaceRect(aContext
, aFlags
);
896 gfxMatrix m
= GetTransformFromRunUserSpaceToFrameUserSpace(aContext
);
897 return m
.TransformBounds(r
.ToThebesRect());
900 SVGBBox
TextRenderedRun::GetUserSpaceRect(
901 nsPresContext
* aContext
, uint32_t aFlags
,
902 const gfxMatrix
* aAdditionalTransform
) const {
903 SVGBBox r
= GetRunUserSpaceRect(aContext
, aFlags
);
907 gfxMatrix m
= GetTransformFromRunUserSpaceToUserSpace(aContext
);
908 if (aAdditionalTransform
) {
909 m
*= *aAdditionalTransform
;
911 return m
.TransformBounds(r
.ToThebesRect());
914 void TextRenderedRun::GetClipEdges(nscoord
& aVisIStartEdge
,
915 nscoord
& aVisIEndEdge
) const {
916 uint32_t contentLength
= mFrame
->GetContentLength();
917 if (mTextFrameContentOffset
== 0 &&
918 mTextFrameContentLength
== contentLength
) {
919 // If the rendered run covers the entire content, we know we don't need
920 // to clip without having to measure anything.
926 gfxSkipCharsIterator it
= mFrame
->EnsureTextRun(nsTextFrame::eInflated
);
927 gfxTextRun
* textRun
= mFrame
->GetTextRun(nsTextFrame::eInflated
);
928 nsTextFrame::PropertyProvider
provider(mFrame
, it
);
930 // Get the covered content offset/length for this rendered run in skipped
931 // characters, since that is what GetAdvanceWidth expects.
932 Range runRange
= ConvertOriginalToSkipped(it
, mTextFrameContentOffset
,
933 mTextFrameContentLength
);
935 // Get the offset/length of the whole nsTextFrame.
936 uint32_t frameOffset
= mFrame
->GetContentOffset();
937 uint32_t frameLength
= mFrame
->GetContentLength();
939 // Trim the whole-nsTextFrame offset/length to remove any leading/trailing
940 // white space, as the nsTextFrame when painting does not include them when
941 // interpreting clip edges.
942 nsTextFrame::TrimmedOffsets trimmedOffsets
=
943 mFrame
->GetTrimmedOffsets(mFrame
->TextFragment());
944 TrimOffsets(frameOffset
, frameLength
, trimmedOffsets
);
946 // Convert the trimmed whole-nsTextFrame offset/length into skipped
948 Range frameRange
= ConvertOriginalToSkipped(it
, frameOffset
, frameLength
);
950 // Measure the advance width in the text run between the start of
951 // frame's content and the start of the rendered run's content,
952 nscoord startEdge
= textRun
->GetAdvanceWidth(
953 Range(frameRange
.start
, runRange
.start
), &provider
);
955 // and between the end of the rendered run's content and the end
956 // of the frame's content.
958 textRun
->GetAdvanceWidth(Range(runRange
.end
, frameRange
.end
), &provider
);
960 if (textRun
->IsRightToLeft()) {
961 aVisIStartEdge
= endEdge
;
962 aVisIEndEdge
= startEdge
;
964 aVisIStartEdge
= startEdge
;
965 aVisIEndEdge
= endEdge
;
969 nscoord
TextRenderedRun::GetAdvanceWidth() const {
970 gfxSkipCharsIterator it
= mFrame
->EnsureTextRun(nsTextFrame::eInflated
);
971 gfxTextRun
* textRun
= mFrame
->GetTextRun(nsTextFrame::eInflated
);
972 nsTextFrame::PropertyProvider
provider(mFrame
, it
);
974 Range range
= ConvertOriginalToSkipped(it
, mTextFrameContentOffset
,
975 mTextFrameContentLength
);
977 return textRun
->GetAdvanceWidth(range
, &provider
);
980 int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext
* aContext
,
981 const gfxPoint
& aPoint
) const {
982 if (mTextFrameContentLength
== 0) {
986 float cssPxPerDevPx
=
987 nsPresContext::AppUnitsToFloatCSSPixels(aContext
->AppUnitsPerDevPixel());
989 // Convert the point from user space into run user space, and take
990 // into account any mFontSizeScaleFactor.
991 gfxMatrix m
= GetTransformFromRunUserSpaceToUserSpace(aContext
);
995 gfxPoint p
= m
.TransformPoint(aPoint
) / cssPxPerDevPx
* mFontSizeScaleFactor
;
997 // First check that the point lies vertically between the top and bottom
998 // edges of the text.
999 gfxFloat ascent
, descent
;
1000 GetAscentAndDescentInAppUnits(mFrame
, ascent
, descent
);
1002 WritingMode writingMode
= mFrame
->GetWritingMode();
1003 if (writingMode
.IsVertical()) {
1004 gfxFloat leftEdge
= mFrame
->GetLogicalBaseline(writingMode
) -
1005 (writingMode
.IsVerticalRL() ? ascent
: descent
);
1006 gfxFloat rightEdge
= leftEdge
+ ascent
+ descent
;
1007 if (p
.x
< aContext
->AppUnitsToGfxUnits(leftEdge
) ||
1008 p
.x
> aContext
->AppUnitsToGfxUnits(rightEdge
)) {
1012 gfxFloat topEdge
= mFrame
->GetLogicalBaseline(writingMode
) - ascent
;
1013 gfxFloat bottomEdge
= topEdge
+ ascent
+ descent
;
1014 if (p
.y
< aContext
->AppUnitsToGfxUnits(topEdge
) ||
1015 p
.y
> aContext
->AppUnitsToGfxUnits(bottomEdge
)) {
1020 gfxSkipCharsIterator it
= mFrame
->EnsureTextRun(nsTextFrame::eInflated
);
1021 gfxTextRun
* textRun
= mFrame
->GetTextRun(nsTextFrame::eInflated
);
1022 nsTextFrame::PropertyProvider
provider(mFrame
, it
);
1024 // Next check that the point lies horizontally within the left and right
1025 // edges of the text.
1026 Range range
= ConvertOriginalToSkipped(it
, mTextFrameContentOffset
,
1027 mTextFrameContentLength
);
1028 gfxFloat runAdvance
=
1029 aContext
->AppUnitsToGfxUnits(textRun
->GetAdvanceWidth(range
, &provider
));
1031 gfxFloat pos
= writingMode
.IsVertical() ? p
.y
: p
.x
;
1032 if (pos
< 0 || pos
>= runAdvance
) {
1036 // Finally, measure progressively smaller portions of the rendered run to
1037 // find which glyph it lies within. This will need to change once we
1038 // support letter-spacing and word-spacing.
1039 bool rtl
= textRun
->IsRightToLeft();
1040 for (int32_t i
= mTextFrameContentLength
- 1; i
>= 0; i
--) {
1041 range
= ConvertOriginalToSkipped(it
, mTextFrameContentOffset
, i
);
1042 gfxFloat advance
= aContext
->AppUnitsToGfxUnits(
1043 textRun
->GetAdvanceWidth(range
, &provider
));
1044 if ((rtl
&& pos
< runAdvance
- advance
) || (!rtl
&& pos
>= advance
)) {
1051 // ----------------------------------------------------------------------------
1054 enum SubtreePosition
{ eBeforeSubtree
, eWithinSubtree
, eAfterSubtree
};
1057 * An iterator class for Text that are descendants of a given node, the
1058 * root. Nodes are iterated in document order. An optional subtree can be
1059 * specified, in which case the iterator will track whether the current state of
1060 * the traversal over the tree is within that subtree or is past that subtree.
1062 class TextNodeIterator
{
1065 * Constructs a TextNodeIterator with the specified root node and optional
1068 explicit TextNodeIterator(nsIContent
* aRoot
, nsIContent
* aSubtree
= nullptr)
1070 mSubtree(aSubtree
== aRoot
? nullptr : aSubtree
),
1072 mSubtreePosition(mSubtree
? eBeforeSubtree
: eWithinSubtree
) {
1073 NS_ASSERTION(aRoot
, "expected non-null root");
1074 if (!aRoot
->IsText()) {
1080 * Returns the current Text, or null if the iterator has finished.
1082 Text
* Current() const { return mCurrent
? mCurrent
->AsText() : nullptr; }
1085 * Advances to the next Text and returns it, or null if the end of
1086 * iteration has been reached.
1091 * Returns whether the iterator is currently within the subtree rooted
1092 * at mSubtree. Returns true if we are not tracking a subtree (we consider
1093 * that we're always within the subtree).
1095 bool IsWithinSubtree() const { return mSubtreePosition
== eWithinSubtree
; }
1098 * Returns whether the iterator is past the subtree rooted at mSubtree.
1099 * Returns false if we are not tracking a subtree.
1101 bool IsAfterSubtree() const { return mSubtreePosition
== eAfterSubtree
; }
1105 * The root under which all Text will be iterated over.
1107 nsIContent
* const mRoot
;
1110 * The node rooting the subtree to track.
1112 nsIContent
* const mSubtree
;
1115 * The current node during iteration.
1117 nsIContent
* mCurrent
;
1120 * The current iterator position relative to mSubtree.
1122 SubtreePosition mSubtreePosition
;
1125 Text
* TextNodeIterator::Next() {
1126 // Starting from mCurrent, we do a non-recursive traversal to the next
1127 // Text beneath mRoot, updating mSubtreePosition appropriately if we
1128 // encounter mSubtree.
1132 IsTextContentElement(mCurrent
) ? mCurrent
->GetFirstChild() : nullptr;
1135 if (mCurrent
== mSubtree
) {
1136 mSubtreePosition
= eWithinSubtree
;
1140 if (mCurrent
== mRoot
) {
1144 if (mCurrent
== mSubtree
) {
1145 mSubtreePosition
= eAfterSubtree
;
1147 next
= mCurrent
->GetNextSibling();
1150 if (mCurrent
== mSubtree
) {
1151 mSubtreePosition
= eWithinSubtree
;
1155 if (mCurrent
== mSubtree
) {
1156 mSubtreePosition
= eAfterSubtree
;
1158 mCurrent
= mCurrent
->GetParent();
1161 } while (mCurrent
&& !mCurrent
->IsText());
1164 return mCurrent
? mCurrent
->AsText() : nullptr;
1167 // ----------------------------------------------------------------------------
1168 // TextNodeCorrespondenceRecorder
1171 * TextNodeCorrespondence is used as the value of a frame property that
1172 * is stored on all its descendant nsTextFrames. It stores the number of DOM
1173 * characters between it and the previous nsTextFrame that did not have an
1174 * nsTextFrame created for them, due to either not being in a correctly
1175 * parented text content element, or because they were display:none.
1176 * These are called "undisplayed characters".
1178 * See also TextNodeCorrespondenceRecorder below, which is what sets the
1181 struct TextNodeCorrespondence
{
1182 explicit TextNodeCorrespondence(uint32_t aUndisplayedCharacters
)
1183 : mUndisplayedCharacters(aUndisplayedCharacters
) {}
1185 uint32_t mUndisplayedCharacters
;
1188 NS_DECLARE_FRAME_PROPERTY_DELETABLE(TextNodeCorrespondenceProperty
,
1189 TextNodeCorrespondence
)
1192 * Returns the number of undisplayed characters before the specified
1195 static uint32_t GetUndisplayedCharactersBeforeFrame(nsTextFrame
* aFrame
) {
1196 void* value
= aFrame
->GetProperty(TextNodeCorrespondenceProperty());
1197 TextNodeCorrespondence
* correspondence
=
1198 static_cast<TextNodeCorrespondence
*>(value
);
1199 if (!correspondence
) {
1202 "expected a TextNodeCorrespondenceProperty on nsTextFrame "
1203 "used for SVG text");
1206 return correspondence
->mUndisplayedCharacters
;
1210 * Traverses the nsTextFrames for an SVGTextFrame and records a
1211 * TextNodeCorrespondenceProperty on each for the number of undisplayed DOM
1212 * characters between each frame. This is done by iterating simultaneously
1213 * over the Text and nsTextFrames and noting when Text (or
1214 * parts of them) are skipped when finding the next nsTextFrame.
1216 class TextNodeCorrespondenceRecorder
{
1219 * Entry point for the TextNodeCorrespondenceProperty recording.
1221 static void RecordCorrespondence(SVGTextFrame
* aRoot
);
1224 explicit TextNodeCorrespondenceRecorder(SVGTextFrame
* aRoot
)
1225 : mNodeIterator(aRoot
->GetContent()),
1226 mPreviousNode(nullptr),
1227 mNodeCharIndex(0) {}
1229 void Record(SVGTextFrame
* aRoot
);
1230 void TraverseAndRecord(nsIFrame
* aFrame
);
1233 * Returns the next non-empty Text.
1238 * The iterator over the Text that we use as we simultaneously
1239 * iterate over the nsTextFrames.
1241 TextNodeIterator mNodeIterator
;
1244 * The previous Text we iterated over.
1246 Text
* mPreviousNode
;
1249 * The index into the current Text's character content.
1251 uint32_t mNodeCharIndex
;
1255 void TextNodeCorrespondenceRecorder::RecordCorrespondence(SVGTextFrame
* aRoot
) {
1256 if (aRoot
->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
)) {
1257 // Resolve bidi so that continuation frames are created if necessary:
1258 aRoot
->MaybeResolveBidiForAnonymousBlockChild();
1259 TextNodeCorrespondenceRecorder
recorder(aRoot
);
1260 recorder
.Record(aRoot
);
1261 aRoot
->RemoveStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
);
1265 void TextNodeCorrespondenceRecorder::Record(SVGTextFrame
* aRoot
) {
1266 if (!mNodeIterator
.Current()) {
1267 // If there are no Text nodes then there is nothing to do.
1271 // Traverse over all the nsTextFrames and record the number of undisplayed
1273 TraverseAndRecord(aRoot
);
1275 // Find how many undisplayed characters there are after the final nsTextFrame.
1276 uint32_t undisplayed
= 0;
1277 if (mNodeIterator
.Current()) {
1278 if (mPreviousNode
&& mPreviousNode
->TextLength() != mNodeCharIndex
) {
1279 // The last nsTextFrame ended part way through a Text node. The
1280 // remaining characters count as undisplayed.
1281 NS_ASSERTION(mNodeCharIndex
< mPreviousNode
->TextLength(),
1282 "incorrect tracking of undisplayed characters in "
1284 undisplayed
+= mPreviousNode
->TextLength() - mNodeCharIndex
;
1286 // All the remaining Text that we iterate must also be undisplayed.
1287 for (Text
* textNode
= mNodeIterator
.Current(); textNode
;
1288 textNode
= NextNode()) {
1289 undisplayed
+= textNode
->TextLength();
1293 // Record the trailing number of undisplayed characters on the
1295 aRoot
->mTrailingUndisplayedCharacters
= undisplayed
;
1298 Text
* TextNodeCorrespondenceRecorder::NextNode() {
1299 mPreviousNode
= mNodeIterator
.Current();
1302 next
= mNodeIterator
.Next();
1303 } while (next
&& next
->TextLength() == 0);
1307 void TextNodeCorrespondenceRecorder::TraverseAndRecord(nsIFrame
* aFrame
) {
1308 // Recursively iterate over the frame tree, for frames that correspond
1309 // to text content elements.
1310 if (IsTextContentElement(aFrame
->GetContent())) {
1311 for (nsIFrame
* f
: aFrame
->PrincipalChildList()) {
1312 TraverseAndRecord(f
);
1317 nsTextFrame
* frame
; // The current text frame.
1318 Text
* node
; // The text node for the current text frame.
1319 if (!GetNonEmptyTextFrameAndNode(aFrame
, frame
, node
)) {
1320 // If this isn't an nsTextFrame, or is empty, nothing to do.
1324 NS_ASSERTION(frame
->GetContentOffset() >= 0,
1325 "don't know how to handle negative content indexes");
1327 uint32_t undisplayed
= 0;
1328 if (!mPreviousNode
) {
1329 // Must be the very first text frame.
1330 NS_ASSERTION(mNodeCharIndex
== 0,
1331 "incorrect tracking of undisplayed "
1332 "characters in text nodes");
1333 if (!mNodeIterator
.Current()) {
1334 MOZ_ASSERT_UNREACHABLE(
1335 "incorrect tracking of correspondence between "
1336 "text frames and text nodes");
1338 // Each whole Text we find before we get to the text node for the
1339 // first text frame must be undisplayed.
1340 while (mNodeIterator
.Current() != node
) {
1341 undisplayed
+= mNodeIterator
.Current()->TextLength();
1344 // If the first text frame starts at a non-zero content offset, then those
1345 // earlier characters are also undisplayed.
1346 undisplayed
+= frame
->GetContentOffset();
1349 } else if (mPreviousNode
== node
) {
1350 // Same text node as last time.
1351 if (static_cast<uint32_t>(frame
->GetContentOffset()) != mNodeCharIndex
) {
1352 // We have some characters in the middle of the text node
1353 // that are undisplayed.
1355 mNodeCharIndex
< static_cast<uint32_t>(frame
->GetContentOffset()),
1356 "incorrect tracking of undisplayed characters in "
1358 undisplayed
= frame
->GetContentOffset() - mNodeCharIndex
;
1361 // Different text node from last time.
1362 if (mPreviousNode
->TextLength() != mNodeCharIndex
) {
1363 NS_ASSERTION(mNodeCharIndex
< mPreviousNode
->TextLength(),
1364 "incorrect tracking of undisplayed characters in "
1366 // Any trailing characters at the end of the previous Text are
1368 undisplayed
= mPreviousNode
->TextLength() - mNodeCharIndex
;
1370 // Each whole Text we find before we get to the text node for
1371 // the current text frame must be undisplayed.
1372 while (mNodeIterator
.Current() && mNodeIterator
.Current() != node
) {
1373 undisplayed
+= mNodeIterator
.Current()->TextLength();
1376 // If the current text frame starts at a non-zero content offset, then those
1377 // earlier characters are also undisplayed.
1378 undisplayed
+= frame
->GetContentOffset();
1382 // Set the frame property.
1383 frame
->SetProperty(TextNodeCorrespondenceProperty(),
1384 new TextNodeCorrespondence(undisplayed
));
1386 // Remember how far into the current Text we are.
1387 mNodeCharIndex
= frame
->GetContentEnd();
1390 // ----------------------------------------------------------------------------
1391 // TextFrameIterator
1394 * An iterator class for nsTextFrames that are descendants of an
1395 * SVGTextFrame. The iterator can optionally track whether the
1396 * current nsTextFrame is for a descendant of, or past, a given subtree
1397 * content node or frame. (This functionality is used for example by the SVG
1398 * DOM text methods to get only the nsTextFrames for a particular <tspan>.)
1400 * TextFrameIterator also tracks and exposes other information about the
1401 * current nsTextFrame:
1403 * * how many undisplayed characters came just before it
1404 * * its position (in app units) relative to the SVGTextFrame's anonymous
1406 * * what nsInlineFrame corresponding to a <textPath> element it is a
1408 * * what computed dominant-baseline value applies to it
1410 * Note that any text frames that are empty -- whose ContentLength() is 0 --
1411 * will be skipped over.
1413 class MOZ_STACK_CLASS TextFrameIterator
{
1416 * Constructs a TextFrameIterator for the specified SVGTextFrame
1417 * with an optional frame subtree to restrict iterated text frames to.
1419 explicit TextFrameIterator(SVGTextFrame
* aRoot
,
1420 const nsIFrame
* aSubtree
= nullptr)
1421 : mRootFrame(aRoot
),
1423 mCurrentFrame(aRoot
),
1424 mSubtreePosition(mSubtree
? eBeforeSubtree
: eWithinSubtree
) {
1429 * Constructs a TextFrameIterator for the specified SVGTextFrame
1430 * with an optional frame content subtree to restrict iterated text frames to.
1432 TextFrameIterator(SVGTextFrame
* aRoot
, nsIContent
* aSubtree
)
1433 : mRootFrame(aRoot
),
1434 mSubtree(aRoot
&& aSubtree
&& aSubtree
!= aRoot
->GetContent()
1435 ? aSubtree
->GetPrimaryFrame()
1437 mCurrentFrame(aRoot
),
1438 mSubtreePosition(mSubtree
? eBeforeSubtree
: eWithinSubtree
) {
1443 * Returns the root SVGTextFrame this TextFrameIterator is iterating over.
1445 SVGTextFrame
* Root() const { return mRootFrame
; }
1448 * Returns the current nsTextFrame.
1450 nsTextFrame
* Current() const { return do_QueryFrame(mCurrentFrame
); }
1453 * Returns the number of undisplayed characters in the DOM just before the
1456 uint32_t UndisplayedCharacters() const;
1459 * Returns the current frame's position, in app units, relative to the
1460 * root SVGTextFrame's anonymous block frame.
1462 nsPoint
Position() const { return mCurrentPosition
; }
1465 * Advances to the next nsTextFrame and returns it.
1467 nsTextFrame
* Next();
1470 * Returns whether the iterator is within the subtree.
1472 bool IsWithinSubtree() const { return mSubtreePosition
== eWithinSubtree
; }
1475 * Returns whether the iterator is past the subtree.
1477 bool IsAfterSubtree() const { return mSubtreePosition
== eAfterSubtree
; }
1480 * Returns the frame corresponding to the <textPath> element, if we
1483 nsIFrame
* TextPathFrame() const {
1484 return mTextPathFrames
.IsEmpty() ? nullptr : mTextPathFrames
.LastElement();
1488 * Returns the current frame's computed dominant-baseline value.
1490 StyleDominantBaseline
DominantBaseline() const {
1491 return mBaselines
.LastElement();
1495 * Finishes the iterator.
1497 void Close() { mCurrentFrame
= nullptr; }
1501 * Initializes the iterator and advances to the first item.
1508 mBaselines
.AppendElement(mRootFrame
->StyleSVG()->mDominantBaseline
);
1513 * Pushes the specified frame's computed dominant-baseline value.
1514 * If the value of the property is "auto", then the parent frame's
1515 * computed value is used.
1517 void PushBaseline(nsIFrame
* aNextFrame
);
1520 * Pops the current dominant-baseline off the stack.
1525 * The root frame we are iterating through.
1527 SVGTextFrame
* const mRootFrame
;
1530 * The frame for the subtree we are also interested in tracking.
1532 const nsIFrame
* const mSubtree
;
1535 * The current value of the iterator.
1537 nsIFrame
* mCurrentFrame
;
1540 * The position, in app units, of the current frame relative to mRootFrame.
1542 nsPoint mCurrentPosition
;
1545 * Stack of frames corresponding to <textPath> elements that are in scope
1546 * for the current frame.
1548 AutoTArray
<nsIFrame
*, 1> mTextPathFrames
;
1551 * Stack of dominant-baseline values to record as we traverse through the
1554 AutoTArray
<StyleDominantBaseline
, 8> mBaselines
;
1557 * The iterator's current position relative to mSubtree.
1559 SubtreePosition mSubtreePosition
;
1562 uint32_t TextFrameIterator::UndisplayedCharacters() const {
1564 !mRootFrame
->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
),
1565 "Text correspondence must be up to date");
1567 if (!mCurrentFrame
) {
1568 return mRootFrame
->mTrailingUndisplayedCharacters
;
1571 nsTextFrame
* frame
= do_QueryFrame(mCurrentFrame
);
1572 return GetUndisplayedCharactersBeforeFrame(frame
);
1575 nsTextFrame
* TextFrameIterator::Next() {
1576 // Starting from mCurrentFrame, we do a non-recursive traversal to the next
1577 // nsTextFrame beneath mRoot, updating mSubtreePosition appropriately if we
1578 // encounter mSubtree.
1579 if (mCurrentFrame
) {
1581 nsIFrame
* next
= IsTextContentElement(mCurrentFrame
->GetContent())
1582 ? mCurrentFrame
->PrincipalChildList().FirstChild()
1585 // Descend into this frame, and accumulate its position.
1586 mCurrentPosition
+= next
->GetPosition();
1587 if (next
->GetContent()->IsSVGElement(nsGkAtoms::textPath
)) {
1588 // Record this <textPath> frame.
1589 mTextPathFrames
.AppendElement(next
);
1591 // Record the frame's baseline.
1593 mCurrentFrame
= next
;
1594 if (mCurrentFrame
== mSubtree
) {
1595 // If the current frame is mSubtree, we have now moved into it.
1596 mSubtreePosition
= eWithinSubtree
;
1600 // We want to move past the current frame.
1601 if (mCurrentFrame
== mRootFrame
) {
1602 // If we've reached the root frame, we're finished.
1603 mCurrentFrame
= nullptr;
1606 // Remove the current frame's position.
1607 mCurrentPosition
-= mCurrentFrame
->GetPosition();
1608 if (mCurrentFrame
->GetContent()->IsSVGElement(nsGkAtoms::textPath
)) {
1609 // Pop off the <textPath> frame if this is a <textPath>.
1610 mTextPathFrames
.RemoveLastElement();
1612 // Pop off the current baseline.
1614 if (mCurrentFrame
== mSubtree
) {
1615 // If this was mSubtree, we have now moved past it.
1616 mSubtreePosition
= eAfterSubtree
;
1618 next
= mCurrentFrame
->GetNextSibling();
1620 // Moving to the next sibling.
1621 mCurrentPosition
+= next
->GetPosition();
1622 if (next
->GetContent()->IsSVGElement(nsGkAtoms::textPath
)) {
1623 // Record this <textPath> frame.
1624 mTextPathFrames
.AppendElement(next
);
1626 // Record the frame's baseline.
1628 mCurrentFrame
= next
;
1629 if (mCurrentFrame
== mSubtree
) {
1630 // If the current frame is mSubtree, we have now moved into it.
1631 mSubtreePosition
= eWithinSubtree
;
1635 if (mCurrentFrame
== mSubtree
) {
1636 // If there is no next sibling frame, and the current frame is
1637 // mSubtree, we have now moved past it.
1638 mSubtreePosition
= eAfterSubtree
;
1640 // Ascend out of this frame.
1641 mCurrentFrame
= mCurrentFrame
->GetParent();
1644 } while (mCurrentFrame
&& !IsNonEmptyTextFrame(mCurrentFrame
));
1650 void TextFrameIterator::PushBaseline(nsIFrame
* aNextFrame
) {
1651 StyleDominantBaseline baseline
= aNextFrame
->StyleSVG()->mDominantBaseline
;
1652 mBaselines
.AppendElement(baseline
);
1655 void TextFrameIterator::PopBaseline() {
1656 NS_ASSERTION(!mBaselines
.IsEmpty(), "popped too many baselines");
1657 mBaselines
.RemoveLastElement();
1660 // -----------------------------------------------------------------------------
1661 // TextRenderedRunIterator
1664 * Iterator for TextRenderedRun objects for the SVGTextFrame.
1666 class TextRenderedRunIterator
{
1669 * Values for the aFilter argument of the constructor, to indicate which
1670 * frames we should be limited to iterating TextRenderedRun objects for.
1672 enum RenderedRunFilter
{
1673 // Iterate TextRenderedRuns for all nsTextFrames.
1675 // Iterate only TextRenderedRuns for nsTextFrames that are
1676 // visibility:visible.
1681 * Constructs a TextRenderedRunIterator with an optional frame subtree to
1682 * restrict iterated rendered runs to.
1684 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1686 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1688 * @param aSubtree An optional frame subtree to restrict iterated rendered
1691 explicit TextRenderedRunIterator(SVGTextFrame
* aSVGTextFrame
,
1692 RenderedRunFilter aFilter
= eAllFrames
,
1693 const nsIFrame
* aSubtree
= nullptr)
1694 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame
), aSubtree
),
1696 mTextElementCharIndex(0),
1697 mFrameStartTextElementCharIndex(0),
1698 mFontSizeScaleFactor(aSVGTextFrame
->mFontSizeScaleFactor
),
1699 mCurrent(First()) {}
1702 * Constructs a TextRenderedRunIterator with a content subtree to restrict
1703 * iterated rendered runs to.
1705 * @param aSVGTextFrame The SVGTextFrame whose rendered runs to iterate
1707 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1709 * @param aSubtree A content subtree to restrict iterated rendered runs to.
1711 TextRenderedRunIterator(SVGTextFrame
* aSVGTextFrame
,
1712 RenderedRunFilter aFilter
, nsIContent
* aSubtree
)
1713 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame
), aSubtree
),
1715 mTextElementCharIndex(0),
1716 mFrameStartTextElementCharIndex(0),
1717 mFontSizeScaleFactor(aSVGTextFrame
->mFontSizeScaleFactor
),
1718 mCurrent(First()) {}
1721 * Returns the current TextRenderedRun.
1723 TextRenderedRun
Current() const { return mCurrent
; }
1726 * Advances to the next TextRenderedRun and returns it.
1728 TextRenderedRun
Next();
1732 * Returns the root SVGTextFrame this iterator is for.
1734 SVGTextFrame
* Root() const { return mFrameIterator
.Root(); }
1737 * Advances to the first TextRenderedRun and returns it.
1739 TextRenderedRun
First();
1742 * The frame iterator to use.
1744 TextFrameIterator mFrameIterator
;
1747 * The filter indicating which TextRenderedRuns to return.
1749 RenderedRunFilter mFilter
;
1752 * The character index across the entire <text> element we are currently
1755 uint32_t mTextElementCharIndex
;
1758 * The character index across the entire <text> for the start of the current
1761 uint32_t mFrameStartTextElementCharIndex
;
1764 * The font-size scale factor we used when constructing the nsTextFrames.
1766 double mFontSizeScaleFactor
;
1769 * The current TextRenderedRun.
1771 TextRenderedRun mCurrent
;
1774 TextRenderedRun
TextRenderedRunIterator::Next() {
1775 if (!mFrameIterator
.Current()) {
1776 // If there are no more frames, then there are no more rendered runs to
1778 mCurrent
= TextRenderedRun();
1782 // The values we will use to initialize the TextRenderedRun with.
1787 uint32_t offset
, length
;
1790 // We loop, because we want to skip over rendered runs that either aren't
1791 // within our subtree of interest, because they don't match the filter,
1792 // or because they are hidden due to having fallen off the end of a
1795 if (mFrameIterator
.IsAfterSubtree()) {
1796 mCurrent
= TextRenderedRun();
1800 frame
= mFrameIterator
.Current();
1802 charIndex
= mTextElementCharIndex
;
1804 // Find the end of the rendered run, by looking through the
1805 // SVGTextFrame's positions array until we find one that is recorded
1806 // as a run boundary.
1808 runEnd
; // XXX Replace runStart with mTextElementCharIndex.
1809 runStart
= mTextElementCharIndex
;
1810 runEnd
= runStart
+ 1;
1811 while (runEnd
< Root()->mPositions
.Length() &&
1812 !Root()->mPositions
[runEnd
].mRunBoundary
) {
1816 // Convert the global run start/end indexes into an offset/length into the
1817 // current frame's Text.
1819 frame
->GetContentOffset() + runStart
- mFrameStartTextElementCharIndex
;
1820 length
= runEnd
- runStart
;
1822 // If the end of the frame's content comes before the run boundary we found
1823 // in SVGTextFrame's position array, we need to shorten the rendered run.
1824 uint32_t contentEnd
= frame
->GetContentEnd();
1825 if (offset
+ length
> contentEnd
) {
1826 length
= contentEnd
- offset
;
1829 NS_ASSERTION(offset
>= uint32_t(frame
->GetContentOffset()),
1831 NS_ASSERTION(offset
+ length
<= contentEnd
, "invalid offset or length");
1833 // Get the frame's baseline position.
1834 frame
->EnsureTextRun(nsTextFrame::eInflated
);
1835 baseline
= GetBaselinePosition(
1836 frame
, frame
->GetTextRun(nsTextFrame::eInflated
),
1837 mFrameIterator
.DominantBaseline(), mFontSizeScaleFactor
);
1839 // Trim the offset/length to remove any leading/trailing white space.
1840 uint32_t untrimmedOffset
= offset
;
1841 uint32_t untrimmedLength
= length
;
1842 nsTextFrame::TrimmedOffsets trimmedOffsets
=
1843 frame
->GetTrimmedOffsets(frame
->TextFragment());
1844 TrimOffsets(offset
, length
, trimmedOffsets
);
1845 charIndex
+= offset
- untrimmedOffset
;
1847 // Get the position and rotation of the character that begins this
1849 pt
= Root()->mPositions
[charIndex
].mPosition
;
1850 rotate
= Root()->mPositions
[charIndex
].mAngle
;
1852 // Determine if we should skip this rendered run.
1853 bool skip
= !mFrameIterator
.IsWithinSubtree() ||
1854 Root()->mPositions
[mTextElementCharIndex
].mHidden
;
1855 if (mFilter
== eVisibleFrames
) {
1856 skip
= skip
|| !frame
->StyleVisibility()->IsVisible();
1859 // Update our global character index to move past the characters
1860 // corresponding to this rendered run.
1861 mTextElementCharIndex
+= untrimmedLength
;
1863 // If we have moved past the end of the current frame's content, we need to
1864 // advance to the next frame.
1865 if (offset
+ untrimmedLength
>= contentEnd
) {
1866 mFrameIterator
.Next();
1867 mTextElementCharIndex
+= mFrameIterator
.UndisplayedCharacters();
1868 mFrameStartTextElementCharIndex
= mTextElementCharIndex
;
1871 if (!mFrameIterator
.Current()) {
1873 // That was the last frame, and we skipped this rendered run. So we
1874 // have no rendered run to return.
1875 mCurrent
= TextRenderedRun();
1881 if (length
&& !skip
) {
1882 // Only return a rendered run if it didn't get collapsed away entirely
1883 // (due to it being all white space) and if we don't want to skip it.
1888 mCurrent
= TextRenderedRun(frame
, pt
, Root()->mLengthAdjustScaleFactor
,
1889 rotate
, mFontSizeScaleFactor
, baseline
, offset
,
1894 TextRenderedRun
TextRenderedRunIterator::First() {
1895 if (!mFrameIterator
.Current()) {
1896 return TextRenderedRun();
1899 if (Root()->mPositions
.IsEmpty()) {
1900 mFrameIterator
.Close();
1901 return TextRenderedRun();
1904 // Get the character index for the start of this rendered run, by skipping
1905 // any undisplayed characters.
1906 mTextElementCharIndex
= mFrameIterator
.UndisplayedCharacters();
1907 mFrameStartTextElementCharIndex
= mTextElementCharIndex
;
1912 // -----------------------------------------------------------------------------
1916 * Iterator for characters within an SVGTextFrame.
1918 class MOZ_STACK_CLASS CharIterator
{
1919 using Range
= gfxTextRun::Range
;
1923 * Values for the aFilter argument of the constructor, to indicate which
1924 * characters we should be iterating over.
1926 enum CharacterFilter
{
1927 // Iterate over all original characters from the DOM that are within valid
1928 // text content elements.
1930 // Iterate only over characters that are not skipped characters.
1932 // Iterate only over characters that are addressable by the positioning
1933 // attributes x="", y="", etc. This includes all characters after
1934 // collapsing white space as required by the value of 'white-space'.
1939 * Constructs a CharIterator.
1941 * @param aSVGTextFrame The SVGTextFrame whose characters to iterate
1943 * @param aFilter Indicates which characters to iterate over.
1944 * @param aSubtree A content subtree to track whether the current character
1947 CharIterator(SVGTextFrame
* aSVGTextFrame
, CharacterFilter aFilter
,
1948 nsIContent
* aSubtree
, bool aPostReflow
= true);
1951 * Returns whether the iterator is finished.
1953 bool AtEnd() const { return !mFrameIterator
.Current(); }
1956 * Advances to the next matching character. Returns true if there was a
1957 * character to advance to, and false otherwise.
1962 * Advances ahead aCount matching characters. Returns true if there were
1963 * enough characters to advance past, and false otherwise.
1965 bool Next(uint32_t aCount
);
1968 * Advances ahead up to aCount matching characters.
1970 void NextWithinSubtree(uint32_t aCount
);
1973 * Advances to the character with the specified index. The index is in the
1974 * space of original characters (i.e., all DOM characters under the <text>
1975 * that are within valid text content elements).
1977 bool AdvanceToCharacter(uint32_t aTextElementCharIndex
);
1980 * Advances to the first matching character after the current nsTextFrame.
1982 bool AdvancePastCurrentFrame();
1985 * Advances to the first matching character after the frames within
1986 * the current <textPath>.
1988 bool AdvancePastCurrentTextPathFrame();
1991 * Advances to the first matching character of the subtree. Returns true
1992 * if we successfully advance to the subtree, or if we are already within
1993 * the subtree. Returns false if we are past the subtree.
1995 bool AdvanceToSubtree();
1998 * Returns the nsTextFrame for the current character.
2000 nsTextFrame
* TextFrame() const { return mFrameIterator
.Current(); }
2003 * Returns whether the iterator is within the subtree.
2005 bool IsWithinSubtree() const { return mFrameIterator
.IsWithinSubtree(); }
2008 * Returns whether the iterator is past the subtree.
2010 bool IsAfterSubtree() const { return mFrameIterator
.IsAfterSubtree(); }
2013 * Returns whether the current character is a skipped character.
2015 bool IsOriginalCharSkipped() const {
2016 return mSkipCharsIterator
.IsOriginalCharSkipped();
2020 * Returns whether the current character is the start of a cluster and
2023 bool IsClusterAndLigatureGroupStart() const {
2024 return mTextRun
->IsLigatureGroupStart(
2025 mSkipCharsIterator
.GetSkippedOffset()) &&
2026 mTextRun
->IsClusterStart(mSkipCharsIterator
.GetSkippedOffset());
2030 * Returns the glyph run for the current character.
2032 const gfxTextRun::GlyphRun
& GlyphRun() const {
2033 return *mTextRun
->FindFirstGlyphRunContaining(
2034 mSkipCharsIterator
.GetSkippedOffset());
2038 * Returns whether the current character is trimmed away when painting,
2039 * due to it being leading/trailing white space.
2041 bool IsOriginalCharTrimmed() const;
2044 * Returns whether the current character is unaddressable from the SVG glyph
2045 * positioning attributes.
2047 bool IsOriginalCharUnaddressable() const {
2048 return IsOriginalCharSkipped() || IsOriginalCharTrimmed();
2052 * Returns the text run for the current character.
2054 gfxTextRun
* TextRun() const { return mTextRun
; }
2057 * Returns the current character index.
2059 uint32_t TextElementCharIndex() const { return mTextElementCharIndex
; }
2062 * Returns the character index for the start of the cluster/ligature group it
2065 uint32_t GlyphStartTextElementCharIndex() const {
2066 return mGlyphStartTextElementCharIndex
;
2070 * Gets the advance, in user units, of the current character. If the
2071 * character is a part of ligature, then the advance returned will be
2072 * a fraction of the ligature glyph's advance.
2074 * @param aContext The context to use for unit conversions.
2076 gfxFloat
GetAdvance(nsPresContext
* aContext
) const;
2079 * Returns the frame corresponding to the <textPath> that the current
2080 * character is within.
2082 nsIFrame
* TextPathFrame() const { return mFrameIterator
.TextPathFrame(); }
2086 * Returns the subtree we were constructed with.
2088 nsIContent
* GetSubtree() const { return mSubtree
; }
2091 * Returns the CharacterFilter mode in use.
2093 CharacterFilter
Filter() const { return mFilter
; }
2098 * Advances to the next character without checking it against the filter.
2099 * Returns true if there was a next character to advance to, or false
2102 bool NextCharacter();
2105 * Returns whether the current character matches the filter.
2107 bool MatchesFilter() const;
2110 * If this is the start of a glyph, record it.
2112 void UpdateGlyphStartTextElementCharIndex() {
2113 if (!IsOriginalCharSkipped() && IsClusterAndLigatureGroupStart()) {
2114 mGlyphStartTextElementCharIndex
= mTextElementCharIndex
;
2119 * The filter to use.
2121 CharacterFilter mFilter
;
2124 * The iterator for text frames.
2126 TextFrameIterator mFrameIterator
;
2130 * The subtree we were constructed with.
2132 nsIContent
* const mSubtree
;
2136 * A gfxSkipCharsIterator for the text frame the current character is
2139 gfxSkipCharsIterator mSkipCharsIterator
;
2141 // Cache for information computed by IsOriginalCharTrimmed.
2142 mutable nsTextFrame
* mFrameForTrimCheck
;
2143 mutable uint32_t mTrimmedOffset
;
2144 mutable uint32_t mTrimmedLength
;
2147 * The text run the current character is a part of.
2149 gfxTextRun
* mTextRun
;
2152 * The current character's index.
2154 uint32_t mTextElementCharIndex
;
2157 * The index of the character that starts the cluster/ligature group the
2158 * current character is a part of.
2160 uint32_t mGlyphStartTextElementCharIndex
;
2163 * The scale factor to apply to glyph advances returned by
2164 * GetAdvance etc. to take into account textLength="".
2166 float mLengthAdjustScaleFactor
;
2169 * Whether the instance of this class is being used after reflow has occurred
2175 CharIterator::CharIterator(SVGTextFrame
* aSVGTextFrame
,
2176 CharIterator::CharacterFilter aFilter
,
2177 nsIContent
* aSubtree
, bool aPostReflow
)
2179 mFrameIterator(aSVGTextFrame
, aSubtree
),
2183 mFrameForTrimCheck(nullptr),
2187 mTextElementCharIndex(0),
2188 mGlyphStartTextElementCharIndex(0),
2189 mLengthAdjustScaleFactor(aSVGTextFrame
->mLengthAdjustScaleFactor
),
2190 mPostReflow(aPostReflow
) {
2192 mSkipCharsIterator
= TextFrame()->EnsureTextRun(nsTextFrame::eInflated
);
2193 mTextRun
= TextFrame()->GetTextRun(nsTextFrame::eInflated
);
2194 mTextElementCharIndex
= mFrameIterator
.UndisplayedCharacters();
2195 UpdateGlyphStartTextElementCharIndex();
2196 if (!MatchesFilter()) {
2202 bool CharIterator::Next() {
2203 while (NextCharacter()) {
2204 if (MatchesFilter()) {
2211 bool CharIterator::Next(uint32_t aCount
) {
2212 if (aCount
== 0 && AtEnd()) {
2224 void CharIterator::NextWithinSubtree(uint32_t aCount
) {
2225 while (IsWithinSubtree() && aCount
) {
2233 bool CharIterator::AdvanceToCharacter(uint32_t aTextElementCharIndex
) {
2234 while (mTextElementCharIndex
< aTextElementCharIndex
) {
2242 bool CharIterator::AdvancePastCurrentFrame() {
2243 // XXX Can do this better than one character at a time if it matters.
2244 nsTextFrame
* currentFrame
= TextFrame();
2249 } while (TextFrame() == currentFrame
);
2253 bool CharIterator::AdvancePastCurrentTextPathFrame() {
2254 nsIFrame
* currentTextPathFrame
= TextPathFrame();
2255 NS_ASSERTION(currentTextPathFrame
,
2256 "expected AdvancePastCurrentTextPathFrame to be called only "
2257 "within a text path frame");
2259 if (!AdvancePastCurrentFrame()) {
2262 } while (TextPathFrame() == currentTextPathFrame
);
2266 bool CharIterator::AdvanceToSubtree() {
2267 while (!IsWithinSubtree()) {
2268 if (IsAfterSubtree()) {
2271 if (!AdvancePastCurrentFrame()) {
2278 bool CharIterator::IsOriginalCharTrimmed() const {
2279 if (mFrameForTrimCheck
!= TextFrame()) {
2280 // Since we do a lot of trim checking, we cache the trimmed offsets and
2281 // lengths while we are in the same frame.
2282 mFrameForTrimCheck
= TextFrame();
2283 uint32_t offset
= mFrameForTrimCheck
->GetContentOffset();
2284 uint32_t length
= mFrameForTrimCheck
->GetContentLength();
2285 nsTextFrame::TrimmedOffsets trim
= mFrameForTrimCheck
->GetTrimmedOffsets(
2286 mFrameForTrimCheck
->TextFragment(),
2287 (mPostReflow
? nsTextFrame::TrimmedOffsetFlags::Default
2288 : nsTextFrame::TrimmedOffsetFlags::NotPostReflow
));
2289 TrimOffsets(offset
, length
, trim
);
2290 mTrimmedOffset
= offset
;
2291 mTrimmedLength
= length
;
2294 // A character is trimmed if it is outside the mTrimmedOffset/mTrimmedLength
2295 // range and it is not a significant newline character.
2296 uint32_t index
= mSkipCharsIterator
.GetOriginalOffset();
2298 (index
>= mTrimmedOffset
&& index
< mTrimmedOffset
+ mTrimmedLength
) ||
2299 (index
>= mTrimmedOffset
+ mTrimmedLength
&&
2300 mFrameForTrimCheck
->StyleText()->NewlineIsSignificant(
2301 mFrameForTrimCheck
) &&
2302 mFrameForTrimCheck
->TextFragment()->CharAt(index
) == '\n'));
2305 gfxFloat
CharIterator::GetAdvance(nsPresContext
* aContext
) const {
2306 float cssPxPerDevPx
=
2307 nsPresContext::AppUnitsToFloatCSSPixels(aContext
->AppUnitsPerDevPixel());
2309 gfxSkipCharsIterator start
=
2310 TextFrame()->EnsureTextRun(nsTextFrame::eInflated
);
2311 nsTextFrame::PropertyProvider
provider(TextFrame(), start
);
2313 uint32_t offset
= mSkipCharsIterator
.GetSkippedOffset();
2315 mTextRun
->GetAdvanceWidth(Range(offset
, offset
+ 1), &provider
);
2316 return aContext
->AppUnitsToGfxUnits(advance
) * mLengthAdjustScaleFactor
*
2320 bool CharIterator::NextCharacter() {
2325 mTextElementCharIndex
++;
2327 // Advance within the current text run.
2328 mSkipCharsIterator
.AdvanceOriginal(1);
2329 if (mSkipCharsIterator
.GetOriginalOffset() < TextFrame()->GetContentEnd()) {
2330 // We're still within the part of the text run for the current text frame.
2331 UpdateGlyphStartTextElementCharIndex();
2335 // Advance to the next frame.
2336 mFrameIterator
.Next();
2338 // Skip any undisplayed characters.
2339 uint32_t undisplayed
= mFrameIterator
.UndisplayedCharacters();
2340 mTextElementCharIndex
+= undisplayed
;
2342 // We're at the end.
2343 mSkipCharsIterator
= gfxSkipCharsIterator();
2347 mSkipCharsIterator
= TextFrame()->EnsureTextRun(nsTextFrame::eInflated
);
2348 mTextRun
= TextFrame()->GetTextRun(nsTextFrame::eInflated
);
2349 UpdateGlyphStartTextElementCharIndex();
2353 bool CharIterator::MatchesFilter() const {
2358 return !IsOriginalCharSkipped();
2360 return !IsOriginalCharSkipped() && !IsOriginalCharUnaddressable();
2362 MOZ_ASSERT_UNREACHABLE("Invalid mFilter value");
2366 // -----------------------------------------------------------------------------
2367 // SVGTextDrawPathCallbacks
2370 * Text frame draw callback class that paints the text and text decoration parts
2371 * of an nsTextFrame using SVG painting properties, and selection backgrounds
2372 * and decorations as they would normally.
2374 * An instance of this class is passed to nsTextFrame::PaintText if painting
2375 * cannot be done directly (e.g. if we are using an SVG pattern fill, stroking
2378 class SVGTextDrawPathCallbacks final
: public nsTextFrame::DrawPathCallbacks
{
2379 using imgDrawingParams
= image::imgDrawingParams
;
2383 * Constructs an SVGTextDrawPathCallbacks.
2385 * @param aSVGTextFrame The ancestor text frame.
2386 * @param aContext The context to use for painting.
2387 * @param aFrame The nsTextFrame to paint.
2388 * @param aCanvasTM The transformation matrix to set when painting; this
2389 * should be the FOR_OUTERSVG_TM canvas TM of the text, so that
2390 * paint servers are painted correctly.
2391 * @param aImgParams Whether we need to synchronously decode images.
2392 * @param aShouldPaintSVGGlyphs Whether SVG glyphs should be painted.
2394 SVGTextDrawPathCallbacks(SVGTextFrame
* aSVGTextFrame
, gfxContext
& aContext
,
2395 nsTextFrame
* aFrame
, const gfxMatrix
& aCanvasTM
,
2396 imgDrawingParams
& aImgParams
,
2397 bool aShouldPaintSVGGlyphs
)
2398 : DrawPathCallbacks(aShouldPaintSVGGlyphs
),
2399 mSVGTextFrame(aSVGTextFrame
),
2402 mCanvasTM(aCanvasTM
),
2403 mImgParams(aImgParams
),
2406 void NotifySelectionBackgroundNeedsFill(const Rect
& aBackgroundRect
,
2408 DrawTarget
& aDrawTarget
) override
;
2409 void PaintDecorationLine(Rect aPath
, nscolor aColor
) override
;
2410 void PaintSelectionDecorationLine(Rect aPath
, nscolor aColor
) override
;
2411 void NotifyBeforeText(nscolor aColor
) override
;
2412 void NotifyGlyphPathEmitted() override
;
2413 void NotifyAfterText() override
;
2416 void SetupContext();
2418 bool IsClipPathChild() const {
2419 return mSVGTextFrame
->HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD
);
2423 * Paints a piece of text geometry. This is called when glyphs
2424 * or text decorations have been emitted to the gfxContext.
2426 void HandleTextGeometry();
2429 * Sets the gfxContext paint to the appropriate color or pattern
2430 * for filling text geometry.
2432 void MakeFillPattern(GeneralPattern
* aOutPattern
);
2435 * Fills and strokes a piece of text geometry, using group opacity
2436 * if the selection style requires it.
2438 void FillAndStrokeGeometry();
2441 * Fills a piece of text geometry.
2443 void FillGeometry();
2446 * Strokes a piece of text geometry.
2448 void StrokeGeometry();
2450 SVGTextFrame
* const mSVGTextFrame
;
2451 gfxContext
& mContext
;
2452 nsTextFrame
* const mFrame
;
2453 const gfxMatrix
& mCanvasTM
;
2454 imgDrawingParams
& mImgParams
;
2457 * The color that we were last told from one of the path callback functions.
2458 * This color can be the special NS_SAME_AS_FOREGROUND_COLOR,
2459 * NS_40PERCENT_FOREGROUND_COLOR and NS_TRANSPARENT colors when we are
2460 * painting selections or IME decorations.
2465 void SVGTextDrawPathCallbacks::NotifySelectionBackgroundNeedsFill(
2466 const Rect
& aBackgroundRect
, nscolor aColor
, DrawTarget
& aDrawTarget
) {
2467 if (IsClipPathChild()) {
2468 // Don't paint selection backgrounds when in a clip path.
2472 mColor
= aColor
; // currently needed by MakeFillPattern
2474 GeneralPattern fillPattern
;
2475 MakeFillPattern(&fillPattern
);
2476 if (fillPattern
.GetPattern()) {
2477 DrawOptions
drawOptions(aColor
== NS_40PERCENT_FOREGROUND_COLOR
? 0.4
2479 aDrawTarget
.FillRect(aBackgroundRect
, fillPattern
, drawOptions
);
2483 void SVGTextDrawPathCallbacks::NotifyBeforeText(nscolor aColor
) {
2489 void SVGTextDrawPathCallbacks::NotifyGlyphPathEmitted() {
2490 HandleTextGeometry();
2494 void SVGTextDrawPathCallbacks::NotifyAfterText() { mContext
.Restore(); }
2496 void SVGTextDrawPathCallbacks::PaintDecorationLine(Rect aPath
, nscolor aColor
) {
2498 AntialiasMode aaMode
=
2499 SVGUtils::ToAntialiasMode(mFrame
->StyleText()->mTextRendering
);
2503 mContext
.SetAntialiasMode(aaMode
);
2504 mContext
.Rectangle(ThebesRect(aPath
));
2505 HandleTextGeometry();
2510 void SVGTextDrawPathCallbacks::PaintSelectionDecorationLine(Rect aPath
,
2512 if (IsClipPathChild()) {
2513 // Don't paint selection decorations when in a clip path.
2521 mContext
.Rectangle(ThebesRect(aPath
));
2522 FillAndStrokeGeometry();
2526 void SVGTextDrawPathCallbacks::SetupContext() {
2529 // XXX This is copied from nsSVGGlyphFrame::Render, but cairo doesn't actually
2530 // seem to do anything with the antialias mode. So we can perhaps remove it,
2531 // or make SetAntialiasMode set cairo text antialiasing too.
2532 switch (mFrame
->StyleText()->mTextRendering
) {
2533 case StyleTextRendering::Optimizespeed
:
2534 mContext
.SetAntialiasMode(AntialiasMode::NONE
);
2537 mContext
.SetAntialiasMode(AntialiasMode::SUBPIXEL
);
2542 void SVGTextDrawPathCallbacks::HandleTextGeometry() {
2543 if (IsClipPathChild()) {
2544 RefPtr
<Path
> path
= mContext
.GetPath();
2546 DeviceColor(1.f
, 1.f
, 1.f
, 1.f
)); // for masking, so no ToDeviceColor
2547 mContext
.GetDrawTarget()->Fill(path
, white
);
2550 gfxContextMatrixAutoSaveRestore
saveMatrix(&mContext
);
2551 mContext
.SetMatrixDouble(mCanvasTM
);
2553 FillAndStrokeGeometry();
2557 void SVGTextDrawPathCallbacks::MakeFillPattern(GeneralPattern
* aOutPattern
) {
2558 if (mColor
== NS_SAME_AS_FOREGROUND_COLOR
||
2559 mColor
== NS_40PERCENT_FOREGROUND_COLOR
) {
2560 SVGUtils::MakeFillPatternFor(mFrame
, &mContext
, aOutPattern
, mImgParams
);
2564 if (mColor
== NS_TRANSPARENT
) {
2568 aOutPattern
->InitColorPattern(ToDeviceColor(mColor
));
2571 void SVGTextDrawPathCallbacks::FillAndStrokeGeometry() {
2572 gfxGroupForBlendAutoSaveRestore
autoGroupForBlend(&mContext
);
2573 if (mColor
== NS_40PERCENT_FOREGROUND_COLOR
) {
2574 autoGroupForBlend
.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA
, 0.4f
);
2577 uint32_t paintOrder
= mFrame
->StyleSVG()->mPaintOrder
;
2582 while (paintOrder
) {
2583 auto component
= StylePaintOrder(paintOrder
& kPaintOrderMask
);
2584 switch (component
) {
2585 case StylePaintOrder::Fill
:
2588 case StylePaintOrder::Stroke
:
2592 MOZ_FALLTHROUGH_ASSERT("Unknown paint-order value");
2593 case StylePaintOrder::Markers
:
2594 case StylePaintOrder::Normal
:
2597 paintOrder
>>= kPaintOrderShift
;
2602 void SVGTextDrawPathCallbacks::FillGeometry() {
2603 GeneralPattern fillPattern
;
2604 MakeFillPattern(&fillPattern
);
2605 if (fillPattern
.GetPattern()) {
2606 RefPtr
<Path
> path
= mContext
.GetPath();
2607 FillRule fillRule
= SVGUtils::ToFillRule(mFrame
->StyleSVG()->mFillRule
);
2608 if (fillRule
!= path
->GetFillRule()) {
2609 RefPtr
<PathBuilder
> builder
= path
->CopyToBuilder(fillRule
);
2610 path
= builder
->Finish();
2612 mContext
.GetDrawTarget()->Fill(path
, fillPattern
);
2616 void SVGTextDrawPathCallbacks::StrokeGeometry() {
2617 // We don't paint the stroke when we are filling with a selection color.
2618 if (mColor
== NS_SAME_AS_FOREGROUND_COLOR
||
2619 mColor
== NS_40PERCENT_FOREGROUND_COLOR
) {
2620 if (SVGUtils::HasStroke(mFrame
, /*aContextPaint*/ nullptr)) {
2621 GeneralPattern strokePattern
;
2622 SVGUtils::MakeStrokePatternFor(mFrame
, &mContext
, &strokePattern
,
2623 mImgParams
, /*aContextPaint*/ nullptr);
2624 if (strokePattern
.GetPattern()) {
2625 if (!mFrame
->GetParent()->GetContent()->IsSVGElement()) {
2626 // The cast that follows would be unsafe
2627 MOZ_ASSERT(false, "Our nsTextFrame's parent's content should be SVG");
2630 SVGElement
* svgOwner
=
2631 static_cast<SVGElement
*>(mFrame
->GetParent()->GetContent());
2633 // Apply any stroke-specific transform
2634 gfxMatrix outerSVGToUser
;
2635 if (SVGUtils::GetNonScalingStrokeTransform(mFrame
, &outerSVGToUser
) &&
2636 outerSVGToUser
.Invert()) {
2637 mContext
.Multiply(outerSVGToUser
);
2640 RefPtr
<Path
> path
= mContext
.GetPath();
2641 SVGContentUtils::AutoStrokeOptions strokeOptions
;
2642 SVGContentUtils::GetStrokeOptions(&strokeOptions
, svgOwner
,
2644 /*aContextPaint*/ nullptr);
2645 DrawOptions drawOptions
;
2646 drawOptions
.mAntialiasMode
=
2647 SVGUtils::ToAntialiasMode(mFrame
->StyleText()->mTextRendering
);
2648 mContext
.GetDrawTarget()->Stroke(path
, strokePattern
, strokeOptions
);
2654 // ============================================================================
2657 // ----------------------------------------------------------------------------
2658 // Display list item
2660 class DisplaySVGText final
: public DisplaySVGItem
{
2662 DisplaySVGText(nsDisplayListBuilder
* aBuilder
, SVGTextFrame
* aFrame
)
2663 : DisplaySVGItem(aBuilder
, aFrame
) {
2664 MOZ_COUNT_CTOR(DisplaySVGText
);
2667 MOZ_COUNTED_DTOR_OVERRIDE(DisplaySVGText
)
2669 NS_DISPLAY_DECL_NAME("DisplaySVGText", TYPE_SVG_TEXT
)
2671 nsDisplayItemGeometry
* AllocateGeometry(
2672 nsDisplayListBuilder
* aBuilder
) override
{
2673 return new nsDisplayItemGenericGeometry(this, aBuilder
);
2676 nsRect
GetComponentAlphaBounds(
2677 nsDisplayListBuilder
* aBuilder
) const override
{
2679 return GetBounds(aBuilder
, &snap
);
2683 // ---------------------------------------------------------------------
2684 // nsQueryFrame methods
2686 NS_QUERYFRAME_HEAD(SVGTextFrame
)
2687 NS_QUERYFRAME_ENTRY(SVGTextFrame
)
2688 NS_QUERYFRAME_TAIL_INHERITING(SVGDisplayContainerFrame
)
2690 } // namespace mozilla
2692 // ---------------------------------------------------------------------
2695 nsIFrame
* NS_NewSVGTextFrame(mozilla::PresShell
* aPresShell
,
2696 mozilla::ComputedStyle
* aStyle
) {
2697 return new (aPresShell
)
2698 mozilla::SVGTextFrame(aStyle
, aPresShell
->GetPresContext());
2703 NS_IMPL_FRAMEARENA_HELPERS(SVGTextFrame
)
2705 // ---------------------------------------------------------------------
2708 void SVGTextFrame::Init(nsIContent
* aContent
, nsContainerFrame
* aParent
,
2709 nsIFrame
* aPrevInFlow
) {
2710 NS_ASSERTION(aContent
->IsSVGElement(nsGkAtoms::text
),
2711 "Content is not an SVG text");
2713 SVGDisplayContainerFrame::Init(aContent
, aParent
, aPrevInFlow
);
2714 AddStateBits(aParent
->GetStateBits() & NS_STATE_SVG_CLIPPATH_CHILD
);
2716 mMutationObserver
= new MutationObserver(this);
2718 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
2719 // We're inserting a new <text> element into a non-display context.
2720 // Ensure that we get reflowed.
2721 ScheduleReflowSVGNonDisplayText(
2722 IntrinsicDirty::FrameAncestorsAndDescendants
);
2726 void SVGTextFrame::BuildDisplayList(nsDisplayListBuilder
* aBuilder
,
2727 const nsDisplayListSet
& aLists
) {
2728 if (IsSubtreeDirty()) {
2729 // We can sometimes be asked to paint before reflow happens and we
2730 // have updated mPositions, etc. In this case, we just avoid
2734 if (!IsVisibleForPainting() && aBuilder
->IsForPainting()) {
2737 DisplayOutline(aBuilder
, aLists
);
2738 aLists
.Content()->AppendNewToTop
<DisplaySVGText
>(aBuilder
, this);
2741 nsresult
SVGTextFrame::AttributeChanged(int32_t aNameSpaceID
,
2742 nsAtom
* aAttribute
, int32_t aModType
) {
2743 if (aNameSpaceID
!= kNameSpaceID_None
) {
2747 if (aAttribute
== nsGkAtoms::transform
) {
2748 // We don't invalidate for transform changes (the layers code does that).
2749 // Also note that SVGTransformableElement::GetAttributeChangeHint will
2750 // return nsChangeHint_UpdateOverflow for "transform" attribute changes
2751 // and cause DoApplyRenderingChangeToTree to make the SchedulePaint call.
2753 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW
) && mCanvasTM
&&
2754 mCanvasTM
->IsSingular()) {
2755 // We won't have calculated the glyph positions correctly.
2756 NotifyGlyphMetricsChange(false);
2758 mCanvasTM
= nullptr;
2759 } else if (IsGlyphPositioningAttribute(aAttribute
) ||
2760 aAttribute
== nsGkAtoms::textLength
||
2761 aAttribute
== nsGkAtoms::lengthAdjust
) {
2762 NotifyGlyphMetricsChange(false);
2768 void SVGTextFrame::ReflowSVGNonDisplayText() {
2769 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
2770 "only call ReflowSVGNonDisplayText when an outer SVG frame is "
2772 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
),
2773 "only call ReflowSVGNonDisplayText if the frame is "
2774 "NS_FRAME_IS_NONDISPLAY");
2776 // We had a style change, so we mark this frame as dirty so that the next
2777 // time it is painted, we reflow the anonymous block frame.
2778 this->MarkSubtreeDirty();
2780 // Finally, we need to actually reflow the anonymous block frame and update
2781 // mPositions, in case we are being reflowed immediately after a DOM
2782 // mutation that needs frame reconstruction.
2783 MaybeReflowAnonymousBlockChild();
2784 UpdateGlyphPositioning();
2787 void SVGTextFrame::ScheduleReflowSVGNonDisplayText(IntrinsicDirty aReason
) {
2788 MOZ_ASSERT(!SVGUtils::OuterSVGIsCallingReflowSVG(this),
2789 "do not call ScheduleReflowSVGNonDisplayText when the outer SVG "
2790 "frame is under ReflowSVG");
2791 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW
),
2792 "do not call ScheduleReflowSVGNonDisplayText while reflowing the "
2793 "anonymous block child");
2795 // We need to find an ancestor frame that we can call FrameNeedsReflow
2796 // on that will cause the document to be marked as needing relayout,
2797 // and for that ancestor (or some further ancestor) to be marked as
2798 // a root to reflow. We choose the closest ancestor frame that is not
2799 // NS_FRAME_IS_NONDISPLAY and which is either an outer SVG frame or a
2800 // non-SVG frame. (We don't consider displayed SVG frame ancestors other
2801 // than SVGOuterSVGFrame, since calling FrameNeedsReflow on those other
2802 // SVG frames would do a bunch of unnecessary work on the SVG frames up to
2803 // the SVGOuterSVGFrame.)
2807 if (!f
->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
2808 if (f
->IsSubtreeDirty()) {
2809 // This is a displayed frame, so if it is already dirty, we will be
2810 // reflowed soon anyway. No need to call FrameNeedsReflow again, then.
2813 if (!f
->HasAnyStateBits(NS_FRAME_SVG_LAYOUT
)) {
2816 f
->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN
);
2821 MOZ_ASSERT(f
, "should have found an ancestor frame to reflow");
2823 PresShell()->FrameNeedsReflow(f
, aReason
, NS_FRAME_IS_DIRTY
);
2826 NS_IMPL_ISUPPORTS(SVGTextFrame::MutationObserver
, nsIMutationObserver
)
2828 void SVGTextFrame::MutationObserver::ContentAppended(
2829 nsIContent
* aFirstNewContent
) {
2830 mFrame
->NotifyGlyphMetricsChange(true);
2833 void SVGTextFrame::MutationObserver::ContentInserted(nsIContent
* aChild
) {
2834 mFrame
->NotifyGlyphMetricsChange(true);
2837 void SVGTextFrame::MutationObserver::ContentRemoved(
2838 nsIContent
* aChild
, nsIContent
* aPreviousSibling
) {
2839 mFrame
->NotifyGlyphMetricsChange(true);
2842 void SVGTextFrame::MutationObserver::CharacterDataChanged(
2843 nsIContent
* aContent
, const CharacterDataChangeInfo
&) {
2844 mFrame
->NotifyGlyphMetricsChange(true);
2847 void SVGTextFrame::MutationObserver::AttributeChanged(
2848 Element
* aElement
, int32_t aNameSpaceID
, nsAtom
* aAttribute
,
2849 int32_t aModType
, const nsAttrValue
* aOldValue
) {
2850 if (!aElement
->IsSVGElement()) {
2854 // Attribute changes on this element will be handled by
2855 // SVGTextFrame::AttributeChanged.
2856 if (aElement
== mFrame
->GetContent()) {
2860 mFrame
->HandleAttributeChangeInDescendant(aElement
, aNameSpaceID
, aAttribute
);
2863 void SVGTextFrame::HandleAttributeChangeInDescendant(Element
* aElement
,
2864 int32_t aNameSpaceID
,
2865 nsAtom
* aAttribute
) {
2866 if (aElement
->IsSVGElement(nsGkAtoms::textPath
)) {
2867 if (aNameSpaceID
== kNameSpaceID_None
&&
2868 (aAttribute
== nsGkAtoms::startOffset
||
2869 aAttribute
== nsGkAtoms::path
|| aAttribute
== nsGkAtoms::side_
)) {
2870 NotifyGlyphMetricsChange(false);
2871 } else if ((aNameSpaceID
== kNameSpaceID_XLink
||
2872 aNameSpaceID
== kNameSpaceID_None
) &&
2873 aAttribute
== nsGkAtoms::href
) {
2874 // Blow away our reference, if any
2875 nsIFrame
* childElementFrame
= aElement
->GetPrimaryFrame();
2876 if (childElementFrame
) {
2877 SVGObserverUtils::RemoveTextPathObserver(childElementFrame
);
2878 NotifyGlyphMetricsChange(false);
2882 if (aNameSpaceID
== kNameSpaceID_None
&&
2883 IsGlyphPositioningAttribute(aAttribute
)) {
2884 NotifyGlyphMetricsChange(false);
2889 void SVGTextFrame::FindCloserFrameForSelection(
2890 const nsPoint
& aPoint
, FrameWithDistance
* aCurrentBestFrame
) {
2891 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
2895 UpdateGlyphPositioning();
2897 nsPresContext
* presContext
= PresContext();
2899 // Find the frame that has the closest rendered run rect to aPoint.
2900 TextRenderedRunIterator
it(this);
2901 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
2902 uint32_t flags
= TextRenderedRun::eIncludeFill
|
2903 TextRenderedRun::eIncludeStroke
|
2904 TextRenderedRun::eNoHorizontalOverflow
;
2905 SVGBBox userRect
= run
.GetUserSpaceRect(presContext
, flags
);
2906 float devPxPerCSSPx
= presContext
->CSSPixelsToDevPixels(1.f
);
2907 userRect
.Scale(devPxPerCSSPx
);
2909 if (!userRect
.IsEmpty()) {
2912 SVGUtils::ToCanvasBounds(userRect
.ToThebesRect(), m
, presContext
);
2914 if (nsLayoutUtils::PointIsCloserToRect(aPoint
, rect
,
2915 aCurrentBestFrame
->mXDistance
,
2916 aCurrentBestFrame
->mYDistance
)) {
2917 aCurrentBestFrame
->mFrame
= run
.mFrame
;
2923 //----------------------------------------------------------------------
2924 // ISVGDisplayableFrame methods
2926 void SVGTextFrame::NotifySVGChanged(uint32_t aFlags
) {
2927 MOZ_ASSERT(aFlags
& (TRANSFORM_CHANGED
| COORD_CONTEXT_CHANGED
),
2928 "Invalidation logic may need adjusting");
2930 bool needNewBounds
= false;
2931 bool needGlyphMetricsUpdate
= false;
2932 bool needNewCanvasTM
= false;
2934 if ((aFlags
& COORD_CONTEXT_CHANGED
) &&
2935 HasAnyStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES
)) {
2936 needGlyphMetricsUpdate
= true;
2939 if (aFlags
& TRANSFORM_CHANGED
) {
2940 needNewCanvasTM
= true;
2941 if (mCanvasTM
&& mCanvasTM
->IsSingular()) {
2942 // We won't have calculated the glyph positions correctly.
2943 needNewBounds
= true;
2944 needGlyphMetricsUpdate
= true;
2946 if (StyleSVGReset()->HasNonScalingStroke()) {
2947 // Stroke currently contributes to our mRect, and our stroke depends on
2948 // the transform to our outer-<svg> if |vector-effect:non-scaling-stroke|.
2949 needNewBounds
= true;
2953 // If the scale at which we computed our mFontSizeScaleFactor has changed by
2954 // at least a factor of two, reflow the text. This avoids reflowing text
2955 // at every tick of a transform animation, but ensures our glyph metrics
2956 // do not get too far out of sync with the final font size on the screen.
2957 if (needNewCanvasTM
&& mLastContextScale
!= 0.0f
) {
2958 mCanvasTM
= nullptr;
2959 // If we are a non-display frame, then we don't want to call
2960 // GetCanvasTM(), since the context scale does not use it.
2962 HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
) ? gfxMatrix() : GetCanvasTM();
2963 // Compare the old and new context scales.
2964 float scale
= GetContextScale(newTM
);
2965 float change
= scale
/ mLastContextScale
;
2966 if (change
>= 2.0f
|| change
<= 0.5f
) {
2967 needNewBounds
= true;
2968 needGlyphMetricsUpdate
= true;
2972 if (needNewBounds
) {
2973 // Ancestor changes can't affect how we render from the perspective of
2974 // any rendering observers that we may have, so we don't need to
2975 // invalidate them. We also don't need to invalidate ourself, since our
2976 // changed ancestor will have invalidated its entire area, which includes
2978 ScheduleReflowSVG();
2981 if (needGlyphMetricsUpdate
) {
2982 // If we are positioned using percentage values we need to update our
2983 // position whenever our viewport's dimensions change. But only do this if
2984 // we have been reflowed once, otherwise the glyph positioning will be
2985 // wrong. (We need to wait until bidi reordering has been done.)
2986 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW
)) {
2987 NotifyGlyphMetricsChange(false);
2993 * Gets the offset into a DOM node that the specified caret is positioned at.
2995 static int32_t GetCaretOffset(nsCaret
* aCaret
) {
2996 RefPtr
<Selection
> selection
= aCaret
->GetSelection();
3001 return selection
->AnchorOffset();
3005 * Returns whether the caret should be painted for a given TextRenderedRun
3006 * by checking whether the caret is in the range covered by the rendered run.
3008 * @param aThisRun The TextRenderedRun to be painted.
3009 * @param aCaret The caret.
3011 static bool ShouldPaintCaret(const TextRenderedRun
& aThisRun
, nsCaret
* aCaret
) {
3012 int32_t caretOffset
= GetCaretOffset(aCaret
);
3014 if (caretOffset
< 0) {
3018 return uint32_t(caretOffset
) >= aThisRun
.mTextFrameContentOffset
&&
3019 uint32_t(caretOffset
) < aThisRun
.mTextFrameContentOffset
+
3020 aThisRun
.mTextFrameContentLength
;
3023 void SVGTextFrame::PaintSVG(gfxContext
& aContext
, const gfxMatrix
& aTransform
,
3024 imgDrawingParams
& aImgParams
) {
3025 DrawTarget
& aDrawTarget
= *aContext
.GetDrawTarget();
3026 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3031 nsPresContext
* presContext
= PresContext();
3033 gfxMatrix initialMatrix
= aContext
.CurrentMatrixDouble();
3035 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
3036 // If we are in a canvas DrawWindow call that used the
3037 // DRAWWINDOW_DO_NOT_FLUSH flag, then we may still have out
3038 // of date frames. Just don't paint anything if they are
3040 if (presContext
->PresShell()->InDrawWindowNotFlushing() &&
3044 // Text frames inside <clipPath>, <mask>, etc. will never have had
3045 // ReflowSVG called on them, so call UpdateGlyphPositioning to do this now.
3046 UpdateGlyphPositioning();
3047 } else if (IsSubtreeDirty()) {
3048 // If we are asked to paint before reflow has recomputed mPositions etc.
3049 // directly via PaintSVG, rather than via a display list, then we need
3050 // to bail out here too.
3054 const float epsilon
= 0.0001;
3055 if (abs(mLengthAdjustScaleFactor
) < epsilon
) {
3056 // A zero scale factor can be caused by having forced the text length to
3057 // zero. In this situation there is nothing to show.
3061 if (aTransform
.IsSingular()) {
3062 NS_WARNING("Can't render text element!");
3066 gfxMatrix matrixForPaintServers
= aTransform
* initialMatrix
;
3068 // SVG frames' PaintSVG methods paint in CSS px, but normally frames paint in
3069 // dev pixels. Here we multiply a CSS-px-to-dev-pixel factor onto aTransform
3070 // so our non-SVG nsTextFrame children paint correctly.
3071 auto auPerDevPx
= presContext
->AppUnitsPerDevPixel();
3072 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(auPerDevPx
);
3073 gfxMatrix canvasTMForChildren
= aTransform
;
3074 canvasTMForChildren
.PreScale(cssPxPerDevPx
, cssPxPerDevPx
);
3075 initialMatrix
.PreScale(1 / cssPxPerDevPx
, 1 / cssPxPerDevPx
);
3077 gfxContextMatrixAutoSaveRestore
matSR(&aContext
);
3079 aContext
.Multiply(canvasTMForChildren
);
3080 gfxMatrix currentMatrix
= aContext
.CurrentMatrixDouble();
3082 RefPtr
<nsCaret
> caret
= presContext
->PresShell()->GetCaret();
3084 nsIFrame
* caretFrame
= caret
->GetPaintGeometry(&caretRect
);
3086 gfxContextAutoSaveRestore ctxSR
;
3087 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eVisibleFrames
);
3088 TextRenderedRun run
= it
.Current();
3090 SVGContextPaint
* outerContextPaint
=
3091 SVGContextPaint::GetContextPaint(GetContent());
3093 while (run
.mFrame
) {
3094 nsTextFrame
* frame
= run
.mFrame
;
3096 RefPtr
<SVGContextPaintImpl
> contextPaint
= new SVGContextPaintImpl();
3097 DrawMode drawMode
= contextPaint
->Init(&aDrawTarget
, initialMatrix
, frame
,
3098 outerContextPaint
, aImgParams
);
3099 if (drawMode
& DrawMode::GLYPH_STROKE
) {
3100 ctxSR
.EnsureSaved(&aContext
);
3101 // This may change the gfxContext's transform (for non-scaling stroke),
3102 // in which case this needs to happen before we call SetMatrix() below.
3103 SVGUtils::SetupStrokeGeometry(frame
->GetParent(), &aContext
,
3107 nscoord startEdge
, endEdge
;
3108 run
.GetClipEdges(startEdge
, endEdge
);
3110 // Set up the transform for painting the text frame for the substring
3111 // indicated by the run.
3112 gfxMatrix runTransform
= run
.GetTransformFromUserSpaceForPainting(
3113 presContext
, startEdge
, endEdge
) *
3115 aContext
.SetMatrixDouble(runTransform
);
3117 if (drawMode
!= DrawMode(0)) {
3118 bool paintSVGGlyphs
;
3119 nsTextFrame::PaintTextParams
params(&aContext
);
3120 params
.framePt
= Point();
3122 LayoutDevicePixel::FromAppUnits(frame
->InkOverflowRect(), auPerDevPx
);
3123 params
.contextPaint
= contextPaint
;
3125 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD
)) {
3126 params
.state
= nsTextFrame::PaintTextParams::GenerateTextMask
;
3129 isSelected
= frame
->IsSelected();
3131 gfxGroupForBlendAutoSaveRestore
autoGroupForBlend(&aContext
);
3132 float opacity
= 1.0f
;
3133 nsIFrame
* ancestor
= frame
->GetParent();
3134 while (ancestor
!= this) {
3135 opacity
*= ancestor
->StyleEffects()->mOpacity
;
3136 ancestor
= ancestor
->GetParent();
3138 if (opacity
< 1.0f
) {
3139 autoGroupForBlend
.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA
,
3143 if (ShouldRenderAsPath(frame
, paintSVGGlyphs
)) {
3144 SVGTextDrawPathCallbacks
callbacks(this, aContext
, frame
,
3145 matrixForPaintServers
, aImgParams
,
3147 params
.callbacks
= &callbacks
;
3148 frame
->PaintText(params
, startEdge
, endEdge
, nsPoint(), isSelected
);
3150 frame
->PaintText(params
, startEdge
, endEdge
, nsPoint(), isSelected
);
3154 if (frame
== caretFrame
&& ShouldPaintCaret(run
, caret
)) {
3155 // XXX Should we be looking at the fill/stroke colours to paint the
3156 // caret with, rather than using the color property?
3157 caret
->PaintCaret(aDrawTarget
, frame
, nsPoint());
3165 nsIFrame
* SVGTextFrame::GetFrameForPoint(const gfxPoint
& aPoint
) {
3166 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3168 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
3169 // Text frames inside <clipPath> will never have had ReflowSVG called on
3170 // them, so call UpdateGlyphPositioning to do this now. (Text frames
3171 // inside <mask> and other non-display containers will never need to
3173 UpdateGlyphPositioning();
3175 NS_ASSERTION(!IsSubtreeDirty(), "reflow should have happened");
3178 // Hit-testing any clip-path will typically be a lot quicker than the
3179 // hit-testing of our text frames in the loop below, so we do the former up
3180 // front to avoid unnecessarily wasting cycles on the latter.
3181 if (!SVGUtils::HitTestClip(this, aPoint
)) {
3185 nsPresContext
* presContext
= PresContext();
3187 // Ideally we'd iterate backwards so that we can just return the first frame
3188 // that is under aPoint. In practice this will rarely matter though since it
3189 // is rare for text in/under an SVG <text> element to overlap (i.e. the first
3190 // text frame that is hit will likely be the only text frame that is hit).
3192 TextRenderedRunIterator
it(this);
3193 nsIFrame
* hit
= nullptr;
3194 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
3195 uint16_t hitTestFlags
= SVGUtils::GetGeometryHitTestFlags(run
.mFrame
);
3196 if (!hitTestFlags
) {
3200 gfxMatrix m
= run
.GetTransformFromRunUserSpaceToUserSpace(presContext
);
3205 gfxPoint pointInRunUserSpace
= m
.TransformPoint(aPoint
);
3206 gfxRect frameRect
= run
.GetRunUserSpaceRect(
3207 presContext
, TextRenderedRun::eIncludeFill
|
3208 TextRenderedRun::eIncludeStroke
)
3211 if (Inside(frameRect
, pointInRunUserSpace
)) {
3218 void SVGTextFrame::ReflowSVG() {
3219 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
3220 "This call is probaby a wasteful mistake");
3222 MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
),
3223 "ReflowSVG mechanism not designed for this");
3225 if (!SVGUtils::NeedsReflowSVG(this)) {
3226 MOZ_ASSERT(!HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
|
3227 NS_STATE_SVG_POSITIONING_DIRTY
),
3228 "How did this happen?");
3232 MaybeReflowAnonymousBlockChild();
3233 UpdateGlyphPositioning();
3235 nsPresContext
* presContext
= PresContext();
3238 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eAllFrames
);
3239 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
3240 uint32_t runFlags
= 0;
3241 if (!run
.mFrame
->StyleSVG()->mFill
.kind
.IsNone()) {
3242 runFlags
|= TextRenderedRun::eIncludeFill
;
3244 if (SVGUtils::HasStroke(run
.mFrame
)) {
3245 runFlags
|= TextRenderedRun::eIncludeStroke
;
3247 // Our "visual" overflow rect needs to be valid for building display lists
3248 // for hit testing, which means that for certain values of 'pointer-events'
3249 // it needs to include the geometry of the fill or stroke even when the
3250 // fill/ stroke don't actually render (e.g. when stroke="none" or
3251 // stroke-opacity="0"). GetGeometryHitTestFlags accounts for
3252 // 'pointer-events'. The text-shadow is not part of the hit-test area.
3253 uint16_t hitTestFlags
= SVGUtils::GetGeometryHitTestFlags(run
.mFrame
);
3254 if (hitTestFlags
& SVG_HIT_TEST_FILL
) {
3255 runFlags
|= TextRenderedRun::eIncludeFill
;
3257 if (hitTestFlags
& SVG_HIT_TEST_STROKE
) {
3258 runFlags
|= TextRenderedRun::eIncludeStroke
;
3262 r
.UnionEdges(run
.GetUserSpaceRect(presContext
, runFlags
));
3269 mRect
= nsLayoutUtils::RoundGfxRectToAppRect(r
.ToThebesRect(),
3270 AppUnitsPerCSSPixel());
3272 // Due to rounding issues when we have a transform applied, we sometimes
3273 // don't include an additional row of pixels. For now, just inflate our
3275 mRect
.Inflate(ceil(presContext
->AppUnitsPerDevPixel() / mLastContextScale
));
3278 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW
)) {
3279 // Make sure we have our filter property (if any) before calling
3280 // FinishAndStoreOverflow (subsequent filter changes are handled off
3281 // nsChangeHint_UpdateEffects):
3282 SVGObserverUtils::UpdateEffects(this);
3285 // Now unset the various reflow bits. Do this before calling
3286 // FinishAndStoreOverflow since FinishAndStoreOverflow can require glyph
3287 // positions (to resolve transform-origin).
3288 RemoveStateBits(NS_FRAME_FIRST_REFLOW
| NS_FRAME_IS_DIRTY
|
3289 NS_FRAME_HAS_DIRTY_CHILDREN
);
3291 nsRect overflow
= nsRect(nsPoint(0, 0), mRect
.Size());
3292 OverflowAreas
overflowAreas(overflow
, overflow
);
3293 FinishAndStoreOverflow(overflowAreas
, mRect
.Size());
3297 * Converts SVGUtils::eBBox* flags into TextRenderedRun flags appropriate
3298 * for the specified rendered run.
3300 static uint32_t TextRenderedRunFlagsForBBoxContribution(
3301 const TextRenderedRun
& aRun
, uint32_t aBBoxFlags
) {
3303 if ((aBBoxFlags
& SVGUtils::eBBoxIncludeFillGeometry
) ||
3304 ((aBBoxFlags
& SVGUtils::eBBoxIncludeFill
) &&
3305 !aRun
.mFrame
->StyleSVG()->mFill
.kind
.IsNone())) {
3306 flags
|= TextRenderedRun::eIncludeFill
;
3308 if ((aBBoxFlags
& SVGUtils::eBBoxIncludeStrokeGeometry
) ||
3309 ((aBBoxFlags
& SVGUtils::eBBoxIncludeStroke
) &&
3310 SVGUtils::HasStroke(aRun
.mFrame
))) {
3311 flags
|= TextRenderedRun::eIncludeStroke
;
3316 SVGBBox
SVGTextFrame::GetBBoxContribution(const Matrix
& aToBBoxUserspace
,
3318 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3321 if (aFlags
& SVGUtils::eForGetClientRects
) {
3322 Rect rect
= NSRectToRect(mRect
, AppUnitsPerCSSPixel());
3323 if (!rect
.IsEmpty()) {
3324 bbox
= aToBBoxUserspace
.TransformBounds(rect
);
3329 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3330 if (kid
&& kid
->IsSubtreeDirty()) {
3331 // Return an empty bbox if our kid's subtree is dirty. This may be called
3332 // in that situation, e.g. when we're building a display list after an
3333 // interrupted reflow. This can also be called during reflow before we've
3334 // been reflowed, e.g. if an earlier sibling is calling
3335 // FinishAndStoreOverflow and needs our parent's perspective matrix, which
3336 // depends on the SVG bbox contribution of this frame. In the latter
3337 // situation, when all siblings have been reflowed, the parent will compute
3338 // its perspective and rerun FinishAndStoreOverflow for all its children.
3342 UpdateGlyphPositioning();
3344 nsPresContext
* presContext
= PresContext();
3346 TextRenderedRunIterator
it(this);
3347 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
3348 uint32_t flags
= TextRenderedRunFlagsForBBoxContribution(run
, aFlags
);
3349 gfxMatrix m
= ThebesMatrix(aToBBoxUserspace
);
3350 SVGBBox bboxForRun
= run
.GetUserSpaceRect(presContext
, flags
, &m
);
3351 bbox
.UnionEdges(bboxForRun
);
3357 //----------------------------------------------------------------------
3358 // SVGTextFrame SVG DOM methods
3361 * Returns whether the specified node has any non-empty Text
3364 static bool HasTextContent(nsIContent
* aContent
) {
3365 NS_ASSERTION(aContent
, "expected non-null aContent");
3367 TextNodeIterator
it(aContent
);
3368 for (Text
* text
= it
.Current(); text
; text
= it
.Next()) {
3369 if (text
->TextLength() != 0) {
3377 * Returns the number of DOM characters beneath the specified node.
3379 static uint32_t GetTextContentLength(nsIContent
* aContent
) {
3380 NS_ASSERTION(aContent
, "expected non-null aContent");
3382 uint32_t length
= 0;
3383 TextNodeIterator
it(aContent
);
3384 for (Text
* text
= it
.Current(); text
; text
= it
.Next()) {
3385 length
+= text
->TextLength();
3390 int32_t SVGTextFrame::ConvertTextElementCharIndexToAddressableIndex(
3391 int32_t aIndex
, nsIContent
* aContent
) {
3392 CharIterator
it(this, CharIterator::eOriginal
, aContent
);
3393 if (!it
.AdvanceToSubtree()) {
3397 int32_t textElementCharIndex
;
3398 while (!it
.AtEnd() && it
.IsWithinSubtree()) {
3399 bool addressable
= !it
.IsOriginalCharUnaddressable();
3400 textElementCharIndex
= it
.TextElementCharIndex();
3402 uint32_t delta
= it
.TextElementCharIndex() - textElementCharIndex
;
3415 * Implements the SVG DOM GetNumberOfChars method for the specified
3416 * text content element.
3418 uint32_t SVGTextFrame::GetNumberOfChars(nsIContent
* aContent
) {
3419 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3420 if (kid
->IsSubtreeDirty()) {
3421 // We're never reflowed if we're under a non-SVG element that is
3422 // never reflowed (such as the HTML 'caption' element).
3426 UpdateGlyphPositioning();
3429 CharIterator
it(this, CharIterator::eAddressable
, aContent
);
3430 if (it
.AdvanceToSubtree()) {
3431 while (!it
.AtEnd() && it
.IsWithinSubtree()) {
3440 * Implements the SVG DOM GetComputedTextLength method for the specified
3441 * text child element.
3443 float SVGTextFrame::GetComputedTextLength(nsIContent
* aContent
) {
3444 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3445 if (kid
->IsSubtreeDirty()) {
3446 // We're never reflowed if we're under a non-SVG element that is
3447 // never reflowed (such as the HTML 'caption' element).
3449 // If we ever decide that we need to return accurate values here,
3450 // we could do similar work to GetSubStringLength.
3454 UpdateGlyphPositioning();
3456 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
3457 PresContext()->AppUnitsPerDevPixel());
3460 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eAllFrames
,
3462 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
3463 length
+= run
.GetAdvanceWidth();
3466 return PresContext()->AppUnitsToGfxUnits(length
) * cssPxPerDevPx
*
3467 mLengthAdjustScaleFactor
/ mFontSizeScaleFactor
;
3471 * Implements the SVG DOM SelectSubString method for the specified
3472 * text content element.
3474 void SVGTextFrame::SelectSubString(nsIContent
* aContent
, uint32_t charnum
,
3475 uint32_t nchars
, ErrorResult
& aRv
) {
3476 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3477 if (kid
->IsSubtreeDirty()) {
3478 // We're never reflowed if we're under a non-SVG element that is
3479 // never reflowed (such as the HTML 'caption' element).
3480 // XXXbz Should this just return without throwing like the no-frame case?
3481 aRv
.ThrowInvalidStateError("No layout information available for SVG text");
3485 UpdateGlyphPositioning();
3487 // Convert charnum/nchars from addressable characters relative to
3488 // aContent to global character indices.
3489 CharIterator
chit(this, CharIterator::eAddressable
, aContent
);
3490 if (!chit
.AdvanceToSubtree() || !chit
.Next(charnum
) ||
3491 chit
.IsAfterSubtree()) {
3492 aRv
.ThrowIndexSizeError("Character index out of range");
3495 charnum
= chit
.TextElementCharIndex();
3496 const RefPtr
<nsIContent
> content
= chit
.TextFrame()->GetContent();
3497 chit
.NextWithinSubtree(nchars
);
3498 nchars
= chit
.TextElementCharIndex() - charnum
;
3500 RefPtr
<nsFrameSelection
> frameSelection
= GetFrameSelection();
3502 frameSelection
->HandleClick(content
, charnum
, charnum
+ nchars
,
3503 nsFrameSelection::FocusMode::kCollapseToNewPoint
,
3504 CARET_ASSOCIATE_BEFORE
);
3508 * For some content we cannot (or currently cannot) compute the length
3509 * without reflowing. In those cases we need to fall back to using
3510 * GetSubStringLengthSlowFallback.
3512 * We fall back for textPath since we need glyph positioning in order to
3513 * tell if any characters should be ignored due to having fallen off the
3514 * end of the textPath.
3516 * We fall back for bidi because GetTrimmedOffsets does not produce the
3517 * correct results for bidi continuations when passed aPostReflow = false.
3518 * XXX It may be possible to determine which continuations to trim from (and
3519 * which sides), but currently we don't do that. It would require us to
3520 * identify the visual (rather than logical) start and end of the line, to
3521 * avoid trimming at line-internal frame boundaries. Maybe nsBidiPresUtils
3522 * methods like GetFrameToRightOf and GetFrameToLeftOf would help?
3525 bool SVGTextFrame::RequiresSlowFallbackForSubStringLength() {
3526 TextFrameIterator
frameIter(this);
3527 for (nsTextFrame
* frame
= frameIter
.Current(); frame
;
3528 frame
= frameIter
.Next()) {
3529 if (frameIter
.TextPathFrame() || frame
->GetNextContinuation()) {
3537 * Implements the SVG DOM GetSubStringLength method for the specified
3538 * text content element.
3540 float SVGTextFrame::GetSubStringLengthFastPath(nsIContent
* aContent
,
3544 MOZ_ASSERT(!RequiresSlowFallbackForSubStringLength());
3546 // We only need our text correspondence to be up to date (no need to call
3547 // UpdateGlyphPositioning).
3548 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
3550 // Convert charnum/nchars from addressable characters relative to
3551 // aContent to global character indices.
3552 CharIterator
chit(this, CharIterator::eAddressable
, aContent
,
3553 /* aPostReflow */ false);
3554 if (!chit
.AdvanceToSubtree() || !chit
.Next(charnum
) ||
3555 chit
.IsAfterSubtree()) {
3556 aRv
.ThrowIndexSizeError("Character index out of range");
3560 // We do this after the ThrowIndexSizeError() bit so JS calls correctly throw
3566 charnum
= chit
.TextElementCharIndex();
3567 chit
.NextWithinSubtree(nchars
);
3568 nchars
= chit
.TextElementCharIndex() - charnum
;
3570 // Sum of the substring advances.
3571 nscoord textLength
= 0;
3573 TextFrameIterator
frit(this); // aSubtree = nullptr
3575 // Index of the first non-skipped char in the frame, and of a subsequent char
3576 // that we're interested in. Both are relative to the index of the first
3577 // non-skipped char in the ancestor <text> element.
3578 uint32_t frameStartTextElementCharIndex
= 0;
3579 uint32_t textElementCharIndex
;
3581 for (nsTextFrame
* frame
= frit
.Current(); frame
; frame
= frit
.Next()) {
3582 frameStartTextElementCharIndex
+= frit
.UndisplayedCharacters();
3583 textElementCharIndex
= frameStartTextElementCharIndex
;
3585 // Offset into frame's Text:
3586 const uint32_t untrimmedOffset
= frame
->GetContentOffset();
3587 const uint32_t untrimmedLength
= frame
->GetContentEnd() - untrimmedOffset
;
3589 // Trim the offset/length to remove any leading/trailing white space.
3590 uint32_t trimmedOffset
= untrimmedOffset
;
3591 uint32_t trimmedLength
= untrimmedLength
;
3592 nsTextFrame::TrimmedOffsets trimmedOffsets
= frame
->GetTrimmedOffsets(
3593 frame
->TextFragment(), nsTextFrame::TrimmedOffsetFlags::NotPostReflow
);
3594 TrimOffsets(trimmedOffset
, trimmedLength
, trimmedOffsets
);
3596 textElementCharIndex
+= trimmedOffset
- untrimmedOffset
;
3598 if (textElementCharIndex
>= charnum
+ nchars
) {
3599 break; // we're past the end of the substring
3602 uint32_t offset
= textElementCharIndex
;
3604 // Intersect the substring we are interested in with the range covered by
3606 IntersectInterval(offset
, trimmedLength
, charnum
, nchars
);
3608 if (trimmedLength
!= 0) {
3609 // Convert offset into an index into the frame.
3610 offset
+= trimmedOffset
- textElementCharIndex
;
3612 gfxSkipCharsIterator it
= frame
->EnsureTextRun(nsTextFrame::eInflated
);
3613 gfxTextRun
* textRun
= frame
->GetTextRun(nsTextFrame::eInflated
);
3614 nsTextFrame::PropertyProvider
provider(frame
, it
);
3616 Range range
= ConvertOriginalToSkipped(it
, offset
, trimmedLength
);
3618 // Accumulate the advance.
3619 textLength
+= textRun
->GetAdvanceWidth(range
, &provider
);
3622 // Advance, ready for next call:
3623 frameStartTextElementCharIndex
+= untrimmedLength
;
3626 nsPresContext
* presContext
= PresContext();
3627 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
3628 presContext
->AppUnitsPerDevPixel());
3630 return presContext
->AppUnitsToGfxUnits(textLength
) * cssPxPerDevPx
/
3631 mFontSizeScaleFactor
;
3634 float SVGTextFrame::GetSubStringLengthSlowFallback(nsIContent
* aContent
,
3638 UpdateGlyphPositioning();
3640 // Convert charnum/nchars from addressable characters relative to
3641 // aContent to global character indices.
3642 CharIterator
chit(this, CharIterator::eAddressable
, aContent
);
3643 if (!chit
.AdvanceToSubtree() || !chit
.Next(charnum
) ||
3644 chit
.IsAfterSubtree()) {
3645 aRv
.ThrowIndexSizeError("Character index out of range");
3653 charnum
= chit
.TextElementCharIndex();
3654 chit
.NextWithinSubtree(nchars
);
3655 nchars
= chit
.TextElementCharIndex() - charnum
;
3657 // Find each rendered run that intersects with the range defined
3658 // by charnum/nchars.
3659 nscoord textLength
= 0;
3660 TextRenderedRunIterator
runIter(this, TextRenderedRunIterator::eAllFrames
);
3661 TextRenderedRun run
= runIter
.Current();
3662 while (run
.mFrame
) {
3663 // If this rendered run is past the substring we are interested in, we
3665 uint32_t offset
= run
.mTextElementCharIndex
;
3666 if (offset
>= charnum
+ nchars
) {
3670 // Intersect the substring we are interested in with the range covered by
3671 // the rendered run.
3672 uint32_t length
= run
.mTextFrameContentLength
;
3673 IntersectInterval(offset
, length
, charnum
, nchars
);
3676 // Convert offset into an index into the frame.
3677 offset
+= run
.mTextFrameContentOffset
- run
.mTextElementCharIndex
;
3679 gfxSkipCharsIterator it
=
3680 run
.mFrame
->EnsureTextRun(nsTextFrame::eInflated
);
3681 gfxTextRun
* textRun
= run
.mFrame
->GetTextRun(nsTextFrame::eInflated
);
3682 nsTextFrame::PropertyProvider
provider(run
.mFrame
, it
);
3684 Range range
= ConvertOriginalToSkipped(it
, offset
, length
);
3686 // Accumulate the advance.
3687 textLength
+= textRun
->GetAdvanceWidth(range
, &provider
);
3690 run
= runIter
.Next();
3693 nsPresContext
* presContext
= PresContext();
3694 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
3695 presContext
->AppUnitsPerDevPixel());
3697 return presContext
->AppUnitsToGfxUnits(textLength
) * cssPxPerDevPx
/
3698 mFontSizeScaleFactor
;
3702 * Implements the SVG DOM GetCharNumAtPosition method for the specified
3703 * text content element.
3705 int32_t SVGTextFrame::GetCharNumAtPosition(nsIContent
* aContent
,
3706 const DOMPointInit
& aPoint
) {
3707 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3708 if (kid
->IsSubtreeDirty()) {
3709 // We're never reflowed if we're under a non-SVG element that is
3710 // never reflowed (such as the HTML 'caption' element).
3714 UpdateGlyphPositioning();
3716 nsPresContext
* context
= PresContext();
3718 gfxPoint
p(aPoint
.mX
, aPoint
.mY
);
3720 int32_t result
= -1;
3722 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eAllFrames
,
3724 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
3725 // Hit test this rendered run. Later runs will override earlier ones.
3726 int32_t index
= run
.GetCharNumAtPosition(context
, p
);
3728 result
= index
+ run
.mTextElementCharIndex
;
3736 return ConvertTextElementCharIndexToAddressableIndex(result
, aContent
);
3740 * Implements the SVG DOM GetStartPositionOfChar method for the specified
3741 * text content element.
3743 already_AddRefed
<DOMSVGPoint
> SVGTextFrame::GetStartPositionOfChar(
3744 nsIContent
* aContent
, uint32_t aCharNum
, ErrorResult
& aRv
) {
3745 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3746 if (kid
->IsSubtreeDirty()) {
3747 // We're never reflowed if we're under a non-SVG element that is
3748 // never reflowed (such as the HTML 'caption' element).
3749 aRv
.ThrowInvalidStateError("No layout information available for SVG text");
3753 UpdateGlyphPositioning();
3755 CharIterator
it(this, CharIterator::eAddressable
, aContent
);
3756 if (!it
.AdvanceToSubtree() || !it
.Next(aCharNum
)) {
3757 aRv
.ThrowIndexSizeError("Character index out of range");
3761 // We need to return the start position of the whole glyph.
3762 uint32_t startIndex
= it
.GlyphStartTextElementCharIndex();
3764 RefPtr
<DOMSVGPoint
> point
=
3765 new DOMSVGPoint(ToPoint(mPositions
[startIndex
].mPosition
));
3766 return point
.forget();
3770 * Returns the advance of the entire glyph whose starting character is at
3771 * aTextElementCharIndex.
3773 * aIterator, if provided, must be a CharIterator that already points to
3774 * aTextElementCharIndex that is restricted to aContent and is using
3775 * filter mode eAddressable.
3777 static gfxFloat
GetGlyphAdvance(SVGTextFrame
* aFrame
, nsIContent
* aContent
,
3778 uint32_t aTextElementCharIndex
,
3779 CharIterator
* aIterator
) {
3780 MOZ_ASSERT(!aIterator
|| (aIterator
->Filter() == CharIterator::eAddressable
&&
3781 aIterator
->GetSubtree() == aContent
&&
3782 aIterator
->GlyphStartTextElementCharIndex() ==
3783 aTextElementCharIndex
),
3784 "Invalid aIterator");
3786 Maybe
<CharIterator
> newIterator
;
3787 CharIterator
* it
= aIterator
;
3789 newIterator
.emplace(aFrame
, CharIterator::eAddressable
, aContent
);
3790 if (!newIterator
->AdvanceToSubtree()) {
3791 MOZ_ASSERT_UNREACHABLE("Invalid aContent");
3794 it
= newIterator
.ptr();
3797 while (it
->GlyphStartTextElementCharIndex() != aTextElementCharIndex
) {
3799 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3805 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3809 nsPresContext
* presContext
= aFrame
->PresContext();
3810 gfxFloat advance
= 0.0;
3813 advance
+= it
->GetAdvance(presContext
);
3815 it
->GlyphStartTextElementCharIndex() != aTextElementCharIndex
) {
3824 * Implements the SVG DOM GetEndPositionOfChar method for the specified
3825 * text content element.
3827 already_AddRefed
<DOMSVGPoint
> SVGTextFrame::GetEndPositionOfChar(
3828 nsIContent
* aContent
, uint32_t aCharNum
, ErrorResult
& aRv
) {
3829 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3830 if (kid
->IsSubtreeDirty()) {
3831 // We're never reflowed if we're under a non-SVG element that is
3832 // never reflowed (such as the HTML 'caption' element).
3833 aRv
.ThrowInvalidStateError("No layout information available for SVG text");
3837 UpdateGlyphPositioning();
3839 CharIterator
it(this, CharIterator::eAddressable
, aContent
);
3840 if (!it
.AdvanceToSubtree() || !it
.Next(aCharNum
)) {
3841 aRv
.ThrowIndexSizeError("Character index out of range");
3845 // We need to return the end position of the whole glyph.
3846 uint32_t startIndex
= it
.GlyphStartTextElementCharIndex();
3848 // Get the advance of the glyph.
3850 GetGlyphAdvance(this, aContent
, startIndex
,
3851 it
.IsClusterAndLigatureGroupStart() ? &it
: nullptr);
3852 if (it
.TextRun()->IsRightToLeft()) {
3856 // The end position is the start position plus the advance in the direction
3857 // of the glyph's rotation.
3858 Matrix m
= Matrix::Rotation(mPositions
[startIndex
].mAngle
) *
3859 Matrix::Translation(ToPoint(mPositions
[startIndex
].mPosition
));
3860 Point p
= m
.TransformPoint(Point(advance
/ mFontSizeScaleFactor
, 0));
3862 RefPtr
<DOMSVGPoint
> point
= new DOMSVGPoint(p
);
3863 return point
.forget();
3867 * Implements the SVG DOM GetExtentOfChar method for the specified
3868 * text content element.
3870 already_AddRefed
<SVGRect
> SVGTextFrame::GetExtentOfChar(nsIContent
* aContent
,
3873 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3874 if (kid
->IsSubtreeDirty()) {
3875 // We're never reflowed if we're under a non-SVG element that is
3876 // never reflowed (such as the HTML 'caption' element).
3877 aRv
.ThrowInvalidStateError("No layout information available for SVG text");
3881 UpdateGlyphPositioning();
3883 // Search for the character whose addressable index is aCharNum.
3884 CharIterator
it(this, CharIterator::eAddressable
, aContent
);
3885 if (!it
.AdvanceToSubtree() || !it
.Next(aCharNum
)) {
3886 aRv
.ThrowIndexSizeError("Character index out of range");
3890 nsPresContext
* presContext
= PresContext();
3891 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
3892 presContext
->AppUnitsPerDevPixel());
3894 nsTextFrame
* textFrame
= it
.TextFrame();
3895 uint32_t startIndex
= it
.GlyphStartTextElementCharIndex();
3896 bool isRTL
= it
.TextRun()->IsRightToLeft();
3897 bool isVertical
= it
.TextRun()->IsVertical();
3899 // Get the glyph advance.
3901 GetGlyphAdvance(this, aContent
, startIndex
,
3902 it
.IsClusterAndLigatureGroupStart() ? &it
: nullptr);
3903 gfxFloat x
= isRTL
? -advance
: 0.0;
3905 // The ascent and descent gives the height of the glyph.
3906 gfxFloat ascent
, descent
;
3907 GetAscentAndDescentInAppUnits(textFrame
, ascent
, descent
);
3909 // The horizontal extent is the origin of the glyph plus the advance
3910 // in the direction of the glyph's rotation.
3912 m
.PreTranslate(mPositions
[startIndex
].mPosition
);
3913 m
.PreRotate(mPositions
[startIndex
].mAngle
);
3914 m
.PreScale(1 / mFontSizeScaleFactor
, 1 / mFontSizeScaleFactor
);
3918 glyphRect
= gfxRect(
3919 -presContext
->AppUnitsToGfxUnits(descent
) * cssPxPerDevPx
, x
,
3920 presContext
->AppUnitsToGfxUnits(ascent
+ descent
) * cssPxPerDevPx
,
3923 glyphRect
= gfxRect(
3924 x
, -presContext
->AppUnitsToGfxUnits(ascent
) * cssPxPerDevPx
, advance
,
3925 presContext
->AppUnitsToGfxUnits(ascent
+ descent
) * cssPxPerDevPx
);
3928 // Transform the glyph's rect into user space.
3929 gfxRect r
= m
.TransformBounds(glyphRect
);
3931 RefPtr
<SVGRect
> rect
= new SVGRect(aContent
, ToRect(r
));
3932 return rect
.forget();
3936 * Implements the SVG DOM GetRotationOfChar method for the specified
3937 * text content element.
3939 float SVGTextFrame::GetRotationOfChar(nsIContent
* aContent
, uint32_t aCharNum
,
3941 nsIFrame
* kid
= PrincipalChildList().FirstChild();
3942 if (kid
->IsSubtreeDirty()) {
3943 // We're never reflowed if we're under a non-SVG element that is
3944 // never reflowed (such as the HTML 'caption' element).
3945 aRv
.ThrowInvalidStateError("No layout information available for SVG text");
3949 UpdateGlyphPositioning();
3951 CharIterator
it(this, CharIterator::eAddressable
, aContent
);
3952 if (!it
.AdvanceToSubtree() || !it
.Next(aCharNum
)) {
3953 aRv
.ThrowIndexSizeError("Character index out of range");
3957 // we need to account for the glyph's underlying orientation
3958 const gfxTextRun::GlyphRun
& glyphRun
= it
.GlyphRun();
3959 int32_t glyphOrientation
=
3960 90 * (glyphRun
.IsSidewaysRight() - glyphRun
.IsSidewaysLeft());
3962 return mPositions
[it
.TextElementCharIndex()].mAngle
* 180.0 / M_PI
+
3966 //----------------------------------------------------------------------
3967 // SVGTextFrame text layout methods
3970 * Given the character position array before values have been filled in
3971 * to any unspecified positions, and an array of dx/dy values, returns whether
3972 * a character at a given index should start a new rendered run.
3974 * @param aPositions The array of character positions before unspecified
3975 * positions have been filled in and dx/dy values have been added to them.
3976 * @param aDeltas The array of dx/dy values.
3977 * @param aIndex The character index in question.
3979 static bool ShouldStartRunAtIndex(const nsTArray
<CharPosition
>& aPositions
,
3980 const nsTArray
<gfxPoint
>& aDeltas
,
3986 if (aIndex
< aPositions
.Length()) {
3987 // If an explicit x or y value was given, start a new run.
3988 if (aPositions
[aIndex
].IsXSpecified() ||
3989 aPositions
[aIndex
].IsYSpecified()) {
3993 // If a non-zero rotation was given, or the previous character had a non-
3994 // zero rotation, start a new run.
3995 if ((aPositions
[aIndex
].IsAngleSpecified() &&
3996 aPositions
[aIndex
].mAngle
!= 0.0f
) ||
3997 (aPositions
[aIndex
- 1].IsAngleSpecified() &&
3998 (aPositions
[aIndex
- 1].mAngle
!= 0.0f
))) {
4003 if (aIndex
< aDeltas
.Length()) {
4004 // If a non-zero dx or dy value was given, start a new run.
4005 if (aDeltas
[aIndex
].x
!= 0.0 || aDeltas
[aIndex
].y
!= 0.0) {
4013 bool SVGTextFrame::ResolvePositionsForNode(nsIContent
* aContent
,
4014 uint32_t& aIndex
, bool aInTextPath
,
4015 bool& aForceStartOfChunk
,
4016 nsTArray
<gfxPoint
>& aDeltas
) {
4017 if (aContent
->IsText()) {
4018 // We found a text node.
4019 uint32_t length
= aContent
->AsText()->TextLength();
4021 uint32_t end
= aIndex
+ length
;
4022 if (MOZ_UNLIKELY(end
> mPositions
.Length())) {
4023 MOZ_ASSERT_UNREACHABLE(
4024 "length of mPositions does not match characters "
4025 "found by iterating content");
4028 if (aForceStartOfChunk
) {
4029 // Note this character as starting a new anchored chunk.
4030 mPositions
[aIndex
].mStartOfChunk
= true;
4031 aForceStartOfChunk
= false;
4033 while (aIndex
< end
) {
4034 // Record whether each of these characters should start a new rendered
4035 // run. That is always the case for characters on a text path.
4037 // Run boundaries due to rotate="" values are handled in
4038 // DoGlyphPositioning.
4039 if (aInTextPath
|| ShouldStartRunAtIndex(mPositions
, aDeltas
, aIndex
)) {
4040 mPositions
[aIndex
].mRunBoundary
= true;
4048 // Skip past elements that aren't text content elements.
4049 if (!IsTextContentElement(aContent
)) {
4053 if (aContent
->IsSVGElement(nsGkAtoms::textPath
)) {
4054 // Any ‘y’ attributes on horizontal <textPath> elements are ignored.
4055 // Similarly, for vertical <texPath>s x attributes are ignored.
4056 // <textPath> elements behave as if they have x="0" y="0" on them, but only
4057 // if there is not a value for the non-ignored coordinate that got inherited
4058 // from a parent. We skip this if there is no text content, so that empty
4059 // <textPath>s don't interrupt the layout of text in the parent element.
4060 if (HasTextContent(aContent
)) {
4061 if (MOZ_UNLIKELY(aIndex
>= mPositions
.Length())) {
4062 MOZ_ASSERT_UNREACHABLE(
4063 "length of mPositions does not match characters "
4064 "found by iterating content");
4067 bool vertical
= GetWritingMode().IsVertical();
4068 if (vertical
|| !mPositions
[aIndex
].IsXSpecified()) {
4069 mPositions
[aIndex
].mPosition
.x
= 0.0;
4071 if (!vertical
|| !mPositions
[aIndex
].IsYSpecified()) {
4072 mPositions
[aIndex
].mPosition
.y
= 0.0;
4074 mPositions
[aIndex
].mStartOfChunk
= true;
4076 } else if (!aContent
->IsSVGElement(nsGkAtoms::a
)) {
4077 MOZ_ASSERT(aContent
->IsSVGElement());
4079 // We have a text content element that can have x/y/dx/dy/rotate attributes.
4080 SVGElement
* element
= static_cast<SVGElement
*>(aContent
);
4082 // Get x, y, dx, dy.
4083 SVGUserUnitList x
, y
, dx
, dy
;
4084 element
->GetAnimatedLengthListValues(&x
, &y
, &dx
, &dy
, nullptr);
4087 const SVGNumberList
* rotate
= nullptr;
4088 SVGAnimatedNumberList
* animatedRotate
=
4089 element
->GetAnimatedNumberList(nsGkAtoms::rotate
);
4090 if (animatedRotate
) {
4091 rotate
= &animatedRotate
->GetAnimValue();
4094 bool percentages
= false;
4095 uint32_t count
= GetTextContentLength(aContent
);
4097 if (MOZ_UNLIKELY(aIndex
+ count
> mPositions
.Length())) {
4098 MOZ_ASSERT_UNREACHABLE(
4099 "length of mPositions does not match characters "
4100 "found by iterating content");
4104 // New text anchoring chunks start at each character assigned a position
4105 // with x="" or y="", or if we forced one with aForceStartOfChunk due to
4106 // being just after a <textPath>.
4107 uint32_t newChunkCount
= std::max(x
.Length(), y
.Length());
4108 if (!newChunkCount
&& aForceStartOfChunk
) {
4111 for (uint32_t i
= 0, j
= 0; i
< newChunkCount
&& j
< count
; j
++) {
4112 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4113 mPositions
[aIndex
+ j
].mStartOfChunk
= true;
4118 // Copy dx="" and dy="" values into aDeltas.
4119 if (!dx
.IsEmpty() || !dy
.IsEmpty()) {
4120 // Any unspecified deltas when we grow the array just get left as 0s.
4121 aDeltas
.EnsureLengthAtLeast(aIndex
+ count
);
4122 for (uint32_t i
= 0, j
= 0; i
< dx
.Length() && j
< count
; j
++) {
4123 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4124 aDeltas
[aIndex
+ j
].x
= dx
[i
];
4125 percentages
= percentages
|| dx
.HasPercentageValueAt(i
);
4129 for (uint32_t i
= 0, j
= 0; i
< dy
.Length() && j
< count
; j
++) {
4130 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4131 aDeltas
[aIndex
+ j
].y
= dy
[i
];
4132 percentages
= percentages
|| dy
.HasPercentageValueAt(i
);
4138 // Copy x="" and y="" values.
4139 for (uint32_t i
= 0, j
= 0; i
< x
.Length() && j
< count
; j
++) {
4140 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4141 mPositions
[aIndex
+ j
].mPosition
.x
= x
[i
];
4142 percentages
= percentages
|| x
.HasPercentageValueAt(i
);
4146 for (uint32_t i
= 0, j
= 0; i
< y
.Length() && j
< count
; j
++) {
4147 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4148 mPositions
[aIndex
+ j
].mPosition
.y
= y
[i
];
4149 percentages
= percentages
|| y
.HasPercentageValueAt(i
);
4154 // Copy rotate="" values.
4155 if (rotate
&& !rotate
->IsEmpty()) {
4156 uint32_t i
= 0, j
= 0;
4157 while (i
< rotate
->Length() && j
< count
) {
4158 if (!mPositions
[aIndex
+ j
].mUnaddressable
) {
4159 mPositions
[aIndex
+ j
].mAngle
= M_PI
* (*rotate
)[i
] / 180.0;
4164 // Propagate final rotate="" value to the end of this element.
4166 mPositions
[aIndex
+ j
].mAngle
= mPositions
[aIndex
+ j
- 1].mAngle
;
4172 AddStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES
);
4176 // Recurse to children.
4177 bool inTextPath
= aInTextPath
|| aContent
->IsSVGElement(nsGkAtoms::textPath
);
4178 for (nsIContent
* child
= aContent
->GetFirstChild(); child
;
4179 child
= child
->GetNextSibling()) {
4180 bool ok
= ResolvePositionsForNode(child
, aIndex
, inTextPath
,
4181 aForceStartOfChunk
, aDeltas
);
4187 if (aContent
->IsSVGElement(nsGkAtoms::textPath
)) {
4188 // Force a new anchored chunk just after a <textPath>.
4189 aForceStartOfChunk
= true;
4195 bool SVGTextFrame::ResolvePositions(nsTArray
<gfxPoint
>& aDeltas
,
4196 bool aRunPerGlyph
) {
4197 NS_ASSERTION(mPositions
.IsEmpty(), "expected mPositions to be empty");
4198 RemoveStateBits(NS_STATE_SVG_POSITIONING_MAY_USE_PERCENTAGES
);
4200 CharIterator
it(this, CharIterator::eOriginal
, /* aSubtree */ nullptr);
4205 // We assume the first character position is (0,0) unless we later see
4206 // otherwise, and note it as unaddressable if it is.
4207 bool firstCharUnaddressable
= it
.IsOriginalCharUnaddressable();
4208 mPositions
.AppendElement(CharPosition::Unspecified(firstCharUnaddressable
));
4210 // Fill in unspecified positions for all remaining characters, noting
4211 // them as unaddressable if they are.
4214 while (++index
< it
.TextElementCharIndex()) {
4215 mPositions
.AppendElement(CharPosition::Unspecified(false));
4217 mPositions
.AppendElement(
4218 CharPosition::Unspecified(it
.IsOriginalCharUnaddressable()));
4220 while (++index
< it
.TextElementCharIndex()) {
4221 mPositions
.AppendElement(CharPosition::Unspecified(false));
4224 // Recurse over the content and fill in character positions as we go.
4225 bool forceStartOfChunk
= false;
4227 bool ok
= ResolvePositionsForNode(mContent
, index
, aRunPerGlyph
,
4228 forceStartOfChunk
, aDeltas
);
4229 return ok
&& index
> 0;
4232 void SVGTextFrame::DetermineCharPositions(nsTArray
<nsPoint
>& aPositions
) {
4233 NS_ASSERTION(aPositions
.IsEmpty(), "expected aPositions to be empty");
4237 TextFrameIterator
frit(this);
4238 for (nsTextFrame
* frame
= frit
.Current(); frame
; frame
= frit
.Next()) {
4239 gfxSkipCharsIterator it
= frame
->EnsureTextRun(nsTextFrame::eInflated
);
4240 gfxTextRun
* textRun
= frame
->GetTextRun(nsTextFrame::eInflated
);
4241 nsTextFrame::PropertyProvider
provider(frame
, it
);
4243 // Reset the position to the new frame's position.
4244 position
= frit
.Position();
4245 if (textRun
->IsVertical()) {
4246 if (textRun
->IsRightToLeft()) {
4247 position
.y
+= frame
->GetRect().height
;
4249 position
.x
+= GetBaselinePosition(frame
, textRun
, frit
.DominantBaseline(),
4250 mFontSizeScaleFactor
);
4252 if (textRun
->IsRightToLeft()) {
4253 position
.x
+= frame
->GetRect().width
;
4255 position
.y
+= GetBaselinePosition(frame
, textRun
, frit
.DominantBaseline(),
4256 mFontSizeScaleFactor
);
4259 // Any characters not in a frame, e.g. when display:none.
4260 for (uint32_t i
= 0; i
< frit
.UndisplayedCharacters(); i
++) {
4261 aPositions
.AppendElement(position
);
4264 // Any white space characters trimmed at the start of the line of text.
4265 nsTextFrame::TrimmedOffsets trimmedOffsets
=
4266 frame
->GetTrimmedOffsets(frame
->TextFragment());
4267 while (it
.GetOriginalOffset() < trimmedOffsets
.mStart
) {
4268 aPositions
.AppendElement(position
);
4269 it
.AdvanceOriginal(1);
4272 // Visible characters in the text frame.
4273 while (it
.GetOriginalOffset() < frame
->GetContentEnd()) {
4274 aPositions
.AppendElement(position
);
4275 if (!it
.IsOriginalCharSkipped()) {
4276 // Accumulate partial ligature advance into position. (We must get
4277 // partial advances rather than get the advance of the whole ligature
4278 // group / cluster at once, since the group may span text frames, and
4279 // the PropertyProvider only has spacing information for the current
4281 uint32_t offset
= it
.GetSkippedOffset();
4283 textRun
->GetAdvanceWidth(Range(offset
, offset
+ 1), &provider
);
4284 (textRun
->IsVertical() ? position
.y
: position
.x
) +=
4285 textRun
->IsRightToLeft() ? -advance
: advance
;
4287 it
.AdvanceOriginal(1);
4291 // Finally any characters at the end that are not in a frame.
4292 for (uint32_t i
= 0; i
< frit
.UndisplayedCharacters(); i
++) {
4293 aPositions
.AppendElement(position
);
4298 * Physical text-anchor values.
4300 enum TextAnchorSide
{ eAnchorLeft
, eAnchorMiddle
, eAnchorRight
};
4303 * Converts a logical text-anchor value to its physical value, based on whether
4304 * it is for an RTL frame.
4306 static TextAnchorSide
ConvertLogicalTextAnchorToPhysical(
4307 StyleTextAnchor aTextAnchor
, bool aIsRightToLeft
) {
4308 NS_ASSERTION(uint8_t(aTextAnchor
) <= 3, "unexpected value for aTextAnchor");
4309 if (!aIsRightToLeft
) {
4310 return TextAnchorSide(uint8_t(aTextAnchor
));
4312 return TextAnchorSide(2 - uint8_t(aTextAnchor
));
4316 * Shifts the recorded character positions for an anchored chunk.
4318 * @param aCharPositions The recorded character positions.
4319 * @param aChunkStart The character index the starts the anchored chunk. This
4320 * character's initial position is the anchor point.
4321 * @param aChunkEnd The character index just after the end of the anchored
4323 * @param aVisIStartEdge The left/top-most edge of any of the glyphs within the
4325 * @param aVisIEndEdge The right/bottom-most edge of any of the glyphs within
4326 * the anchored chunk.
4327 * @param aAnchorSide The direction to anchor.
4329 static void ShiftAnchoredChunk(nsTArray
<CharPosition
>& aCharPositions
,
4330 uint32_t aChunkStart
, uint32_t aChunkEnd
,
4331 gfxFloat aVisIStartEdge
, gfxFloat aVisIEndEdge
,
4332 TextAnchorSide aAnchorSide
, bool aVertical
) {
4333 NS_ASSERTION(aVisIStartEdge
<= aVisIEndEdge
,
4334 "unexpected anchored chunk edges");
4335 NS_ASSERTION(aChunkStart
< aChunkEnd
,
4336 "unexpected values for aChunkStart and aChunkEnd");
4338 gfxFloat shift
= aVertical
? aCharPositions
[aChunkStart
].mPosition
.y
4339 : aCharPositions
[aChunkStart
].mPosition
.x
;
4340 switch (aAnchorSide
) {
4342 shift
-= aVisIStartEdge
;
4345 shift
-= (aVisIStartEdge
+ aVisIEndEdge
) / 2;
4348 shift
-= aVisIEndEdge
;
4351 MOZ_ASSERT_UNREACHABLE("unexpected value for aAnchorSide");
4356 for (uint32_t i
= aChunkStart
; i
< aChunkEnd
; i
++) {
4357 aCharPositions
[i
].mPosition
.y
+= shift
;
4360 for (uint32_t i
= aChunkStart
; i
< aChunkEnd
; i
++) {
4361 aCharPositions
[i
].mPosition
.x
+= shift
;
4367 void SVGTextFrame::AdjustChunksForLineBreaks() {
4368 nsBlockFrame
* block
= do_QueryFrame(PrincipalChildList().FirstChild());
4369 NS_ASSERTION(block
, "expected block frame");
4371 nsBlockFrame::LineIterator line
= block
->LinesBegin();
4373 CharIterator
it(this, CharIterator::eOriginal
, /* aSubtree */ nullptr);
4374 while (!it
.AtEnd() && line
!= block
->LinesEnd()) {
4375 if (it
.TextFrame() == line
->mFirstChild
) {
4376 mPositions
[it
.TextElementCharIndex()].mStartOfChunk
= true;
4379 it
.AdvancePastCurrentFrame();
4383 void SVGTextFrame::AdjustPositionsForClusters() {
4384 nsPresContext
* presContext
= PresContext();
4386 // Find all of the characters that are in the middle of a cluster or
4387 // ligature group, and adjust their positions and rotations to match
4388 // the first character of the cluster/group.
4390 // Also move the boundaries of text rendered runs and anchored chunks to
4391 // not lie in the middle of cluster/group.
4393 // The partial advance of the current cluster or ligature group that we
4394 // have accumulated.
4395 gfxFloat partialAdvance
= 0.0;
4397 CharIterator
it(this, CharIterator::eUnskipped
, /* aSubtree */ nullptr);
4398 bool isFirst
= true;
4399 while (!it
.AtEnd()) {
4400 if (it
.IsClusterAndLigatureGroupStart() || isFirst
) {
4401 // If we're at the start of a new cluster or ligature group, reset our
4402 // accumulated partial advance. Also treat the beginning of the text as
4403 // an anchor, even if it is a combining character and therefore was
4404 // marked as being a Unicode cluster continuation.
4405 partialAdvance
= 0.0;
4408 // Otherwise, we're in the middle of a cluster or ligature group, and
4409 // we need to use the currently accumulated partial advance to adjust
4410 // the character's position and rotation.
4412 // Find the start of the cluster/ligature group.
4413 uint32_t charIndex
= it
.TextElementCharIndex();
4414 uint32_t startIndex
= it
.GlyphStartTextElementCharIndex();
4415 MOZ_ASSERT(charIndex
!= startIndex
,
4416 "If the current character is in the middle of a cluster or "
4417 "ligature group, then charIndex must be different from "
4420 mPositions
[charIndex
].mClusterOrLigatureGroupMiddle
= true;
4422 // Don't allow different rotations on ligature parts.
4423 bool rotationAdjusted
= false;
4424 double angle
= mPositions
[startIndex
].mAngle
;
4425 if (mPositions
[charIndex
].mAngle
!= angle
) {
4426 mPositions
[charIndex
].mAngle
= angle
;
4427 rotationAdjusted
= true;
4430 // Update the character position.
4431 gfxFloat advance
= partialAdvance
/ mFontSizeScaleFactor
;
4432 gfxPoint direction
= gfxPoint(cos(angle
), sin(angle
)) *
4433 (it
.TextRun()->IsRightToLeft() ? -1.0 : 1.0);
4434 if (it
.TextRun()->IsVertical()) {
4435 std::swap(direction
.x
, direction
.y
);
4437 mPositions
[charIndex
].mPosition
=
4438 mPositions
[startIndex
].mPosition
+ direction
* advance
;
4440 // Ensure any runs that would end in the middle of a ligature now end just
4441 // after the ligature.
4442 if (mPositions
[charIndex
].mRunBoundary
) {
4443 mPositions
[charIndex
].mRunBoundary
= false;
4444 if (charIndex
+ 1 < mPositions
.Length()) {
4445 mPositions
[charIndex
+ 1].mRunBoundary
= true;
4447 } else if (rotationAdjusted
) {
4448 if (charIndex
+ 1 < mPositions
.Length()) {
4449 mPositions
[charIndex
+ 1].mRunBoundary
= true;
4453 // Ensure any anchored chunks that would begin in the middle of a ligature
4454 // now begin just after the ligature.
4455 if (mPositions
[charIndex
].mStartOfChunk
) {
4456 mPositions
[charIndex
].mStartOfChunk
= false;
4457 if (charIndex
+ 1 < mPositions
.Length()) {
4458 mPositions
[charIndex
+ 1].mStartOfChunk
= true;
4463 // Accumulate the current character's partial advance.
4464 partialAdvance
+= it
.GetAdvance(presContext
);
4470 already_AddRefed
<Path
> SVGTextFrame::GetTextPath(nsIFrame
* aTextPathFrame
) {
4471 nsIContent
* content
= aTextPathFrame
->GetContent();
4472 SVGTextPathElement
* tp
= static_cast<SVGTextPathElement
*>(content
);
4473 if (tp
->mPath
.IsRendered()) {
4474 // This is just an attribute so there's no transform that can apply
4475 // so we can just return the path directly.
4476 return tp
->mPath
.GetAnimValue().BuildPathForMeasuring();
4479 SVGGeometryElement
* geomElement
=
4480 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame
);
4485 RefPtr
<Path
> path
= geomElement
->GetOrBuildPathForMeasuring();
4490 gfxMatrix matrix
= geomElement
->PrependLocalTransformsTo(gfxMatrix());
4491 if (!matrix
.IsIdentity()) {
4492 // Apply the geometry element's transform
4493 RefPtr
<PathBuilder
> builder
=
4494 path
->TransformedCopyToBuilder(ToMatrix(matrix
));
4495 path
= builder
->Finish();
4498 return path
.forget();
4501 gfxFloat
SVGTextFrame::GetOffsetScale(nsIFrame
* aTextPathFrame
) {
4502 nsIContent
* content
= aTextPathFrame
->GetContent();
4503 SVGTextPathElement
* tp
= static_cast<SVGTextPathElement
*>(content
);
4504 if (tp
->mPath
.IsRendered()) {
4505 // A path attribute has no pathLength or transform
4506 // so we return a unit scale.
4510 SVGGeometryElement
* geomElement
=
4511 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame
);
4515 return geomElement
->GetPathLengthScale(SVGGeometryElement::eForTextPath
);
4518 gfxFloat
SVGTextFrame::GetStartOffset(nsIFrame
* aTextPathFrame
) {
4519 SVGTextPathElement
* tp
=
4520 static_cast<SVGTextPathElement
*>(aTextPathFrame
->GetContent());
4521 SVGAnimatedLength
* length
=
4522 &tp
->mLengthAttributes
[SVGTextPathElement::STARTOFFSET
];
4524 if (length
->IsPercentage()) {
4525 if (!std::isfinite(GetOffsetScale(aTextPathFrame
))) {
4526 // Either pathLength="0" for this path or the path has 0 length.
4529 RefPtr
<Path
> data
= GetTextPath(aTextPathFrame
);
4530 return data
? length
->GetAnimValInSpecifiedUnits() * data
->ComputeLength() /
4534 float lengthValue
= length
->GetAnimValue(tp
);
4535 // If offsetScale is infinity we want to return 0 not NaN
4536 return lengthValue
== 0 ? 0.0 : lengthValue
* GetOffsetScale(aTextPathFrame
);
4539 void SVGTextFrame::DoTextPathLayout() {
4540 nsPresContext
* context
= PresContext();
4542 CharIterator
it(this, CharIterator::eOriginal
, /* aSubtree */ nullptr);
4543 while (!it
.AtEnd()) {
4544 nsIFrame
* textPathFrame
= it
.TextPathFrame();
4545 if (!textPathFrame
) {
4546 // Skip past this frame if we're not in a text path.
4547 it
.AdvancePastCurrentFrame();
4551 // Get the path itself.
4552 RefPtr
<Path
> path
= GetTextPath(textPathFrame
);
4554 uint32_t start
= it
.TextElementCharIndex();
4555 it
.AdvancePastCurrentTextPathFrame();
4556 uint32_t end
= it
.TextElementCharIndex();
4557 for (uint32_t i
= start
; i
< end
; i
++) {
4558 mPositions
[i
].mHidden
= true;
4563 SVGTextPathElement
* textPath
=
4564 static_cast<SVGTextPathElement
*>(textPathFrame
->GetContent());
4566 textPath
->EnumAttributes()[SVGTextPathElement::SIDE
].GetAnimValue();
4568 gfxFloat offset
= GetStartOffset(textPathFrame
);
4569 Float pathLength
= path
->ComputeLength();
4571 // If the first character within the text path is in the middle of a
4572 // cluster or ligature group, just skip it and don't apply text path
4574 while (!it
.AtEnd()) {
4575 if (it
.IsOriginalCharSkipped()) {
4579 if (it
.IsClusterAndLigatureGroupStart()) {
4585 bool skippedEndOfTextPath
= false;
4587 // Loop for each character in the text path.
4588 while (!it
.AtEnd() && it
.TextPathFrame() &&
4589 it
.TextPathFrame()->GetContent() == textPath
) {
4590 // The index of the cluster or ligature group's first character.
4591 uint32_t i
= it
.TextElementCharIndex();
4593 // The index of the next character of the cluster or ligature.
4594 // We track this as we loop over the characters below so that we
4595 // can detect undisplayed characters and append entries into
4596 // partialAdvances for them.
4599 MOZ_ASSERT(!mPositions
[i
].mClusterOrLigatureGroupMiddle
);
4601 gfxFloat sign
= it
.TextRun()->IsRightToLeft() ? -1.0 : 1.0;
4602 bool vertical
= it
.TextRun()->IsVertical();
4604 // Compute cumulative advances for each character of the cluster or
4606 AutoTArray
<gfxFloat
, 4> partialAdvances
;
4607 gfxFloat partialAdvance
= it
.GetAdvance(context
);
4608 partialAdvances
.AppendElement(partialAdvance
);
4610 // Append entries for any undisplayed characters the CharIterator
4612 MOZ_ASSERT(j
<= it
.TextElementCharIndex());
4613 while (j
< it
.TextElementCharIndex()) {
4614 partialAdvances
.AppendElement(partialAdvance
);
4617 // This loop may end up outside of the current text path, but
4618 // that's OK; we'll consider any complete cluster or ligature
4619 // group that begins inside the text path as being affected
4621 if (it
.IsOriginalCharSkipped()) {
4622 if (!it
.TextPathFrame()) {
4623 skippedEndOfTextPath
= true;
4626 // Leave partialAdvance unchanged.
4627 } else if (it
.IsClusterAndLigatureGroupStart()) {
4630 partialAdvance
+= it
.GetAdvance(context
);
4632 partialAdvances
.AppendElement(partialAdvance
);
4635 if (!skippedEndOfTextPath
) {
4636 // Any final undisplayed characters the CharIterator skipped over.
4637 MOZ_ASSERT(j
<= it
.TextElementCharIndex());
4638 while (j
< it
.TextElementCharIndex()) {
4639 partialAdvances
.AppendElement(partialAdvance
);
4644 gfxFloat halfAdvance
=
4645 partialAdvances
.LastElement() / mFontSizeScaleFactor
/ 2.0;
4647 (vertical
? mPositions
[i
].mPosition
.y
: mPositions
[i
].mPosition
.x
) +
4648 sign
* halfAdvance
+ offset
;
4650 // Hide the character if it falls off the end of the path.
4651 mPositions
[i
].mHidden
= midx
< 0 || midx
> pathLength
;
4653 // Position the character on the path at the right angle.
4654 Point tangent
; // Unit vector tangent to the point we find.
4656 if (side
== TEXTPATH_SIDETYPE_RIGHT
) {
4657 pt
= path
->ComputePointAtLength(Float(pathLength
- midx
), &tangent
);
4660 pt
= path
->ComputePointAtLength(Float(midx
), &tangent
);
4662 Float rotation
= vertical
? atan2f(-tangent
.x
, tangent
.y
)
4663 : atan2f(tangent
.y
, tangent
.x
);
4664 Point
normal(-tangent
.y
, tangent
.x
); // Unit vector normal to the point.
4665 Point offsetFromPath
= normal
* (vertical
? -mPositions
[i
].mPosition
.x
4666 : mPositions
[i
].mPosition
.y
);
4667 pt
+= offsetFromPath
;
4668 Point direction
= tangent
* sign
;
4669 mPositions
[i
].mPosition
=
4670 ThebesPoint(pt
) - ThebesPoint(direction
) * halfAdvance
;
4671 mPositions
[i
].mAngle
+= rotation
;
4673 // Position any characters for a partial ligature.
4674 for (uint32_t k
= i
+ 1; k
< j
; k
++) {
4675 gfxPoint partialAdvance
= ThebesPoint(direction
) *
4676 partialAdvances
[k
- i
] / mFontSizeScaleFactor
;
4677 mPositions
[k
].mPosition
= mPositions
[i
].mPosition
+ partialAdvance
;
4678 mPositions
[k
].mAngle
= mPositions
[i
].mAngle
;
4679 mPositions
[k
].mHidden
= mPositions
[i
].mHidden
;
4685 void SVGTextFrame::DoAnchoring() {
4686 nsPresContext
* presContext
= PresContext();
4688 CharIterator
it(this, CharIterator::eOriginal
, /* aSubtree */ nullptr);
4690 // Don't need to worry about skipped or trimmed characters.
4691 while (!it
.AtEnd() &&
4692 (it
.IsOriginalCharSkipped() || it
.IsOriginalCharTrimmed())) {
4696 bool vertical
= GetWritingMode().IsVertical();
4697 uint32_t start
= it
.TextElementCharIndex();
4698 while (start
< mPositions
.Length()) {
4699 it
.AdvanceToCharacter(start
);
4700 nsTextFrame
* chunkFrame
= it
.TextFrame();
4702 // Measure characters in this chunk to find the left-most and right-most
4703 // edges of all glyphs within the chunk.
4704 uint32_t index
= it
.TextElementCharIndex();
4705 uint32_t end
= start
;
4706 gfxFloat left
= std::numeric_limits
<gfxFloat
>::infinity();
4707 gfxFloat right
= -std::numeric_limits
<gfxFloat
>::infinity();
4709 if (!it
.IsOriginalCharSkipped() && !it
.IsOriginalCharTrimmed()) {
4710 gfxFloat advance
= it
.GetAdvance(presContext
) / mFontSizeScaleFactor
;
4711 gfxFloat pos
= it
.TextRun()->IsVertical()
4712 ? mPositions
[index
].mPosition
.y
4713 : mPositions
[index
].mPosition
.x
;
4714 if (it
.TextRun()->IsRightToLeft()) {
4715 left
= std::min(left
, pos
- advance
);
4716 right
= std::max(right
, pos
);
4718 left
= std::min(left
, pos
);
4719 right
= std::max(right
, pos
+ advance
);
4723 index
= end
= it
.TextElementCharIndex();
4724 } while (!it
.AtEnd() && !mPositions
[end
].mStartOfChunk
);
4726 if (left
!= std::numeric_limits
<gfxFloat
>::infinity()) {
4728 chunkFrame
->StyleVisibility()->mDirection
== StyleDirection::Rtl
;
4729 TextAnchorSide anchor
= ConvertLogicalTextAnchorToPhysical(
4730 chunkFrame
->StyleSVG()->mTextAnchor
, isRTL
);
4732 ShiftAnchoredChunk(mPositions
, start
, end
, left
, right
, anchor
, vertical
);
4735 start
= it
.TextElementCharIndex();
4739 void SVGTextFrame::DoGlyphPositioning() {
4741 RemoveStateBits(NS_STATE_SVG_POSITIONING_DIRTY
);
4743 nsIFrame
* kid
= PrincipalChildList().FirstChild();
4744 if (kid
&& kid
->IsSubtreeDirty()) {
4745 MOZ_ASSERT(false, "should have already reflowed the kid");
4749 // Since we can be called directly via GetBBoxContribution, our correspondence
4750 // may not be up to date.
4751 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
4753 // Determine the positions of each character in app units.
4754 AutoTArray
<nsPoint
, 64> charPositions
;
4755 DetermineCharPositions(charPositions
);
4757 if (charPositions
.IsEmpty()) {
4758 // No characters, so nothing to do.
4762 // If the textLength="" attribute was specified, then we need ResolvePositions
4763 // to record that a new run starts with each glyph.
4764 SVGTextContentElement
* element
=
4765 static_cast<SVGTextContentElement
*>(GetContent());
4766 SVGAnimatedLength
* textLengthAttr
=
4767 element
->GetAnimatedLength(nsGkAtoms::textLength
);
4768 uint16_t lengthAdjust
=
4769 element
->EnumAttributes()[SVGTextContentElement::LENGTHADJUST
]
4771 bool adjustingTextLength
= textLengthAttr
->IsExplicitlySet();
4772 float expectedTextLength
= textLengthAttr
->GetAnimValue(element
);
4774 if (adjustingTextLength
&&
4775 (expectedTextLength
< 0.0f
|| lengthAdjust
== LENGTHADJUST_UNKNOWN
)) {
4776 // If textLength="" is less than zero or lengthAdjust is unknown, ignore it.
4777 adjustingTextLength
= false;
4780 // Get the x, y, dx, dy, rotate values for the subtree.
4781 AutoTArray
<gfxPoint
, 16> deltas
;
4782 if (!ResolvePositions(deltas
, adjustingTextLength
)) {
4783 // If ResolvePositions returned false, it means either there were some
4784 // characters in the DOM but none of them are displayed, or there was
4785 // an error in processing mPositions. Clear out mPositions so that we don't
4786 // attempt to do any painting later.
4791 // XXX We might be able to do less work when there is at most a single
4792 // x/y/dx/dy position.
4794 // Truncate the positioning arrays to the actual number of characters present.
4795 TruncateTo(deltas
, charPositions
);
4796 TruncateTo(mPositions
, charPositions
);
4798 // Fill in an unspecified character position at index 0.
4799 if (!mPositions
[0].IsXSpecified()) {
4800 mPositions
[0].mPosition
.x
= 0.0;
4802 if (!mPositions
[0].IsYSpecified()) {
4803 mPositions
[0].mPosition
.y
= 0.0;
4805 if (!mPositions
[0].IsAngleSpecified()) {
4806 mPositions
[0].mAngle
= 0.0;
4809 nsPresContext
* presContext
= PresContext();
4810 bool vertical
= GetWritingMode().IsVertical();
4812 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
4813 presContext
->AppUnitsPerDevPixel());
4814 double factor
= cssPxPerDevPx
/ mFontSizeScaleFactor
;
4816 // Determine how much to compress or expand glyph positions due to
4817 // textLength="" and lengthAdjust="".
4818 double adjustment
= 0.0;
4819 mLengthAdjustScaleFactor
= 1.0f
;
4820 if (adjustingTextLength
) {
4821 nscoord frameLength
=
4822 vertical
? PrincipalChildList().FirstChild()->GetRect().height
4823 : PrincipalChildList().FirstChild()->GetRect().width
;
4824 float actualTextLength
= static_cast<float>(
4825 presContext
->AppUnitsToGfxUnits(frameLength
) * factor
);
4827 switch (lengthAdjust
) {
4828 case LENGTHADJUST_SPACINGANDGLYPHS
:
4829 // Scale the glyphs and their positions.
4830 if (actualTextLength
> 0) {
4831 mLengthAdjustScaleFactor
= expectedTextLength
/ actualTextLength
;
4836 MOZ_ASSERT(lengthAdjust
== LENGTHADJUST_SPACING
);
4837 // Just add space between each glyph.
4838 int32_t adjustableSpaces
= 0;
4839 for (uint32_t i
= 1; i
< mPositions
.Length(); i
++) {
4840 if (!mPositions
[i
].mUnaddressable
) {
4844 if (adjustableSpaces
) {
4846 (expectedTextLength
- actualTextLength
) / adjustableSpaces
;
4852 // Fill in any unspecified character positions based on the positions recorded
4853 // in charPositions, and also add in the dx/dy values.
4854 if (!deltas
.IsEmpty()) {
4855 mPositions
[0].mPosition
+= deltas
[0];
4858 gfxFloat xLengthAdjustFactor
= vertical
? 1.0 : mLengthAdjustScaleFactor
;
4859 gfxFloat yLengthAdjustFactor
= vertical
? mLengthAdjustScaleFactor
: 1.0;
4860 for (uint32_t i
= 1; i
< mPositions
.Length(); i
++) {
4861 // Fill in unspecified x position.
4862 if (!mPositions
[i
].IsXSpecified()) {
4863 nscoord d
= charPositions
[i
].x
- charPositions
[i
- 1].x
;
4864 mPositions
[i
].mPosition
.x
=
4865 mPositions
[i
- 1].mPosition
.x
+
4866 presContext
->AppUnitsToGfxUnits(d
) * factor
* xLengthAdjustFactor
;
4867 if (!vertical
&& !mPositions
[i
].mUnaddressable
) {
4868 mPositions
[i
].mPosition
.x
+= adjustment
;
4871 // Fill in unspecified y position.
4872 if (!mPositions
[i
].IsYSpecified()) {
4873 nscoord d
= charPositions
[i
].y
- charPositions
[i
- 1].y
;
4874 mPositions
[i
].mPosition
.y
=
4875 mPositions
[i
- 1].mPosition
.y
+
4876 presContext
->AppUnitsToGfxUnits(d
) * factor
* yLengthAdjustFactor
;
4877 if (vertical
&& !mPositions
[i
].mUnaddressable
) {
4878 mPositions
[i
].mPosition
.y
+= adjustment
;
4882 if (i
< deltas
.Length()) {
4883 mPositions
[i
].mPosition
+= deltas
[i
];
4885 // Fill in unspecified rotation values.
4886 if (!mPositions
[i
].IsAngleSpecified()) {
4887 mPositions
[i
].mAngle
= 0.0f
;
4891 MOZ_ASSERT(mPositions
.Length() == charPositions
.Length());
4893 AdjustChunksForLineBreaks();
4894 AdjustPositionsForClusters();
4899 bool SVGTextFrame::ShouldRenderAsPath(nsTextFrame
* aFrame
,
4900 bool& aShouldPaintSVGGlyphs
) {
4901 // Rendering to a clip path.
4902 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD
)) {
4903 aShouldPaintSVGGlyphs
= false;
4907 aShouldPaintSVGGlyphs
= true;
4909 const nsStyleSVG
* style
= aFrame
->StyleSVG();
4911 // Fill is a non-solid paint, has a non-default fill-rule or has
4913 if (!(style
->mFill
.kind
.IsNone() ||
4914 (style
->mFill
.kind
.IsColor() && style
->mFillOpacity
.IsOpacity() &&
4915 style
->mFillOpacity
.AsOpacity() == 1))) {
4919 // Text has a stroke.
4920 if (style
->HasStroke()) {
4921 if (style
->mStrokeWidth
.IsContextValue()) {
4924 if (SVGContentUtils::CoordToFloat(
4925 static_cast<SVGElement
*>(GetContent()),
4926 style
->mStrokeWidth
.AsLengthPercentage()) > 0) {
4934 void SVGTextFrame::ScheduleReflowSVG() {
4935 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
4936 ScheduleReflowSVGNonDisplayText(
4937 IntrinsicDirty::FrameAncestorsAndDescendants
);
4939 SVGUtils::ScheduleReflowSVG(this);
4943 void SVGTextFrame::NotifyGlyphMetricsChange(bool aUpdateTextCorrespondence
) {
4944 if (aUpdateTextCorrespondence
) {
4945 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
);
4947 AddStateBits(NS_STATE_SVG_POSITIONING_DIRTY
);
4948 nsLayoutUtils::PostRestyleEvent(mContent
->AsElement(), RestyleHint
{0},
4949 nsChangeHint_InvalidateRenderingObservers
);
4950 ScheduleReflowSVG();
4953 void SVGTextFrame::UpdateGlyphPositioning() {
4954 nsIFrame
* kid
= PrincipalChildList().FirstChild();
4959 if (HasAnyStateBits(NS_STATE_SVG_POSITIONING_DIRTY
)) {
4960 DoGlyphPositioning();
4964 void SVGTextFrame::MaybeResolveBidiForAnonymousBlockChild() {
4965 nsIFrame
* kid
= PrincipalChildList().FirstChild();
4967 if (kid
&& kid
->HasAnyStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION
) &&
4968 PresContext()->BidiEnabled()) {
4969 MOZ_ASSERT(static_cast<nsBlockFrame
*>(do_QueryFrame(kid
)),
4970 "Expect anonymous child to be an nsBlockFrame");
4971 nsBidiPresUtils::Resolve(static_cast<nsBlockFrame
*>(kid
));
4975 void SVGTextFrame::MaybeReflowAnonymousBlockChild() {
4976 nsIFrame
* kid
= PrincipalChildList().FirstChild();
4981 NS_ASSERTION(!kid
->HasAnyStateBits(NS_FRAME_IN_REFLOW
),
4982 "should not be in reflow when about to reflow again");
4984 if (IsSubtreeDirty()) {
4985 if (HasAnyStateBits(NS_FRAME_IS_DIRTY
)) {
4986 // If we require a full reflow, ensure our kid is marked fully dirty.
4987 // (Note that our anonymous nsBlockFrame is not an ISVGDisplayableFrame,
4988 // so even when we are called via our ReflowSVG this will not be done for
4989 // us by SVGDisplayContainerFrame::ReflowSVG.)
4990 kid
->MarkSubtreeDirty();
4993 // The RecordCorrespondence and DoReflow calls can result in new text frames
4994 // being created (due to bidi resolution or reflow). We set this bit to
4995 // guard against unnecessarily calling back in to
4996 // ScheduleReflowSVGNonDisplayText from nsIFrame::DidSetComputedStyle on
4997 // those new text frames.
4998 AddStateBits(NS_STATE_SVG_TEXT_IN_REFLOW
);
5000 TextNodeCorrespondenceRecorder::RecordCorrespondence(this);
5002 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
5003 "should be under ReflowSVG");
5004 nsPresContext::InterruptPreventer
noInterrupts(PresContext());
5007 RemoveStateBits(NS_STATE_SVG_TEXT_IN_REFLOW
);
5011 void SVGTextFrame::DoReflow() {
5012 MOZ_ASSERT(HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW
));
5014 // Since we are going to reflow the anonymous block frame, we will
5015 // need to update mPositions.
5016 // We also mark our text correspondence as dirty since we can end up needing
5017 // reflow in ways that do not set NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY.
5018 // (We'd then fail the "expected a TextNodeCorrespondenceProperty" assertion
5019 // when UpdateGlyphPositioning() is called after we return.)
5020 AddStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY
|
5021 NS_STATE_SVG_POSITIONING_DIRTY
);
5023 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
5024 // Normally, these dirty flags would be cleared in ReflowSVG(), but that
5025 // doesn't get called for non-display frames. We don't want to reflow our
5026 // descendants every time SVGTextFrame::PaintSVG makes sure that we have
5027 // valid positions by calling UpdateGlyphPositioning(), so we need to clear
5028 // these dirty bits. Note that this also breaks an invalidation loop where
5029 // our descendants invalidate as they reflow, which invalidates rendering
5030 // observers, which reschedules the frame that is currently painting by
5031 // referencing us to paint again. See bug 839958 comment 7. Hopefully we
5032 // will break that loop more convincingly at some point.
5033 RemoveStateBits(NS_FRAME_IS_DIRTY
| NS_FRAME_HAS_DIRTY_CHILDREN
);
5036 nsPresContext
* presContext
= PresContext();
5037 nsIFrame
* kid
= PrincipalChildList().FirstChild();
5042 UniquePtr
<gfxContext
> renderingContext
=
5043 presContext
->PresShell()->CreateReferenceRenderingContext();
5045 if (UpdateFontSizeScaleFactor()) {
5046 // If the font size scale factor changed, we need the block to report
5047 // an updated preferred width.
5048 kid
->MarkIntrinsicISizesDirty();
5051 nscoord inlineSize
= kid
->GetPrefISize(renderingContext
.get());
5052 WritingMode wm
= kid
->GetWritingMode();
5053 ReflowInput
reflowInput(presContext
, kid
, renderingContext
.get(),
5054 LogicalSize(wm
, inlineSize
, NS_UNCONSTRAINEDSIZE
));
5055 ReflowOutput
desiredSize(reflowInput
);
5056 nsReflowStatus status
;
5059 reflowInput
.ComputedPhysicalBorderPadding() == nsMargin(0, 0, 0, 0) &&
5060 reflowInput
.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0),
5061 "style system should ensure that :-moz-svg-text "
5062 "does not get styled");
5064 kid
->Reflow(presContext
, desiredSize
, reflowInput
, status
);
5065 kid
->DidReflow(presContext
, &reflowInput
);
5066 kid
->SetSize(wm
, desiredSize
.Size(wm
));
5069 // Usable font size range in devpixels / user-units
5070 #define CLAMP_MIN_SIZE 8.0
5071 #define CLAMP_MAX_SIZE 200.0
5072 #define PRECISE_SIZE 200.0
5074 bool SVGTextFrame::UpdateFontSizeScaleFactor() {
5075 double oldFontSizeScaleFactor
= mFontSizeScaleFactor
;
5077 nsPresContext
* presContext
= PresContext();
5079 bool geometricPrecision
= false;
5080 CSSCoord min
= std::numeric_limits
<float>::max();
5081 CSSCoord max
= std::numeric_limits
<float>::min();
5082 bool anyText
= false;
5084 // Find the minimum and maximum font sizes used over all the
5086 TextFrameIterator
it(this);
5087 nsTextFrame
* f
= it
.Current();
5089 if (!geometricPrecision
) {
5090 // Unfortunately we can't treat text-rendering:geometricPrecision
5091 // separately for each text frame.
5092 geometricPrecision
= f
->StyleText()->mTextRendering
==
5093 StyleTextRendering::Geometricprecision
;
5095 const auto& fontSize
= f
->StyleFont()->mFont
.size
;
5096 if (!fontSize
.IsZero()) {
5097 min
= std::min(min
, fontSize
.ToCSSPixels());
5098 max
= std::max(max
, fontSize
.ToCSSPixels());
5105 // No text, so no need for scaling.
5106 mFontSizeScaleFactor
= 1.0;
5107 return mFontSizeScaleFactor
!= oldFontSizeScaleFactor
;
5110 if (geometricPrecision
) {
5111 // We want to ensure minSize is scaled to PRECISE_SIZE.
5112 mFontSizeScaleFactor
= PRECISE_SIZE
/ min
;
5113 return mFontSizeScaleFactor
!= oldFontSizeScaleFactor
;
5116 // When we are non-display, we could be painted in different coordinate
5117 // spaces, and we don't want to have to reflow for each of these. We
5118 // just assume that the context scale is 1.0 for them all, so we don't
5119 // get stuck with a font size scale factor based on whichever referencing
5120 // frame happens to reflow first.
5121 double contextScale
= 1.0;
5122 if (!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY
)) {
5123 gfxMatrix
m(GetCanvasTM());
5124 if (!m
.IsSingular()) {
5125 contextScale
= GetContextScale(m
);
5126 if (!std::isfinite(contextScale
)) {
5127 contextScale
= 1.0f
;
5131 mLastContextScale
= contextScale
;
5133 // But we want to ignore any scaling required due to HiDPI displays, since
5134 // regular CSS text frames will still create text runs using the font size
5135 // in CSS pixels, and we want SVG text to have the same rendering as HTML
5136 // text for regular font sizes.
5137 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
5138 presContext
->AppUnitsPerDevPixel());
5139 contextScale
*= cssPxPerDevPx
;
5141 double minTextRunSize
= min
* contextScale
;
5142 double maxTextRunSize
= max
* contextScale
;
5144 if (minTextRunSize
>= CLAMP_MIN_SIZE
&& maxTextRunSize
<= CLAMP_MAX_SIZE
) {
5145 // We are already in the ideal font size range for all text frames,
5146 // so we only have to take into account the contextScale.
5147 mFontSizeScaleFactor
= contextScale
;
5148 } else if (max
/ min
> CLAMP_MAX_SIZE
/ CLAMP_MIN_SIZE
) {
5149 // We can't scale the font sizes so that all of the text frames lie
5150 // within our ideal font size range.
5151 // Heuristically, if the maxTextRunSize is within the CLAMP_MAX_SIZE
5152 // as a reasonable value, it's likely to be the user's intent to
5153 // get a valid font for the maxTextRunSize one, we should honor it.
5154 // The same for minTextRunSize.
5155 if (maxTextRunSize
<= CLAMP_MAX_SIZE
) {
5156 mFontSizeScaleFactor
= CLAMP_MAX_SIZE
/ max
;
5157 } else if (minTextRunSize
>= CLAMP_MIN_SIZE
) {
5158 mFontSizeScaleFactor
= CLAMP_MIN_SIZE
/ min
;
5160 // So maxTextRunSize is too big, minTextRunSize is too small,
5161 // we can't really do anything for this case, just leave it as is.
5162 mFontSizeScaleFactor
= contextScale
;
5164 } else if (minTextRunSize
< CLAMP_MIN_SIZE
) {
5165 mFontSizeScaleFactor
= CLAMP_MIN_SIZE
/ min
;
5167 mFontSizeScaleFactor
= CLAMP_MAX_SIZE
/ max
;
5170 return mFontSizeScaleFactor
!= oldFontSizeScaleFactor
;
5173 double SVGTextFrame::GetFontSizeScaleFactor() const {
5174 return mFontSizeScaleFactor
;
5178 * Take aPoint, which is in the <text> element's user space, and convert
5179 * it to the appropriate frame user space of aChildFrame according to
5180 * which rendered run the point hits.
5182 Point
SVGTextFrame::TransformFramePointToTextChild(
5183 const Point
& aPoint
, const nsIFrame
* aChildFrame
) {
5184 NS_ASSERTION(aChildFrame
&& nsLayoutUtils::GetClosestFrameOfType(
5185 aChildFrame
->GetParent(),
5186 LayoutFrameType::SVGText
) == this,
5187 "aChildFrame must be a descendant of this frame");
5189 UpdateGlyphPositioning();
5191 nsPresContext
* presContext
= PresContext();
5193 // Add in the mRect offset to aPoint, as that will have been taken into
5194 // account when transforming the point from the ancestor frame down
5196 float cssPxPerDevPx
= nsPresContext::AppUnitsToFloatCSSPixels(
5197 presContext
->AppUnitsPerDevPixel());
5198 float factor
= AppUnitsPerCSSPixel();
5199 Point
framePosition(NSAppUnitsToFloatPixels(mRect
.x
, factor
),
5200 NSAppUnitsToFloatPixels(mRect
.y
, factor
));
5201 Point pointInUserSpace
= aPoint
* cssPxPerDevPx
+ framePosition
;
5203 // Find the closest rendered run for the text frames beneath aChildFrame.
5204 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eAllFrames
,
5206 TextRenderedRun hit
;
5207 gfxPoint pointInRun
;
5208 nscoord dx
= nscoord_MAX
;
5209 nscoord dy
= nscoord_MAX
;
5210 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
5211 uint32_t flags
= TextRenderedRun::eIncludeFill
|
5212 TextRenderedRun::eIncludeStroke
|
5213 TextRenderedRun::eNoHorizontalOverflow
;
5215 run
.GetRunUserSpaceRect(presContext
, flags
).ToThebesRect();
5217 gfxMatrix m
= run
.GetTransformFromRunUserSpaceToUserSpace(presContext
);
5221 gfxPoint pointInRunUserSpace
=
5222 m
.TransformPoint(ThebesPoint(pointInUserSpace
));
5224 if (Inside(runRect
, pointInRunUserSpace
)) {
5225 // The point was inside the rendered run's rect, so we choose it.
5228 pointInRun
= pointInRunUserSpace
;
5230 } else if (nsLayoutUtils::PointIsCloserToRect(pointInRunUserSpace
, runRect
,
5232 // The point was closer to this rendered run's rect than any others
5233 // we've seen so far.
5235 clamped(pointInRunUserSpace
.x
.value
, runRect
.X(), runRect
.XMost());
5237 clamped(pointInRunUserSpace
.y
.value
, runRect
.Y(), runRect
.YMost());
5243 // We didn't find any rendered runs for the frame.
5247 // Return the point in user units relative to the nsTextFrame,
5248 // but taking into account mFontSizeScaleFactor.
5249 gfxMatrix m
= hit
.GetTransformFromRunUserSpaceToFrameUserSpace(presContext
);
5250 m
.PreScale(mFontSizeScaleFactor
, mFontSizeScaleFactor
);
5251 return ToPoint(m
.TransformPoint(pointInRun
) / cssPxPerDevPx
);
5255 * For each rendered run beneath aChildFrame, translate aRect from
5256 * aChildFrame to the run's text frame, transform it then into
5257 * the run's frame user space, intersect it with the run's
5258 * frame user space rect, then transform it up to user space.
5259 * The result is the union of all of these.
5261 gfxRect
SVGTextFrame::TransformFrameRectFromTextChild(
5262 const nsRect
& aRect
, const nsIFrame
* aChildFrame
) {
5263 NS_ASSERTION(aChildFrame
&& nsLayoutUtils::GetClosestFrameOfType(
5264 aChildFrame
->GetParent(),
5265 LayoutFrameType::SVGText
) == this,
5266 "aChildFrame must be a descendant of this frame");
5268 UpdateGlyphPositioning();
5270 nsPresContext
* presContext
= PresContext();
5273 TextRenderedRunIterator
it(this, TextRenderedRunIterator::eAllFrames
,
5275 for (TextRenderedRun run
= it
.Current(); run
.mFrame
; run
= it
.Next()) {
5276 // First, translate aRect from aChildFrame to this run's frame.
5277 nsRect rectInTextFrame
= aRect
+ aChildFrame
->GetOffsetTo(run
.mFrame
);
5279 // Scale it into frame user space.
5280 gfxRect rectInFrameUserSpace
= AppUnitsToFloatCSSPixels(
5281 gfxRect(rectInTextFrame
.x
, rectInTextFrame
.y
, rectInTextFrame
.width
,
5282 rectInTextFrame
.height
),
5285 // Intersect it with the run.
5287 TextRenderedRun::eIncludeFill
| TextRenderedRun::eIncludeStroke
;
5289 if (rectInFrameUserSpace
.IntersectRect(
5290 rectInFrameUserSpace
,
5291 run
.GetFrameUserSpaceRect(presContext
, flags
).ToThebesRect())) {
5292 // Transform it up to user space of the <text>
5293 gfxMatrix m
= run
.GetTransformFromRunUserSpaceToUserSpace(presContext
);
5294 gfxRect rectInUserSpace
= m
.TransformRect(rectInFrameUserSpace
);
5296 // Union it into the result.
5297 result
.UnionRect(result
, rectInUserSpace
);
5301 // Subtract the mRect offset from the result, as our user space for
5302 // this frame is relative to the top-left of mRect.
5303 float factor
= AppUnitsPerCSSPixel();
5304 gfxPoint
framePosition(NSAppUnitsToFloatPixels(mRect
.x
, factor
),
5305 NSAppUnitsToFloatPixels(mRect
.y
, factor
));
5307 return result
- framePosition
;
5310 Rect
SVGTextFrame::TransformFrameRectFromTextChild(
5311 const Rect
& aRect
, const nsIFrame
* aChildFrame
) {
5312 nscoord appUnitsPerDevPixel
= PresContext()->AppUnitsPerDevPixel();
5313 nsRect r
= LayoutDevicePixel::ToAppUnits(
5314 LayoutDeviceRect::FromUnknownRect(aRect
), appUnitsPerDevPixel
);
5315 gfxRect resultCssUnits
= TransformFrameRectFromTextChild(r
, aChildFrame
);
5316 float devPixelPerCSSPixel
=
5317 float(AppUnitsPerCSSPixel()) / appUnitsPerDevPixel
;
5318 resultCssUnits
.Scale(devPixelPerCSSPixel
);
5319 return ToRect(resultCssUnits
);
5322 Point
SVGTextFrame::TransformFramePointFromTextChild(
5323 const Point
& aPoint
, const nsIFrame
* aChildFrame
) {
5324 return TransformFrameRectFromTextChild(Rect(aPoint
, Size(1, 1)), aChildFrame
)
5328 void SVGTextFrame::AppendDirectlyOwnedAnonBoxes(
5329 nsTArray
<OwnedAnonBox
>& aResult
) {
5330 MOZ_ASSERT(PrincipalChildList().FirstChild(), "Must have our anon box");
5331 aResult
.AppendElement(OwnedAnonBox(PrincipalChildList().FirstChild()));
5334 } // namespace mozilla