-
Notifications
You must be signed in to change notification settings - Fork 54
/
gfxTextRun.cpp
3526 lines (3170 loc) · 128 KB
/
gfxTextRun.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: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=4 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/. */
#include "gfxTextRun.h"
#include "gfxGlyphExtents.h"
#include "gfxHarfBuzzShaper.h"
#include "gfxPlatformFontList.h"
#include "gfxUserFontSet.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/Sprintf.h"
#include "gfxContext.h"
#include "gfxFontConstants.h"
#include "gfxFontMissingGlyphs.h"
#include "gfxScriptItemizer.h"
#include "nsUnicodeProperties.h"
#include "nsStyleConsts.h"
#include "nsStyleUtil.h"
#include "mozilla/Likely.h"
#include "gfx2DGlue.h"
#include "mozilla/gfx/Logging.h" // for gfxCriticalError
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "SharedFontList-impl.h"
#include "TextDrawTarget.h"
#include <unicode/unorm2.h>
#ifdef XP_WIN
# include "gfxWindowsPlatform.h"
#endif
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;
using mozilla::services::GetObserverService;
static const char16_t kEllipsisChar[] = {0x2026, 0x0};
static const char16_t kASCIIPeriodsChar[] = {'.', '.', '.', 0x0};
#ifdef DEBUG_roc
# define DEBUG_TEXT_RUN_STORAGE_METRICS
#endif
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
extern uint32_t gTextRunStorageHighWaterMark;
extern uint32_t gTextRunStorage;
extern uint32_t gFontCount;
extern uint32_t gGlyphExtentsCount;
extern uint32_t gGlyphExtentsWidthsTotalSize;
extern uint32_t gGlyphExtentsSetupEagerSimple;
extern uint32_t gGlyphExtentsSetupEagerTight;
extern uint32_t gGlyphExtentsSetupLazyTight;
extern uint32_t gGlyphExtentsSetupFallBackToTight;
#endif
bool gfxTextRun::GlyphRunIterator::NextRun() {
int32_t glyphRunCount;
if (mTextRun->mHasGlyphRunArray) {
glyphRunCount = mTextRun->mGlyphRunArray.Length();
if (mNextIndex >= glyphRunCount || mNextIndex < 0) {
return false;
}
mGlyphRun = &mTextRun->mGlyphRunArray[mNextIndex];
} else {
if (mNextIndex != 0 || !mTextRun->mSingleGlyphRun.mFont) {
return false;
}
glyphRunCount = 1;
mGlyphRun = &mTextRun->mSingleGlyphRun;
}
if (mGlyphRun->mCharacterOffset >= mEndOffset) {
return false;
}
uint32_t glyphRunEndOffset =
mNextIndex + 1 < (int32_t)glyphRunCount
? mTextRun->mGlyphRunArray[mNextIndex + 1].mCharacterOffset
: mTextRun->GetLength();
if (glyphRunEndOffset <= mStartOffset) {
return false;
}
mStringEnd = std::min(mEndOffset, glyphRunEndOffset);
mStringStart = std::max(mStartOffset, mGlyphRun->mCharacterOffset);
mNextIndex += mDirection;
return true;
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
static void AccountStorageForTextRun(gfxTextRun* aTextRun, int32_t aSign) {
// Ignores detailed glyphs... we don't know when those have been constructed
// Also ignores gfxSkipChars dynamic storage (which won't be anything
// for preformatted text)
// Also ignores GlyphRun array, again because it hasn't been constructed
// by the time this gets called. If there's only one glyphrun that's stored
// directly in the textrun anyway so no additional overhead.
uint32_t length = aTextRun->GetLength();
int32_t bytes = length * sizeof(gfxTextRun::CompressedGlyph);
bytes += sizeof(gfxTextRun);
gTextRunStorage += bytes * aSign;
gTextRunStorageHighWaterMark =
std::max(gTextRunStorageHighWaterMark, gTextRunStorage);
}
#endif
static bool NeedsGlyphExtents(gfxTextRun* aTextRun) {
if (aTextRun->GetFlags() & gfx::ShapedTextFlags::TEXT_NEED_BOUNDING_BOX)
return true;
uint32_t numRuns;
const gfxTextRun::GlyphRun* glyphRuns = aTextRun->GetGlyphRuns(&numRuns);
for (uint32_t i = 0; i < numRuns; ++i) {
if (glyphRuns[i].mFont->GetFontEntry()->IsUserFont()) return true;
}
return false;
}
// Helper for textRun creation to preallocate storage for glyph records;
// this function returns a pointer to the newly-allocated glyph storage.
// Returns nullptr if allocation fails.
void* gfxTextRun::AllocateStorageForTextRun(size_t aSize, uint32_t aLength) {
// Allocate the storage we need, returning nullptr on failure rather than
// throwing an exception (because web content can create huge runs).
void* storage = malloc(aSize + aLength * sizeof(CompressedGlyph));
if (!storage) {
NS_WARNING("failed to allocate storage for text run!");
return nullptr;
}
// Initialize the glyph storage (beyond aSize) to zero
memset(reinterpret_cast<char*>(storage) + aSize, 0,
aLength * sizeof(CompressedGlyph));
return storage;
}
already_AddRefed<gfxTextRun> gfxTextRun::Create(
const gfxTextRunFactory::Parameters* aParams, uint32_t aLength,
gfxFontGroup* aFontGroup, gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2) {
void* storage = AllocateStorageForTextRun(sizeof(gfxTextRun), aLength);
if (!storage) {
return nullptr;
}
RefPtr<gfxTextRun> result =
new (storage) gfxTextRun(aParams, aLength, aFontGroup, aFlags, aFlags2);
return result.forget();
}
gfxTextRun::gfxTextRun(const gfxTextRunFactory::Parameters* aParams,
uint32_t aLength, gfxFontGroup* aFontGroup,
gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2)
: gfxShapedText(aLength, aFlags, aParams->mAppUnitsPerDevUnit),
mSingleGlyphRun(),
mUserData(aParams->mUserData),
mFontGroup(aFontGroup),
mFlags2(aFlags2),
mReleasedFontGroup(false),
mHasGlyphRunArray(false),
mShapingState(eShapingState_Normal) {
NS_ASSERTION(mAppUnitsPerDevUnit > 0, "Invalid app unit scale");
NS_ADDREF(mFontGroup);
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = aFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunConst++;
}
#endif
mCharacterGlyphs = reinterpret_cast<CompressedGlyph*>(this + 1);
if (aParams->mSkipChars) {
mSkipChars.TakeFrom(aParams->mSkipChars);
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, 1);
#endif
mSkipDrawing =
mFontGroup->ShouldSkipDrawing() &&
!(aFlags2 & nsTextFrameUtils::Flags::DontSkipDrawingForPendingUserFonts);
}
gfxTextRun::~gfxTextRun() {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, -1);
#endif
#ifdef DEBUG
// Make it easy to detect a dead text run
mFlags = ~gfx::ShapedTextFlags();
mFlags2 = ~nsTextFrameUtils::Flags();
#endif
if (mHasGlyphRunArray) {
mGlyphRunArray.~nsTArray<GlyphRun>();
} else {
mSingleGlyphRun.mFont = nullptr;
}
// The cached ellipsis textrun (if any) in a fontgroup will have already
// been told to release its reference to the group, so we mustn't do that
// again here.
if (!mReleasedFontGroup) {
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = mFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunDestr++;
}
#endif
NS_RELEASE(mFontGroup);
}
}
void gfxTextRun::ReleaseFontGroup() {
NS_ASSERTION(!mReleasedFontGroup, "doubly released!");
NS_RELEASE(mFontGroup);
mReleasedFontGroup = true;
}
bool gfxTextRun::SetPotentialLineBreaks(Range aRange,
const uint8_t* aBreakBefore) {
NS_ASSERTION(aRange.end <= GetLength(), "Overflow");
uint32_t changed = 0;
CompressedGlyph* cg = mCharacterGlyphs + aRange.start;
const CompressedGlyph* const end = cg + aRange.Length();
while (cg < end) {
uint8_t canBreak = *aBreakBefore++;
if (canBreak && !cg->IsClusterStart()) {
// XXX If we replace the line-breaker with one based more closely
// on UAX#14 (e.g. using ICU), this may not be needed any more.
// Avoid possible breaks inside a cluster, EXCEPT when the previous
// character was a space (compare UAX#14 rules LB9, LB10).
if (cg == mCharacterGlyphs || !(cg - 1)->CharIsSpace()) {
canBreak = CompressedGlyph::FLAG_BREAK_TYPE_NONE;
}
}
changed |= cg->SetCanBreakBefore(canBreak);
++cg;
}
return changed != 0;
}
gfxTextRun::LigatureData gfxTextRun::ComputeLigatureData(
Range aPartRange, PropertyProvider* aProvider) const {
NS_ASSERTION(aPartRange.start < aPartRange.end,
"Computing ligature data for empty range");
NS_ASSERTION(aPartRange.end <= GetLength(), "Character length overflow");
LigatureData result;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
uint32_t i;
for (i = aPartRange.start; !charGlyphs[i].IsLigatureGroupStart(); --i) {
NS_ASSERTION(i > 0, "Ligature at the start of the run??");
}
result.mRange.start = i;
for (i = aPartRange.start + 1;
i < GetLength() && !charGlyphs[i].IsLigatureGroupStart(); ++i) {
}
result.mRange.end = i;
int32_t ligatureWidth = GetAdvanceForGlyphs(result.mRange);
// Count the number of started clusters we have seen
uint32_t totalClusterCount = 0;
uint32_t partClusterIndex = 0;
uint32_t partClusterCount = 0;
for (i = result.mRange.start; i < result.mRange.end; ++i) {
// Treat the first character of the ligature as the start of a
// cluster for our purposes of allocating ligature width to its
// characters.
if (i == result.mRange.start || charGlyphs[i].IsClusterStart()) {
++totalClusterCount;
if (i < aPartRange.start) {
++partClusterIndex;
} else if (i < aPartRange.end) {
++partClusterCount;
}
}
}
NS_ASSERTION(totalClusterCount > 0, "Ligature involving no clusters??");
result.mPartAdvance = partClusterIndex * (ligatureWidth / totalClusterCount);
result.mPartWidth = partClusterCount * (ligatureWidth / totalClusterCount);
// Any rounding errors are apportioned to the final part of the ligature,
// so that measuring all parts of a ligature and summing them is equal to
// the ligature width.
if (aPartRange.end == result.mRange.end) {
gfxFloat allParts = totalClusterCount * (ligatureWidth / totalClusterCount);
result.mPartWidth += ligatureWidth - allParts;
}
if (partClusterCount == 0) {
// nothing to draw
result.mClipBeforePart = result.mClipAfterPart = true;
} else {
// Determine whether we should clip before or after this part when
// drawing its slice of the ligature.
// We need to clip before the part if any cluster is drawn before
// this part.
result.mClipBeforePart = partClusterIndex > 0;
// We need to clip after the part if any cluster is drawn after
// this part.
result.mClipAfterPart =
partClusterIndex + partClusterCount < totalClusterCount;
}
if (aProvider && (mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
gfxFont::Spacing spacing;
if (aPartRange.start == result.mRange.start) {
aProvider->GetSpacing(Range(aPartRange.start, aPartRange.start + 1),
&spacing);
result.mPartWidth += spacing.mBefore;
}
if (aPartRange.end == result.mRange.end) {
aProvider->GetSpacing(Range(aPartRange.end - 1, aPartRange.end),
&spacing);
result.mPartWidth += spacing.mAfter;
}
}
return result;
}
gfxFloat gfxTextRun::ComputePartialLigatureWidth(
Range aPartRange, PropertyProvider* aProvider) const {
if (aPartRange.start >= aPartRange.end) return 0;
LigatureData data = ComputeLigatureData(aPartRange, aProvider);
return data.mPartWidth;
}
int32_t gfxTextRun::GetAdvanceForGlyphs(Range aRange) const {
int32_t advance = 0;
for (auto i = aRange.start; i < aRange.end; ++i) {
advance += GetAdvanceForGlyph(i);
}
return advance;
}
static void GetAdjustedSpacing(
const gfxTextRun* aTextRun, gfxTextRun::Range aRange,
gfxTextRun::PropertyProvider* aProvider,
gfxTextRun::PropertyProvider::Spacing* aSpacing) {
if (aRange.start >= aRange.end) return;
aProvider->GetSpacing(aRange, aSpacing);
#ifdef DEBUG
// Check to see if we have spacing inside ligatures
const gfxTextRun::CompressedGlyph* charGlyphs =
aTextRun->GetCharacterGlyphs();
uint32_t i;
for (i = aRange.start; i < aRange.end; ++i) {
if (!charGlyphs[i].IsLigatureGroupStart()) {
NS_ASSERTION(i == aRange.start || aSpacing[i - aRange.start].mBefore == 0,
"Before-spacing inside a ligature!");
NS_ASSERTION(
i - 1 <= aRange.start || aSpacing[i - 1 - aRange.start].mAfter == 0,
"After-spacing inside a ligature!");
}
}
#endif
}
bool gfxTextRun::GetAdjustedSpacingArray(
Range aRange, PropertyProvider* aProvider, Range aSpacingRange,
nsTArray<PropertyProvider::Spacing>* aSpacing) const {
if (!aProvider || !(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
return false;
}
if (!aSpacing->AppendElements(aRange.Length(), fallible)) {
return false;
}
auto spacingOffset = aSpacingRange.start - aRange.start;
memset(aSpacing->Elements(), 0, sizeof(gfxFont::Spacing) * spacingOffset);
GetAdjustedSpacing(this, aSpacingRange, aProvider,
aSpacing->Elements() + spacingOffset);
memset(aSpacing->Elements() + aSpacingRange.end - aRange.start, 0,
sizeof(gfxFont::Spacing) * (aRange.end - aSpacingRange.end));
return true;
}
void gfxTextRun::ShrinkToLigatureBoundaries(Range* aRange) const {
if (aRange->start >= aRange->end) return;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
while (aRange->start < aRange->end &&
!charGlyphs[aRange->start].IsLigatureGroupStart()) {
++aRange->start;
}
if (aRange->end < GetLength()) {
while (aRange->end > aRange->start &&
!charGlyphs[aRange->end].IsLigatureGroupStart()) {
--aRange->end;
}
}
}
void gfxTextRun::DrawGlyphs(gfxFont* aFont, Range aRange, gfx::Point* aPt,
PropertyProvider* aProvider, Range aSpacingRange,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
aParams.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
aFont->Draw(this, aRange.start, aRange.end, aPt, aParams, aOrientation);
}
static void ClipPartialLigature(const gfxTextRun* aTextRun, gfxFloat* aStart,
gfxFloat* aEnd, gfxFloat aOrigin,
gfxTextRun::LigatureData* aLigature) {
if (aLigature->mClipBeforePart) {
if (aTextRun->IsRightToLeft()) {
*aEnd = std::min(*aEnd, aOrigin);
} else {
*aStart = std::max(*aStart, aOrigin);
}
}
if (aLigature->mClipAfterPart) {
gfxFloat endEdge =
aOrigin + aTextRun->GetDirection() * aLigature->mPartWidth;
if (aTextRun->IsRightToLeft()) {
*aStart = std::max(*aStart, endEdge);
} else {
*aEnd = std::min(*aEnd, endEdge);
}
}
}
void gfxTextRun::DrawPartialLigature(gfxFont* aFont, Range aRange,
gfx::Point* aPt,
PropertyProvider* aProvider,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
if (aRange.start >= aRange.end) {
return;
}
// Draw partial ligature. We hack this by clipping the ligature.
LigatureData data = ComputeLigatureData(aRange, aProvider);
gfxRect clipExtents = aParams.context->GetClipExtents();
gfxFloat start, end;
if (aParams.isVerticalRun) {
start = clipExtents.Y() * mAppUnitsPerDevUnit;
end = clipExtents.YMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->y, &data);
} else {
start = clipExtents.X() * mAppUnitsPerDevUnit;
end = clipExtents.XMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->x, &data);
}
{
// use division here to ensure that when the rect is aligned on multiples
// of mAppUnitsPerDevUnit, we clip to true device unit boundaries.
// Also, make sure we snap the rectangle to device pixels.
Rect clipRect =
aParams.isVerticalRun
? Rect(clipExtents.X(), start / mAppUnitsPerDevUnit,
clipExtents.Width(), (end - start) / mAppUnitsPerDevUnit)
: Rect(start / mAppUnitsPerDevUnit, clipExtents.Y(),
(end - start) / mAppUnitsPerDevUnit, clipExtents.Height());
MaybeSnapToDevicePixels(clipRect, *aParams.dt, true);
aParams.context->Clip(clipRect);
}
gfx::Point pt;
if (aParams.isVerticalRun) {
pt = Point(aPt->x, aPt->y - aParams.direction * data.mPartAdvance);
} else {
pt = Point(aPt->x - aParams.direction * data.mPartAdvance, aPt->y);
}
DrawGlyphs(aFont, data.mRange, &pt, aProvider, aRange, aParams, aOrientation);
aParams.context->PopClip();
if (aParams.isVerticalRun) {
aPt->y += aParams.direction * data.mPartWidth;
} else {
aPt->x += aParams.direction * data.mPartWidth;
}
}
// Returns true if the font has synthetic bolding enabled,
// or is a color font (COLR/SVG/sbix/CBDT), false otherwise. This is used to
// check whether the text run needs to be explicitly composited in order to
// support opacity.
static bool HasSyntheticBoldOrColor(gfxFont* aFont) {
if (aFont->IsSyntheticBold()) {
return true;
}
gfxFontEntry* fe = aFont->GetFontEntry();
if (fe->TryGetSVGData(aFont) || fe->TryGetColorGlyphs()) {
return true;
}
#if defined(XP_MACOSX) // sbix fonts only supported via Core Text
if (fe->HasFontTable(TRUETYPE_TAG('s', 'b', 'i', 'x'))) {
return true;
}
#endif
return false;
}
// helper class for double-buffering drawing with non-opaque color
struct MOZ_STACK_CLASS BufferAlphaColor {
explicit BufferAlphaColor(gfxContext* aContext) : mContext(aContext) {}
~BufferAlphaColor() = default;
void PushSolidColor(const gfxRect& aBounds, const DeviceColor& aAlphaColor,
uint32_t appsPerDevUnit) {
mContext->Save();
mContext->SnappedClip(gfxRect(
aBounds.X() / appsPerDevUnit, aBounds.Y() / appsPerDevUnit,
aBounds.Width() / appsPerDevUnit, aBounds.Height() / appsPerDevUnit));
mContext->SetDeviceColor(
DeviceColor(aAlphaColor.r, aAlphaColor.g, aAlphaColor.b));
mContext->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, aAlphaColor.a);
}
void PopAlpha() {
// pop the text, using the color alpha as the opacity
mContext->PopGroupAndBlend();
mContext->Restore();
}
gfxContext* mContext;
};
void gfxTextRun::Draw(const Range aRange, const gfx::Point aPt,
const DrawParams& aParams) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH ||
!(aParams.drawMode & DrawMode::GLYPH_PATH),
"GLYPH_PATH cannot be used with GLYPH_FILL, GLYPH_STROKE or "
"GLYPH_STROKE_UNDERNEATH");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH || !aParams.callbacks,
"callback must not be specified unless using GLYPH_PATH");
bool skipDrawing = mSkipDrawing;
if (aParams.drawMode & DrawMode::GLYPH_FILL) {
DeviceColor currentColor;
if (aParams.context->GetDeviceColor(currentColor) && currentColor.a == 0 &&
!aParams.context->GetTextDrawer()) {
skipDrawing = true;
}
}
gfxFloat direction = GetDirection();
if (skipDrawing) {
// We don't need to draw anything;
// but if the caller wants advance width, we need to compute it here
if (aParams.advanceWidth) {
gfxTextRun::Metrics metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
*aParams.advanceWidth = metrics.mAdvanceWidth * direction;
}
// return without drawing
return;
}
// synthetic bolding draws glyphs twice ==> colors with opacity won't draw
// correctly unless first drawn without alpha
BufferAlphaColor syntheticBoldBuffer(aParams.context);
DeviceColor currentColor;
bool mayNeedBuffering =
aParams.drawMode & DrawMode::GLYPH_FILL &&
aParams.context->HasNonOpaqueNonTransparentColor(currentColor) &&
!aParams.context->GetTextDrawer();
// If we need to double-buffer, we'll need to measure the text first to
// get the bounds of the area of interest. Ideally we'd do that just for
// the specific glyph run(s) that need buffering, but because of bug
// 1612610 we currently use the extent of the entire range even when
// just buffering a subrange. So we'll measure the full range once and
// keep the metrics on hand for any subsequent subranges.
gfxTextRun::Metrics metrics;
bool gotMetrics = false;
// Set up parameters that will be constant across all glyph runs we need
// to draw, regardless of the font used.
TextRunDrawParams params;
params.context = aParams.context;
params.devPerApp = 1.0 / double(GetAppUnitsPerDevUnit());
params.isVerticalRun = IsVertical();
params.isRTL = IsRightToLeft();
params.direction = direction;
params.strokeOpts = aParams.strokeOpts;
params.textStrokeColor = aParams.textStrokeColor;
params.textStrokePattern = aParams.textStrokePattern;
params.drawOpts = aParams.drawOpts;
params.drawMode = aParams.drawMode;
params.callbacks = aParams.callbacks;
params.runContextPaint = aParams.contextPaint;
params.paintSVGGlyphs =
!aParams.callbacks || aParams.callbacks->mShouldPaintSVGGlyphs;
params.dt = aParams.context->GetDrawTarget();
GlyphRunIterator iter(this, aRange);
gfxFloat advance = 0.0;
gfx::Point pt = aPt;
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
Range runRange(iter.GetStringStart(), iter.GetStringEnd());
bool needToRestore = false;
if (mayNeedBuffering && HasSyntheticBoldOrColor(font)) {
needToRestore = true;
if (!gotMetrics) {
// Measure text; use the bounding box to determine the area we need
// to buffer. We measure the entire range, rather than just the glyph
// run that we're actually handling, because of bug 1612610: if the
// bounding box passed to PushSolidColor does not intersect the
// drawTarget's current clip, the skia backend fails to clip properly.
// This means we may use a larger buffer than actually needed, but is
// otherwise harmless.
metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
if (IsRightToLeft()) {
metrics.mBoundingBox.MoveBy(
gfxPoint(aPt.x - metrics.mAdvanceWidth, aPt.y));
} else {
metrics.mBoundingBox.MoveBy(gfxPoint(aPt.x, aPt.y));
}
gotMetrics = true;
}
syntheticBoldBuffer.PushSolidColor(metrics.mBoundingBox, currentColor,
GetAppUnitsPerDevUnit());
}
Range ligatureRange(runRange);
ShrinkToLigatureBoundaries(&ligatureRange);
bool drawPartial =
(aParams.drawMode & (DrawMode::GLYPH_FILL | DrawMode::GLYPH_STROKE)) ||
(aParams.drawMode == DrawMode::GLYPH_PATH && aParams.callbacks);
gfx::Point origPt = pt;
if (drawPartial) {
DrawPartialLigature(font, Range(runRange.start, ligatureRange.start), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
DrawGlyphs(font, ligatureRange, &pt, aParams.provider, ligatureRange,
params, iter.GetGlyphRun()->mOrientation);
if (drawPartial) {
DrawPartialLigature(font, Range(ligatureRange.end, runRange.end), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
if (params.isVerticalRun) {
advance += (pt.y - origPt.y) * params.direction;
} else {
advance += (pt.x - origPt.x) * params.direction;
}
// composite result when synthetic bolding used
if (needToRestore) {
syntheticBoldBuffer.PopAlpha();
}
}
if (aParams.advanceWidth) {
*aParams.advanceWidth = advance;
}
}
// This method is mostly parallel to Draw().
void gfxTextRun::DrawEmphasisMarks(gfxContext* aContext, gfxTextRun* aMark,
gfxFloat aMarkAdvance, gfx::Point aPt,
Range aRange,
PropertyProvider* aProvider) const {
MOZ_ASSERT(aRange.end <= GetLength());
EmphasisMarkDrawParams params;
params.context = aContext;
params.mark = aMark;
params.advance = aMarkAdvance;
params.direction = GetDirection();
params.isVertical = IsVertical();
float& inlineCoord = params.isVertical ? aPt.y : aPt.x;
float direction = params.direction;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
inlineCoord +=
direction * ComputePartialLigatureWidth(
Range(start, ligatureRange.start), aProvider);
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing = GetAdjustedSpacingArray(ligatureRange, aProvider,
ligatureRange, &spacingBuffer);
params.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
font->DrawEmphasisMarks(this, &aPt, ligatureRange.start,
ligatureRange.Length(), params);
inlineCoord += direction * ComputePartialLigatureWidth(
Range(ligatureRange.end, end), aProvider);
}
}
void gfxTextRun::AccumulateMetricsForRun(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
Range aSpacingRange, gfx::ShapedTextFlags aOrientation,
Metrics* aMetrics) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
Metrics metrics = aFont->Measure(
this, aRange.start, aRange.end, aBoundingBoxType, aRefDrawTarget,
haveSpacing ? spacingBuffer.Elements() : nullptr, aOrientation);
aMetrics->CombineWith(metrics, IsRightToLeft());
}
void gfxTextRun::AccumulatePartialLigatureMetrics(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
gfx::ShapedTextFlags aOrientation, Metrics* aMetrics) const {
if (aRange.start >= aRange.end) return;
// Measure partial ligature. We hack this by clipping the metrics in the
// same way we clip the drawing.
LigatureData data = ComputeLigatureData(aRange, aProvider);
// First measure the complete ligature
Metrics metrics;
AccumulateMetricsForRun(aFont, data.mRange, aBoundingBoxType, aRefDrawTarget,
aProvider, aRange, aOrientation, &metrics);
// Clip the bounding box to the ligature part
gfxFloat bboxLeft = metrics.mBoundingBox.X();
gfxFloat bboxRight = metrics.mBoundingBox.XMost();
// Where we are going to start "drawing" relative to our left baseline origin
gfxFloat origin =
IsRightToLeft() ? metrics.mAdvanceWidth - data.mPartAdvance : 0;
ClipPartialLigature(this, &bboxLeft, &bboxRight, origin, &data);
metrics.mBoundingBox.SetBoxX(bboxLeft, bboxRight);
// mBoundingBox is now relative to the left baseline origin for the entire
// ligature. Shift it left.
metrics.mBoundingBox.MoveByX(
-(IsRightToLeft()
? metrics.mAdvanceWidth - (data.mPartAdvance + data.mPartWidth)
: data.mPartAdvance));
metrics.mAdvanceWidth = data.mPartWidth;
aMetrics->CombineWith(metrics, IsRightToLeft());
}
gfxTextRun::Metrics gfxTextRun::MeasureText(
Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
Metrics accumulatedMetrics;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
AccumulatePartialLigatureMetrics(
font, Range(start, ligatureRange.start), aBoundingBoxType,
aRefDrawTarget, aProvider, iter.GetGlyphRun()->mOrientation,
&accumulatedMetrics);
// XXX This sucks. We have to get glyph extents just so we can detect
// glyphs outside the font box, even when aBoundingBoxType is LOOSE,
// even though in almost all cases we could get correct results just
// by getting some ascent/descent from the font and using our stored
// advance widths.
AccumulateMetricsForRun(
font, ligatureRange, aBoundingBoxType, aRefDrawTarget, aProvider,
ligatureRange, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
AccumulatePartialLigatureMetrics(
font, Range(ligatureRange.end, end), aBoundingBoxType, aRefDrawTarget,
aProvider, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
}
return accumulatedMetrics;
}
#define MEASUREMENT_BUFFER_SIZE 100
void gfxTextRun::ClassifyAutoHyphenations(uint32_t aStart, Range aRange,
nsTArray<HyphenType>& aHyphenBuffer,
HyphenationState* aWordState) {
MOZ_ASSERT(
aRange.end - aStart <= aHyphenBuffer.Length() && aRange.start >= aStart,
"Range out of bounds");
MOZ_ASSERT(aWordState->mostRecentBoundary >= aStart,
"Unexpected aMostRecentWordBoundary!!");
uint32_t start =
std::min<uint32_t>(aRange.start, aWordState->mostRecentBoundary);
for (uint32_t i = start; i < aRange.end; ++i) {
if (aHyphenBuffer[i - aStart] == HyphenType::Explicit &&
!aWordState->hasExplicitHyphen) {
aWordState->hasExplicitHyphen = true;
}
if (!aWordState->hasManualHyphen &&
(aHyphenBuffer[i - aStart] == HyphenType::Soft ||
aHyphenBuffer[i - aStart] == HyphenType::Explicit)) {
aWordState->hasManualHyphen = true;
// This is the first manual hyphen in the current word. We can only
// know if the current word has a manual hyphen until now. So, we need
// to run a sub loop to update the auto hyphens between the start of
// the current word and this manual hyphen.
if (aWordState->hasAutoHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j < i; j++) {
if (aHyphenBuffer[j - aStart] ==
HyphenType::AutoWithoutManualInSameWord) {
aHyphenBuffer[j - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
}
}
if (aHyphenBuffer[i - aStart] == HyphenType::AutoWithoutManualInSameWord) {
if (!aWordState->hasAutoHyphen) {
aWordState->hasAutoHyphen = true;
}
if (aWordState->hasManualHyphen) {
aHyphenBuffer[i - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
// If we're at the word boundary, clear/reset couple states.
if (mCharacterGlyphs[i].CharIsSpace() || mCharacterGlyphs[i].CharIsTab() ||
mCharacterGlyphs[i].CharIsNewline() ||
// Since we will not have a boundary in the end of the string, let's
// call the end of the string a special case for word boundary.
i == GetLength() - 1) {
// We can only get to know whether we should raise/clear an explicit
// manual hyphen until we get to the end of a word, because this depends
// on whether there exists at least one auto hyphen in the same word.
if (!aWordState->hasAutoHyphen && aWordState->hasExplicitHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j <= i; j++) {
if (aHyphenBuffer[j - aStart] == HyphenType::Explicit) {
aHyphenBuffer[j - aStart] = HyphenType::None;
}
}
}
aWordState->mostRecentBoundary = i;
aWordState->hasManualHyphen = false;
aWordState->hasAutoHyphen = false;
aWordState->hasExplicitHyphen = false;
}
}
}
uint32_t gfxTextRun::BreakAndMeasureText(
uint32_t aStart, uint32_t aMaxLength, bool aLineBreakBefore,
gfxFloat aWidth, PropertyProvider* aProvider, SuppressBreak aSuppressBreak,
gfxFloat* aTrimWhitespace, bool aWhitespaceCanHang, Metrics* aMetrics,
gfxFont::BoundingBoxType aBoundingBoxType, DrawTarget* aRefDrawTarget,
bool* aUsedHyphenation, uint32_t* aLastBreak, bool aCanWordWrap,
bool aCanWhitespaceWrap, gfxBreakPriority* aBreakPriority) {
aMaxLength = std::min(aMaxLength, GetLength() - aStart);
NS_ASSERTION(aStart + aMaxLength <= GetLength(), "Substring out of range");
Range bufferRange(
aStart, aStart + std::min<uint32_t>(aMaxLength, MEASUREMENT_BUFFER_SIZE));
PropertyProvider::Spacing spacingBuffer[MEASUREMENT_BUFFER_SIZE];
bool haveSpacing =
aProvider && !!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING);
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
AutoTArray<HyphenType, 4096> hyphenBuffer;
HyphenationState wordState;
wordState.mostRecentBoundary = aStart;
bool haveHyphenation =
aProvider &&
(aProvider->GetHyphensOption() == StyleHyphens::Auto ||
(aProvider->GetHyphensOption() == StyleHyphens::Manual &&
!!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_HYPHEN_BREAKS)));
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(bufferRange, hyphenBuffer.Elements());
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer, &wordState);
}
} else {
haveHyphenation = false;
}
}
gfxFloat width = 0;
gfxFloat advance = 0;
// The number of space characters that can be trimmed or hang at a soft-wrap
uint32_t trimmableChars = 0;
// The amount of space removed by ignoring trimmableChars
gfxFloat trimmableAdvance = 0;
int32_t lastBreak = -1;
int32_t lastBreakTrimmableChars = -1;
gfxFloat lastBreakTrimmableAdvance = -1;
// Cache the last candidate break
int32_t lastCandidateBreak = -1;
int32_t lastCandidateBreakTrimmableChars = -1;
gfxFloat lastCandidateBreakTrimmableAdvance = -1;
bool lastCandidateBreakUsedHyphenation = false;
gfxBreakPriority lastCandidateBreakPriority = gfxBreakPriority::eNoBreak;
bool aborted = false;
uint32_t end = aStart + aMaxLength;
bool lastBreakUsedHyphenation = false;
Range ligatureRange(aStart, end);
ShrinkToLigatureBoundaries(&ligatureRange);
// We may need to move `i` backwards in the following loop, and re-scan
// part of the textrun; we'll use `rescanLimit` so we can tell when that
// is happening: if `i < rescanLimit` then we're rescanning.
uint32_t rescanLimit = aStart;
for (uint32_t i = aStart; i < end; ++i) {
if (i >= bufferRange.end) {
// Fetch more spacing and hyphenation data
uint32_t oldHyphenBufferLength = hyphenBuffer.Length();
bufferRange.start = i;
bufferRange.end =
std::min(aStart + aMaxLength, i + MEASUREMENT_BUFFER_SIZE);
// For spacing, we always overwrite the old data with the newly
// fetched one. However, for hyphenation, hyphenation data sometimes
// depends on the context in every word (if "hyphens: auto" is set).
// To ensure we get enough information between neighboring buffers,
// we grow the hyphenBuffer instead of overwrite it.
// NOTE that this means bufferRange does not correspond to the
// entire hyphenBuffer, but only to the most recently added portion.
// Therefore, we need to add the old length to hyphenBuffer.Elements()
// when getting more data.
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(
bufferRange, hyphenBuffer.Elements() + oldHyphenBufferLength);
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
uint32_t prevMostRecentWordBoundary = wordState.mostRecentBoundary;
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer,
&wordState);
// If the buffer boundary is in the middle of a word,
// we need to go back to the start of the current word.
// So, we can correct the wrong candidates that we set
// in the previous runs of the loop.
if (prevMostRecentWordBoundary < oldHyphenBufferLength) {
rescanLimit = i;
i = prevMostRecentWordBoundary - 1;
continue;
}
}
} else {
haveHyphenation = false;
}
}
}
// There can't be a word-wrap break opportunity at the beginning of the
// line: if the width is too small for even one character to fit, it
// could be the first and last break opportunity on the line, and that
// would trigger an infinite loop.
if (aSuppressBreak != eSuppressAllBreaks &&
(aSuppressBreak != eSuppressInitialBreak || i > aStart)) {
bool atNaturalBreak = mCharacterGlyphs[i].CanBreakBefore() == 1;
// atHyphenationBreak indicates we're at a "soft" hyphen, where an extra
// hyphen glyph will need to be painted. It is NOT set for breaks at an