forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgfxFcPlatformFontList.cpp
2955 lines (2622 loc) · 100 KB
/
gfxFcPlatformFontList.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: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* 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 "mozilla/Logging.h"
#include "gfxFcPlatformFontList.h"
#include "gfxFont.h"
#include "gfxFontConstants.h"
#include "gfxFT2Utils.h"
#include "gfxPlatform.h"
#include "nsPresContext.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/Preferences.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "nsGkAtoms.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsUnicodeProperties.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsXULAppAPI.h"
#include "SharedFontList-impl.h"
#include "StandardFonts-linux.inc"
#include "mozilla/intl/Locale.h"
#include "mozilla/gfx/HelpersCairo.h"
#include <cairo-ft.h>
#include <fontconfig/fcfreetype.h>
#include <fontconfig/fontconfig.h>
#include <harfbuzz/hb.h>
#include <dlfcn.h>
#include <unistd.h>
#ifdef MOZ_WIDGET_GTK
# include <gdk/gdk.h>
# include <gtk/gtk.h>
# include "gfxPlatformGtk.h"
# include "mozilla/WidgetUtilsGtk.h"
#endif
#ifdef MOZ_X11
# include "mozilla/X11Util.h"
#endif
#if defined(MOZ_SANDBOX) && defined(XP_LINUX)
# include "mozilla/SandboxBrokerPolicyFactory.h"
# include "mozilla/SandboxSettings.h"
#endif
#include FT_MULTIPLE_MASTERS_H
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;
using namespace mozilla::intl;
#ifndef FC_POSTSCRIPT_NAME
# define FC_POSTSCRIPT_NAME "postscriptname" /* String */
#endif
#ifndef FC_VARIABLE
# define FC_VARIABLE "variable" /* Bool */
#endif
#define PRINTING_FC_PROPERTY "gfx.printing"
#define LOG_FONTLIST(args) \
MOZ_LOG(gfxPlatform::GetLog(eGfxLog_fontlist), LogLevel::Debug, args)
#define LOG_FONTLIST_ENABLED() \
MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_fontlist), LogLevel::Debug)
#define LOG_CMAPDATA_ENABLED() \
MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_cmapdata), LogLevel::Debug)
static const FcChar8* ToFcChar8Ptr(const char* aStr) {
return reinterpret_cast<const FcChar8*>(aStr);
}
static const char* ToCharPtr(const FcChar8* aStr) {
return reinterpret_cast<const char*>(aStr);
}
// canonical name ==> first en name or first name if no en name
// This is the required logic for fullname lookups as per CSS3 Fonts spec.
static uint32_t FindCanonicalNameIndex(FcPattern* aFont,
const char* aLangField) {
uint32_t n = 0, en = 0;
FcChar8* lang;
while (FcPatternGetString(aFont, aLangField, n, &lang) == FcResultMatch) {
// look for 'en' or variants, en-US, en-JP etc.
uint32_t len = strlen(ToCharPtr(lang));
bool enPrefix = (strncmp(ToCharPtr(lang), "en", 2) == 0);
if (enPrefix && (len == 2 || (len > 2 && aLangField[2] == '-'))) {
en = n;
break;
}
n++;
}
return en;
}
static void GetFaceNames(FcPattern* aFont, const nsACString& aFamilyName,
nsACString& aPostscriptName, nsACString& aFullname) {
// get the Postscript name
FcChar8* psname;
if (FcPatternGetString(aFont, FC_POSTSCRIPT_NAME, 0, &psname) ==
FcResultMatch) {
aPostscriptName = ToCharPtr(psname);
}
// get the canonical fullname (i.e. en name or first name)
uint32_t en = FindCanonicalNameIndex(aFont, FC_FULLNAMELANG);
FcChar8* fullname;
if (FcPatternGetString(aFont, FC_FULLNAME, en, &fullname) == FcResultMatch) {
aFullname = ToCharPtr(fullname);
}
// if have fullname, done
if (!aFullname.IsEmpty()) {
return;
}
// otherwise, set the fullname to family + style name [en] and use that
aFullname = aFamilyName;
// figure out the en style name
en = FindCanonicalNameIndex(aFont, FC_STYLELANG);
nsAutoCString style;
FcChar8* stylename = nullptr;
FcPatternGetString(aFont, FC_STYLE, en, &stylename);
if (stylename) {
style = ToCharPtr(stylename);
}
if (!style.IsEmpty() && !style.EqualsLiteral("Regular")) {
aFullname.Append(' ');
aFullname.Append(style);
}
}
static FontWeight MapFcWeight(int aFcWeight) {
if (aFcWeight <= (FC_WEIGHT_THIN + FC_WEIGHT_EXTRALIGHT) / 2) {
return FontWeight::FromInt(100);
}
if (aFcWeight <= (FC_WEIGHT_EXTRALIGHT + FC_WEIGHT_LIGHT) / 2) {
return FontWeight::FromInt(200);
}
if (aFcWeight <= (FC_WEIGHT_LIGHT + FC_WEIGHT_BOOK) / 2) {
return FontWeight::FromInt(300);
}
if (aFcWeight <= (FC_WEIGHT_REGULAR + FC_WEIGHT_MEDIUM) / 2) {
// This includes FC_WEIGHT_BOOK
return FontWeight::FromInt(400);
}
if (aFcWeight <= (FC_WEIGHT_MEDIUM + FC_WEIGHT_DEMIBOLD) / 2) {
return FontWeight::FromInt(500);
}
if (aFcWeight <= (FC_WEIGHT_DEMIBOLD + FC_WEIGHT_BOLD) / 2) {
return FontWeight::FromInt(600);
}
if (aFcWeight <= (FC_WEIGHT_BOLD + FC_WEIGHT_EXTRABOLD) / 2) {
return FontWeight::FromInt(700);
}
if (aFcWeight <= (FC_WEIGHT_EXTRABOLD + FC_WEIGHT_BLACK) / 2) {
return FontWeight::FromInt(800);
}
if (aFcWeight <= FC_WEIGHT_BLACK) {
return FontWeight::FromInt(900);
}
// including FC_WEIGHT_EXTRABLACK
return FontWeight::FromInt(901);
}
// TODO(emilio, jfkthame): I think this can now be more fine-grained.
static FontStretch MapFcWidth(int aFcWidth) {
if (aFcWidth <= (FC_WIDTH_ULTRACONDENSED + FC_WIDTH_EXTRACONDENSED) / 2) {
return FontStretch::ULTRA_CONDENSED;
}
if (aFcWidth <= (FC_WIDTH_EXTRACONDENSED + FC_WIDTH_CONDENSED) / 2) {
return FontStretch::EXTRA_CONDENSED;
}
if (aFcWidth <= (FC_WIDTH_CONDENSED + FC_WIDTH_SEMICONDENSED) / 2) {
return FontStretch::CONDENSED;
}
if (aFcWidth <= (FC_WIDTH_SEMICONDENSED + FC_WIDTH_NORMAL) / 2) {
return FontStretch::SEMI_CONDENSED;
}
if (aFcWidth <= (FC_WIDTH_NORMAL + FC_WIDTH_SEMIEXPANDED) / 2) {
return FontStretch::NORMAL;
}
if (aFcWidth <= (FC_WIDTH_SEMIEXPANDED + FC_WIDTH_EXPANDED) / 2) {
return FontStretch::SEMI_EXPANDED;
}
if (aFcWidth <= (FC_WIDTH_EXPANDED + FC_WIDTH_EXTRAEXPANDED) / 2) {
return FontStretch::EXPANDED;
}
if (aFcWidth <= (FC_WIDTH_EXTRAEXPANDED + FC_WIDTH_ULTRAEXPANDED) / 2) {
return FontStretch::EXTRA_EXPANDED;
}
return FontStretch::ULTRA_EXPANDED;
}
static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight,
StretchRange* aStretch,
SlantStyleRange* aSlantStyle,
uint16_t* aSize = nullptr) {
// weight
int weight;
if (FcPatternGetInteger(aFontPattern, FC_WEIGHT, 0, &weight) !=
FcResultMatch) {
weight = FC_WEIGHT_REGULAR;
}
*aWeight = WeightRange(MapFcWeight(weight));
// width
int width;
if (FcPatternGetInteger(aFontPattern, FC_WIDTH, 0, &width) != FcResultMatch) {
width = FC_WIDTH_NORMAL;
}
*aStretch = StretchRange(MapFcWidth(width));
// italic
int slant;
if (FcPatternGetInteger(aFontPattern, FC_SLANT, 0, &slant) != FcResultMatch) {
slant = FC_SLANT_ROMAN;
}
if (slant == FC_SLANT_OBLIQUE) {
*aSlantStyle = SlantStyleRange(FontSlantStyle::OBLIQUE);
} else if (slant > 0) {
*aSlantStyle = SlantStyleRange(FontSlantStyle::ITALIC);
}
if (aSize) {
// pixel size, or zero if scalable
FcBool scalable;
if (FcPatternGetBool(aFontPattern, FC_SCALABLE, 0, &scalable) ==
FcResultMatch &&
scalable) {
*aSize = 0;
} else {
double size;
if (FcPatternGetDouble(aFontPattern, FC_PIXEL_SIZE, 0, &size) ==
FcResultMatch) {
*aSize = uint16_t(NS_round(size));
} else {
*aSize = 0;
}
}
}
}
void gfxFontconfigFontEntry::GetUserFontFeatures(FcPattern* aPattern) {
int fontFeaturesNum = 0;
char* s;
hb_feature_t tmpFeature;
while (FcResultMatch == FcPatternGetString(aPattern, "fontfeatures",
fontFeaturesNum, (FcChar8**)&s)) {
bool ret = hb_feature_from_string(s, -1, &tmpFeature);
if (ret) {
mFeatureSettings.AppendElement(
(gfxFontFeature){tmpFeature.tag, tmpFeature.value});
}
fontFeaturesNum++;
}
}
gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
FcPattern* aFontPattern,
bool aIgnoreFcCharmap)
: gfxFT2FontEntryBase(aFaceName),
mFontPattern(aFontPattern),
mFTFaceInitialized(false),
mIgnoreFcCharmap(aIgnoreFcCharmap) {
GetFontProperties(aFontPattern, &mWeightRange, &mStretchRange, &mStyleRange);
GetUserFontFeatures(mFontPattern);
}
gfxFontEntry* gfxFontconfigFontEntry::Clone() const {
MOZ_ASSERT(!IsUserFont(), "we can only clone installed fonts!");
return new gfxFontconfigFontEntry(Name(), mFontPattern, mIgnoreFcCharmap);
}
static already_AddRefed<FcPattern> CreatePatternForFace(FT_Face aFace) {
// Use fontconfig to fill out the pattern from the FTFace.
// The "file" argument cannot be nullptr (in fontconfig-2.6.0 at
// least). The dummy file passed here is removed below.
//
// When fontconfig scans the system fonts, FcConfigGetBlanks(nullptr)
// is passed as the "blanks" argument, which provides that unexpectedly
// blank glyphs are elided. Here, however, we pass nullptr for
// "blanks", effectively assuming that, if the font has a blank glyph,
// then the author intends any associated character to be rendered
// blank.
RefPtr<FcPattern> pattern =
dont_AddRef(FcFreeTypeQueryFace(aFace, ToFcChar8Ptr(""), 0, nullptr));
// given that we have a FT_Face, not really sure this is possible...
if (!pattern) {
pattern = dont_AddRef(FcPatternCreate());
}
FcPatternDel(pattern, FC_FILE);
FcPatternDel(pattern, FC_INDEX);
// Make a new pattern and store the face in it so that cairo uses
// that when creating a cairo font face.
FcPatternAddFTFace(pattern, FC_FT_FACE, aFace);
return pattern.forget();
}
static already_AddRefed<SharedFTFace> CreateFaceForPattern(
FcPattern* aPattern) {
FcChar8* filename;
if (FcPatternGetString(aPattern, FC_FILE, 0, &filename) != FcResultMatch) {
return nullptr;
}
int index;
if (FcPatternGetInteger(aPattern, FC_INDEX, 0, &index) != FcResultMatch) {
index = 0; // default to 0 if not found in pattern
}
return Factory::NewSharedFTFace(nullptr, ToCharPtr(filename), index);
}
gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
WeightRange aWeight,
StretchRange aStretch,
SlantStyleRange aStyle,
RefPtr<SharedFTFace>&& aFace)
: gfxFT2FontEntryBase(aFaceName),
mFontPattern(CreatePatternForFace(aFace->GetFace())),
mFTFace(aFace.forget().take()),
mFTFaceInitialized(true),
mIgnoreFcCharmap(true) {
mWeightRange = aWeight;
mStyleRange = aStyle;
mStretchRange = aStretch;
mIsDataUserFont = true;
}
gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
FcPattern* aFontPattern,
WeightRange aWeight,
StretchRange aStretch,
SlantStyleRange aStyle)
: gfxFT2FontEntryBase(aFaceName),
mFontPattern(aFontPattern),
mFTFaceInitialized(false) {
mWeightRange = aWeight;
mStyleRange = aStyle;
mStretchRange = aStretch;
mIsLocalUserFont = true;
// The proper setting of mIgnoreFcCharmap is tricky for fonts loaded
// via src:local()...
// If the local font happens to come from the application fontset,
// we want to set it to true so that color/svg fonts will work even
// if the default glyphs are blank; but if the local font is a non-
// sfnt face (e.g. legacy type 1) then we need to set it to false
// because our cmap-reading code will fail and we depend on FT+Fc to
// determine the coverage.
// We set the flag here, but may flip it the first time TestCharacterMap
// is called, at which point we'll look to see whether a 'cmap' is
// actually present in the font.
mIgnoreFcCharmap = true;
GetUserFontFeatures(mFontPattern);
}
typedef FT_Error (*GetVarFunc)(FT_Face, FT_MM_Var**);
typedef FT_Error (*DoneVarFunc)(FT_Library, FT_MM_Var*);
static GetVarFunc sGetVar;
static DoneVarFunc sDoneVar;
static bool sInitializedVarFuncs = false;
static void InitializeVarFuncs() {
if (sInitializedVarFuncs) {
return;
}
sInitializedVarFuncs = true;
#if MOZ_TREE_FREETYPE
sGetVar = &FT_Get_MM_Var;
sDoneVar = &FT_Done_MM_Var;
#else
sGetVar = (GetVarFunc)dlsym(RTLD_DEFAULT, "FT_Get_MM_Var");
sDoneVar = (DoneVarFunc)dlsym(RTLD_DEFAULT, "FT_Done_MM_Var");
#endif
}
gfxFontconfigFontEntry::~gfxFontconfigFontEntry() {
if (mMMVar) {
// Prior to freetype 2.9, there was no specific function to free the
// FT_MM_Var record, and the docs just said to use free().
// InitializeVarFuncs must have been called in order for mMMVar to be
// non-null here, so we don't need to do it again.
if (sDoneVar) {
auto ftFace = GetFTFace();
MOZ_ASSERT(ftFace, "How did mMMVar get set without a face?");
(*sDoneVar)(ftFace->GetFace()->glyph->library, mMMVar);
} else {
free(mMMVar);
}
}
if (mFTFaceInitialized) {
auto face = mFTFace.exchange(nullptr);
NS_IF_RELEASE(face);
}
}
nsresult gfxFontconfigFontEntry::ReadCMAP(FontInfoData* aFontInfoData) {
// attempt this once, if errors occur leave a blank cmap
if (mCharacterMap) {
return NS_OK;
}
RefPtr<gfxCharacterMap> charmap;
nsresult rv;
uint32_t uvsOffset = 0;
if (aFontInfoData &&
(charmap = GetCMAPFromFontInfo(aFontInfoData, uvsOffset))) {
rv = NS_OK;
} else {
uint32_t kCMAP = TRUETYPE_TAG('c', 'm', 'a', 'p');
charmap = new gfxCharacterMap();
AutoTable cmapTable(this, kCMAP);
if (cmapTable) {
uint32_t cmapLen;
const uint8_t* cmapData = reinterpret_cast<const uint8_t*>(
hb_blob_get_data(cmapTable, &cmapLen));
rv = gfxFontUtils::ReadCMAP(cmapData, cmapLen, *charmap, uvsOffset);
} else {
rv = NS_ERROR_NOT_AVAILABLE;
}
}
mUVSOffset.exchange(uvsOffset);
bool setCharMap = true;
if (NS_SUCCEEDED(rv)) {
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
fontlist::FontList* sharedFontList = pfl->SharedFontList();
if (!IsUserFont() && mShmemFace) {
mShmemFace->SetCharacterMap(sharedFontList, charmap); // async
if (TrySetShmemCharacterMap()) {
setCharMap = false;
}
} else {
charmap = pfl->FindCharMap(charmap);
}
mHasCmapTable = true;
} else {
// if error occurred, initialize to null cmap
charmap = new gfxCharacterMap();
mHasCmapTable = false;
}
if (setCharMap) {
if (mCharacterMap.compareExchange(nullptr, charmap.get())) {
charmap.get()->AddRef();
}
}
LOG_FONTLIST(("(fontlist-cmap) name: %s, size: %zu hash: %8.8x%s\n",
mName.get(), charmap->SizeOfIncludingThis(moz_malloc_size_of),
charmap->mHash, mCharacterMap == charmap ? " new" : ""));
if (LOG_CMAPDATA_ENABLED()) {
char prefix[256];
SprintfLiteral(prefix, "(cmapdata) name: %.220s", mName.get());
charmap->Dump(prefix, eGfxLog_cmapdata);
}
return rv;
}
static bool HasChar(FcPattern* aFont, FcChar32 aCh) {
FcCharSet* charset = nullptr;
FcPatternGetCharSet(aFont, FC_CHARSET, 0, &charset);
return charset && FcCharSetHasChar(charset, aCh);
}
bool gfxFontconfigFontEntry::TestCharacterMap(uint32_t aCh) {
// For user fonts, or for fonts bundled with the app (which might include
// color/svg glyphs where the default glyphs may be blank, and thus confuse
// fontconfig/freetype's char map checking), we instead check the cmap
// directly for character coverage.
if (mIgnoreFcCharmap) {
// If it does not actually have a cmap, switch our strategy to use
// fontconfig's charmap after all (except for data fonts, which must
// always have a cmap to have passed OTS validation).
if (!mIsDataUserFont && !HasFontTable(TRUETYPE_TAG('c', 'm', 'a', 'p'))) {
mIgnoreFcCharmap = false;
// ...and continue with HasChar() below.
} else {
return gfxFontEntry::TestCharacterMap(aCh);
}
}
// otherwise (for system fonts), use the charmap in the pattern
return HasChar(mFontPattern, aCh);
}
bool gfxFontconfigFontEntry::HasFontTable(uint32_t aTableTag) {
if (FTUserFontData* ufd = GetUserFontData()) {
if (ufd->FontData()) {
return !!gfxFontUtils::FindTableDirEntry(ufd->FontData(), aTableTag);
}
}
return gfxFT2FontEntryBase::FaceHasTable(GetFTFace(), aTableTag);
}
hb_blob_t* gfxFontconfigFontEntry::GetFontTable(uint32_t aTableTag) {
// for data fonts, read directly from the font data
if (FTUserFontData* ufd = GetUserFontData()) {
if (ufd->FontData()) {
return gfxFontUtils::GetTableFromFontData(ufd->FontData(), aTableTag);
}
}
return gfxFontEntry::GetFontTable(aTableTag);
}
double gfxFontconfigFontEntry::GetAspect(uint8_t aSizeAdjustBasis) {
using FontSizeAdjust = gfxFont::FontSizeAdjust;
if (FontSizeAdjust::Tag(aSizeAdjustBasis) == FontSizeAdjust::Tag::ExHeight ||
FontSizeAdjust::Tag(aSizeAdjustBasis) == FontSizeAdjust::Tag::CapHeight) {
// try to compute aspect from OS/2 metrics if available
AutoTable os2Table(this, TRUETYPE_TAG('O', 'S', '/', '2'));
if (os2Table) {
uint16_t upem = UnitsPerEm();
if (upem != kInvalidUPEM) {
uint32_t len;
const auto* os2 =
reinterpret_cast<const OS2Table*>(hb_blob_get_data(os2Table, &len));
if (uint16_t(os2->version) >= 2) {
// XXX(jfkthame) Other implementations don't have the check for
// values <= 0.1em; should we drop that here? Just require it to be
// a positive number?
if (FontSizeAdjust::Tag(aSizeAdjustBasis) ==
FontSizeAdjust::Tag::ExHeight) {
if (len >= offsetof(OS2Table, sxHeight) + sizeof(int16_t) &&
int16_t(os2->sxHeight) > 0.1 * upem) {
return double(int16_t(os2->sxHeight)) / upem;
}
}
if (FontSizeAdjust::Tag(aSizeAdjustBasis) ==
FontSizeAdjust::Tag::CapHeight) {
if (len >= offsetof(OS2Table, sCapHeight) + sizeof(int16_t) &&
int16_t(os2->sCapHeight) > 0.1 * upem) {
return double(int16_t(os2->sCapHeight)) / upem;
}
}
}
}
}
}
// create a font to calculate the requested aspect
gfxFontStyle s;
s.size = 256.0; // pick large size to reduce hinting artifacts
RefPtr<gfxFont> font = FindOrMakeFont(&s);
if (font) {
const gfxFont::Metrics& metrics =
font->GetMetrics(nsFontMetrics::eHorizontal);
if (metrics.emHeight == 0) {
return 0;
}
switch (FontSizeAdjust::Tag(aSizeAdjustBasis)) {
case FontSizeAdjust::Tag::ExHeight:
return metrics.xHeight / metrics.emHeight;
case FontSizeAdjust::Tag::CapHeight:
return metrics.capHeight / metrics.emHeight;
case FontSizeAdjust::Tag::ChWidth:
return metrics.zeroWidth > 0 ? metrics.zeroWidth / metrics.emHeight
: 0.5;
case FontSizeAdjust::Tag::IcWidth:
case FontSizeAdjust::Tag::IcHeight: {
bool vertical = FontSizeAdjust::Tag(aSizeAdjustBasis) ==
FontSizeAdjust::Tag::IcHeight;
gfxFloat advance =
font->GetCharAdvance(gfxFont::kWaterIdeograph, vertical);
return advance > 0 ? advance / metrics.emHeight : 1.0;
}
default:
break;
}
}
MOZ_ASSERT_UNREACHABLE("failed to compute size-adjust aspect");
return 0.5;
}
static void PrepareFontOptions(FcPattern* aPattern, int* aOutLoadFlags,
unsigned int* aOutSynthFlags) {
int loadFlags = FT_LOAD_DEFAULT;
unsigned int synthFlags = 0;
// xxx - taken from the gfxFontconfigFonts code, needs to be reviewed
FcBool printing;
if (FcPatternGetBool(aPattern, PRINTING_FC_PROPERTY, 0, &printing) !=
FcResultMatch) {
printing = FcFalse;
}
// Font options are set explicitly here to improve cairo's caching
// behavior and to record the relevant parts of the pattern so that
// the pattern can be released.
//
// Most font_options have already been set as defaults on the FcPattern
// with cairo_ft_font_options_substitute(), then user and system
// fontconfig configurations were applied. The resulting font_options
// have been recorded on the face during
// cairo_ft_font_face_create_for_pattern().
//
// None of the settings here cause this scaled_font to behave any
// differently from how it would behave if it were created from the same
// face with default font_options.
//
// We set options explicitly so that the same scaled_font will be found in
// the cairo_scaled_font_map when cairo loads glyphs from a context with
// the same font_face, font_matrix, ctm, and surface font_options.
//
// Unfortunately, _cairo_scaled_font_keys_equal doesn't know about the
// font_options on the cairo_ft_font_face, and doesn't consider default
// option values to not match any explicit values.
//
// Even after cairo_set_scaled_font is used to set font_options for the
// cairo context, when cairo looks for a scaled_font for the context, it
// will look for a font with some option values from the target surface if
// any values are left default on the context font_options. If this
// scaled_font is created with default font_options, cairo will not find
// it.
//
// The one option not recorded in the pattern is hint_metrics, which will
// affect glyph metrics. The default behaves as CAIRO_HINT_METRICS_ON.
// We should be considering the font_options of the surface on which this
// font will be used, but currently we don't have different gfxFonts for
// different surface font_options, so we'll create a font suitable for the
// Screen. Image and xlib surfaces default to CAIRO_HINT_METRICS_ON.
// The remaining options have been recorded on the pattern and the face.
// _cairo_ft_options_merge has some logic to decide which options from the
// scaled_font or from the cairo_ft_font_face take priority in the way the
// font behaves.
//
// In the majority of cases, _cairo_ft_options_merge uses the options from
// the cairo_ft_font_face, so sometimes it is not so important which
// values are set here so long as they are not defaults, but we'll set
// them to the exact values that we expect from the font, to be consistent
// and to protect against changes in cairo.
//
// In some cases, _cairo_ft_options_merge uses some options from the
// scaled_font's font_options rather than options on the
// cairo_ft_font_face (from fontconfig).
// https://bugs.freedesktop.org/show_bug.cgi?id=11838
//
// Surface font options were set on the pattern in
// cairo_ft_font_options_substitute. If fontconfig has changed the
// hint_style then that is what the user (or distribution) wants, so we
// use the setting from the FcPattern.
//
// Fallback values here mirror treatment of defaults in cairo-ft-font.c.
FcBool hinting = FcFalse;
if (FcPatternGetBool(aPattern, FC_HINTING, 0, &hinting) != FcResultMatch) {
hinting = FcTrue;
}
int fc_hintstyle = FC_HINT_NONE;
if (!printing && hinting &&
FcPatternGetInteger(aPattern, FC_HINT_STYLE, 0, &fc_hintstyle) !=
FcResultMatch) {
fc_hintstyle = FC_HINT_FULL;
}
switch (fc_hintstyle) {
case FC_HINT_NONE:
loadFlags = FT_LOAD_NO_HINTING;
break;
case FC_HINT_SLIGHT:
loadFlags = FT_LOAD_TARGET_LIGHT;
break;
}
FcBool fc_antialias;
if (FcPatternGetBool(aPattern, FC_ANTIALIAS, 0, &fc_antialias) !=
FcResultMatch) {
fc_antialias = FcTrue;
}
if (!fc_antialias) {
if (fc_hintstyle != FC_HINT_NONE) {
loadFlags = FT_LOAD_TARGET_MONO;
}
loadFlags |= FT_LOAD_MONOCHROME;
} else if (fc_hintstyle == FC_HINT_FULL) {
int fc_rgba;
if (FcPatternGetInteger(aPattern, FC_RGBA, 0, &fc_rgba) != FcResultMatch) {
fc_rgba = FC_RGBA_UNKNOWN;
}
switch (fc_rgba) {
case FC_RGBA_RGB:
case FC_RGBA_BGR:
loadFlags = FT_LOAD_TARGET_LCD;
break;
case FC_RGBA_VRGB:
case FC_RGBA_VBGR:
loadFlags = FT_LOAD_TARGET_LCD_V;
break;
}
}
if (!FcPatternAllowsBitmaps(aPattern, fc_antialias != FcFalse,
fc_hintstyle != FC_HINT_NONE)) {
loadFlags |= FT_LOAD_NO_BITMAP;
}
FcBool autohint;
if (FcPatternGetBool(aPattern, FC_AUTOHINT, 0, &autohint) == FcResultMatch &&
autohint) {
loadFlags |= FT_LOAD_FORCE_AUTOHINT;
}
FcBool embolden;
if (FcPatternGetBool(aPattern, FC_EMBOLDEN, 0, &embolden) == FcResultMatch &&
embolden) {
synthFlags |= CAIRO_FT_SYNTHESIZE_BOLD;
}
*aOutLoadFlags = loadFlags;
*aOutSynthFlags = synthFlags;
}
#ifdef MOZ_X11
static bool GetXftInt(Display* aDisplay, const char* aName, int* aResult) {
if (!aDisplay) {
return false;
}
char* value = XGetDefault(aDisplay, "Xft", aName);
if (!value) {
return false;
}
if (FcNameConstant(const_cast<FcChar8*>(ToFcChar8Ptr(value)), aResult)) {
return true;
}
char* end;
*aResult = strtol(value, &end, 0);
if (end != value) {
return true;
}
return false;
}
#endif
static void PreparePattern(FcPattern* aPattern, bool aIsPrinterFont) {
FcConfigSubstitute(nullptr, aPattern, FcMatchPattern);
// This gets cairo_font_options_t for the Screen. We should have
// different font options for printing (no hinting) but we are not told
// what we are measuring for.
//
// If cairo adds support for lcd_filter, gdk will not provide the default
// setting for that option. We could get the default setting by creating
// an xlib surface once, recording its font_options, and then merging the
// gdk options.
//
// Using an xlib surface would also be an option to get Screen font
// options for non-GTK X11 toolkits, but less efficient than using GDK to
// pick up dynamic changes.
if (aIsPrinterFont) {
cairo_font_options_t* options = cairo_font_options_create();
cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_NONE);
cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
cairo_ft_font_options_substitute(options, aPattern);
cairo_font_options_destroy(options);
FcPatternAddBool(aPattern, PRINTING_FC_PROPERTY, FcTrue);
#ifdef MOZ_WIDGET_GTK
} else {
gfxFcPlatformFontList::PlatformFontList()->SubstituteSystemFontOptions(
aPattern);
#endif // MOZ_WIDGET_GTK
}
FcDefaultSubstitute(aPattern);
}
void gfxFontconfigFontEntry::UnscaledFontCache::MoveToFront(size_t aIndex) {
if (aIndex > 0) {
ThreadSafeWeakPtr<UnscaledFontFontconfig> front =
std::move(mUnscaledFonts[aIndex]);
for (size_t i = aIndex; i > 0; i--) {
mUnscaledFonts[i] = std::move(mUnscaledFonts[i - 1]);
}
mUnscaledFonts[0] = std::move(front);
}
}
already_AddRefed<UnscaledFontFontconfig>
gfxFontconfigFontEntry::UnscaledFontCache::Lookup(const std::string& aFile,
uint32_t aIndex) {
for (size_t i = 0; i < kNumEntries; i++) {
RefPtr<UnscaledFontFontconfig> entry(mUnscaledFonts[i]);
if (entry && entry->GetFile() == aFile && entry->GetIndex() == aIndex) {
MoveToFront(i);
return entry.forget();
}
}
return nullptr;
}
static inline gfxFloat SizeForStyle(gfxFontconfigFontEntry* aEntry,
const gfxFontStyle& aStyle) {
return StyleFontSizeAdjust::Tag(aStyle.sizeAdjustBasis) !=
StyleFontSizeAdjust::Tag::None
? aStyle.GetAdjustedSize(aEntry->GetAspect(aStyle.sizeAdjustBasis))
: aStyle.size * aEntry->mSizeAdjust;
}
static double ChooseFontSize(gfxFontconfigFontEntry* aEntry,
const gfxFontStyle& aStyle) {
double requestedSize = SizeForStyle(aEntry, aStyle);
double bestDist = -1.0;
double bestSize = requestedSize;
double size;
int v = 0;
while (FcPatternGetDouble(aEntry->GetPattern(), FC_PIXEL_SIZE, v, &size) ==
FcResultMatch) {
++v;
double dist = fabs(size - requestedSize);
if (bestDist < 0.0 || dist < bestDist) {
bestDist = dist;
bestSize = size;
}
}
// If the font has bitmaps but wants to be scaled, then let it scale.
if (bestSize >= 0.0) {
FcBool scalable;
if (FcPatternGetBool(aEntry->GetPattern(), FC_SCALABLE, 0, &scalable) ==
FcResultMatch &&
scalable) {
return requestedSize;
}
}
return bestSize;
}
gfxFont* gfxFontconfigFontEntry::CreateFontInstance(
const gfxFontStyle* aFontStyle) {
RefPtr<FcPattern> pattern = dont_AddRef(FcPatternCreate());
if (!pattern) {
NS_WARNING("Failed to create Fontconfig pattern for font instance");
return nullptr;
}
double size = ChooseFontSize(this, *aFontStyle);
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, size);
RefPtr<SharedFTFace> face = GetFTFace();
if (!face) {
NS_WARNING("Failed to get FreeType face for pattern");
return nullptr;
}
if (HasVariations()) {
// For variation fonts, we create a new FT_Face here so that
// variation coordinates from the style can be applied without
// affecting other font instances created from the same entry
// (font resource).
// For user fonts: create a new FT_Face from the font data, and then make
// a pattern from that.
// For system fonts: create a new FT_Face and store it in a copy of the
// original mFontPattern.
RefPtr<SharedFTFace> varFace = face->GetData()
? face->GetData()->CloneFace()
: CreateFaceForPattern(mFontPattern);
if (varFace) {
AutoTArray<gfxFontVariation, 8> settings;
GetVariationsForStyle(settings, *aFontStyle);
gfxFT2FontBase::SetupVarCoords(GetMMVar(), settings, varFace->GetFace());
face = std::move(varFace);
}
}
PreparePattern(pattern, aFontStyle->printerFont);
RefPtr<FcPattern> renderPattern =
dont_AddRef(FcFontRenderPrepare(nullptr, pattern, mFontPattern));
if (!renderPattern) {
NS_WARNING("Failed to prepare Fontconfig pattern for font instance");
return nullptr;
}
if (aFontStyle->NeedsSyntheticBold(this)) {
FcPatternAddBool(renderPattern, FC_EMBOLDEN, FcTrue);
}
// will synthetic oblique be applied using a transform?
if (IsUpright() && !aFontStyle->style.IsNormal() &&
aFontStyle->allowSyntheticStyle) {
// disable embedded bitmaps (mimics behavior in 90-synthetic.conf)
FcPatternDel(renderPattern, FC_EMBEDDED_BITMAP);
FcPatternAddBool(renderPattern, FC_EMBEDDED_BITMAP, FcFalse);
}
int loadFlags;
unsigned int synthFlags;
PrepareFontOptions(renderPattern, &loadFlags, &synthFlags);
std::string file;
int index = 0;
if (!face->GetData()) {
const FcChar8* fcFile;
if (FcPatternGetString(renderPattern, FC_FILE, 0,
const_cast<FcChar8**>(&fcFile)) != FcResultMatch ||
FcPatternGetInteger(renderPattern, FC_INDEX, 0, &index) !=
FcResultMatch) {
NS_WARNING("No file in Fontconfig pattern for font instance");
return nullptr;
}
file = ToCharPtr(fcFile);
}
RefPtr<UnscaledFontFontconfig> unscaledFont;
{
AutoReadLock lock(mLock);
unscaledFont = mUnscaledFontCache.Lookup(file, index);
}
if (!unscaledFont) {
AutoWriteLock lock(mLock);
// Here, we use the original mFTFace, not a potential clone with variation
// settings applied.
auto ftFace = GetFTFace();
unscaledFont = ftFace->GetData() ? new UnscaledFontFontconfig(ftFace)
: new UnscaledFontFontconfig(
std::move(file), index, ftFace);
mUnscaledFontCache.Add(unscaledFont);
}
gfxFont* newFont = new gfxFontconfigFont(
unscaledFont, std::move(face), renderPattern, size, this, aFontStyle,
loadFlags, (synthFlags & CAIRO_FT_SYNTHESIZE_BOLD) != 0);
return newFont;
}
SharedFTFace* gfxFontconfigFontEntry::GetFTFace() {
if (!mFTFaceInitialized) {
RefPtr<SharedFTFace> face = CreateFaceForPattern(mFontPattern);
if (face) {
if (mFTFace.compareExchange(nullptr, face.get())) {
Unused << face.forget(); // The reference is now owned by mFTFace.
mFTFaceInitialized = true;
} else {
// We lost a race to set mFTFace! Just discard our new face.
}
}
}
return mFTFace;
}
FTUserFontData* gfxFontconfigFontEntry::GetUserFontData() {
auto face = GetFTFace();
if (face && face->GetData()) {
return static_cast<FTUserFontData*>(face->GetData());
}
return nullptr;
}
bool gfxFontconfigFontEntry::HasVariations() {
// If the answer is already cached, just return it.
switch (mHasVariations) {
case HasVariationsState::No:
return false;
case HasVariationsState::Yes:
return true;
case HasVariationsState::Uninitialized:
break;
}
// Figure out whether we have variations, and record in mHasVariations.
// (It doesn't matter if we race with another thread to set this; the result
// will be the same.)
if (!gfxPlatform::HasVariationFontSupport()) {
mHasVariations = HasVariationsState::No;
return false;
}
// For installed fonts, query the fontconfig pattern rather than paying
// the cost of loading a FT_Face that we otherwise might never need.
if (!IsUserFont() || IsLocalUserFont()) {
FcBool variable;
if ((FcPatternGetBool(mFontPattern, FC_VARIABLE, 0, &variable) ==
FcResultMatch) &&
variable) {
mHasVariations = HasVariationsState::Yes;
return true;
}