-
Notifications
You must be signed in to change notification settings - Fork 54
/
gfxPlatformFontList.cpp
1674 lines (1437 loc) · 55.2 KB
/
gfxPlatformFontList.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 "mozilla/intl/LocaleService.h"
#include "mozilla/intl/MozLocale.h"
#include "mozilla/intl/OSPreferences.h"
#include "gfxPlatformFontList.h"
#include "gfxTextRun.h"
#include "gfxUserFontSet.h"
#include "nsCRT.h"
#include "nsGkAtoms.h"
#include "nsServiceManagerUtils.h"
#include "nsUnicharUtils.h"
#include "nsUnicodeRange.h"
#include "nsUnicodeProperties.h"
#include "nsXULAppAPI.h"
#include "mozilla/Attributes.h"
#include "mozilla/Likely.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Mutex.h"
#include "mozilla/Preferences.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/gfx/2D.h"
#include <locale.h>
using namespace mozilla;
using mozilla::intl::Locale;
using mozilla::intl::LocaleService;
using mozilla::intl::OSPreferences;
#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_FONTINIT(args) \
MOZ_LOG(gfxPlatform::GetLog(eGfxLog_fontinit), LogLevel::Debug, args)
#define LOG_FONTINIT_ENABLED() \
MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_fontinit), LogLevel::Debug)
gfxPlatformFontList* gfxPlatformFontList::sPlatformFontList = nullptr;
// Character ranges that require complex-script shaping support in the font,
// and so should be masked out by ReadCMAP if the necessary layout tables
// are not present.
// Currently used by the Mac and FT2 implementations only, but probably should
// be supported on Windows as well.
const gfxFontEntry::ScriptRange gfxPlatformFontList::sComplexScriptRanges[] = {
// Actually, now that harfbuzz supports presentation-forms shaping for
// Arabic, we can render it without layout tables. So maybe we don't
// want to mask the basic Arabic block here?
// This affects the arabic-fallback-*.html reftests, which rely on
// loading a font that *doesn't* have any GSUB table.
{0x0600, 0x06FF, {TRUETYPE_TAG('a', 'r', 'a', 'b'), 0, 0}},
{0x0700, 0x074F, {TRUETYPE_TAG('s', 'y', 'r', 'c'), 0, 0}},
{0x0750, 0x077F, {TRUETYPE_TAG('a', 'r', 'a', 'b'), 0, 0}},
{0x08A0, 0x08FF, {TRUETYPE_TAG('a', 'r', 'a', 'b'), 0, 0}},
{0x0900,
0x097F,
{TRUETYPE_TAG('d', 'e', 'v', '2'), TRUETYPE_TAG('d', 'e', 'v', 'a'), 0}},
{0x0980,
0x09FF,
{TRUETYPE_TAG('b', 'n', 'g', '2'), TRUETYPE_TAG('b', 'e', 'n', 'g'), 0}},
{0x0A00,
0x0A7F,
{TRUETYPE_TAG('g', 'u', 'r', '2'), TRUETYPE_TAG('g', 'u', 'r', 'u'), 0}},
{0x0A80,
0x0AFF,
{TRUETYPE_TAG('g', 'j', 'r', '2'), TRUETYPE_TAG('g', 'u', 'j', 'r'), 0}},
{0x0B00,
0x0B7F,
{TRUETYPE_TAG('o', 'r', 'y', '2'), TRUETYPE_TAG('o', 'r', 'y', 'a'), 0}},
{0x0B80,
0x0BFF,
{TRUETYPE_TAG('t', 'm', 'l', '2'), TRUETYPE_TAG('t', 'a', 'm', 'l'), 0}},
{0x0C00,
0x0C7F,
{TRUETYPE_TAG('t', 'e', 'l', '2'), TRUETYPE_TAG('t', 'e', 'l', 'u'), 0}},
{0x0C80,
0x0CFF,
{TRUETYPE_TAG('k', 'n', 'd', '2'), TRUETYPE_TAG('k', 'n', 'd', 'a'), 0}},
{0x0D00,
0x0D7F,
{TRUETYPE_TAG('m', 'l', 'm', '2'), TRUETYPE_TAG('m', 'l', 'y', 'm'), 0}},
{0x0D80, 0x0DFF, {TRUETYPE_TAG('s', 'i', 'n', 'h'), 0, 0}},
{0x0E80, 0x0EFF, {TRUETYPE_TAG('l', 'a', 'o', ' '), 0, 0}},
{0x0F00, 0x0FFF, {TRUETYPE_TAG('t', 'i', 'b', 't'), 0, 0}},
{0x1000,
0x109f,
{TRUETYPE_TAG('m', 'y', 'm', 'r'), TRUETYPE_TAG('m', 'y', 'm', '2'), 0}},
{0x1780, 0x17ff, {TRUETYPE_TAG('k', 'h', 'm', 'r'), 0, 0}},
// Khmer Symbols (19e0..19ff) don't seem to need any special shaping
{0xaa60,
0xaa7f,
{TRUETYPE_TAG('m', 'y', 'm', 'r'), TRUETYPE_TAG('m', 'y', 'm', '2'), 0}},
// Thai seems to be "renderable" without AAT morphing tables
{0, 0, {0, 0, 0}} // terminator
};
// prefs for the font info loader
#define FONT_LOADER_DELAY_PREF "gfx.font_loader.delay"
#define FONT_LOADER_INTERVAL_PREF "gfx.font_loader.interval"
static const char* kObservedPrefs[] = {"font.", "font.name-list.",
"intl.accept_languages", // hmmmm...
nullptr};
static const char kFontSystemWhitelistPref[] = "font.system.whitelist";
// xxx - this can probably be eliminated by reworking pref font handling code
static const char* gPrefLangNames[] = {
#define FONT_PREF_LANG(enum_id_, str_, atom_id_) str_
#include "gfxFontPrefLangList.h"
#undef FONT_PREF_LANG
};
static_assert(MOZ_ARRAY_LENGTH(gPrefLangNames) == uint32_t(eFontPrefLang_Count),
"size of pref lang name array doesn't match pref lang enum size");
class gfxFontListPrefObserver final : public nsIObserver {
~gfxFontListPrefObserver() {}
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
};
static void FontListPrefChanged(const char* aPref, void* aData = nullptr) {
// XXX this could be made to only clear out the cache for the prefs that were
// changed but it probably isn't that big a deal.
gfxPlatformFontList::PlatformFontList()->ClearLangGroupPrefFonts();
gfxFontCache::GetCache()->AgeAllGenerations();
}
static gfxFontListPrefObserver* gFontListPrefObserver = nullptr;
NS_IMPL_ISUPPORTS(gfxFontListPrefObserver, nsIObserver)
#define LOCALES_CHANGED_TOPIC "intl:system-locales-changed"
NS_IMETHODIMP
gfxFontListPrefObserver::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
NS_ASSERTION(!strcmp(aTopic, LOCALES_CHANGED_TOPIC), "invalid topic");
FontListPrefChanged(nullptr);
if (XRE_IsParentProcess()) {
gfxPlatform::ForceGlobalReflow();
}
return NS_OK;
}
MOZ_DEFINE_MALLOC_SIZE_OF(FontListMallocSizeOf)
NS_IMPL_ISUPPORTS(gfxPlatformFontList::MemoryReporter, nsIMemoryReporter)
NS_IMETHODIMP
gfxPlatformFontList::MemoryReporter::CollectReports(
nsIHandleReportCallback* aHandleReport, nsISupports* aData,
bool aAnonymize) {
FontListSizes sizes;
sizes.mFontListSize = 0;
sizes.mFontTableCacheSize = 0;
sizes.mCharMapsSize = 0;
sizes.mLoaderSize = 0;
gfxPlatformFontList::PlatformFontList()->AddSizeOfIncludingThis(
&FontListMallocSizeOf, &sizes);
MOZ_COLLECT_REPORT(
"explicit/gfx/font-list", KIND_HEAP, UNITS_BYTES, sizes.mFontListSize,
"Memory used to manage the list of font families and faces.");
MOZ_COLLECT_REPORT(
"explicit/gfx/font-charmaps", KIND_HEAP, UNITS_BYTES, sizes.mCharMapsSize,
"Memory used to record the character coverage of individual fonts.");
if (sizes.mFontTableCacheSize) {
MOZ_COLLECT_REPORT(
"explicit/gfx/font-tables", KIND_HEAP, UNITS_BYTES,
sizes.mFontTableCacheSize,
"Memory used for cached font metrics and layout tables.");
}
if (sizes.mLoaderSize) {
MOZ_COLLECT_REPORT("explicit/gfx/font-loader", KIND_HEAP, UNITS_BYTES,
sizes.mLoaderSize,
"Memory used for (platform-specific) font loader.");
}
return NS_OK;
}
gfxPlatformFontList::gfxPlatformFontList(bool aNeedFullnamePostscriptNames)
: mFontFamiliesMutex("gfxPlatformFontList::mFontFamiliesMutex"),
mFontFamilies(64),
mOtherFamilyNames(16),
mSharedCmaps(8),
mStartIndex(0),
mNumFamilies(0),
mFontlistInitCount(0),
mFontFamilyWhitelistActive(false) {
mOtherFamilyNamesInitialized = false;
if (aNeedFullnamePostscriptNames) {
mExtraNames = MakeUnique<ExtraNames>();
}
mFaceNameListsInitialized = false;
mLangService = nsLanguageAtomService::GetService();
LoadBadUnderlineList();
// pref changes notification setup
NS_ASSERTION(!gFontListPrefObserver,
"There has been font list pref observer already");
gFontListPrefObserver = new gfxFontListPrefObserver();
NS_ADDREF(gFontListPrefObserver);
Preferences::RegisterPrefixCallbacks(FontListPrefChanged, kObservedPrefs);
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (obs) {
obs->AddObserver(gFontListPrefObserver, LOCALES_CHANGED_TOPIC, false);
}
// Only the parent process listens for whitelist changes; it will then
// notify its children to rebuild their font lists.
if (XRE_IsParentProcess()) {
Preferences::RegisterCallback(FontWhitelistPrefChanged,
kFontSystemWhitelistPref);
}
RegisterStrongMemoryReporter(new MemoryReporter());
}
gfxPlatformFontList::~gfxPlatformFontList() {
mSharedCmaps.Clear();
ClearLangGroupPrefFonts();
NS_ASSERTION(gFontListPrefObserver, "There is no font list pref observer");
Preferences::UnregisterPrefixCallbacks(FontListPrefChanged, kObservedPrefs);
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (obs) {
obs->RemoveObserver(gFontListPrefObserver, LOCALES_CHANGED_TOPIC);
}
if (XRE_IsParentProcess()) {
Preferences::UnregisterCallback(FontWhitelistPrefChanged,
kFontSystemWhitelistPref);
}
NS_RELEASE(gFontListPrefObserver);
}
/* static */
void gfxPlatformFontList::FontWhitelistPrefChanged(const char* aPref,
void* aClosure) {
MOZ_ASSERT(XRE_IsParentProcess());
gfxPlatformFontList::PlatformFontList()->UpdateFontList();
mozilla::dom::ContentParent::NotifyUpdatedFonts();
}
// number of CSS generic font families
const uint32_t kNumGenerics = 5;
void gfxPlatformFontList::ApplyWhitelist() {
nsTArray<nsCString> list;
gfxFontUtils::GetPrefsFontList(kFontSystemWhitelistPref, list);
uint32_t numFonts = list.Length();
mFontFamilyWhitelistActive = (numFonts > 0);
if (!mFontFamilyWhitelistActive) {
return;
}
nsTHashtable<nsCStringHashKey> familyNamesWhitelist;
for (uint32_t i = 0; i < numFonts; i++) {
nsAutoCString key;
ToLowerCase(list[i], key);
familyNamesWhitelist.PutEntry(key);
}
for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
// Don't continue if we only have one font left.
if (mFontFamilies.Count() == 1) {
break;
}
nsAutoCString fontFamilyName(iter.Key());
ToLowerCase(fontFamilyName);
if (!familyNamesWhitelist.Contains(fontFamilyName)) {
iter.Remove();
}
}
}
bool gfxPlatformFontList::AddWithLegacyFamilyName(const nsACString& aLegacyName,
gfxFontEntry* aFontEntry) {
bool added = false;
nsAutoCString key;
ToLowerCase(aLegacyName, key);
gfxFontFamily* family = mOtherFamilyNames.GetWeak(key);
if (!family) {
family = CreateFontFamily(aLegacyName);
family->SetHasStyles(true); // we don't want the family to search for
// faces, we're adding them directly here
mOtherFamilyNames.Put(key, family);
added = true;
}
family->AddFontEntry(aFontEntry->Clone());
return added;
}
nsresult gfxPlatformFontList::InitFontList() {
mFontlistInitCount++;
if (LOG_FONTINIT_ENABLED()) {
LOG_FONTINIT(("(fontinit) system fontlist initialization\n"));
}
// rebuilding fontlist so clear out font/word caches
gfxFontCache* fontCache = gfxFontCache::GetCache();
if (fontCache) {
fontCache->AgeAllGenerations();
fontCache->FlushShapedWordCaches();
}
gfxPlatform::PurgeSkiaFontCache();
CancelInitOtherFamilyNamesTask();
MutexAutoLock lock(mFontFamiliesMutex);
mFontFamilies.Clear();
mOtherFamilyNames.Clear();
mOtherFamilyNamesInitialized = false;
if (mExtraNames) {
mExtraNames->mFullnames.Clear();
mExtraNames->mPostscriptNames.Clear();
}
mFaceNameListsInitialized = false;
ClearLangGroupPrefFonts();
mReplacementCharFallbackFamily = nullptr;
CancelLoader();
// initialize ranges of characters for which system-wide font search should be
// skipped
mCodepointsWithNoFonts.reset();
mCodepointsWithNoFonts.SetRange(0, 0x1f); // C0 controls
mCodepointsWithNoFonts.SetRange(0x7f, 0x9f); // C1 controls
sPlatformFontList = this;
nsresult rv = InitFontListForPlatform();
if (NS_FAILED(rv)) {
return rv;
}
ApplyWhitelist();
return NS_OK;
}
void gfxPlatformFontList::GenerateFontListKey(const nsACString& aKeyName,
nsACString& aResult) {
aResult = aKeyName;
ToLowerCase(aResult);
}
#define OTHERNAMES_TIMEOUT 200
void gfxPlatformFontList::InitOtherFamilyNames(
bool aDeferOtherFamilyNamesLoading) {
if (mOtherFamilyNamesInitialized) {
return;
}
// If the font loader delay has been set to zero, we don't defer loading
// additional family names (regardless of the aDefer... parameter), as we
// take this to mean availability of font info is to be prioritized over
// potential startup perf or main-thread jank.
// (This is used so we can reliably run reftests that depend on localized
// font-family names being available.)
if (aDeferOtherFamilyNamesLoading &&
Preferences::GetUint(FONT_LOADER_DELAY_PREF) > 0) {
if (!mPendingOtherFamilyNameTask) {
RefPtr<mozilla::CancelableRunnable> task =
new InitOtherFamilyNamesRunnable();
mPendingOtherFamilyNameTask = task;
NS_IdleDispatchToMainThread(task.forget());
}
} else {
InitOtherFamilyNamesInternal(false);
}
}
// time limit for loading facename lists (ms)
#define NAMELIST_TIMEOUT 200
gfxFontEntry* gfxPlatformFontList::SearchFamiliesForFaceName(
const nsACString& aFaceName) {
TimeStamp start = TimeStamp::Now();
bool timedOut = false;
// if mFirstChar is not 0, only load facenames for families
// that start with this character
char16_t firstChar = 0;
gfxFontEntry* lookup = nullptr;
// iterate over familes starting with the same letter
firstChar = ToLowerCase(aFaceName.CharAt(0));
for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
nsCStringHashKey::KeyType key = iter.Key();
RefPtr<gfxFontFamily>& family = iter.Data();
// when filtering, skip names that don't start with the filter character
if (firstChar && ToLowerCase(key.CharAt(0)) != firstChar) {
continue;
}
family->ReadFaceNames(this, NeedFullnamePostscriptNames());
TimeDuration elapsed = TimeStamp::Now() - start;
if (elapsed.ToMilliseconds() > NAMELIST_TIMEOUT) {
timedOut = true;
break;
}
}
lookup = FindFaceName(aFaceName);
TimeStamp end = TimeStamp::Now();
Telemetry::AccumulateTimeDelta(Telemetry::FONTLIST_INITFACENAMELISTS, start,
end);
if (LOG_FONTINIT_ENABLED()) {
TimeDuration elapsed = end - start;
LOG_FONTINIT(("(fontinit) SearchFamiliesForFaceName took %8.2f ms %s %s",
elapsed.ToMilliseconds(), (lookup ? "found name" : ""),
(timedOut ? "timeout" : "")));
}
return lookup;
}
gfxFontEntry* gfxPlatformFontList::FindFaceName(const nsACString& aFaceName) {
gfxFontEntry* lookup;
// lookup in name lookup tables, return null if not found
if (mExtraNames &&
((lookup = mExtraNames->mPostscriptNames.GetWeak(aFaceName)) ||
(lookup = mExtraNames->mFullnames.GetWeak(aFaceName)))) {
return lookup;
}
return nullptr;
}
gfxFontEntry* gfxPlatformFontList::LookupInFaceNameLists(
const nsACString& aFaceName) {
gfxFontEntry* lookup = nullptr;
// initialize facename lookup tables if needed
// note: this can terminate early or time out, in which case
// mFaceNameListsInitialized remains false
if (!mFaceNameListsInitialized) {
lookup = SearchFamiliesForFaceName(aFaceName);
if (lookup) {
return lookup;
}
}
// lookup in name lookup tables, return null if not found
if (!(lookup = FindFaceName(aFaceName))) {
// names not completely initialized, so keep track of lookup misses
if (!mFaceNameListsInitialized) {
if (!mFaceNamesMissed) {
mFaceNamesMissed = MakeUnique<nsTHashtable<nsCStringHashKey>>(2);
}
mFaceNamesMissed->PutEntry(aFaceName);
}
}
return lookup;
}
void gfxPlatformFontList::PreloadNamesList() {
AutoTArray<nsCString, 10> preloadFonts;
gfxFontUtils::GetPrefsFontList("font.preload-names-list", preloadFonts);
uint32_t numFonts = preloadFonts.Length();
for (uint32_t i = 0; i < numFonts; i++) {
nsAutoCString key;
GenerateFontListKey(preloadFonts[i], key);
// only search canonical names!
gfxFontFamily* familyEntry = mFontFamilies.GetWeak(key);
if (familyEntry) {
familyEntry->ReadOtherFamilyNames(this);
}
}
}
void gfxPlatformFontList::LoadBadUnderlineList() {
gfxFontUtils::GetPrefsFontList("font.blacklist.underline_offset",
mBadUnderlineFamilyNames);
for (auto& fam : mBadUnderlineFamilyNames) {
ToLowerCase(fam);
}
mBadUnderlineFamilyNames.Compact();
mBadUnderlineFamilyNames.Sort();
}
void gfxPlatformFontList::UpdateFontList() {
InitFontList();
RebuildLocalFonts();
}
void gfxPlatformFontList::GetFontList(nsAtom* aLangGroup,
const nsACString& aGenericFamily,
nsTArray<nsString>& aListOfFonts) {
MutexAutoLock lock(mFontFamiliesMutex);
for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
RefPtr<gfxFontFamily>& family = iter.Data();
if (family->FilterForFontList(aLangGroup, aGenericFamily)) {
nsAutoCString localizedFamilyName;
family->LocalizedName(localizedFamilyName);
aListOfFonts.AppendElement(NS_ConvertUTF8toUTF16(localizedFamilyName));
}
}
aListOfFonts.Sort();
aListOfFonts.Compact();
}
void gfxPlatformFontList::GetFontFamilyList(
nsTArray<RefPtr<gfxFontFamily>>& aFamilyArray) {
for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
RefPtr<gfxFontFamily>& family = iter.Data();
aFamilyArray.AppendElement(family);
}
}
gfxFontEntry* gfxPlatformFontList::SystemFindFontForChar(
uint32_t aCh, uint32_t aNextCh, Script aRunScript,
const gfxFontStyle* aStyle) {
gfxFontEntry* fontEntry = nullptr;
// is codepoint with no matching font? return null immediately
if (mCodepointsWithNoFonts.test(aCh)) {
return nullptr;
}
// Try to short-circuit font fallback for U+FFFD, used to represent
// encoding errors: just use cached family from last time U+FFFD was seen.
// This helps speed up pages with lots of encoding errors, binary-as-text,
// etc.
if (aCh == 0xFFFD && mReplacementCharFallbackFamily) {
fontEntry = mReplacementCharFallbackFamily->FindFontForStyle(*aStyle);
// this should never fail, as we must have found U+FFFD in order to set
// mReplacementCharFallbackFamily at all, but better play it safe
if (fontEntry && fontEntry->HasCharacter(aCh)) {
return fontEntry;
}
}
TimeStamp start = TimeStamp::Now();
// search commonly available fonts
bool common = true;
gfxFontFamily* fallbackFamily = nullptr;
fontEntry =
CommonFontFallback(aCh, aNextCh, aRunScript, aStyle, &fallbackFamily);
// if didn't find a font, do system-wide fallback (except for specials)
uint32_t cmapCount = 0;
if (!fontEntry) {
common = false;
fontEntry =
GlobalFontFallback(aCh, aRunScript, aStyle, cmapCount, &fallbackFamily);
}
TimeDuration elapsed = TimeStamp::Now() - start;
LogModule* log = gfxPlatform::GetLog(eGfxLog_textrun);
if (MOZ_UNLIKELY(MOZ_LOG_TEST(log, LogLevel::Warning))) {
uint32_t unicodeRange = FindCharUnicodeRange(aCh);
Script script = mozilla::unicode::GetScriptCode(aCh);
MOZ_LOG(log, LogLevel::Warning,
("(textrun-systemfallback-%s) char: u+%6.6x "
"unicode-range: %d script: %d match: [%s]"
" time: %dus cmaps: %d\n",
(common ? "common" : "global"), aCh, unicodeRange,
static_cast<int>(script),
(fontEntry ? fontEntry->Name().get() : "<none>"),
int32_t(elapsed.ToMicroseconds()), cmapCount));
}
// no match? add to set of non-matching codepoints
if (!fontEntry) {
mCodepointsWithNoFonts.set(aCh);
} else if (aCh == 0xFFFD && fontEntry && fallbackFamily) {
mReplacementCharFallbackFamily = fallbackFamily;
}
// track system fallback time
static bool first = true;
int32_t intElapsed =
int32_t(first ? elapsed.ToMilliseconds() : elapsed.ToMicroseconds());
Telemetry::Accumulate((first ? Telemetry::SYSTEM_FONT_FALLBACK_FIRST
: Telemetry::SYSTEM_FONT_FALLBACK),
intElapsed);
first = false;
// track the script for which fallback occurred (incremented one make it
// 1-based)
Telemetry::Accumulate(Telemetry::SYSTEM_FONT_FALLBACK_SCRIPT,
int(aRunScript) + 1);
return fontEntry;
}
#define NUM_FALLBACK_FONTS 8
gfxFontEntry* gfxPlatformFontList::CommonFontFallback(
uint32_t aCh, uint32_t aNextCh, Script aRunScript,
const gfxFontStyle* aMatchStyle, gfxFontFamily** aMatchedFamily) {
AutoTArray<const char*, NUM_FALLBACK_FONTS> defaultFallbacks;
uint32_t i, numFallbacks;
gfxPlatform::GetPlatform()->GetCommonFallbackFonts(aCh, aNextCh, aRunScript,
defaultFallbacks);
numFallbacks = defaultFallbacks.Length();
for (i = 0; i < numFallbacks; i++) {
nsAutoCString familyName(defaultFallbacks[i]);
gfxFontFamily* fallback = FindFamilyByCanonicalName(familyName);
if (!fallback) {
continue;
}
gfxFontEntry* fontEntry;
// use first font in list that supports a given character
fontEntry = fallback->FindFontForStyle(*aMatchStyle);
if (fontEntry) {
if (fontEntry->HasCharacter(aCh)) {
*aMatchedFamily = fallback;
return fontEntry;
}
// If we requested a styled font (bold and/or italic), and the char
// was not available, check other faces of the family.
if (!fontEntry->IsNormalStyle()) {
// If style/weight/stretch was not Normal, see if we can
// fall back to a next-best face (e.g. Arial Black -> Bold,
// or Arial Narrow -> Regular).
GlobalFontMatch data(aCh, *aMatchStyle);
fallback->SearchAllFontsForChar(&data);
if (data.mBestMatch) {
*aMatchedFamily = fallback;
return data.mBestMatch;
}
}
}
}
return nullptr;
}
gfxFontEntry* gfxPlatformFontList::GlobalFontFallback(
const uint32_t aCh, Script aRunScript, const gfxFontStyle* aMatchStyle,
uint32_t& aCmapCount, gfxFontFamily** aMatchedFamily) {
bool useCmaps = IsFontFamilyWhitelistActive() ||
gfxPlatform::GetPlatform()->UseCmapsDuringSystemFallback();
if (!useCmaps) {
// Allow platform-specific fallback code to try and find a usable font
gfxFontEntry* fe = PlatformGlobalFontFallback(aCh, aRunScript, aMatchStyle,
aMatchedFamily);
if (fe) {
return fe;
}
}
// otherwise, try to find it among local fonts
GlobalFontMatch data(aCh, *aMatchStyle);
// iterate over all font families to find a font that support the character
for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
RefPtr<gfxFontFamily>& family = iter.Data();
// evaluate all fonts in this family for a match
family->FindFontForChar(&data);
}
aCmapCount = data.mCmapsTested;
*aMatchedFamily = data.mMatchedFamily;
return data.mBestMatch;
}
gfxFontFamily* gfxPlatformFontList::CheckFamily(gfxFontFamily* aFamily) {
if (aFamily && !aFamily->HasStyles()) {
aFamily->FindStyleVariations();
aFamily->CheckForSimpleFamily();
}
if (aFamily && aFamily->GetFontList().Length() == 0) {
// failed to load any faces for this family, so discard it
nsAutoCString key;
GenerateFontListKey(aFamily->Name(), key);
mFontFamilies.Remove(key);
return nullptr;
}
return aFamily;
}
bool gfxPlatformFontList::FindAndAddFamilies(
const nsACString& aFamily, nsTArray<FamilyAndGeneric>* aOutput,
FindFamiliesFlags aFlags, gfxFontStyle* aStyle, gfxFloat aDevToCssSize) {
nsAutoCString key;
GenerateFontListKey(aFamily, key);
NS_ASSERTION(mFontFamilies.Count() != 0,
"system font list was not initialized correctly");
// lookup in canonical (i.e. English) family name list
gfxFontFamily* familyEntry = mFontFamilies.GetWeak(key);
// if not found, lookup in other family names list (mostly localized names)
if (!familyEntry) {
familyEntry = mOtherFamilyNames.GetWeak(key);
}
// if still not found and other family names not yet fully initialized,
// initialize the rest of the list and try again. this is done lazily
// since reading name table entries is expensive.
// although ASCII localized family names are possible they don't occur
// in practice so avoid pulling in names at startup
if (!familyEntry && !mOtherFamilyNamesInitialized && !IsASCII(aFamily)) {
InitOtherFamilyNames(
!(aFlags & FindFamiliesFlags::eForceOtherFamilyNamesLoading));
familyEntry = mOtherFamilyNames.GetWeak(key);
if (!familyEntry && !mOtherFamilyNamesInitialized &&
!(aFlags & FindFamiliesFlags::eNoAddToNamesMissedWhenSearching)) {
// localized family names load timed out, add name to list of
// names to check after localized names are loaded
if (!mOtherNamesMissed) {
mOtherNamesMissed = MakeUnique<nsTHashtable<nsCStringHashKey>>(2);
}
mOtherNamesMissed->PutEntry(key);
}
}
familyEntry = CheckFamily(familyEntry);
// If we failed to find the requested family, check for a space in the
// name; if found, and if the "base" name (up to the last space) exists
// as a family, then this might be a legacy GDI-style family name for
// an additional weight/width. Try searching the faces of the base family
// and create any corresponding legacy families.
if (!familyEntry &&
!(aFlags & FindFamiliesFlags::eNoSearchForLegacyFamilyNames)) {
// We don't have nsAString::RFindChar, so look for a space manually
const char* data = aFamily.BeginReading();
int32_t index = aFamily.Length();
while (--index > 0) {
if (data[index] == ' ') {
break;
}
}
if (index > 0) {
gfxFontFamily* base =
FindFamily(Substring(aFamily, 0, index),
FindFamiliesFlags::eNoSearchForLegacyFamilyNames);
// If we found the "base" family name, and if it has members with
// legacy names, this will add corresponding font-family entries to
// the mOtherFamilyNames list; then retry the legacy-family search.
if (base && base->CheckForLegacyFamilyNames(this)) {
familyEntry = mOtherFamilyNames.GetWeak(key);
}
}
}
if (familyEntry) {
aOutput->AppendElement(FamilyAndGeneric(familyEntry));
return true;
}
return false;
}
gfxFontEntry* gfxPlatformFontList::FindFontForFamily(
const nsACString& aFamily, const gfxFontStyle* aStyle) {
gfxFontFamily* familyEntry = FindFamily(aFamily);
if (familyEntry) return familyEntry->FindFontForStyle(*aStyle);
return nullptr;
}
void gfxPlatformFontList::AddOtherFamilyName(gfxFontFamily* aFamilyEntry,
nsCString& aOtherFamilyName) {
nsAutoCString key;
GenerateFontListKey(aOtherFamilyName, key);
if (!mOtherFamilyNames.GetWeak(key)) {
mOtherFamilyNames.Put(key, aFamilyEntry);
LOG_FONTLIST(
("(fontlist-otherfamily) canonical family: %s, "
"other family: %s\n",
aFamilyEntry->Name().get(), aOtherFamilyName.get()));
if (mBadUnderlineFamilyNames.ContainsSorted(key)) {
aFamilyEntry->SetBadUnderlineFamily();
}
}
}
void gfxPlatformFontList::AddFullname(gfxFontEntry* aFontEntry,
const nsCString& aFullname) {
if (!mExtraNames->mFullnames.GetWeak(aFullname)) {
mExtraNames->mFullnames.Put(aFullname, aFontEntry);
LOG_FONTLIST(("(fontlist-fullname) name: %s, fullname: %s\n",
aFontEntry->Name().get(), aFullname.get()));
}
}
void gfxPlatformFontList::AddPostscriptName(gfxFontEntry* aFontEntry,
const nsCString& aPostscriptName) {
if (!mExtraNames->mPostscriptNames.GetWeak(aPostscriptName)) {
mExtraNames->mPostscriptNames.Put(aPostscriptName, aFontEntry);
LOG_FONTLIST(("(fontlist-postscript) name: %s, psname: %s\n",
aFontEntry->Name().get(), aPostscriptName.get()));
}
}
bool gfxPlatformFontList::GetStandardFamilyName(const nsCString& aFontName,
nsACString& aFamilyName) {
aFamilyName.Truncate();
gfxFontFamily* ff = FindFamily(aFontName);
if (!ff) {
return false;
}
aFamilyName = ff->Name();
return true;
}
gfxFontFamily* gfxPlatformFontList::GetDefaultFontFamily(
const nsACString& aLangGroup, const nsACString& aGenericFamily) {
if (NS_WARN_IF(aLangGroup.IsEmpty()) ||
NS_WARN_IF(aGenericFamily.IsEmpty())) {
return nullptr;
}
AutoTArray<nsCString, 4> names;
gfxFontUtils::AppendPrefsFontList(
NameListPref(aGenericFamily, aLangGroup).get(), names);
for (const nsCString& name : names) {
gfxFontFamily* fontFamily = FindFamily(name);
if (fontFamily) {
return fontFamily;
}
}
return nullptr;
}
gfxCharacterMap* gfxPlatformFontList::FindCharMap(gfxCharacterMap* aCmap) {
aCmap->CalcHash();
gfxCharacterMap* cmap = AddCmap(aCmap);
cmap->mShared = true;
return cmap;
}
// add a cmap to the shared cmap set
gfxCharacterMap* gfxPlatformFontList::AddCmap(const gfxCharacterMap* aCharMap) {
CharMapHashKey* found =
mSharedCmaps.PutEntry(const_cast<gfxCharacterMap*>(aCharMap));
return found->GetKey();
}
// remove the cmap from the shared cmap set
void gfxPlatformFontList::RemoveCmap(const gfxCharacterMap* aCharMap) {
// skip lookups during teardown
if (mSharedCmaps.Count() == 0) {
return;
}
// cmap needs to match the entry *and* be the same ptr before removing
CharMapHashKey* found =
mSharedCmaps.GetEntry(const_cast<gfxCharacterMap*>(aCharMap));
if (found && found->GetKey() == aCharMap) {
mSharedCmaps.RemoveEntry(found);
}
}
void gfxPlatformFontList::ResolveGenericFontNames(
FontFamilyType aGenericType, eFontPrefLang aPrefLang,
nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies) {
const char* langGroupStr = GetPrefLangName(aPrefLang);
const char* generic = GetGenericName(aGenericType);
if (!generic) {
return;
}
AutoTArray<nsCString, 4> genericFamilies;
// load family for "font.name.generic.lang"
gfxFontUtils::AppendPrefsFontList(NamePref(generic, langGroupStr).get(),
genericFamilies);
// load fonts for "font.name-list.generic.lang"
gfxFontUtils::AppendPrefsFontList(NameListPref(generic, langGroupStr).get(),
genericFamilies);
nsAtom* langGroup = GetLangGroupForPrefLang(aPrefLang);
NS_ASSERTION(langGroup, "null lang group for pref lang");
gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(
genericFamilies, langGroup, aGenericFamilies);
#if 0 // dump out generic mappings
printf("%s ===> ", prefFontName.get());
for (uint32_t k = 0; k < aGenericFamilies->Length(); k++) {
if (k > 0) printf(", ");
printf("%s", aGenericFamilies[k]->Name().get());
}
printf("\n");
#endif
}
void gfxPlatformFontList::ResolveEmojiFontNames(
nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies) {
// emoji preference has no lang name
AutoTArray<nsCString, 4> genericFamilies;
nsAutoCString prefFontListName("font.name-list.emoji");
gfxFontUtils::AppendPrefsFontList(prefFontListName.get(), genericFamilies);
gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(
genericFamilies, nullptr, aGenericFamilies);
}
void gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(
nsTArray<nsCString>& aGenericNameFamilies, nsAtom* aLangGroup,
nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies) {
// lookup and add platform fonts uniquely
for (const nsCString& genericFamily : aGenericNameFamilies) {
gfxFontStyle style;
style.language = aLangGroup;
style.systemFont = false;
AutoTArray<FamilyAndGeneric, 10> families;
FindAndAddFamilies(genericFamily, &families, FindFamiliesFlags(0), &style);
for (const FamilyAndGeneric& f : families) {
if (!aGenericFamilies->Contains(f.mFamily)) {
aGenericFamilies->AppendElement(f.mFamily);
}
}
}
}
nsTArray<RefPtr<gfxFontFamily>>* gfxPlatformFontList::GetPrefFontsLangGroup(
mozilla::FontFamilyType aGenericType, eFontPrefLang aPrefLang) {
// treat -moz-fixed as monospace
if (aGenericType == eFamily_moz_fixed) {
aGenericType = eFamily_monospace;
}
if (aGenericType == eFamily_moz_emoji) {
// Emoji font has no lang
PrefFontList* prefFonts = mEmojiPrefFont.get();
if (MOZ_UNLIKELY(!prefFonts)) {
prefFonts = new PrefFontList;
ResolveEmojiFontNames(prefFonts);
mEmojiPrefFont.reset(prefFonts);
}
return prefFonts;
}
PrefFontList* prefFonts = mLangGroupPrefFonts[aPrefLang][aGenericType].get();
if (MOZ_UNLIKELY(!prefFonts)) {
prefFonts = new PrefFontList;
ResolveGenericFontNames(aGenericType, aPrefLang, prefFonts);
mLangGroupPrefFonts[aPrefLang][aGenericType].reset(prefFonts);
}
return prefFonts;
}
void gfxPlatformFontList::AddGenericFonts(
mozilla::FontFamilyType aGenericType, nsAtom* aLanguage,
nsTArray<FamilyAndGeneric>& aFamilyList) {
// map lang ==> langGroup
nsAtom* langGroup = GetLangGroup(aLanguage);
// langGroup ==> prefLang
eFontPrefLang prefLang = GetFontPrefLangFor(langGroup);
// lookup pref fonts