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