Bug 1858915 [wpt PR 42525] - Use taskcluster-run in infra tests, a=testonly
[gecko.git] / layout / svg / SVGTextFrame.cpp
blob06d96b9a52c025bb88dee5ad68b7a52eb02d9ede
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 // Main header first:
8 #include "SVGTextFrame.h"
10 // Keep others in (case-insensitive) order:
11 #include "DOMSVGPoint.h"
12 #include "gfx2DGlue.h"
13 #include "gfxContext.h"
14 #include "gfxFont.h"
15 #include "gfxSkipChars.h"
16 #include "gfxTypes.h"
17 #include "gfxUtils.h"
18 #include "LookAndFeel.h"
19 #include "nsAlgorithm.h"
20 #include "nsBidiPresUtils.h"
21 #include "nsBlockFrame.h"
22 #include "nsCaret.h"
23 #include "nsContentUtils.h"
24 #include "nsGkAtoms.h"
25 #include "nsQuickSort.h"
26 #include "SVGPaintServerFrame.h"
27 #include "nsTArray.h"
28 #include "nsTextFrame.h"
29 #include "SVGAnimatedNumberList.h"
30 #include "SVGContentUtils.h"
31 #include "SVGContextPaint.h"
32 #include "SVGLengthList.h"
33 #include "SVGNumberList.h"
34 #include "nsLayoutUtils.h"
35 #include "nsFrameSelection.h"
36 #include "nsStyleStructInlines.h"
37 #include "mozilla/DisplaySVGItem.h"
38 #include "mozilla/Likely.h"
39 #include "mozilla/PresShell.h"
40 #include "mozilla/SVGObserverUtils.h"
41 #include "mozilla/SVGOuterSVGFrame.h"
42 #include "mozilla/SVGUtils.h"
43 #include "mozilla/dom/DOMPointBinding.h"
44 #include "mozilla/dom/Selection.h"
45 #include "mozilla/dom/SVGGeometryElement.h"
46 #include "mozilla/dom/SVGRect.h"
47 #include "mozilla/dom/SVGTextContentElementBinding.h"
48 #include "mozilla/dom/SVGTextPathElement.h"
49 #include "mozilla/dom/Text.h"
50 #include "mozilla/gfx/2D.h"
51 #include "mozilla/gfx/PatternHelpers.h"
52 #include <algorithm>
53 #include <cmath>
54 #include <limits>
56 using namespace mozilla::dom;
57 using namespace mozilla::dom::SVGTextContentElement_Binding;
58 using namespace mozilla::gfx;
59 using namespace mozilla::image;
61 namespace mozilla {
63 // ============================================================================
64 // Utility functions
66 /**
67 * Using the specified gfxSkipCharsIterator, converts an offset and length
68 * in original char indexes to skipped char indexes.
70 * @param aIterator The gfxSkipCharsIterator to use for the conversion.
71 * @param aOriginalOffset The original offset.
72 * @param aOriginalLength The original length.
74 static gfxTextRun::Range ConvertOriginalToSkipped(
75 gfxSkipCharsIterator& aIterator, uint32_t aOriginalOffset,
76 uint32_t aOriginalLength) {
77 uint32_t start = aIterator.ConvertOriginalToSkipped(aOriginalOffset);
78 aIterator.AdvanceOriginal(aOriginalLength);
79 return gfxTextRun::Range(start, aIterator.GetSkippedOffset());
82 /**
83 * Converts an nsPoint from app units to user space units using the specified
84 * nsPresContext and returns it as a gfxPoint.
86 static gfxPoint AppUnitsToGfxUnits(const nsPoint& aPoint,
87 const nsPresContext* aContext) {
88 return gfxPoint(aContext->AppUnitsToGfxUnits(aPoint.x),
89 aContext->AppUnitsToGfxUnits(aPoint.y));
92 /**
93 * Converts a gfxRect that is in app units to CSS pixels using the specified
94 * nsPresContext and returns it as a gfxRect.
96 static gfxRect AppUnitsToFloatCSSPixels(const gfxRect& aRect,
97 const nsPresContext* aContext) {
98 return gfxRect(nsPresContext::AppUnitsToFloatCSSPixels(aRect.x),
99 nsPresContext::AppUnitsToFloatCSSPixels(aRect.y),
100 nsPresContext::AppUnitsToFloatCSSPixels(aRect.width),
101 nsPresContext::AppUnitsToFloatCSSPixels(aRect.height));
105 * Returns whether a gfxPoint lies within a gfxRect.
107 static bool Inside(const gfxRect& aRect, const gfxPoint& aPoint) {
108 return aPoint.x >= aRect.x && aPoint.x < aRect.XMost() &&
109 aPoint.y >= aRect.y && aPoint.y < aRect.YMost();
113 * Gets the measured ascent and descent of the text in the given nsTextFrame
114 * in app units.
116 * @param aFrame The text frame.
117 * @param aAscent The ascent in app units (output).
118 * @param aDescent The descent in app units (output).
120 static void GetAscentAndDescentInAppUnits(nsTextFrame* aFrame,
121 gfxFloat& aAscent,
122 gfxFloat& aDescent) {
123 gfxSkipCharsIterator it = aFrame->EnsureTextRun(nsTextFrame::eInflated);
124 gfxTextRun* textRun = aFrame->GetTextRun(nsTextFrame::eInflated);
126 gfxTextRun::Range range = ConvertOriginalToSkipped(
127 it, aFrame->GetContentOffset(), aFrame->GetContentLength());
129 textRun->GetLineHeightMetrics(range, aAscent, aDescent);
133 * Updates an interval by intersecting it with another interval.
134 * The intervals are specified using a start index and a length.
136 static void IntersectInterval(uint32_t& aStart, uint32_t& aLength,
137 uint32_t aStartOther, uint32_t aLengthOther) {
138 uint32_t aEnd = aStart + aLength;
139 uint32_t aEndOther = aStartOther + aLengthOther;
141 if (aStartOther >= aEnd || aStart >= aEndOther) {
142 aLength = 0;
143 } else {
144 if (aStartOther >= aStart) aStart = aStartOther;
145 aLength = std::min(aEnd, aEndOther) - aStart;
150 * Intersects an interval as IntersectInterval does but by taking
151 * the offset and length of the other interval from a
152 * nsTextFrame::TrimmedOffsets object.
154 static void TrimOffsets(uint32_t& aStart, uint32_t& aLength,
155 const nsTextFrame::TrimmedOffsets& aTrimmedOffsets) {
156 IntersectInterval(aStart, aLength, aTrimmedOffsets.mStart,
157 aTrimmedOffsets.mLength);
161 * Returns the closest ancestor-or-self node that is not an SVG <a>
162 * element.
164 static nsIContent* GetFirstNonAAncestor(nsIContent* aContent) {
165 while (aContent && aContent->IsSVGElement(nsGkAtoms::a)) {
166 aContent = aContent->GetParent();
168 return aContent;
172 * Returns whether the given node is a text content element[1], taking into
173 * account whether it has a valid parent.
175 * For example, in:
177 * <svg xmlns="http://www.w3.org/2000/svg">
178 * <text><a/><text/></text>
179 * <tspan/>
180 * </svg>
182 * true would be returned for the outer <text> element and the <a> element,
183 * and false for the inner <text> element (since a <text> is not allowed
184 * to be a child of another <text>) and the <tspan> element (because it
185 * must be inside a <text> subtree).
187 * Note that we don't support the <tref> element yet and this function
188 * returns false for it.
190 * [1] https://svgwg.org/svg2-draft/intro.html#TermTextContentElement
192 static bool IsTextContentElement(nsIContent* aContent) {
193 if (aContent->IsSVGElement(nsGkAtoms::text)) {
194 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
195 return !parent || !IsTextContentElement(parent);
198 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
199 nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
200 return parent && parent->IsSVGElement(nsGkAtoms::text);
203 return aContent->IsAnyOfSVGElements(nsGkAtoms::a, nsGkAtoms::tspan);
207 * Returns whether the specified frame is an nsTextFrame that has some text
208 * content.
210 static bool IsNonEmptyTextFrame(nsIFrame* aFrame) {
211 nsTextFrame* textFrame = do_QueryFrame(aFrame);
212 if (!textFrame) {
213 return false;
216 return textFrame->GetContentLength() != 0;
220 * Takes an nsIFrame and if it is a text frame that has some text content,
221 * returns it as an nsTextFrame and its corresponding Text.
223 * @param aFrame The frame to look at.
224 * @param aTextFrame aFrame as an nsTextFrame (output).
225 * @param aTextNode The Text content of aFrame (output).
226 * @return true if aFrame is a non-empty text frame, false otherwise.
228 static bool GetNonEmptyTextFrameAndNode(nsIFrame* aFrame,
229 nsTextFrame*& aTextFrame,
230 Text*& aTextNode) {
231 nsTextFrame* text = do_QueryFrame(aFrame);
232 bool isNonEmptyTextFrame = text && text->GetContentLength() != 0;
234 if (isNonEmptyTextFrame) {
235 nsIContent* content = text->GetContent();
236 NS_ASSERTION(content && content->IsText(),
237 "unexpected content type for nsTextFrame");
239 Text* node = content->AsText();
240 MOZ_ASSERT(node->TextLength() != 0,
241 "frame's GetContentLength() should be 0 if the text node "
242 "has no content");
244 aTextFrame = text;
245 aTextNode = node;
248 MOZ_ASSERT(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame,
249 "our logic should agree with IsNonEmptyTextFrame");
250 return isNonEmptyTextFrame;
254 * Returns whether the specified atom is for one of the five
255 * glyph positioning attributes that can appear on SVG text
256 * elements -- x, y, dx, dy or rotate.
258 static bool IsGlyphPositioningAttribute(nsAtom* aAttribute) {
259 return aAttribute == nsGkAtoms::x || aAttribute == nsGkAtoms::y ||
260 aAttribute == nsGkAtoms::dx || aAttribute == nsGkAtoms::dy ||
261 aAttribute == nsGkAtoms::rotate;
265 * Returns the position in app units of a given baseline (using an
266 * SVG dominant-baseline property value) for a given nsTextFrame.
268 * @param aFrame The text frame to inspect.
269 * @param aTextRun The text run of aFrame.
270 * @param aDominantBaseline The dominant-baseline value to use.
272 static nscoord GetBaselinePosition(nsTextFrame* aFrame, gfxTextRun* aTextRun,
273 StyleDominantBaseline aDominantBaseline,
274 float aFontSizeScaleFactor) {
275 WritingMode writingMode = aFrame->GetWritingMode();
276 gfxFloat ascent, descent;
277 aTextRun->GetLineHeightMetrics(ascent, descent);
279 auto convertIfVerticalRL = [&](gfxFloat dominantBaseline) {
280 return writingMode.IsVerticalRL() ? ascent + descent - dominantBaseline
281 : dominantBaseline;
284 switch (aDominantBaseline) {
285 case StyleDominantBaseline::Hanging:
286 return convertIfVerticalRL(ascent * 0.2);
287 case StyleDominantBaseline::TextBeforeEdge:
288 return convertIfVerticalRL(0);
290 case StyleDominantBaseline::Alphabetic:
291 return writingMode.IsVerticalRL()
292 ? ascent * 0.5
293 : aFrame->GetLogicalBaseline(writingMode);
295 case StyleDominantBaseline::Auto:
296 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
298 case StyleDominantBaseline::Middle:
299 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode) -
300 SVGContentUtils::GetFontXHeight(aFrame) / 2.0 *
301 AppUnitsPerCSSPixel() *
302 aFontSizeScaleFactor);
304 case StyleDominantBaseline::TextAfterEdge:
305 case StyleDominantBaseline::Ideographic:
306 return writingMode.IsVerticalLR() ? 0 : ascent + descent;
308 case StyleDominantBaseline::Central:
309 return (ascent + descent) / 2.0;
310 case StyleDominantBaseline::Mathematical:
311 return convertIfVerticalRL(ascent / 2.0);
314 MOZ_ASSERT_UNREACHABLE("unexpected dominant-baseline value");
315 return convertIfVerticalRL(aFrame->GetLogicalBaseline(writingMode));
319 * Truncates an array to be at most the length of another array.
321 * @param aArrayToTruncate The array to truncate.
322 * @param aReferenceArray The array whose length will be used to truncate
323 * aArrayToTruncate to.
325 template <typename T, typename U>
326 static void TruncateTo(nsTArray<T>& aArrayToTruncate,
327 const nsTArray<U>& aReferenceArray) {
328 uint32_t length = aReferenceArray.Length();
329 if (aArrayToTruncate.Length() > length) {
330 aArrayToTruncate.TruncateLength(length);
335 * Asserts that the anonymous block child of the SVGTextFrame has been
336 * reflowed (or does not exist). Returns null if the child has not been
337 * reflowed, and the frame otherwise.
339 * We check whether the kid has been reflowed and not the frame itself
340 * since we sometimes need to call this function during reflow, after the
341 * kid has been reflowed but before we have cleared the dirty bits on the
342 * frame itself.
344 static SVGTextFrame* FrameIfAnonymousChildReflowed(SVGTextFrame* aFrame) {
345 MOZ_ASSERT(aFrame, "aFrame must not be null");
346 nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
347 if (kid->IsSubtreeDirty()) {
348 MOZ_ASSERT(false, "should have already reflowed the anonymous block child");
349 return nullptr;
351 return aFrame;
354 static double GetContextScale(const gfxMatrix& aMatrix) {
355 // The context scale is the ratio of the length of the transformed
356 // diagonal vector (1,1) to the length of the untransformed diagonal
357 // (which is sqrt(2)).
358 gfxPoint p = aMatrix.TransformPoint(gfxPoint(1, 1)) -
359 aMatrix.TransformPoint(gfxPoint(0, 0));
360 return SVGContentUtils::ComputeNormalizedHypotenuse(p.x, p.y);
363 // ============================================================================
364 // Utility classes
366 // ----------------------------------------------------------------------------
367 // TextRenderedRun
370 * A run of text within a single nsTextFrame whose glyphs can all be painted
371 * with a single call to nsTextFrame::PaintText. A text rendered run can
372 * be created for a sequence of two or more consecutive glyphs as long as:
374 * - Only the first glyph has (or none of the glyphs have) been positioned
375 * with SVG text positioning attributes
376 * - All of the glyphs have zero rotation
377 * - The glyphs are not on a text path
378 * - The glyphs correspond to content within the one nsTextFrame
380 * A TextRenderedRunIterator produces TextRenderedRuns required for painting a
381 * whole SVGTextFrame.
383 struct TextRenderedRun {
384 using Range = gfxTextRun::Range;
387 * Constructs a TextRenderedRun that is uninitialized except for mFrame
388 * being null.
390 TextRenderedRun() : mFrame(nullptr) {}
393 * Constructs a TextRenderedRun with all of the information required to
394 * paint it. See the comments documenting the member variables below
395 * for descriptions of the arguments.
397 TextRenderedRun(nsTextFrame* aFrame, const gfxPoint& aPosition,
398 float aLengthAdjustScaleFactor, double aRotate,
399 float aFontSizeScaleFactor, nscoord aBaseline,
400 uint32_t aTextFrameContentOffset,
401 uint32_t aTextFrameContentLength,
402 uint32_t aTextElementCharIndex)
403 : mFrame(aFrame),
404 mPosition(aPosition),
405 mLengthAdjustScaleFactor(aLengthAdjustScaleFactor),
406 mRotate(static_cast<float>(aRotate)),
407 mFontSizeScaleFactor(aFontSizeScaleFactor),
408 mBaseline(aBaseline),
409 mTextFrameContentOffset(aTextFrameContentOffset),
410 mTextFrameContentLength(aTextFrameContentLength),
411 mTextElementCharIndex(aTextElementCharIndex) {}
414 * Returns the text run for the text frame that this rendered run is part of.
416 gfxTextRun* GetTextRun() const {
417 mFrame->EnsureTextRun(nsTextFrame::eInflated);
418 return mFrame->GetTextRun(nsTextFrame::eInflated);
422 * Returns whether this rendered run is RTL.
424 bool IsRightToLeft() const { return GetTextRun()->IsRightToLeft(); }
427 * Returns whether this rendered run is vertical.
429 bool IsVertical() const { return GetTextRun()->IsVertical(); }
432 * Returns the transform that converts from a <text> element's user space into
433 * the coordinate space that rendered runs can be painted directly in.
435 * The difference between this method and
436 * GetTransformFromRunUserSpaceToUserSpace is that when calling in to
437 * nsTextFrame::PaintText, it will already take into account any left clip
438 * edge (that is, it doesn't just apply a visual clip to the rendered text, it
439 * shifts the glyphs over so that they are painted with their left edge at the
440 * x coordinate passed in to it). Thus we need to account for this in our
441 * transform.
444 * Assume that we have:
446 * <text x="100" y="100" rotate="0 0 1 0 0 * 1">abcdef</text>.
448 * This would result in four text rendered runs:
450 * - one for "ab"
451 * - one for "c"
452 * - one for "de"
453 * - one for "f"
455 * Assume now that we are painting the third TextRenderedRun. It will have
456 * a left clip edge that is the sum of the advances of "abc", and it will
457 * have a right clip edge that is the advance of "f". In
458 * SVGTextFrame::PaintSVG(), we pass in nsPoint() (i.e., the origin)
459 * as the point at which to paint the text frame, and we pass in the
460 * clip edge values. The nsTextFrame will paint the substring of its
461 * text such that the top-left corner of the "d"'s glyph cell will be at
462 * (0, 0) in the current coordinate system.
464 * Thus, GetTransformFromUserSpaceForPainting must return a transform from
465 * whatever user space the <text> element is in to a coordinate space in
466 * device pixels (as that's what nsTextFrame works in) where the origin is at
467 * the same position as our user space mPositions[i].mPosition value for
468 * the "d" glyph, which will be (100 + userSpaceAdvance("abc"), 100).
469 * The translation required to do this (ignoring the scale to get from
470 * user space to device pixels, and ignoring the
471 * (100 + userSpaceAdvance("abc"), 100) translation) is:
473 * (-leftEdge, -baseline)
475 * where baseline is the distance between the baseline of the text and the top
476 * edge of the nsTextFrame. We translate by -leftEdge horizontally because
477 * the nsTextFrame will already shift the glyphs over by that amount and start
478 * painting glyphs at x = 0. We translate by -baseline vertically so that
479 * painting the top edges of the glyphs at y = 0 will result in their
480 * baselines being at our desired y position.
483 * Now for an example with RTL text. Assume our content is now
484 * <text x="100" y="100" rotate="0 0 1 0 0 1">WERBEH</text>. We'd have
485 * the following text rendered runs:
487 * - one for "EH"
488 * - one for "B"
489 * - one for "ER"
490 * - one for "W"
492 * Again, we are painting the third TextRenderedRun. The left clip edge
493 * is the advance of the "W" and the right clip edge is the sum of the
494 * advances of "BEH". Our translation to get the rendered "ER" glyphs
495 * in the right place this time is:
497 * (-frameWidth + rightEdge, -baseline)
499 * which is equivalent to:
501 * (-(leftEdge + advance("ER")), -baseline)
503 * The reason we have to shift left additionally by the width of the run
504 * of glyphs we are painting is that although the nsTextFrame is RTL,
505 * we still supply the top-left corner to paint the frame at when calling
506 * nsTextFrame::PaintText, even though our user space positions for each
507 * glyph in mPositions specifies the origin of each glyph, which for RTL
508 * glyphs is at the right edge of the glyph cell.
511 * For any other use of an nsTextFrame in the context of a particular run
512 * (such as hit testing, or getting its rectangle),
513 * GetTransformFromRunUserSpaceToUserSpace should be used.
515 * @param aContext The context to use for unit conversions.
517 gfxMatrix GetTransformFromUserSpaceForPainting(
518 nsPresContext* aContext, const nscoord aVisIStartEdge,
519 const nscoord aVisIEndEdge) const;
522 * Returns the transform that converts from "run user space" to a <text>
523 * element's user space. Run user space is a coordinate system that has the
524 * same size as the <text>'s user space but rotated and translated such that
525 * (0,0) is the top-left of the rectangle that bounds the text.
527 * @param aContext The context to use for unit conversions.
529 gfxMatrix GetTransformFromRunUserSpaceToUserSpace(
530 nsPresContext* aContext) const;
533 * Returns the transform that converts from "run user space" to float pixels
534 * relative to the nsTextFrame that this rendered run is a part of.
536 * @param aContext The context to use for unit conversions.
538 gfxMatrix GetTransformFromRunUserSpaceToFrameUserSpace(
539 nsPresContext* aContext) const;
542 * Flag values used for the aFlags arguments of GetRunUserSpaceRect,
543 * GetFrameUserSpaceRect and GetUserSpaceRect.
545 enum {
546 // Includes the fill geometry of the text in the returned rectangle.
547 eIncludeFill = 1,
548 // Includes the stroke geometry of the text in the returned rectangle.
549 eIncludeStroke = 2,
550 // Don't include any horizontal glyph overflow in the returned rectangle.
551 eNoHorizontalOverflow = 4
555 * Returns a rectangle that bounds the fill and/or stroke of the rendered run
556 * in run user space.
558 * @param aContext The context to use for unit conversions.
559 * @param aFlags A combination of the flags above (eIncludeFill and
560 * eIncludeStroke) indicating what parts of the text to include in
561 * the rectangle.
563 SVGBBox GetRunUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
566 * Returns a rectangle that covers the fill and/or stroke of the rendered run
567 * in "frame user space".
569 * Frame user space is a coordinate space of the same scale as the <text>
570 * element's user space, but with its rotation set to the rotation of
571 * the glyphs within this rendered run and its origin set to the position
572 * such that placing the nsTextFrame there would result in the glyphs in
573 * this rendered run being at their correct positions.
575 * For example, say we have <text x="100 150" y="100">ab</text>. Assume
576 * the advance of both the "a" and the "b" is 12 user units, and the
577 * ascent of the text is 8 user units and its descent is 6 user units,
578 * and that we are not measuing the stroke of the text, so that we stay
579 * entirely within the glyph cells.
581 * There will be two text rendered runs, one for "a" and one for "b".
583 * The frame user space for the "a" run will have its origin at
584 * (100, 100 - 8) in the <text> element's user space and will have its
585 * axes aligned with the user space (since there is no rotate="" or
586 * text path involve) and with its scale the same as the user space.
587 * The rect returned by this method will be (0, 0, 12, 14), since the "a"
588 * glyph is right at the left of the nsTextFrame.
590 * The frame user space for the "b" run will have its origin at
591 * (150 - 12, 100 - 8), and scale/rotation the same as above. The rect
592 * returned by this method will be (12, 0, 12, 14), since we are
593 * advance("a") horizontally in to the text frame.
595 * @param aContext The context to use for unit conversions.
596 * @param aFlags A combination of the flags above (eIncludeFill and
597 * eIncludeStroke) indicating what parts of the text to include in
598 * the rectangle.
600 SVGBBox GetFrameUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
603 * Returns a rectangle that covers the fill and/or stroke of the rendered run
604 * in the <text> element's user space.
606 * @param aContext The context to use for unit conversions.
607 * @param aFlags A combination of the flags above indicating what parts of
608 * the text to include in the rectangle.
609 * @param aAdditionalTransform An additional transform to apply to the
610 * frame user space rectangle before its bounds are transformed into
611 * user space.
613 SVGBBox GetUserSpaceRect(
614 nsPresContext* aContext, uint32_t aFlags,
615 const gfxMatrix* aAdditionalTransform = nullptr) const;
618 * Gets the app unit amounts to clip from the left and right edges of
619 * the nsTextFrame in order to paint just this rendered run.
621 * Note that if clip edge amounts land in the middle of a glyph, the
622 * glyph won't be painted at all. The clip edges are thus more of
623 * a selection mechanism for which glyphs will be painted, rather
624 * than a geometric clip.
626 void GetClipEdges(nscoord& aVisIStartEdge, nscoord& aVisIEndEdge) const;
629 * Returns the advance width of the whole rendered run.
631 nscoord GetAdvanceWidth() const;
634 * Returns the index of the character into this rendered run whose
635 * glyph cell contains the given point, or -1 if there is no such
636 * character. This does not hit test against any overflow.
638 * @param aContext The context to use for unit conversions.
639 * @param aPoint The point in the user space of the <text> element.
641 int32_t GetCharNumAtPosition(nsPresContext* aContext,
642 const gfxPoint& aPoint) const;
645 * The text frame that this rendered run lies within.
647 nsTextFrame* mFrame;
650 * The point in user space that the text is positioned at.
652 * For a horizontal run:
653 * The x coordinate is the left edge of a LTR run of text or the right edge of
654 * an RTL run. The y coordinate is the baseline of the text.
655 * For a vertical run:
656 * The x coordinate is the baseline of the text.
657 * The y coordinate is the top edge of a LTR run, or bottom of RTL.
659 gfxPoint mPosition;
662 * The horizontal scale factor to apply when painting glyphs to take
663 * into account textLength="".
665 float mLengthAdjustScaleFactor;
668 * The rotation in radians in the user coordinate system that the text has.
670 float mRotate;
673 * The scale factor that was used to transform the text run's original font
674 * size into a sane range for painting and measurement.
676 double mFontSizeScaleFactor;
679 * The baseline in app units of this text run. The measurement is from the
680 * top of the text frame. (From the left edge if vertical.)
682 nscoord mBaseline;
685 * The offset and length in mFrame's content Text that corresponds to
686 * this text rendered run. These are original char indexes.
688 uint32_t mTextFrameContentOffset;
689 uint32_t mTextFrameContentLength;
692 * The character index in the whole SVG <text> element that this text rendered
693 * run begins at.
695 uint32_t mTextElementCharIndex;
698 gfxMatrix TextRenderedRun::GetTransformFromUserSpaceForPainting(
699 nsPresContext* aContext, const nscoord aVisIStartEdge,
700 const nscoord aVisIEndEdge) const {
701 // We transform to device pixels positioned such that painting the text frame
702 // at (0,0) with aItem will result in the text being in the right place.
704 gfxMatrix m;
705 if (!mFrame) {
706 return m;
709 float cssPxPerDevPx =
710 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
712 // Glyph position in user space.
713 m.PreTranslate(mPosition / cssPxPerDevPx);
715 // Take into account any font size scaling and scaling due to textLength="".
716 m.PreScale(1.0 / mFontSizeScaleFactor, 1.0 / mFontSizeScaleFactor);
718 // Rotation due to rotate="" or a <textPath>.
719 m.PreRotate(mRotate);
721 m.PreScale(mLengthAdjustScaleFactor, 1.0);
723 // Translation to get the text frame in the right place.
724 nsPoint t;
726 if (IsVertical()) {
727 t = nsPoint(-mBaseline, IsRightToLeft()
728 ? -mFrame->GetRect().height + aVisIEndEdge
729 : -aVisIStartEdge);
730 } else {
731 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + aVisIEndEdge
732 : -aVisIStartEdge,
733 -mBaseline);
735 m.PreTranslate(AppUnitsToGfxUnits(t, aContext));
737 return m;
740 gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToUserSpace(
741 nsPresContext* aContext) const {
742 gfxMatrix m;
743 if (!mFrame) {
744 return m;
747 float cssPxPerDevPx =
748 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
750 nscoord start, end;
751 GetClipEdges(start, end);
753 // Glyph position in user space.
754 m.PreTranslate(mPosition);
756 // Rotation due to rotate="" or a <textPath>.
757 m.PreRotate(mRotate);
759 // Scale due to textLength="".
760 m.PreScale(mLengthAdjustScaleFactor, 1.0);
762 // Translation to get the text frame in the right place.
763 nsPoint t;
764 if (IsVertical()) {
765 t = nsPoint(-mBaseline,
766 IsRightToLeft() ? -mFrame->GetRect().height + start + end : 0);
767 } else {
768 t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + start + end : 0,
769 -mBaseline);
771 m.PreTranslate(AppUnitsToGfxUnits(t, aContext) * cssPxPerDevPx /
772 mFontSizeScaleFactor);
774 return m;
777 gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
778 nsPresContext* aContext) const {
779 gfxMatrix m;
780 if (!mFrame) {
781 return m;
784 nscoord start, end;
785 GetClipEdges(start, end);
787 // Translate by the horizontal distance into the text frame this
788 // rendered run is.
789 gfxFloat appPerCssPx = AppUnitsPerCSSPixel();
790 gfxPoint t = IsVertical() ? gfxPoint(0, start / appPerCssPx)
791 : gfxPoint(start / appPerCssPx, 0);
792 return m.PreTranslate(t);
795 SVGBBox TextRenderedRun::GetRunUserSpaceRect(nsPresContext* aContext,
796 uint32_t aFlags) const {
797 SVGBBox r;
798 if (!mFrame) {
799 return r;
802 // Determine the amount of overflow above and below the frame's mRect.
804 // We need to call InkOverflowRectRelativeToSelf because this includes
805 // overflowing decorations, which the MeasureText call below does not. We
806 // assume here the decorations only overflow above and below the frame, never
807 // horizontally.
808 nsRect self = mFrame->InkOverflowRectRelativeToSelf();
809 nsRect rect = mFrame->GetRect();
810 bool vertical = IsVertical();
811 nscoord above = vertical ? -self.x : -self.y;
812 nscoord below =
813 vertical ? self.XMost() - rect.width : self.YMost() - rect.height;
815 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
816 gfxSkipCharsIterator start = it;
817 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
819 // Get the content range for this rendered run.
820 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
821 mTextFrameContentLength);
822 if (range.Length() == 0) {
823 return r;
826 // FIXME(heycam): We could create a single PropertyProvider for all
827 // TextRenderedRuns that correspond to the text frame, rather than recreate
828 // it each time here.
829 nsTextFrame::PropertyProvider provider(mFrame, start);
831 // Measure that range.
832 gfxTextRun::Metrics metrics = textRun->MeasureText(
833 range, gfxFont::LOOSE_INK_EXTENTS, nullptr, &provider);
834 // Make sure it includes the font-box.
835 gfxRect fontBox(0, -metrics.mAscent, metrics.mAdvanceWidth,
836 metrics.mAscent + metrics.mDescent);
837 metrics.mBoundingBox.UnionRect(metrics.mBoundingBox, fontBox);
839 // Determine the rectangle that covers the rendered run's fill,
840 // taking into account the measured vertical overflow due to
841 // decorations.
842 nscoord baseline =
843 NSToCoordRoundWithClamp(metrics.mBoundingBox.y + metrics.mAscent);
844 gfxFloat x, width;
845 if (aFlags & eNoHorizontalOverflow) {
846 x = 0.0;
847 width = textRun->GetAdvanceWidth(range, &provider);
848 if (width < 0.0) {
849 x = width;
850 width = -width;
852 } else {
853 x = metrics.mBoundingBox.x;
854 width = metrics.mBoundingBox.width;
856 nsRect fillInAppUnits(
857 NSToCoordRoundWithClamp(x), baseline - above,
858 NSToCoordRoundWithClamp(width),
859 NSToCoordRoundWithClamp(metrics.mBoundingBox.height) + above + below);
860 if (textRun->IsVertical()) {
861 // Swap line-relative textMetrics dimensions to physical coordinates.
862 std::swap(fillInAppUnits.x, fillInAppUnits.y);
863 std::swap(fillInAppUnits.width, fillInAppUnits.height);
866 // Convert the app units rectangle to user units.
867 gfxRect fill = AppUnitsToFloatCSSPixels(
868 gfxRect(fillInAppUnits.x, fillInAppUnits.y, fillInAppUnits.width,
869 fillInAppUnits.height),
870 aContext);
872 // Scale the rectangle up due to any mFontSizeScaleFactor.
873 fill.Scale(1.0 / mFontSizeScaleFactor);
875 // Include the fill if requested.
876 if (aFlags & eIncludeFill) {
877 r = fill;
880 // Include the stroke if requested.
881 if ((aFlags & eIncludeStroke) && !fill.IsEmpty() &&
882 SVGUtils::GetStrokeWidth(mFrame) > 0) {
883 r.UnionEdges(
884 SVGUtils::PathExtentsToMaxStrokeExtents(fill, mFrame, gfxMatrix()));
887 return r;
890 SVGBBox TextRenderedRun::GetFrameUserSpaceRect(nsPresContext* aContext,
891 uint32_t aFlags) const {
892 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
893 if (r.IsEmpty()) {
894 return r;
896 gfxMatrix m = GetTransformFromRunUserSpaceToFrameUserSpace(aContext);
897 return m.TransformBounds(r.ToThebesRect());
900 SVGBBox TextRenderedRun::GetUserSpaceRect(
901 nsPresContext* aContext, uint32_t aFlags,
902 const gfxMatrix* aAdditionalTransform) const {
903 SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
904 if (r.IsEmpty()) {
905 return r;
907 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
908 if (aAdditionalTransform) {
909 m *= *aAdditionalTransform;
911 return m.TransformBounds(r.ToThebesRect());
914 void TextRenderedRun::GetClipEdges(nscoord& aVisIStartEdge,
915 nscoord& aVisIEndEdge) const {
916 uint32_t contentLength = mFrame->GetContentLength();
917 if (mTextFrameContentOffset == 0 &&
918 mTextFrameContentLength == contentLength) {
919 // If the rendered run covers the entire content, we know we don't need
920 // to clip without having to measure anything.
921 aVisIStartEdge = 0;
922 aVisIEndEdge = 0;
923 return;
926 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
927 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
928 nsTextFrame::PropertyProvider provider(mFrame, it);
930 // Get the covered content offset/length for this rendered run in skipped
931 // characters, since that is what GetAdvanceWidth expects.
932 Range runRange = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
933 mTextFrameContentLength);
935 // Get the offset/length of the whole nsTextFrame.
936 uint32_t frameOffset = mFrame->GetContentOffset();
937 uint32_t frameLength = mFrame->GetContentLength();
939 // Trim the whole-nsTextFrame offset/length to remove any leading/trailing
940 // white space, as the nsTextFrame when painting does not include them when
941 // interpreting clip edges.
942 nsTextFrame::TrimmedOffsets trimmedOffsets =
943 mFrame->GetTrimmedOffsets(mFrame->TextFragment());
944 TrimOffsets(frameOffset, frameLength, trimmedOffsets);
946 // Convert the trimmed whole-nsTextFrame offset/length into skipped
947 // characters.
948 Range frameRange = ConvertOriginalToSkipped(it, frameOffset, frameLength);
950 // Measure the advance width in the text run between the start of
951 // frame's content and the start of the rendered run's content,
952 nscoord startEdge = textRun->GetAdvanceWidth(
953 Range(frameRange.start, runRange.start), &provider);
955 // and between the end of the rendered run's content and the end
956 // of the frame's content.
957 nscoord endEdge =
958 textRun->GetAdvanceWidth(Range(runRange.end, frameRange.end), &provider);
960 if (textRun->IsRightToLeft()) {
961 aVisIStartEdge = endEdge;
962 aVisIEndEdge = startEdge;
963 } else {
964 aVisIStartEdge = startEdge;
965 aVisIEndEdge = endEdge;
969 nscoord TextRenderedRun::GetAdvanceWidth() const {
970 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
971 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
972 nsTextFrame::PropertyProvider provider(mFrame, it);
974 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
975 mTextFrameContentLength);
977 return textRun->GetAdvanceWidth(range, &provider);
980 int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext* aContext,
981 const gfxPoint& aPoint) const {
982 if (mTextFrameContentLength == 0) {
983 return -1;
986 float cssPxPerDevPx =
987 nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
989 // Convert the point from user space into run user space, and take
990 // into account any mFontSizeScaleFactor.
991 gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
992 if (!m.Invert()) {
993 return -1;
995 gfxPoint p = m.TransformPoint(aPoint) / cssPxPerDevPx * mFontSizeScaleFactor;
997 // First check that the point lies vertically between the top and bottom
998 // edges of the text.
999 gfxFloat ascent, descent;
1000 GetAscentAndDescentInAppUnits(mFrame, ascent, descent);
1002 WritingMode writingMode = mFrame->GetWritingMode();
1003 if (writingMode.IsVertical()) {
1004 gfxFloat leftEdge = mFrame->GetLogicalBaseline(writingMode) -
1005 (writingMode.IsVerticalRL() ? ascent : descent);
1006 gfxFloat rightEdge = leftEdge + ascent + descent;
1007 if (p.x < aContext->AppUnitsToGfxUnits(leftEdge) ||
1008 p.x > aContext->AppUnitsToGfxUnits(rightEdge)) {
1009 return -1;
1011 } else {
1012 gfxFloat topEdge = mFrame->GetLogicalBaseline(writingMode) - ascent;
1013 gfxFloat bottomEdge = topEdge + ascent + descent;
1014 if (p.y < aContext->AppUnitsToGfxUnits(topEdge) ||
1015 p.y > aContext->AppUnitsToGfxUnits(bottomEdge)) {
1016 return -1;
1020 gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
1021 gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
1022 nsTextFrame::PropertyProvider provider(mFrame, it);
1024 // Next check that the point lies horizontally within the left and right
1025 // edges of the text.
1026 Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
1027 mTextFrameContentLength);
1028 gfxFloat runAdvance =
1029 aContext->AppUnitsToGfxUnits(textRun->GetAdvanceWidth(range, &provider));
1031 gfxFloat pos = writingMode.IsVertical() ? p.y : p.x;
1032 if (pos < 0 || pos >= runAdvance) {
1033 return -1;
1036 // Finally, measure progressively smaller portions of the rendered run to
1037 // find which glyph it lies within. This will need to change once we
1038 // support letter-spacing and word-spacing.
1039 bool rtl = textRun->IsRightToLeft();
1040 for (int32_t i = mTextFrameContentLength - 1; i >= 0; i--) {
1041 range = ConvertOriginalToSkipped(it, mTextFrameContentOffset, i);
1042 gfxFloat advance = aContext->AppUnitsToGfxUnits(
1043 textRun->GetAdvanceWidth(range, &provider));
1044 if ((rtl && pos < runAdvance - advance) || (!rtl && pos >= advance)) {
1045 return i;
1048 return -1;
1051 // ----------------------------------------------------------------------------
1052 // TextNodeIterator
1054 enum SubtreePosition { eBeforeSubtree, eWithinSubtree, eAfterSubtree };
1057 * An iterator class for Text that are descendants of a given node, the
1058 * root. Nodes are iterated in document order. An optional subtree can be
1059 * specified, in which case the iterator will track whether the current state of
1060 * the traversal over the tree is within that subtree or is past that subtree.
1062 class TextNodeIterator {
1063 public:
1065 * Constructs a TextNodeIterator with the specified root node and optional
1066 * subtree.
1068 explicit TextNodeIterator(nsIContent* aRoot, nsIContent* aSubtree = nullptr)
1069 : mRoot(aRoot),
1070 mSubtree(aSubtree == aRoot ? nullptr : aSubtree),
1071 mCurrent(aRoot),
1072 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1073 NS_ASSERTION(aRoot, "expected non-null root");
1074 if (!aRoot->IsText()) {
1075 Next();
1080 * Returns the current Text, or null if the iterator has finished.
1082 Text* Current() const { return mCurrent ? mCurrent->AsText() : nullptr; }
1085 * Advances to the next Text and returns it, or null if the end of
1086 * iteration has been reached.
1088 Text* Next();
1091 * Returns whether the iterator is currently within the subtree rooted
1092 * at mSubtree. Returns true if we are not tracking a subtree (we consider
1093 * that we're always within the subtree).
1095 bool IsWithinSubtree() const { return mSubtreePosition == eWithinSubtree; }
1098 * Returns whether the iterator is past the subtree rooted at mSubtree.
1099 * Returns false if we are not tracking a subtree.
1101 bool IsAfterSubtree() const { return mSubtreePosition == eAfterSubtree; }
1103 private:
1105 * The root under which all Text will be iterated over.
1107 nsIContent* const mRoot;
1110 * The node rooting the subtree to track.
1112 nsIContent* const mSubtree;
1115 * The current node during iteration.
1117 nsIContent* mCurrent;
1120 * The current iterator position relative to mSubtree.
1122 SubtreePosition mSubtreePosition;
1125 Text* TextNodeIterator::Next() {
1126 // Starting from mCurrent, we do a non-recursive traversal to the next
1127 // Text beneath mRoot, updating mSubtreePosition appropriately if we
1128 // encounter mSubtree.
1129 if (mCurrent) {
1130 do {
1131 nsIContent* next =
1132 IsTextContentElement(mCurrent) ? mCurrent->GetFirstChild() : nullptr;
1133 if (next) {
1134 mCurrent = next;
1135 if (mCurrent == mSubtree) {
1136 mSubtreePosition = eWithinSubtree;
1138 } else {
1139 for (;;) {
1140 if (mCurrent == mRoot) {
1141 mCurrent = nullptr;
1142 break;
1144 if (mCurrent == mSubtree) {
1145 mSubtreePosition = eAfterSubtree;
1147 next = mCurrent->GetNextSibling();
1148 if (next) {
1149 mCurrent = next;
1150 if (mCurrent == mSubtree) {
1151 mSubtreePosition = eWithinSubtree;
1153 break;
1155 if (mCurrent == mSubtree) {
1156 mSubtreePosition = eAfterSubtree;
1158 mCurrent = mCurrent->GetParent();
1161 } while (mCurrent && !mCurrent->IsText());
1164 return mCurrent ? mCurrent->AsText() : nullptr;
1167 // ----------------------------------------------------------------------------
1168 // TextNodeCorrespondenceRecorder
1171 * TextNodeCorrespondence is used as the value of a frame property that
1172 * is stored on all its descendant nsTextFrames. It stores the number of DOM
1173 * characters between it and the previous nsTextFrame that did not have an
1174 * nsTextFrame created for them, due to either not being in a correctly
1175 * parented text content element, or because they were display:none.
1176 * These are called "undisplayed characters".
1178 * See also TextNodeCorrespondenceRecorder below, which is what sets the
1179 * frame property.
1181 struct TextNodeCorrespondence {
1182 explicit TextNodeCorrespondence(uint32_t aUndisplayedCharacters)
1183 : mUndisplayedCharacters(aUndisplayedCharacters) {}
1185 uint32_t mUndisplayedCharacters;
1188 NS_DECLARE_FRAME_PROPERTY_DELETABLE(TextNodeCorrespondenceProperty,
1189 TextNodeCorrespondence)
1192 * Returns the number of undisplayed characters before the specified
1193 * nsTextFrame.
1195 static uint32_t GetUndisplayedCharactersBeforeFrame(nsTextFrame* aFrame) {
1196 void* value = aFrame->GetProperty(TextNodeCorrespondenceProperty());
1197 TextNodeCorrespondence* correspondence =
1198 static_cast<TextNodeCorrespondence*>(value);
1199 if (!correspondence) {
1200 // FIXME bug 903785
1201 NS_ERROR(
1202 "expected a TextNodeCorrespondenceProperty on nsTextFrame "
1203 "used for SVG text");
1204 return 0;
1206 return correspondence->mUndisplayedCharacters;
1210 * Traverses the nsTextFrames for an SVGTextFrame and records a
1211 * TextNodeCorrespondenceProperty on each for the number of undisplayed DOM
1212 * characters between each frame. This is done by iterating simultaneously
1213 * over the Text and nsTextFrames and noting when Text (or
1214 * parts of them) are skipped when finding the next nsTextFrame.
1216 class TextNodeCorrespondenceRecorder {
1217 public:
1219 * Entry point for the TextNodeCorrespondenceProperty recording.
1221 static void RecordCorrespondence(SVGTextFrame* aRoot);
1223 private:
1224 explicit TextNodeCorrespondenceRecorder(SVGTextFrame* aRoot)
1225 : mNodeIterator(aRoot->GetContent()),
1226 mPreviousNode(nullptr),
1227 mNodeCharIndex(0) {}
1229 void Record(SVGTextFrame* aRoot);
1230 void TraverseAndRecord(nsIFrame* aFrame);
1233 * Returns the next non-empty Text.
1235 Text* NextNode();
1238 * The iterator over the Text that we use as we simultaneously
1239 * iterate over the nsTextFrames.
1241 TextNodeIterator mNodeIterator;
1244 * The previous Text we iterated over.
1246 Text* mPreviousNode;
1249 * The index into the current Text's character content.
1251 uint32_t mNodeCharIndex;
1254 /* static */
1255 void TextNodeCorrespondenceRecorder::RecordCorrespondence(SVGTextFrame* aRoot) {
1256 if (aRoot->HasAnyStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY)) {
1257 // Resolve bidi so that continuation frames are created if necessary:
1258 aRoot->MaybeResolveBidiForAnonymousBlockChild();
1259 TextNodeCorrespondenceRecorder recorder(aRoot);
1260 recorder.Record(aRoot);
1261 aRoot->RemoveStateBits(NS_STATE_SVG_TEXT_CORRESPONDENCE_DIRTY);
1265 void TextNodeCorrespondenceRecorder::Record(SVGTextFrame* aRoot) {
1266 if (!mNodeIterator.Current()) {
1267 // If there are no Text nodes then there is nothing to do.
1268 return;
1271 // Traverse over all the nsTextFrames and record the number of undisplayed
1272 // characters.
1273 TraverseAndRecord(aRoot);
1275 // Find how many undisplayed characters there are after the final nsTextFrame.
1276 uint32_t undisplayed = 0;
1277 if (mNodeIterator.Current()) {
1278 if (mPreviousNode && mPreviousNode->TextLength() != mNodeCharIndex) {
1279 // The last nsTextFrame ended part way through a Text node. The
1280 // remaining characters count as undisplayed.
1281 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1282 "incorrect tracking of undisplayed characters in "
1283 "text nodes");
1284 undisplayed += mPreviousNode->TextLength() - mNodeCharIndex;
1286 // All the remaining Text that we iterate must also be undisplayed.
1287 for (Text* textNode = mNodeIterator.Current(); textNode;
1288 textNode = NextNode()) {
1289 undisplayed += textNode->TextLength();
1293 // Record the trailing number of undisplayed characters on the
1294 // SVGTextFrame.
1295 aRoot->mTrailingUndisplayedCharacters = undisplayed;
1298 Text* TextNodeCorrespondenceRecorder::NextNode() {
1299 mPreviousNode = mNodeIterator.Current();
1300 Text* next;
1301 do {
1302 next = mNodeIterator.Next();
1303 } while (next && next->TextLength() == 0);
1304 return next;
1307 void TextNodeCorrespondenceRecorder::TraverseAndRecord(nsIFrame* aFrame) {
1308 // Recursively iterate over the frame tree, for frames that correspond
1309 // to text content elements.
1310 if (IsTextContentElement(aFrame->GetContent())) {
1311 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1312 TraverseAndRecord(f);
1314 return;
1317 nsTextFrame* frame; // The current text frame.
1318 Text* node; // The text node for the current text frame.
1319 if (!GetNonEmptyTextFrameAndNode(aFrame, frame, node)) {
1320 // If this isn't an nsTextFrame, or is empty, nothing to do.
1321 return;
1324 NS_ASSERTION(frame->GetContentOffset() >= 0,
1325 "don't know how to handle negative content indexes");
1327 uint32_t undisplayed = 0;
1328 if (!mPreviousNode) {
1329 // Must be the very first text frame.
1330 NS_ASSERTION(mNodeCharIndex == 0,
1331 "incorrect tracking of undisplayed "
1332 "characters in text nodes");
1333 if (!mNodeIterator.Current()) {
1334 MOZ_ASSERT_UNREACHABLE(
1335 "incorrect tracking of correspondence between "
1336 "text frames and text nodes");
1337 } else {
1338 // Each whole Text we find before we get to the text node for the
1339 // first text frame must be undisplayed.
1340 while (mNodeIterator.Current() != node) {
1341 undisplayed += mNodeIterator.Current()->TextLength();
1342 NextNode();
1344 // If the first text frame starts at a non-zero content offset, then those
1345 // earlier characters are also undisplayed.
1346 undisplayed += frame->GetContentOffset();
1347 NextNode();
1349 } else if (mPreviousNode == node) {
1350 // Same text node as last time.
1351 if (static_cast<uint32_t>(frame->GetContentOffset()) != mNodeCharIndex) {
1352 // We have some characters in the middle of the text node
1353 // that are undisplayed.
1354 NS_ASSERTION(
1355 mNodeCharIndex < static_cast<uint32_t>(frame->GetContentOffset()),
1356 "incorrect tracking of undisplayed characters in "
1357 "text nodes");
1358 undisplayed = frame->GetContentOffset() - mNodeCharIndex;
1360 } else {
1361 // Different text node from last time.
1362 if (mPreviousNode->TextLength() != mNodeCharIndex) {
1363 NS_ASSERTION(mNodeCharIndex < mPreviousNode->TextLength(),
1364 "incorrect tracking of undisplayed characters in "
1365 "text nodes");
1366 // Any trailing characters at the end of the previous Text are
1367 // undisplayed.
1368 undisplayed = mPreviousNode->TextLength() - mNodeCharIndex;
1370 // Each whole Text we find before we get to the text node for
1371 // the current text frame must be undisplayed.
1372 while (mNodeIterator.Current() && mNodeIterator.Current() != node) {
1373 undisplayed += mNodeIterator.Current()->TextLength();
1374 NextNode();
1376 // If the current text frame starts at a non-zero content offset, then those
1377 // earlier characters are also undisplayed.
1378 undisplayed += frame->GetContentOffset();
1379 NextNode();
1382 // Set the frame property.
1383 frame->SetProperty(TextNodeCorrespondenceProperty(),
1384 new TextNodeCorrespondence(undisplayed));
1386 // Remember how far into the current Text we are.
1387 mNodeCharIndex = frame->GetContentEnd();
1390 // ----------------------------------------------------------------------------
1391 // TextFrameIterator
1394 * An iterator class for nsTextFrames that are descendants of an
1395 * SVGTextFrame. The iterator can optionally track whether the
1396 * current nsTextFrame is for a descendant of, or past, a given subtree
1397 * content node or frame. (This functionality is used for example by the SVG
1398 * DOM text methods to get only the nsTextFrames for a particular <tspan>.)
1400 * TextFrameIterator also tracks and exposes other information about the
1401 * current nsTextFrame:
1403 * * how many undisplayed characters came just before it
1404 * * its position (in app units) relative to the SVGTextFrame's anonymous
1405 * block frame
1406 * * what nsInlineFrame corresponding to a <textPath> element it is a
1407 * descendant of
1408 * * what computed dominant-baseline value applies to it
1410 * Note that any text frames that are empty -- whose ContentLength() is 0 --
1411 * will be skipped over.
1413 class MOZ_STACK_CLASS TextFrameIterator {
1414 public:
1416 * Constructs a TextFrameIterator for the specified SVGTextFrame
1417 * with an optional frame subtree to restrict iterated text frames to.
1419 explicit TextFrameIterator(SVGTextFrame* aRoot,
1420 const nsIFrame* aSubtree = nullptr)
1421 : mRootFrame(aRoot),
1422 mSubtree(aSubtree),
1423 mCurrentFrame(aRoot),
1424 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1425 Init();
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()
1436 : nullptr),
1437 mCurrentFrame(aRoot),
1438 mSubtreePosition(mSubtree ? eBeforeSubtree : eWithinSubtree) {
1439 Init();
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
1454 * current frame.
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
1481 * are inside one.
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; }
1499 private:
1501 * Initializes the iterator and advances to the first item.
1503 void Init() {
1504 if (!mRootFrame) {
1505 return;
1508 mBaselines.AppendElement(mRootFrame->StyleSVG()->mDominantBaseline);
1509 Next();
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.
1522 void PopBaseline();
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
1552 * frame tree.
1554 AutoTArray<StyleDominantBaseline, 8> mBaselines;
1557 * The iterator's current position relative to mSubtree.
1559 SubtreePosition mSubtreePosition;
1562 uint32_t TextFrameIterator::UndisplayedCharacters() const {
1563 MOZ_ASSERT(
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) {
1580 do {
1581 nsIFrame* next = IsTextContentElement(mCurrentFrame->GetContent())
1582 ? mCurrentFrame->PrincipalChildList().FirstChild()
1583 : nullptr;
1584 if (next) {
1585 // Descend into this frame, and accumulate its position.
1586 mCurrentPosition += next->GetPosition();
1587 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1588 // Record this <textPath> frame.
1589 mTextPathFrames.AppendElement(next);
1591 // Record the frame's baseline.
1592 PushBaseline(next);
1593 mCurrentFrame = next;
1594 if (mCurrentFrame == mSubtree) {
1595 // If the current frame is mSubtree, we have now moved into it.
1596 mSubtreePosition = eWithinSubtree;
1598 } else {
1599 for (;;) {
1600 // We want to move past the current frame.
1601 if (mCurrentFrame == mRootFrame) {
1602 // If we've reached the root frame, we're finished.
1603 mCurrentFrame = nullptr;
1604 break;
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.
1613 PopBaseline();
1614 if (mCurrentFrame == mSubtree) {
1615 // If this was mSubtree, we have now moved past it.
1616 mSubtreePosition = eAfterSubtree;
1618 next = mCurrentFrame->GetNextSibling();
1619 if (next) {
1620 // Moving to the next sibling.
1621 mCurrentPosition += next->GetPosition();
1622 if (next->GetContent()->IsSVGElement(nsGkAtoms::textPath)) {
1623 // Record this <textPath> frame.
1624 mTextPathFrames.AppendElement(next);
1626 // Record the frame's baseline.
1627 PushBaseline(next);
1628 mCurrentFrame = next;
1629 if (mCurrentFrame == mSubtree) {
1630 // If the current frame is mSubtree, we have now moved into it.
1631 mSubtreePosition = eWithinSubtree;
1633 break;
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));
1647 return Current();
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 {
1667 public:
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.
1674 eAllFrames,
1675 // Iterate only TextRenderedRuns for nsTextFrames that are
1676 // visibility:visible.
1677 eVisibleFrames
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
1685 * through.
1686 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1687 * nsTextFrames.
1688 * @param aSubtree An optional frame subtree to restrict iterated rendered
1689 * runs to.
1691 explicit TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1692 RenderedRunFilter aFilter = eAllFrames,
1693 const nsIFrame* aSubtree = nullptr)
1694 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1695 mFilter(aFilter),
1696 mTextElementCharIndex(0),
1697 mFrameStartTextElementCharIndex(0),
1698 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1699 mCurrent(First()) {}
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
1706 * through.
1707 * @param aFilter Indicates whether to iterate rendered runs for non-visible
1708 * nsTextFrames.
1709 * @param aSubtree A content subtree to restrict iterated rendered runs to.
1711 TextRenderedRunIterator(SVGTextFrame* aSVGTextFrame,
1712 RenderedRunFilter aFilter, nsIContent* aSubtree)
1713 : mFrameIterator(FrameIfAnonymousChildReflowed(aSVGTextFrame), aSubtree),
1714 mFilter(aFilter),
1715 mTextElementCharIndex(0),
1716 mFrameStartTextElementCharIndex(0),
1717 mFontSizeScaleFactor(aSVGTextFrame->mFontSizeScaleFactor),
1718 mCurrent(First()) {}
1721 * Returns the current TextRenderedRun.
1723 TextRenderedRun Current() const { return mCurrent; }
1726 * Advances to the next TextRenderedRun and returns it.
1728 TextRenderedRun Next();
1730 private:
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
1753 * up to.
1755 uint32_t mTextElementCharIndex;
1758 * The character index across the entire <text> for the start of the current
1759 * frame.
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
1777 // return.
1778 mCurrent = TextRenderedRun();
1779 return mCurrent;
1782 // The values we will use to initialize the TextRenderedRun with.
1783 nsTextFrame* frame;
1784 gfxPoint pt;
1785 double rotate;
1786 nscoord baseline;
1787 uint32_t offset, length;
1788 uint32_t charIndex;
1790 // We loop, because we want to skip over rendered runs that either aren't
1791 // within our subtree of interest, because they don't match the filter,
1792 // or because they are hidden due to having fallen off the end of a
1793 // <textPath>.
1794 for (;;) {
1795 if (mFrameIterator.IsAfterSubtree()) {
1796 mCurrent = TextRenderedRun();
1797 return mCurrent;
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.
1807 uint32_t runStart,
1808 runEnd; // XXX Replace runStart with mTextElementCharIndex.
1809 runStart = mTextElementCharIndex;
1810 runEnd = runStart + 1;
1811 while (runEnd < Root()->mPositions.Length() &&
1812 !Root()->mPositions[runEnd].mRunBoundary) {
1813 runEnd++;
1816 // Convert the global run start/end indexes into an offset/length into the
1817 // current frame's Text.
1818 offset =
1819 frame->GetContentOffset() + runStart - mFrameStartTextElementCharIndex;
1820 length = runEnd - runStart;
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()),
1830 "invalid offset");
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
1848 // rendered run.
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()) {
1872 if (skip) {
1873 // That was the last frame, and we skipped this rendered run. So we
1874 // have no rendered run to return.
1875 mCurrent = TextRenderedRun();
1876 return mCurrent;
1878 break;
1881 if (length && !skip) {
1882 // Only return a rendered run if it didn't get collapsed away entirely
1883 // (due to it being all white space) and if we don't want to skip it.
1884 break;
1888 mCurrent = TextRenderedRun(frame, pt, Root()->mLengthAdjustScaleFactor,
1889 rotate, mFontSizeScaleFactor, baseline, offset,
1890 length, charIndex);
1891 return mCurrent;
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;
1909 return Next();
1912 // -----------------------------------------------------------------------------
1913 // CharIterator
1916 * Iterator for characters within an SVGTextFrame.
1918 class MOZ_STACK_CLASS CharIterator {
1919 using Range = gfxTextRun::Range;
1921 public:
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.
1929 eOriginal,
1930 // Iterate only over characters that are not skipped characters.
1931 eUnskipped,
1932 // Iterate only over characters that are addressable by the positioning
1933 // attributes x="", y="", etc. This includes all characters after
1934 // collapsing white space as required by the value of 'white-space'.
1935 eAddressable,
1939 * Constructs a CharIterator.
1941 * @param aSVGTextFrame The SVGTextFrame whose characters to iterate
1942 * through.
1943 * @param aFilter Indicates which characters to iterate over.
1944 * @param aSubtree A content subtree to track whether the current character
1945 * is within.
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.
1959 bool Next();
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
2021 * ligature group.
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
2063 * is part of.
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(); }
2084 #ifdef DEBUG
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; }
2094 #endif
2096 private:
2098 * Advances to the next character without checking it against the filter.
2099 * Returns true if there was a next character to advance to, or false
2100 * otherwise.
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;
2128 #ifdef DEBUG
2130 * The subtree we were constructed with.
2132 nsIContent* const mSubtree;
2133 #endif
2136 * A gfxSkipCharsIterator for the text frame the current character is
2137 * a part of.
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
2170 * or not.
2172 bool mPostReflow;
2175 CharIterator::CharIterator(SVGTextFrame* aSVGTextFrame,
2176 CharIterator::CharacterFilter aFilter,
2177 nsIContent* aSubtree, bool aPostReflow)
2178 : mFilter(aFilter),
2179 mFrameIterator(aSVGTextFrame, aSubtree),
2180 #ifdef DEBUG
2181 mSubtree(aSubtree),
2182 #endif
2183 mFrameForTrimCheck(nullptr),
2184 mTrimmedOffset(0),
2185 mTrimmedLength(0),
2186 mTextRun(nullptr),
2187 mTextElementCharIndex(0),
2188 mGlyphStartTextElementCharIndex(0),
2189 mLengthAdjustScaleFactor(aSVGTextFrame->mLengthAdjustScaleFactor),
2190 mPostReflow(aPostReflow) {
2191 if (!AtEnd()) {
2192 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2193 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2194 mTextElementCharIndex = mFrameIterator.UndisplayedCharacters();
2195 UpdateGlyphStartTextElementCharIndex();
2196 if (!MatchesFilter()) {
2197 Next();
2202 bool CharIterator::Next() {
2203 while (NextCharacter()) {
2204 if (MatchesFilter()) {
2205 return true;
2208 return false;
2211 bool CharIterator::Next(uint32_t aCount) {
2212 if (aCount == 0 && AtEnd()) {
2213 return false;
2215 while (aCount) {
2216 if (!Next()) {
2217 return false;
2219 aCount--;
2221 return true;
2224 void CharIterator::NextWithinSubtree(uint32_t aCount) {
2225 while (IsWithinSubtree() && aCount) {
2226 --aCount;
2227 if (!Next()) {
2228 return;
2233 bool CharIterator::AdvanceToCharacter(uint32_t aTextElementCharIndex) {
2234 while (mTextElementCharIndex < aTextElementCharIndex) {
2235 if (!Next()) {
2236 return false;
2239 return true;
2242 bool CharIterator::AdvancePastCurrentFrame() {
2243 // XXX Can do this better than one character at a time if it matters.
2244 nsTextFrame* currentFrame = TextFrame();
2245 do {
2246 if (!Next()) {
2247 return false;
2249 } while (TextFrame() == currentFrame);
2250 return true;
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");
2258 do {
2259 if (!AdvancePastCurrentFrame()) {
2260 return false;
2262 } while (TextPathFrame() == currentTextPathFrame);
2263 return true;
2266 bool CharIterator::AdvanceToSubtree() {
2267 while (!IsWithinSubtree()) {
2268 if (IsAfterSubtree()) {
2269 return false;
2271 if (!AdvancePastCurrentFrame()) {
2272 return false;
2275 return true;
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();
2297 return !(
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();
2314 gfxFloat advance =
2315 mTextRun->GetAdvanceWidth(Range(offset, offset + 1), &provider);
2316 return aContext->AppUnitsToGfxUnits(advance) * mLengthAdjustScaleFactor *
2317 cssPxPerDevPx;
2320 bool CharIterator::NextCharacter() {
2321 if (AtEnd()) {
2322 return false;
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();
2332 return true;
2335 // Advance to the next frame.
2336 mFrameIterator.Next();
2338 // Skip any undisplayed characters.
2339 uint32_t undisplayed = mFrameIterator.UndisplayedCharacters();
2340 mTextElementCharIndex += undisplayed;
2341 if (!TextFrame()) {
2342 // We're at the end.
2343 mSkipCharsIterator = gfxSkipCharsIterator();
2344 return false;
2347 mSkipCharsIterator = TextFrame()->EnsureTextRun(nsTextFrame::eInflated);
2348 mTextRun = TextFrame()->GetTextRun(nsTextFrame::eInflated);
2349 UpdateGlyphStartTextElementCharIndex();
2350 return true;
2353 bool CharIterator::MatchesFilter() const {
2354 switch (mFilter) {
2355 case eOriginal:
2356 return true;
2357 case eUnskipped:
2358 return !IsOriginalCharSkipped();
2359 case eAddressable:
2360 return !IsOriginalCharSkipped() && !IsOriginalCharUnaddressable();
2362 MOZ_ASSERT_UNREACHABLE("Invalid mFilter value");
2363 return true;
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
2376 * the text, etc.).
2378 class SVGTextDrawPathCallbacks final : public nsTextFrame::DrawPathCallbacks {
2379 using imgDrawingParams = image::imgDrawingParams;
2381 public:
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),
2400 mContext(aContext),
2401 mFrame(aFrame),
2402 mCanvasTM(aCanvasTM),
2403 mImgParams(aImgParams),
2404 mColor(0) {}
2406 void NotifySelectionBackgroundNeedsFill(const Rect& aBackgroundRect,
2407 nscolor aColor,
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;
2415 private:
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.
2462 nscolor mColor;
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.
2469 return;
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
2478 : 1.0);
2479 aDrawTarget.FillRect(aBackgroundRect, fillPattern, drawOptions);
2483 void SVGTextDrawPathCallbacks::NotifyBeforeText(nscolor aColor) {
2484 mColor = aColor;
2485 SetupContext();
2486 mContext.NewPath();
2489 void SVGTextDrawPathCallbacks::NotifyGlyphPathEmitted() {
2490 HandleTextGeometry();
2491 mContext.NewPath();
2494 void SVGTextDrawPathCallbacks::NotifyAfterText() { mContext.Restore(); }
2496 void SVGTextDrawPathCallbacks::PaintDecorationLine(Rect aPath, nscolor aColor) {
2497 mColor = aColor;
2498 AntialiasMode aaMode =
2499 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2501 mContext.Save();
2502 mContext.NewPath();
2503 mContext.SetAntialiasMode(aaMode);
2504 mContext.Rectangle(ThebesRect(aPath));
2505 HandleTextGeometry();
2506 mContext.NewPath();
2507 mContext.Restore();
2510 void SVGTextDrawPathCallbacks::PaintSelectionDecorationLine(Rect aPath,
2511 nscolor aColor) {
2512 if (IsClipPathChild()) {
2513 // Don't paint selection decorations when in a clip path.
2514 return;
2517 mColor = aColor;
2519 mContext.Save();
2520 mContext.NewPath();
2521 mContext.Rectangle(ThebesRect(aPath));
2522 FillAndStrokeGeometry();
2523 mContext.Restore();
2526 void SVGTextDrawPathCallbacks::SetupContext() {
2527 mContext.Save();
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);
2535 break;
2536 default:
2537 mContext.SetAntialiasMode(AntialiasMode::SUBPIXEL);
2538 break;
2542 void SVGTextDrawPathCallbacks::HandleTextGeometry() {
2543 if (IsClipPathChild()) {
2544 RefPtr<Path> path = mContext.GetPath();
2545 ColorPattern white(
2546 DeviceColor(1.f, 1.f, 1.f, 1.f)); // for masking, so no ToDeviceColor
2547 mContext.GetDrawTarget()->Fill(path, white);
2548 } else {
2549 // Normal painting.
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);
2561 return;
2564 if (mColor == NS_TRANSPARENT) {
2565 return;
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;
2578 if (!paintOrder) {
2579 FillGeometry();
2580 StrokeGeometry();
2581 } else {
2582 while (paintOrder) {
2583 auto component = StylePaintOrder(paintOrder & kPaintOrderMask);
2584 switch (component) {
2585 case StylePaintOrder::Fill:
2586 FillGeometry();
2587 break;
2588 case StylePaintOrder::Stroke:
2589 StrokeGeometry();
2590 break;
2591 default:
2592 MOZ_FALLTHROUGH_ASSERT("Unknown paint-order value");
2593 case StylePaintOrder::Markers:
2594 case StylePaintOrder::Normal:
2595 break;
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");
2628 return;
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,
2643 mFrame->Style(),
2644 /*aContextPaint*/ nullptr);
2645 DrawOptions drawOptions;
2646 drawOptions.mAntialiasMode =
2647 SVGUtils::ToAntialiasMode(mFrame->StyleText()->mTextRendering);
2648 mContext.GetDrawTarget()->Stroke(path, strokePattern, strokeOptions);
2654 // ============================================================================
2655 // SVGTextFrame
2657 // ----------------------------------------------------------------------------
2658 // Display list item
2660 class DisplaySVGText final : public DisplaySVGItem {
2661 public:
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 {
2678 bool snap;
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 // ---------------------------------------------------------------------
2693 // Implementation
2695 nsIFrame* NS_NewSVGTextFrame(mozilla::PresShell* aPresShell,
2696 mozilla::ComputedStyle* aStyle) {
2697 return new (aPresShell)
2698 mozilla::SVGTextFrame(aStyle, aPresShell->GetPresContext());
2701 namespace mozilla {
2703 NS_IMPL_FRAMEARENA_HELPERS(SVGTextFrame)
2705 // ---------------------------------------------------------------------
2706 // nsIFrame methods
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
2731 // painting.
2732 return;
2734 if (!IsVisibleForPainting() && aBuilder->IsForPainting()) {
2735 return;
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) {
2744 return NS_OK;
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);
2765 return NS_OK;
2768 void SVGTextFrame::ReflowSVGNonDisplayText() {
2769 MOZ_ASSERT(SVGUtils::AnyOuterSVGIsCallingReflowSVG(this),
2770 "only call ReflowSVGNonDisplayText when an outer SVG frame is "
2771 "under ReflowSVG");
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.)
2805 nsIFrame* f = this;
2806 while (f) {
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.
2811 return;
2813 if (!f->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
2814 break;
2816 f->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
2818 f = f->GetParent();
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()) {
2851 return;
2854 // Attribute changes on this element will be handled by
2855 // SVGTextFrame::AttributeChanged.
2856 if (aElement == mFrame->GetContent()) {
2857 return;
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);
2881 } else {
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)) {
2892 return;
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()) {
2910 gfxMatrix m;
2911 nsRect rect =
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.
2961 gfxMatrix newTM =
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
2977 // our area.
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();
2997 if (!selection) {
2998 return -1;
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) {
3015 return false;
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();
3027 if (!kid) {
3028 return;
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
3039 // dirty.
3040 if (presContext->PresShell()->InDrawWindowNotFlushing() &&
3041 IsSubtreeDirty()) {
3042 return;
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.
3051 return;
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.
3058 return;
3061 if (aTransform.IsSingular()) {
3062 NS_WARNING("Can't render text element!");
3063 return;
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);
3078 aContext.NewPath();
3079 aContext.Multiply(canvasTMForChildren);
3080 gfxMatrix currentMatrix = aContext.CurrentMatrixDouble();
3082 RefPtr<nsCaret> caret = presContext->PresShell()->GetCaret();
3083 nsRect caretRect;
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,
3104 outerContextPaint);
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) *
3114 currentMatrix;
3115 aContext.SetMatrixDouble(runTransform);
3117 if (drawMode != DrawMode(0)) {
3118 bool paintSVGGlyphs;
3119 nsTextFrame::PaintTextParams params(&aContext);
3120 params.framePt = Point();
3121 params.dirtyRect =
3122 LayoutDevicePixel::FromAppUnits(frame->InkOverflowRect(), auPerDevPx);
3123 params.contextPaint = contextPaint;
3124 bool isSelected;
3125 if (HasAnyStateBits(NS_STATE_SVG_CLIPPATH_CHILD)) {
3126 params.state = nsTextFrame::PaintTextParams::GenerateTextMask;
3127 isSelected = false;
3128 } else {
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,
3140 opacity);
3143 if (ShouldRenderAsPath(frame, paintSVGGlyphs)) {
3144 SVGTextDrawPathCallbacks callbacks(this, aContext, frame,
3145 matrixForPaintServers, aImgParams,
3146 paintSVGGlyphs);
3147 params.callbacks = &callbacks;
3148 frame->PaintText(params, startEdge, endEdge, nsPoint(), isSelected);
3149 } else {
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());
3158 aContext.NewPath();
3161 run = it.Next();
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
3172 // be hit tested.)
3173 UpdateGlyphPositioning();
3174 } else {
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)) {
3182 return nullptr;
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) {
3197 continue;
3200 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
3201 if (!m.Invert()) {
3202 return nullptr;
3205 gfxPoint pointInRunUserSpace = m.TransformPoint(aPoint);
3206 gfxRect frameRect = run.GetRunUserSpaceRect(
3207 presContext, TextRenderedRun::eIncludeFill |
3208 TextRenderedRun::eIncludeStroke)
3209 .ToThebesRect();
3211 if (Inside(frameRect, pointInRunUserSpace)) {
3212 hit = run.mFrame;
3215 return hit;
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?");
3229 return;
3232 MaybeReflowAnonymousBlockChild();
3233 UpdateGlyphPositioning();
3235 nsPresContext* presContext = PresContext();
3237 SVGBBox r;
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;
3261 if (runFlags) {
3262 r.UnionEdges(run.GetUserSpaceRect(presContext, runFlags));
3266 if (r.IsEmpty()) {
3267 mRect.SetEmpty();
3268 } else {
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
3274 // covered region.
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) {
3302 uint32_t flags = 0;
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;
3313 return flags;
3316 SVGBBox SVGTextFrame::GetBBoxContribution(const Matrix& aToBBoxUserspace,
3317 uint32_t aFlags) {
3318 NS_ASSERTION(PrincipalChildList().FirstChild(), "must have a child frame");
3319 SVGBBox bbox;
3321 if (aFlags & SVGUtils::eForGetClientRects) {
3322 Rect rect = NSRectToRect(mRect, AppUnitsPerCSSPixel());
3323 if (!rect.IsEmpty()) {
3324 bbox = aToBBoxUserspace.TransformBounds(rect);
3326 return bbox;
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.
3339 return bbox;
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);
3354 return bbox;
3357 //----------------------------------------------------------------------
3358 // SVGTextFrame SVG DOM methods
3361 * Returns whether the specified node has any non-empty Text
3362 * beneath it.
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) {
3370 return true;
3373 return false;
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();
3387 return length;
3390 int32_t SVGTextFrame::ConvertTextElementCharIndexToAddressableIndex(
3391 int32_t aIndex, nsIContent* aContent) {
3392 CharIterator it(this, CharIterator::eOriginal, aContent);
3393 if (!it.AdvanceToSubtree()) {
3394 return -1;
3396 int32_t result = 0;
3397 int32_t textElementCharIndex;
3398 while (!it.AtEnd() && it.IsWithinSubtree()) {
3399 bool addressable = !it.IsOriginalCharUnaddressable();
3400 textElementCharIndex = it.TextElementCharIndex();
3401 it.Next();
3402 uint32_t delta = it.TextElementCharIndex() - textElementCharIndex;
3403 aIndex -= delta;
3404 if (addressable) {
3405 if (aIndex < 0) {
3406 return result;
3408 result += delta;
3411 return -1;
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).
3423 return 0;
3426 UpdateGlyphPositioning();
3428 uint32_t n = 0;
3429 CharIterator it(this, CharIterator::eAddressable, aContent);
3430 if (it.AdvanceToSubtree()) {
3431 while (!it.AtEnd() && it.IsWithinSubtree()) {
3432 n++;
3433 it.Next();
3436 return n;
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.
3451 return 0;
3454 UpdateGlyphPositioning();
3456 float cssPxPerDevPx = nsPresContext::AppUnitsToFloatCSSPixels(
3457 PresContext()->AppUnitsPerDevPixel());
3459 nscoord length = 0;
3460 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3461 aContent);
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");
3482 return;
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");
3493 return;
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()) {
3530 return true;
3533 return false;
3537 * Implements the SVG DOM GetSubStringLength method for the specified
3538 * text content element.
3540 float SVGTextFrame::GetSubStringLengthFastPath(nsIContent* aContent,
3541 uint32_t charnum,
3542 uint32_t nchars,
3543 ErrorResult& aRv) {
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");
3557 return 0;
3560 // We do this after the ThrowIndexSizeError() bit so JS calls correctly throw
3561 // when necessary.
3562 if (nchars == 0) {
3563 return 0.0f;
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
3605 // the nsTextFrame.
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,
3635 uint32_t charnum,
3636 uint32_t nchars,
3637 ErrorResult& aRv) {
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");
3646 return 0;
3649 if (nchars == 0) {
3650 return 0.0f;
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
3664 // are done.
3665 uint32_t offset = run.mTextElementCharIndex;
3666 if (offset >= charnum + nchars) {
3667 break;
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);
3675 if (length != 0) {
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).
3711 return -1;
3714 UpdateGlyphPositioning();
3716 nsPresContext* context = PresContext();
3718 gfxPoint p(aPoint.mX, aPoint.mY);
3720 int32_t result = -1;
3722 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
3723 aContent);
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);
3727 if (index != -1) {
3728 result = index + run.mTextElementCharIndex;
3732 if (result == -1) {
3733 return result;
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");
3750 return nullptr;
3753 UpdateGlyphPositioning();
3755 CharIterator it(this, CharIterator::eAddressable, aContent);
3756 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3757 aRv.ThrowIndexSizeError("Character index out of range");
3758 return nullptr;
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;
3788 if (!it) {
3789 newIterator.emplace(aFrame, CharIterator::eAddressable, aContent);
3790 if (!newIterator->AdvanceToSubtree()) {
3791 MOZ_ASSERT_UNREACHABLE("Invalid aContent");
3792 return 0.0;
3794 it = newIterator.ptr();
3797 while (it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3798 if (!it->Next()) {
3799 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3800 return 0.0;
3804 if (it->AtEnd()) {
3805 MOZ_ASSERT_UNREACHABLE("Invalid aTextElementCharIndex");
3806 return 0.0;
3809 nsPresContext* presContext = aFrame->PresContext();
3810 gfxFloat advance = 0.0;
3812 for (;;) {
3813 advance += it->GetAdvance(presContext);
3814 if (!it->Next() ||
3815 it->GlyphStartTextElementCharIndex() != aTextElementCharIndex) {
3816 break;
3820 return advance;
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");
3834 return nullptr;
3837 UpdateGlyphPositioning();
3839 CharIterator it(this, CharIterator::eAddressable, aContent);
3840 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3841 aRv.ThrowIndexSizeError("Character index out of range");
3842 return nullptr;
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.
3849 gfxFloat advance =
3850 GetGlyphAdvance(this, aContent, startIndex,
3851 it.IsClusterAndLigatureGroupStart() ? &it : nullptr);
3852 if (it.TextRun()->IsRightToLeft()) {
3853 advance = -advance;
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,
3871 uint32_t aCharNum,
3872 ErrorResult& aRv) {
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");
3878 return nullptr;
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");
3887 return nullptr;
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.
3900 gfxFloat 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.
3911 gfxMatrix m;
3912 m.PreTranslate(mPositions[startIndex].mPosition);
3913 m.PreRotate(mPositions[startIndex].mAngle);
3914 m.PreScale(1 / mFontSizeScaleFactor, 1 / mFontSizeScaleFactor);
3916 gfxRect glyphRect;
3917 if (isVertical) {
3918 glyphRect = gfxRect(
3919 -presContext->AppUnitsToGfxUnits(descent) * cssPxPerDevPx, x,
3920 presContext->AppUnitsToGfxUnits(ascent + descent) * cssPxPerDevPx,
3921 advance);
3922 } else {
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,
3940 ErrorResult& aRv) {
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");
3946 return 0;
3949 UpdateGlyphPositioning();
3951 CharIterator it(this, CharIterator::eAddressable, aContent);
3952 if (!it.AdvanceToSubtree() || !it.Next(aCharNum)) {
3953 aRv.ThrowIndexSizeError("Character index out of range");
3954 return 0;
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 +
3963 glyphOrientation;
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,
3981 uint32_t aIndex) {
3982 if (aIndex == 0) {
3983 return true;
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()) {
3990 return true;
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))) {
3999 return true;
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) {
4006 return true;
4010 return false;
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();
4020 if (length) {
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");
4026 return false;
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;
4042 aIndex++;
4045 return true;
4048 // Skip past elements that aren't text content elements.
4049 if (!IsTextContentElement(aContent)) {
4050 return true;
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");
4065 return false;
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);
4086 // Get rotate.
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");
4101 return false;
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) {
4109 newChunkCount = 1;
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;
4114 i++;
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);
4126 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);
4133 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);
4143 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);
4150 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;
4160 i++;
4162 j++;
4164 // Propagate final rotate="" value to the end of this element.
4165 while (j < count) {
4166 mPositions[aIndex + j].mAngle = mPositions[aIndex + j - 1].mAngle;
4167 j++;
4171 if (percentages) {
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);
4182 if (!ok) {
4183 return false;
4187 if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
4188 // Force a new anchored chunk just after a <textPath>.
4189 aForceStartOfChunk = true;
4192 return 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);
4201 if (it.AtEnd()) {
4202 return false;
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.
4212 uint32_t index = 0;
4213 while (it.Next()) {
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;
4226 index = 0;
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");
4235 nsPoint position;
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);
4251 } else {
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
4280 // text frame.)
4281 uint32_t offset = it.GetSkippedOffset();
4282 nscoord advance =
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
4322 * chunk.
4323 * @param aVisIStartEdge The left/top-most edge of any of the glyphs within the
4324 * anchored chunk.
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) {
4341 case eAnchorLeft:
4342 shift -= aVisIStartEdge;
4343 break;
4344 case eAnchorMiddle:
4345 shift -= (aVisIStartEdge + aVisIEndEdge) / 2;
4346 break;
4347 case eAnchorRight:
4348 shift -= aVisIEndEdge;
4349 break;
4350 default:
4351 MOZ_ASSERT_UNREACHABLE("unexpected value for aAnchorSide");
4354 if (shift != 0.0) {
4355 if (aVertical) {
4356 for (uint32_t i = aChunkStart; i < aChunkEnd; i++) {
4357 aCharPositions[i].mPosition.y += shift;
4359 } else {
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;
4377 line++;
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;
4406 isFirst = false;
4407 } else {
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 "
4418 "startIndex");
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);
4466 it.Next();
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);
4481 if (!geomElement) {
4482 return nullptr;
4485 RefPtr<Path> path = geomElement->GetOrBuildPathForMeasuring();
4486 if (!path) {
4487 return nullptr;
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.
4507 return 1.0;
4510 SVGGeometryElement* geomElement =
4511 SVGObserverUtils::GetAndObserveTextPathsPath(aTextPathFrame);
4512 if (!geomElement) {
4513 return 1.0;
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.
4527 return 0.0;
4529 RefPtr<Path> data = GetTextPath(aTextPathFrame);
4530 return data ? length->GetAnimValInSpecifiedUnits() * data->ComputeLength() /
4531 100.0
4532 : 0.0;
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();
4548 continue;
4551 // Get the path itself.
4552 RefPtr<Path> path = GetTextPath(textPathFrame);
4553 if (!path) {
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;
4560 continue;
4563 SVGTextPathElement* textPath =
4564 static_cast<SVGTextPathElement*>(textPathFrame->GetContent());
4565 uint16_t side =
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
4573 // positioning.
4574 while (!it.AtEnd()) {
4575 if (it.IsOriginalCharSkipped()) {
4576 it.Next();
4577 continue;
4579 if (it.IsClusterAndLigatureGroupStart()) {
4580 break;
4582 it.Next();
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.
4597 uint32_t j = i + 1;
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
4605 // ligature group.
4606 AutoTArray<gfxFloat, 4> partialAdvances;
4607 gfxFloat partialAdvance = it.GetAdvance(context);
4608 partialAdvances.AppendElement(partialAdvance);
4609 while (it.Next()) {
4610 // Append entries for any undisplayed characters the CharIterator
4611 // skipped over.
4612 MOZ_ASSERT(j <= it.TextElementCharIndex());
4613 while (j < it.TextElementCharIndex()) {
4614 partialAdvances.AppendElement(partialAdvance);
4615 ++j;
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
4620 // by it.
4621 if (it.IsOriginalCharSkipped()) {
4622 if (!it.TextPathFrame()) {
4623 skippedEndOfTextPath = true;
4624 break;
4626 // Leave partialAdvance unchanged.
4627 } else if (it.IsClusterAndLigatureGroupStart()) {
4628 break;
4629 } else {
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);
4640 ++j;
4644 gfxFloat halfAdvance =
4645 partialAdvances.LastElement() / mFontSizeScaleFactor / 2.0;
4646 gfxFloat midx =
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.
4655 Point pt;
4656 if (side == TEXTPATH_SIDETYPE_RIGHT) {
4657 pt = path->ComputePointAtLength(Float(pathLength - midx), &tangent);
4658 tangent = -tangent;
4659 } else {
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())) {
4693 it.Next();
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();
4708 do {
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);
4717 } else {
4718 left = std::min(left, pos);
4719 right = std::max(right, pos + advance);
4722 it.Next();
4723 index = end = it.TextElementCharIndex();
4724 } while (!it.AtEnd() && !mPositions[end].mStartOfChunk);
4726 if (left != std::numeric_limits<gfxFloat>::infinity()) {
4727 bool isRTL =
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() {
4740 mPositions.Clear();
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");
4746 return;
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.
4759 return;
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]
4770 .GetAnimValue();
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.
4787 mPositions.Clear();
4788 return;
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;
4833 break;
4835 default:
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) {
4841 adjustableSpaces++;
4844 if (adjustableSpaces) {
4845 adjustment =
4846 (expectedTextLength - actualTextLength) / adjustableSpaces;
4848 break;
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;
4881 // Add in dx/dy.
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();
4895 DoAnchoring();
4896 DoTextPathLayout();
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;
4904 return true;
4907 aShouldPaintSVGGlyphs = true;
4909 const nsStyleSVG* style = aFrame->StyleSVG();
4911 // Fill is a non-solid paint, has a non-default fill-rule or has
4912 // non-1 opacity.
4913 if (!(style->mFill.kind.IsNone() ||
4914 (style->mFill.kind.IsColor() && style->mFillOpacity.IsOpacity() &&
4915 style->mFillOpacity.AsOpacity() == 1))) {
4916 return true;
4919 // Text has a stroke.
4920 if (style->HasStroke()) {
4921 if (style->mStrokeWidth.IsContextValue()) {
4922 return true;
4924 if (SVGContentUtils::CoordToFloat(
4925 static_cast<SVGElement*>(GetContent()),
4926 style->mStrokeWidth.AsLengthPercentage()) > 0) {
4927 return true;
4931 return false;
4934 void SVGTextFrame::ScheduleReflowSVG() {
4935 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
4936 ScheduleReflowSVGNonDisplayText(
4937 IntrinsicDirty::FrameAncestorsAndDescendants);
4938 } else {
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();
4955 if (!kid) {
4956 return;
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();
4977 if (!kid) {
4978 return;
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());
5005 DoReflow();
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();
5038 if (!kid) {
5039 return;
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;
5058 NS_ASSERTION(
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
5085 // nsTextFrames.
5086 TextFrameIterator it(this);
5087 nsTextFrame* f = it.Current();
5088 while (f) {
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());
5099 anyText = true;
5101 f = it.Next();
5104 if (!anyText) {
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;
5159 } else {
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;
5166 } else {
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
5195 // to this one.
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,
5205 aChildFrame);
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;
5214 gfxRect runRect =
5215 run.GetRunUserSpaceRect(presContext, flags).ToThebesRect();
5217 gfxMatrix m = run.GetTransformFromRunUserSpaceToUserSpace(presContext);
5218 if (!m.Invert()) {
5219 return aPoint;
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.
5226 dx = 0;
5227 dy = 0;
5228 pointInRun = pointInRunUserSpace;
5229 hit = run;
5230 } else if (nsLayoutUtils::PointIsCloserToRect(pointInRunUserSpace, runRect,
5231 dx, dy)) {
5232 // The point was closer to this rendered run's rect than any others
5233 // we've seen so far.
5234 pointInRun.x =
5235 clamped(pointInRunUserSpace.x.value, runRect.X(), runRect.XMost());
5236 pointInRun.y =
5237 clamped(pointInRunUserSpace.y.value, runRect.Y(), runRect.YMost());
5238 hit = run;
5242 if (!hit.mFrame) {
5243 // We didn't find any rendered runs for the frame.
5244 return aPoint;
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();
5272 gfxRect result;
5273 TextRenderedRunIterator it(this, TextRenderedRunIterator::eAllFrames,
5274 aChildFrame);
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),
5283 presContext);
5285 // Intersect it with the run.
5286 uint32_t flags =
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)
5325 .TopLeft();
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