forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSVGTextFrame.cpp
5359 lines (4648 loc) · 183 KB
/
SVGTextFrame.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Main header first:
#include "SVGTextFrame.h"
// Keep others in (case-insensitive) order:
#include "DOMSVGPoint.h"
#include "gfx2DGlue.h"
#include "gfxContext.h"
#include "gfxFont.h"
#include "gfxSkipChars.h"
#include "gfxTypes.h"
#include "gfxUtils.h"
#include "LookAndFeel.h"
#include "nsAlgorithm.h"
#include "nsBidiPresUtils.h"
#include "nsBlockFrame.h"
#include "nsCaret.h"
#include "nsContentUtils.h"
#include "nsGkAtoms.h"
#include "nsQuickSort.h"
#include "SVGObserverUtils.h"
#include "nsSVGOuterSVGFrame.h"
#include "nsSVGPaintServerFrame.h"
#include "nsSVGIntegrationUtils.h"
#include "nsSVGUtils.h"
#include "nsTArray.h"
#include "nsTextFrame.h"
#include "SVGAnimatedNumberList.h"
#include "SVGContentUtils.h"
#include "SVGContextPaint.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"
#include "SVGGeometryElement.h"
#include "SVGTextPathElement.h"
#include "nsLayoutUtils.h"
#include "nsFrameSelection.h"
#include "nsStyleStructInlines.h"
#include "mozilla/Likely.h"
#include "mozilla/PresShell.h"
#include "mozilla/dom/DOMPointBinding.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/SVGRect.h"
#include "mozilla/dom/SVGTextContentElementBinding.h"
#include "mozilla/dom/Text.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PatternHelpers.h"
#include <algorithm>
#include <cmath>
#include <limits>
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::dom::SVGTextContentElement_Binding;
using namespace mozilla::gfx;
using namespace mozilla::image;
// ============================================================================
// Utility functions
/**
* Using the specified gfxSkipCharsIterator, converts an offset and length
* in original char indexes to skipped char indexes.
*
* @param aIterator The gfxSkipCharsIterator to use for the conversion.
* @param aOriginalOffset The original offset.
* @param aOriginalLength The original length.
*/
static gfxTextRun::Range ConvertOriginalToSkipped(
gfxSkipCharsIterator& aIterator, uint32_t aOriginalOffset,
uint32_t aOriginalLength) {
uint32_t start = aIterator.ConvertOriginalToSkipped(aOriginalOffset);
aIterator.AdvanceOriginal(aOriginalLength);
return gfxTextRun::Range(start, aIterator.GetSkippedOffset());
}
/**
* Converts an nsPoint from app units to user space units using the specified
* nsPresContext and returns it as a gfxPoint.
*/
static gfxPoint AppUnitsToGfxUnits(const nsPoint& aPoint,
const nsPresContext* aContext) {
return gfxPoint(aContext->AppUnitsToGfxUnits(aPoint.x),
aContext->AppUnitsToGfxUnits(aPoint.y));
}
/**
* Converts a gfxRect that is in app units to CSS pixels using the specified
* nsPresContext and returns it as a gfxRect.
*/
static gfxRect AppUnitsToFloatCSSPixels(const gfxRect& aRect,
const nsPresContext* aContext) {
return gfxRect(nsPresContext::AppUnitsToFloatCSSPixels(aRect.x),
nsPresContext::AppUnitsToFloatCSSPixels(aRect.y),
nsPresContext::AppUnitsToFloatCSSPixels(aRect.width),
nsPresContext::AppUnitsToFloatCSSPixels(aRect.height));
}
/**
* Returns whether a gfxPoint lies within a gfxRect.
*/
static bool Inside(const gfxRect& aRect, const gfxPoint& aPoint) {
return aPoint.x >= aRect.x && aPoint.x < aRect.XMost() &&
aPoint.y >= aRect.y && aPoint.y < aRect.YMost();
}
/**
* Gets the measured ascent and descent of the text in the given nsTextFrame
* in app units.
*
* @param aFrame The text frame.
* @param aAscent The ascent in app units (output).
* @param aDescent The descent in app units (output).
*/
static void GetAscentAndDescentInAppUnits(nsTextFrame* aFrame,
gfxFloat& aAscent,
gfxFloat& aDescent) {
gfxSkipCharsIterator it = aFrame->EnsureTextRun(nsTextFrame::eInflated);
gfxTextRun* textRun = aFrame->GetTextRun(nsTextFrame::eInflated);
gfxTextRun::Range range = ConvertOriginalToSkipped(
it, aFrame->GetContentOffset(), aFrame->GetContentLength());
// We pass in null for the PropertyProvider since letter-spacing and
// word-spacing should not affect the ascent and descent values we get.
gfxTextRun::Metrics metrics =
textRun->MeasureText(range, gfxFont::LOOSE_INK_EXTENTS, nullptr, nullptr);
aAscent = metrics.mAscent;
aDescent = metrics.mDescent;
}
/**
* Updates an interval by intersecting it with another interval.
* The intervals are specified using a start index and a length.
*/
static void IntersectInterval(uint32_t& aStart, uint32_t& aLength,
uint32_t aStartOther, uint32_t aLengthOther) {
uint32_t aEnd = aStart + aLength;
uint32_t aEndOther = aStartOther + aLengthOther;
if (aStartOther >= aEnd || aStart >= aEndOther) {
aLength = 0;
} else {
if (aStartOther >= aStart) aStart = aStartOther;
aLength = std::min(aEnd, aEndOther) - aStart;
}
}
/**
* Intersects an interval as IntersectInterval does but by taking
* the offset and length of the other interval from a
* nsTextFrame::TrimmedOffsets object.
*/
static void TrimOffsets(uint32_t& aStart, uint32_t& aLength,
const nsTextFrame::TrimmedOffsets& aTrimmedOffsets) {
IntersectInterval(aStart, aLength, aTrimmedOffsets.mStart,
aTrimmedOffsets.mLength);
}
/**
* Returns the closest ancestor-or-self node that is not an SVG <a>
* element.
*/
static nsIContent* GetFirstNonAAncestor(nsIContent* aContent) {
while (aContent && aContent->IsSVGElement(nsGkAtoms::a)) {
aContent = aContent->GetParent();
}
return aContent;
}
/**
* Returns whether the given node is a text content element[1], taking into
* account whether it has a valid parent.
*
* For example, in:
*
* <svg xmlns="http://www.w3.org/2000/svg">
* <text><a/><text/></text>
* <tspan/>
* </svg>
*
* true would be returned for the outer <text> element and the <a> element,
* and false for the inner <text> element (since a <text> is not allowed
* to be a child of another <text>) and the <tspan> element (because it
* must be inside a <text> subtree).
*
* Note that we don't support the <tref> element yet and this function
* returns false for it.
*
* [1] https://svgwg.org/svg2-draft/intro.html#TermTextContentElement
*/
static bool IsTextContentElement(nsIContent* aContent) {
if (aContent->IsSVGElement(nsGkAtoms::text)) {
nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
return !parent || !IsTextContentElement(parent);
}
if (aContent->IsSVGElement(nsGkAtoms::textPath)) {
nsIContent* parent = GetFirstNonAAncestor(aContent->GetParent());
return parent && parent->IsSVGElement(nsGkAtoms::text);
}
return aContent->IsAnyOfSVGElements(nsGkAtoms::a, nsGkAtoms::tspan);
}
/**
* Returns whether the specified frame is an nsTextFrame that has some text
* content.
*/
static bool IsNonEmptyTextFrame(nsIFrame* aFrame) {
nsTextFrame* textFrame = do_QueryFrame(aFrame);
if (!textFrame) {
return false;
}
return textFrame->GetContentLength() != 0;
}
/**
* Takes an nsIFrame and if it is a text frame that has some text content,
* returns it as an nsTextFrame and its corresponding Text.
*
* @param aFrame The frame to look at.
* @param aTextFrame aFrame as an nsTextFrame (output).
* @param aTextNode The Text content of aFrame (output).
* @return true if aFrame is a non-empty text frame, false otherwise.
*/
static bool GetNonEmptyTextFrameAndNode(nsIFrame* aFrame,
nsTextFrame*& aTextFrame,
Text*& aTextNode) {
nsTextFrame* text = do_QueryFrame(aFrame);
bool isNonEmptyTextFrame = text && text->GetContentLength() != 0;
if (isNonEmptyTextFrame) {
nsIContent* content = text->GetContent();
NS_ASSERTION(content && content->IsText(),
"unexpected content type for nsTextFrame");
Text* node = content->AsText();
MOZ_ASSERT(node->TextLength() != 0,
"frame's GetContentLength() should be 0 if the text node "
"has no content");
aTextFrame = text;
aTextNode = node;
}
MOZ_ASSERT(IsNonEmptyTextFrame(aFrame) == isNonEmptyTextFrame,
"our logic should agree with IsNonEmptyTextFrame");
return isNonEmptyTextFrame;
}
/**
* Returns whether the specified atom is for one of the five
* glyph positioning attributes that can appear on SVG text
* elements -- x, y, dx, dy or rotate.
*/
static bool IsGlyphPositioningAttribute(nsAtom* aAttribute) {
return aAttribute == nsGkAtoms::x || aAttribute == nsGkAtoms::y ||
aAttribute == nsGkAtoms::dx || aAttribute == nsGkAtoms::dy ||
aAttribute == nsGkAtoms::rotate;
}
/**
* Returns the position in app units of a given baseline (using an
* SVG dominant-baseline property value) for a given nsTextFrame.
*
* @param aFrame The text frame to inspect.
* @param aTextRun The text run of aFrame.
* @param aDominantBaseline The dominant-baseline value to use.
*/
static nscoord GetBaselinePosition(nsTextFrame* aFrame, gfxTextRun* aTextRun,
uint8_t aDominantBaseline,
float aFontSizeScaleFactor) {
WritingMode writingMode = aFrame->GetWritingMode();
// We pass in null for the PropertyProvider since letter-spacing and
// word-spacing should not affect the ascent and descent values we get.
gfxTextRun::Metrics metrics =
aTextRun->MeasureText(gfxFont::LOOSE_INK_EXTENTS, nullptr);
switch (aDominantBaseline) {
case NS_STYLE_DOMINANT_BASELINE_HANGING:
case NS_STYLE_DOMINANT_BASELINE_TEXT_BEFORE_EDGE:
return writingMode.IsVerticalRL() ? metrics.mAscent + metrics.mDescent
: 0;
case NS_STYLE_DOMINANT_BASELINE_AUTO:
case NS_STYLE_DOMINANT_BASELINE_ALPHABETIC:
return writingMode.IsVerticalRL()
? metrics.mAscent + metrics.mDescent -
aFrame->GetLogicalBaseline(writingMode)
: aFrame->GetLogicalBaseline(writingMode);
case NS_STYLE_DOMINANT_BASELINE_MIDDLE:
return aFrame->GetLogicalBaseline(writingMode) -
SVGContentUtils::GetFontXHeight(aFrame) / 2.0 *
AppUnitsPerCSSPixel() * aFontSizeScaleFactor;
case NS_STYLE_DOMINANT_BASELINE_TEXT_AFTER_EDGE:
case NS_STYLE_DOMINANT_BASELINE_IDEOGRAPHIC:
return writingMode.IsVerticalLR() ? 0
: metrics.mAscent + metrics.mDescent;
case NS_STYLE_DOMINANT_BASELINE_CENTRAL:
case NS_STYLE_DOMINANT_BASELINE_MATHEMATICAL:
return (metrics.mAscent + metrics.mDescent) / 2.0;
}
MOZ_ASSERT_UNREACHABLE("unexpected dominant-baseline value");
return aFrame->GetLogicalBaseline(writingMode);
}
/**
* Truncates an array to be at most the length of another array.
*
* @param aArrayToTruncate The array to truncate.
* @param aReferenceArray The array whose length will be used to truncate
* aArrayToTruncate to.
*/
template <typename T, typename U>
static void TruncateTo(nsTArray<T>& aArrayToTruncate,
const nsTArray<U>& aReferenceArray) {
uint32_t length = aReferenceArray.Length();
if (aArrayToTruncate.Length() > length) {
aArrayToTruncate.TruncateLength(length);
}
}
/**
* Asserts that the anonymous block child of the SVGTextFrame has been
* reflowed (or does not exist). Returns null if the child has not been
* reflowed, and the frame otherwise.
*
* We check whether the kid has been reflowed and not the frame itself
* since we sometimes need to call this function during reflow, after the
* kid has been reflowed but before we have cleared the dirty bits on the
* frame itself.
*/
static SVGTextFrame* FrameIfAnonymousChildReflowed(SVGTextFrame* aFrame) {
MOZ_ASSERT(aFrame, "aFrame must not be null");
nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
if (NS_SUBTREE_DIRTY(kid)) {
MOZ_ASSERT(false, "should have already reflowed the anonymous block child");
return nullptr;
}
return aFrame;
}
static double GetContextScale(const gfxMatrix& aMatrix) {
// The context scale is the ratio of the length of the transformed
// diagonal vector (1,1) to the length of the untransformed diagonal
// (which is sqrt(2)).
gfxPoint p = aMatrix.TransformPoint(gfxPoint(1, 1)) -
aMatrix.TransformPoint(gfxPoint(0, 0));
return SVGContentUtils::ComputeNormalizedHypotenuse(p.x, p.y);
}
// ============================================================================
// Utility classes
namespace mozilla {
// ----------------------------------------------------------------------------
// TextRenderedRun
/**
* A run of text within a single nsTextFrame whose glyphs can all be painted
* with a single call to nsTextFrame::PaintText. A text rendered run can
* be created for a sequence of two or more consecutive glyphs as long as:
*
* - Only the first glyph has (or none of the glyphs have) been positioned
* with SVG text positioning attributes
* - All of the glyphs have zero rotation
* - The glyphs are not on a text path
* - The glyphs correspond to content within the one nsTextFrame
*
* A TextRenderedRunIterator produces TextRenderedRuns required for painting a
* whole SVGTextFrame.
*/
struct TextRenderedRun {
typedef gfxTextRun::Range Range;
/**
* Constructs a TextRenderedRun that is uninitialized except for mFrame
* being null.
*/
TextRenderedRun() : mFrame(nullptr) {}
/**
* Constructs a TextRenderedRun with all of the information required to
* paint it. See the comments documenting the member variables below
* for descriptions of the arguments.
*/
TextRenderedRun(nsTextFrame* aFrame, const gfxPoint& aPosition,
float aLengthAdjustScaleFactor, double aRotate,
float aFontSizeScaleFactor, nscoord aBaseline,
uint32_t aTextFrameContentOffset,
uint32_t aTextFrameContentLength,
uint32_t aTextElementCharIndex)
: mFrame(aFrame),
mPosition(aPosition),
mLengthAdjustScaleFactor(aLengthAdjustScaleFactor),
mRotate(static_cast<float>(aRotate)),
mFontSizeScaleFactor(aFontSizeScaleFactor),
mBaseline(aBaseline),
mTextFrameContentOffset(aTextFrameContentOffset),
mTextFrameContentLength(aTextFrameContentLength),
mTextElementCharIndex(aTextElementCharIndex) {}
/**
* Returns the text run for the text frame that this rendered run is part of.
*/
gfxTextRun* GetTextRun() const {
mFrame->EnsureTextRun(nsTextFrame::eInflated);
return mFrame->GetTextRun(nsTextFrame::eInflated);
}
/**
* Returns whether this rendered run is RTL.
*/
bool IsRightToLeft() const { return GetTextRun()->IsRightToLeft(); }
/**
* Returns whether this rendered run is vertical.
*/
bool IsVertical() const { return GetTextRun()->IsVertical(); }
/**
* Returns the transform that converts from a <text> element's user space into
* the coordinate space that rendered runs can be painted directly in.
*
* The difference between this method and
* GetTransformFromRunUserSpaceToUserSpace is that when calling in to
* nsTextFrame::PaintText, it will already take into account any left clip
* edge (that is, it doesn't just apply a visual clip to the rendered text, it
* shifts the glyphs over so that they are painted with their left edge at the
* x coordinate passed in to it). Thus we need to account for this in our
* transform.
*
*
* Assume that we have:
*
* <text x="100" y="100" rotate="0 0 1 0 0 * 1">abcdef</text>.
*
* This would result in four text rendered runs:
*
* - one for "ab"
* - one for "c"
* - one for "de"
* - one for "f"
*
* Assume now that we are painting the third TextRenderedRun. It will have
* a left clip edge that is the sum of the advances of "abc", and it will
* have a right clip edge that is the advance of "f". In
* SVGTextFrame::PaintSVG(), we pass in nsPoint() (i.e., the origin)
* as the point at which to paint the text frame, and we pass in the
* clip edge values. The nsTextFrame will paint the substring of its
* text such that the top-left corner of the "d"'s glyph cell will be at
* (0, 0) in the current coordinate system.
*
* Thus, GetTransformFromUserSpaceForPainting must return a transform from
* whatever user space the <text> element is in to a coordinate space in
* device pixels (as that's what nsTextFrame works in) where the origin is at
* the same position as our user space mPositions[i].mPosition value for
* the "d" glyph, which will be (100 + userSpaceAdvance("abc"), 100).
* The translation required to do this (ignoring the scale to get from
* user space to device pixels, and ignoring the
* (100 + userSpaceAdvance("abc"), 100) translation) is:
*
* (-leftEdge, -baseline)
*
* where baseline is the distance between the baseline of the text and the top
* edge of the nsTextFrame. We translate by -leftEdge horizontally because
* the nsTextFrame will already shift the glyphs over by that amount and start
* painting glyphs at x = 0. We translate by -baseline vertically so that
* painting the top edges of the glyphs at y = 0 will result in their
* baselines being at our desired y position.
*
*
* Now for an example with RTL text. Assume our content is now
* <text x="100" y="100" rotate="0 0 1 0 0 1">WERBEH</text>. We'd have
* the following text rendered runs:
*
* - one for "EH"
* - one for "B"
* - one for "ER"
* - one for "W"
*
* Again, we are painting the third TextRenderedRun. The left clip edge
* is the advance of the "W" and the right clip edge is the sum of the
* advances of "BEH". Our translation to get the rendered "ER" glyphs
* in the right place this time is:
*
* (-frameWidth + rightEdge, -baseline)
*
* which is equivalent to:
*
* (-(leftEdge + advance("ER")), -baseline)
*
* The reason we have to shift left additionally by the width of the run
* of glyphs we are painting is that although the nsTextFrame is RTL,
* we still supply the top-left corner to paint the frame at when calling
* nsTextFrame::PaintText, even though our user space positions for each
* glyph in mPositions specifies the origin of each glyph, which for RTL
* glyphs is at the right edge of the glyph cell.
*
*
* For any other use of an nsTextFrame in the context of a particular run
* (such as hit testing, or getting its rectangle),
* GetTransformFromRunUserSpaceToUserSpace should be used.
*
* @param aContext The context to use for unit conversions.
*/
gfxMatrix GetTransformFromUserSpaceForPainting(
nsPresContext* aContext, const nscoord aVisIStartEdge,
const nscoord aVisIEndEdge) const;
/**
* Returns the transform that converts from "run user space" to a <text>
* element's user space. Run user space is a coordinate system that has the
* same size as the <text>'s user space but rotated and translated such that
* (0,0) is the top-left of the rectangle that bounds the text.
*
* @param aContext The context to use for unit conversions.
*/
gfxMatrix GetTransformFromRunUserSpaceToUserSpace(
nsPresContext* aContext) const;
/**
* Returns the transform that converts from "run user space" to float pixels
* relative to the nsTextFrame that this rendered run is a part of.
*
* @param aContext The context to use for unit conversions.
*/
gfxMatrix GetTransformFromRunUserSpaceToFrameUserSpace(
nsPresContext* aContext) const;
/**
* Flag values used for the aFlags arguments of GetRunUserSpaceRect,
* GetFrameUserSpaceRect and GetUserSpaceRect.
*/
enum {
// Includes the fill geometry of the text in the returned rectangle.
eIncludeFill = 1,
// Includes the stroke geometry of the text in the returned rectangle.
eIncludeStroke = 2,
// Includes any text shadow in the returned rectangle.
eIncludeTextShadow = 4,
// Don't include any horizontal glyph overflow in the returned rectangle.
eNoHorizontalOverflow = 8
};
/**
* Returns a rectangle that bounds the fill and/or stroke of the rendered run
* in run user space.
*
* @param aContext The context to use for unit conversions.
* @param aFlags A combination of the flags above (eIncludeFill and
* eIncludeStroke) indicating what parts of the text to include in
* the rectangle.
*/
SVGBBox GetRunUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
/**
* Returns a rectangle that covers the fill and/or stroke of the rendered run
* in "frame user space".
*
* Frame user space is a coordinate space of the same scale as the <text>
* element's user space, but with its rotation set to the rotation of
* the glyphs within this rendered run and its origin set to the position
* such that placing the nsTextFrame there would result in the glyphs in
* this rendered run being at their correct positions.
*
* For example, say we have <text x="100 150" y="100">ab</text>. Assume
* the advance of both the "a" and the "b" is 12 user units, and the
* ascent of the text is 8 user units and its descent is 6 user units,
* and that we are not measuing the stroke of the text, so that we stay
* entirely within the glyph cells.
*
* There will be two text rendered runs, one for "a" and one for "b".
*
* The frame user space for the "a" run will have its origin at
* (100, 100 - 8) in the <text> element's user space and will have its
* axes aligned with the user space (since there is no rotate="" or
* text path involve) and with its scale the same as the user space.
* The rect returned by this method will be (0, 0, 12, 14), since the "a"
* glyph is right at the left of the nsTextFrame.
*
* The frame user space for the "b" run will have its origin at
* (150 - 12, 100 - 8), and scale/rotation the same as above. The rect
* returned by this method will be (12, 0, 12, 14), since we are
* advance("a") horizontally in to the text frame.
*
* @param aContext The context to use for unit conversions.
* @param aFlags A combination of the flags above (eIncludeFill and
* eIncludeStroke) indicating what parts of the text to include in
* the rectangle.
*/
SVGBBox GetFrameUserSpaceRect(nsPresContext* aContext, uint32_t aFlags) const;
/**
* Returns a rectangle that covers the fill and/or stroke of the rendered run
* in the <text> element's user space.
*
* @param aContext The context to use for unit conversions.
* @param aFlags A combination of the flags above indicating what parts of
* the text to include in the rectangle.
* @param aAdditionalTransform An additional transform to apply to the
* frame user space rectangle before its bounds are transformed into
* user space.
*/
SVGBBox GetUserSpaceRect(
nsPresContext* aContext, uint32_t aFlags,
const gfxMatrix* aAdditionalTransform = nullptr) const;
/**
* Gets the app unit amounts to clip from the left and right edges of
* the nsTextFrame in order to paint just this rendered run.
*
* Note that if clip edge amounts land in the middle of a glyph, the
* glyph won't be painted at all. The clip edges are thus more of
* a selection mechanism for which glyphs will be painted, rather
* than a geometric clip.
*/
void GetClipEdges(nscoord& aVisIStartEdge, nscoord& aVisIEndEdge) const;
/**
* Returns the advance width of the whole rendered run.
*/
nscoord GetAdvanceWidth() const;
/**
* Returns the index of the character into this rendered run whose
* glyph cell contains the given point, or -1 if there is no such
* character. This does not hit test against any overflow.
*
* @param aContext The context to use for unit conversions.
* @param aPoint The point in the user space of the <text> element.
*/
int32_t GetCharNumAtPosition(nsPresContext* aContext,
const gfxPoint& aPoint) const;
/**
* The text frame that this rendered run lies within.
*/
nsTextFrame* mFrame;
/**
* The point in user space that the text is positioned at.
*
* For a horizontal run:
* The x coordinate is the left edge of a LTR run of text or the right edge of
* an RTL run. The y coordinate is the baseline of the text.
* For a vertical run:
* The x coordinate is the baseline of the text.
* The y coordinate is the top edge of a LTR run, or bottom of RTL.
*/
gfxPoint mPosition;
/**
* The horizontal scale factor to apply when painting glyphs to take
* into account textLength="".
*/
float mLengthAdjustScaleFactor;
/**
* The rotation in radians in the user coordinate system that the text has.
*/
float mRotate;
/**
* The scale factor that was used to transform the text run's original font
* size into a sane range for painting and measurement.
*/
double mFontSizeScaleFactor;
/**
* The baseline in app units of this text run. The measurement is from the
* top of the text frame. (From the left edge if vertical.)
*/
nscoord mBaseline;
/**
* The offset and length in mFrame's content Text that corresponds to
* this text rendered run. These are original char indexes.
*/
uint32_t mTextFrameContentOffset;
uint32_t mTextFrameContentLength;
/**
* The character index in the whole SVG <text> element that this text rendered
* run begins at.
*/
uint32_t mTextElementCharIndex;
};
gfxMatrix TextRenderedRun::GetTransformFromUserSpaceForPainting(
nsPresContext* aContext, const nscoord aVisIStartEdge,
const nscoord aVisIEndEdge) const {
// We transform to device pixels positioned such that painting the text frame
// at (0,0) with aItem will result in the text being in the right place.
gfxMatrix m;
if (!mFrame) {
return m;
}
float cssPxPerDevPx =
nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
// Glyph position in user space.
m.PreTranslate(mPosition / cssPxPerDevPx);
// Take into account any font size scaling and scaling due to textLength="".
m.PreScale(1.0 / mFontSizeScaleFactor, 1.0 / mFontSizeScaleFactor);
// Rotation due to rotate="" or a <textPath>.
m.PreRotate(mRotate);
m.PreScale(mLengthAdjustScaleFactor, 1.0);
// Translation to get the text frame in the right place.
nsPoint t;
if (IsVertical()) {
t = nsPoint(-mBaseline, IsRightToLeft()
? -mFrame->GetRect().height + aVisIEndEdge
: -aVisIStartEdge);
} else {
t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + aVisIEndEdge
: -aVisIStartEdge,
-mBaseline);
}
m.PreTranslate(AppUnitsToGfxUnits(t, aContext));
return m;
}
gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToUserSpace(
nsPresContext* aContext) const {
gfxMatrix m;
if (!mFrame) {
return m;
}
float cssPxPerDevPx =
nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());
nscoord start, end;
GetClipEdges(start, end);
// Glyph position in user space.
m.PreTranslate(mPosition);
// Rotation due to rotate="" or a <textPath>.
m.PreRotate(mRotate);
// Scale due to textLength="".
m.PreScale(mLengthAdjustScaleFactor, 1.0);
// Translation to get the text frame in the right place.
nsPoint t;
if (IsVertical()) {
t = nsPoint(-mBaseline,
IsRightToLeft() ? -mFrame->GetRect().height + start + end : 0);
} else {
t = nsPoint(IsRightToLeft() ? -mFrame->GetRect().width + start + end : 0,
-mBaseline);
}
m.PreTranslate(AppUnitsToGfxUnits(t, aContext) * cssPxPerDevPx /
mFontSizeScaleFactor);
return m;
}
gfxMatrix TextRenderedRun::GetTransformFromRunUserSpaceToFrameUserSpace(
nsPresContext* aContext) const {
gfxMatrix m;
if (!mFrame) {
return m;
}
nscoord start, end;
GetClipEdges(start, end);
// Translate by the horizontal distance into the text frame this
// rendered run is.
gfxFloat appPerCssPx = AppUnitsPerCSSPixel();
gfxPoint t = IsVertical() ? gfxPoint(0, start / appPerCssPx)
: gfxPoint(start / appPerCssPx, 0);
return m.PreTranslate(t);
}
SVGBBox TextRenderedRun::GetRunUserSpaceRect(nsPresContext* aContext,
uint32_t aFlags) const {
SVGBBox r;
if (!mFrame) {
return r;
}
// Determine the amount of overflow above and below the frame's mRect.
//
// We need to call GetVisualOverflowRectRelativeToSelf because this includes
// overflowing decorations, which the MeasureText call below does not. We
// assume here the decorations only overflow above and below the frame, never
// horizontally.
nsRect self = mFrame->GetVisualOverflowRectRelativeToSelf();
nsRect rect = mFrame->GetRect();
bool vertical = IsVertical();
nscoord above = vertical ? -self.x : -self.y;
nscoord below =
vertical ? self.XMost() - rect.width : self.YMost() - rect.height;
gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
gfxSkipCharsIterator start = it;
gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
// Get the content range for this rendered run.
Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
mTextFrameContentLength);
if (range.Length() == 0) {
return r;
}
// FIXME(heycam): We could create a single PropertyProvider for all
// TextRenderedRuns that correspond to the text frame, rather than recreate
// it each time here.
Maybe<nsTextFrame::PropertyProvider> provider;
if (StaticPrefs::svg_text_spacing_enabled()) {
provider.emplace(mFrame, start);
}
// Measure that range.
gfxTextRun::Metrics metrics = textRun->MeasureText(
range, gfxFont::LOOSE_INK_EXTENTS, nullptr, provider.ptrOr(nullptr));
// Make sure it includes the font-box.
gfxRect fontBox(0, -metrics.mAscent, metrics.mAdvanceWidth,
metrics.mAscent + metrics.mDescent);
metrics.mBoundingBox.UnionRect(metrics.mBoundingBox, fontBox);
// Determine the rectangle that covers the rendered run's fill,
// taking into account the measured vertical overflow due to
// decorations.
nscoord baseline = metrics.mBoundingBox.y + metrics.mAscent;
gfxFloat x, width;
if (aFlags & eNoHorizontalOverflow) {
x = 0.0;
width = textRun->GetAdvanceWidth(range, provider.ptrOr(nullptr));
} else {
x = metrics.mBoundingBox.x;
width = metrics.mBoundingBox.width;
}
nsRect fillInAppUnits(x, baseline - above, width,
metrics.mBoundingBox.height + above + below);
if (textRun->IsVertical()) {
// Swap line-relative textMetrics dimensions to physical coordinates.
std::swap(fillInAppUnits.x, fillInAppUnits.y);
std::swap(fillInAppUnits.width, fillInAppUnits.height);
}
// Account for text-shadow.
if (aFlags & eIncludeTextShadow) {
fillInAppUnits =
nsLayoutUtils::GetTextShadowRectsUnion(fillInAppUnits, mFrame);
}
// Convert the app units rectangle to user units.
gfxRect fill = AppUnitsToFloatCSSPixels(
gfxRect(fillInAppUnits.x, fillInAppUnits.y, fillInAppUnits.width,
fillInAppUnits.height),
aContext);
// Scale the rectangle up due to any mFontSizeScaleFactor.
fill.Scale(1.0 / mFontSizeScaleFactor);
// Include the fill if requested.
if (aFlags & eIncludeFill) {
r = fill;
}
// Include the stroke if requested.
if ((aFlags & eIncludeStroke) && !fill.IsEmpty() &&
nsSVGUtils::GetStrokeWidth(mFrame) > 0) {
r.UnionEdges(
nsSVGUtils::PathExtentsToMaxStrokeExtents(fill, mFrame, gfxMatrix()));
}
return r;
}
SVGBBox TextRenderedRun::GetFrameUserSpaceRect(nsPresContext* aContext,
uint32_t aFlags) const {
SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
if (r.IsEmpty()) {
return r;
}
gfxMatrix m = GetTransformFromRunUserSpaceToFrameUserSpace(aContext);
return m.TransformBounds(r.ToThebesRect());
}
SVGBBox TextRenderedRun::GetUserSpaceRect(
nsPresContext* aContext, uint32_t aFlags,
const gfxMatrix* aAdditionalTransform) const {
SVGBBox r = GetRunUserSpaceRect(aContext, aFlags);
if (r.IsEmpty()) {
return r;
}
gfxMatrix m = GetTransformFromRunUserSpaceToUserSpace(aContext);
if (aAdditionalTransform) {
m *= *aAdditionalTransform;
}
return m.TransformBounds(r.ToThebesRect());
}
void TextRenderedRun::GetClipEdges(nscoord& aVisIStartEdge,
nscoord& aVisIEndEdge) const {
uint32_t contentLength = mFrame->GetContentLength();
if (mTextFrameContentOffset == 0 &&
mTextFrameContentLength == contentLength) {
// If the rendered run covers the entire content, we know we don't need
// to clip without having to measure anything.
aVisIStartEdge = 0;
aVisIEndEdge = 0;
return;
}
gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
Maybe<nsTextFrame::PropertyProvider> provider;
if (StaticPrefs::svg_text_spacing_enabled()) {
provider.emplace(mFrame, it);
}
// Get the covered content offset/length for this rendered run in skipped
// characters, since that is what GetAdvanceWidth expects.
Range runRange = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
mTextFrameContentLength);
// Get the offset/length of the whole nsTextFrame.
uint32_t frameOffset = mFrame->GetContentOffset();
uint32_t frameLength = mFrame->GetContentLength();
// Trim the whole-nsTextFrame offset/length to remove any leading/trailing
// white space, as the nsTextFrame when painting does not include them when
// interpreting clip edges.
nsTextFrame::TrimmedOffsets trimmedOffsets =
mFrame->GetTrimmedOffsets(mFrame->TextFragment());
TrimOffsets(frameOffset, frameLength, trimmedOffsets);
// Convert the trimmed whole-nsTextFrame offset/length into skipped
// characters.
Range frameRange = ConvertOriginalToSkipped(it, frameOffset, frameLength);
// Measure the advance width in the text run between the start of
// frame's content and the start of the rendered run's content,
nscoord startEdge = textRun->GetAdvanceWidth(
Range(frameRange.start, runRange.start), provider.ptrOr(nullptr));
// and between the end of the rendered run's content and the end
// of the frame's content.
nscoord endEdge = textRun->GetAdvanceWidth(
Range(runRange.end, frameRange.end), provider.ptrOr(nullptr));
if (textRun->IsRightToLeft()) {
aVisIStartEdge = endEdge;
aVisIEndEdge = startEdge;
} else {
aVisIStartEdge = startEdge;
aVisIEndEdge = endEdge;
}
}
nscoord TextRenderedRun::GetAdvanceWidth() const {
gfxSkipCharsIterator it = mFrame->EnsureTextRun(nsTextFrame::eInflated);
gfxTextRun* textRun = mFrame->GetTextRun(nsTextFrame::eInflated);
Maybe<nsTextFrame::PropertyProvider> provider;
if (StaticPrefs::svg_text_spacing_enabled()) {
provider.emplace(mFrame, it);
}
Range range = ConvertOriginalToSkipped(it, mTextFrameContentOffset,
mTextFrameContentLength);
return textRun->GetAdvanceWidth(range, provider.ptrOr(nullptr));
}
int32_t TextRenderedRun::GetCharNumAtPosition(nsPresContext* aContext,
const gfxPoint& aPoint) const {
if (mTextFrameContentLength == 0) {
return -1;
}
float cssPxPerDevPx =
nsPresContext::AppUnitsToFloatCSSPixels(aContext->AppUnitsPerDevPixel());