forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFontFaceSet.cpp
1955 lines (1698 loc) · 60.2 KB
/
FontFaceSet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "FontFaceSet.h"
#include "gfxFontConstants.h"
#include "gfxFontSrcPrincipal.h"
#include "gfxFontSrcURI.h"
#include "mozilla/css/Loader.h"
#include "mozilla/dom/FontFaceSetBinding.h"
#include "mozilla/dom/FontFaceSetIterator.h"
#include "mozilla/dom/FontFaceSetLoadEvent.h"
#include "mozilla/dom/FontFaceSetLoadEventBinding.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/net/ReferrerPolicy.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Logging.h"
#include "mozilla/Preferences.h"
#include "mozilla/ServoCSSParser.h"
#include "mozilla/ServoFontFaceRule.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/ServoUtils.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticPrefs.h"
#include "mozilla/Telemetry.h"
#include "mozilla/LoadInfo.h"
#include "nsAutoPtr.h"
#include "nsContentPolicyUtils.h"
#include "nsCSSParser.h"
#include "nsDeviceContext.h"
#include "nsFontFaceLoader.h"
#include "nsIConsoleService.h"
#include "nsIContentPolicy.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIDocShell.h"
#include "nsIDocument.h"
#include "nsILoadContext.h"
#include "nsINetworkPredictor.h"
#include "nsIPresShell.h"
#include "nsIPresShellInlines.h"
#include "nsIPrincipal.h"
#include "nsISupportsPriority.h"
#include "nsIWebNavigation.h"
#include "nsNetUtil.h"
#include "nsIProtocolHandler.h"
#include "nsIInputStream.h"
#include "nsLayoutUtils.h"
#include "nsPresContext.h"
#include "nsPrintfCString.h"
#include "nsUTF8Utils.h"
#include "nsDOMNavigationTiming.h"
using namespace mozilla;
using namespace mozilla::css;
using namespace mozilla::dom;
#define LOG(args) MOZ_LOG(gfxUserFontSet::GetUserFontsLog(), mozilla::LogLevel::Debug, args)
#define LOG_ENABLED() MOZ_LOG_TEST(gfxUserFontSet::GetUserFontsLog(), \
LogLevel::Debug)
#define FONT_LOADING_API_ENABLED_PREF "layout.css.font-loading-api.enabled"
NS_IMPL_CYCLE_COLLECTION_CLASS(FontFaceSet)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(FontFaceSet, DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument);
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReady);
for (size_t i = 0; i < tmp->mRuleFaces.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRuleFaces[i].mFontFace);
}
for (size_t i = 0; i < tmp->mNonRuleFaces.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNonRuleFaces[i].mFontFace);
}
if (tmp->mUserFontSet) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mUserFontSet->mFontFaceSet);
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(FontFaceSet, DOMEventTargetHelper)
tmp->Disconnect();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocument);
NS_IMPL_CYCLE_COLLECTION_UNLINK(mReady);
for (size_t i = 0; i < tmp->mRuleFaces.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_UNLINK(mRuleFaces[i].mFontFace);
}
for (size_t i = 0; i < tmp->mNonRuleFaces.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_UNLINK(mNonRuleFaces[i].mFontFace);
}
if (tmp->mUserFontSet) {
NS_IMPL_CYCLE_COLLECTION_UNLINK(mUserFontSet->mFontFaceSet);
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mUserFontSet);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_ADDREF_INHERITED(FontFaceSet, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(FontFaceSet, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(FontFaceSet)
NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
NS_INTERFACE_MAP_ENTRY(nsICSSLoaderObserver)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
FontFaceSet::FontFaceSet(nsPIDOMWindowInner* aWindow, nsIDocument* aDocument)
: DOMEventTargetHelper(aWindow)
, mDocument(aDocument)
, mStandardFontLoadPrincipal(new gfxFontSrcPrincipal(mDocument->NodePrincipal()))
, mResolveLazilyCreatedReadyPromise(false)
, mStatus(FontFaceSetLoadStatus::Loaded)
, mNonRuleFacesDirty(false)
, mHasLoadingFontFaces(false)
, mHasLoadingFontFacesIsDirty(false)
, mDelayedLoadCheck(false)
, mBypassCache(false)
, mPrivateBrowsing(false)
{
MOZ_ASSERT(mDocument, "We should get a valid document from the caller!");
mStandardFontLoadPrincipal =
new gfxFontSrcPrincipal(mDocument->NodePrincipal());
// If the pref is not set, don't create the Promise (which the page wouldn't
// be able to get to anyway) as it causes the window.FontFaceSet constructor
// to be created.
if (aWindow && PrefEnabled()) {
mResolveLazilyCreatedReadyPromise = true;
}
// Record the state of the "bypass cache" flags from the docshell now,
// since we want to look at them from style worker threads, and we can
// only get to the docshell through a weak pointer (which is only
// possible on the main thread).
//
// In theory the load type of a docshell could change after the document
// is loaded, but handling that doesn't seem too important.
if (nsCOMPtr<nsIDocShell> docShell = mDocument->GetDocShell()) {
uint32_t loadType;
uint32_t flags;
if ((NS_SUCCEEDED(docShell->GetLoadType(&loadType)) &&
((loadType >> 16) & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE)) ||
(NS_SUCCEEDED(docShell->GetDefaultLoadFlags(&flags)) &&
(flags & nsIRequest::LOAD_BYPASS_CACHE))) {
mBypassCache = true;
}
}
// Same for the "private browsing" flag.
if (nsCOMPtr<nsILoadContext> loadContext = mDocument->GetLoadContext()) {
mPrivateBrowsing = loadContext->UsePrivateBrowsing();
}
if (!mDocument->DidFireDOMContentLoaded()) {
mDocument->AddSystemEventListener(NS_LITERAL_STRING("DOMContentLoaded"),
this, false, false);
}
mDocument->CSSLoader()->AddObserver(this);
mUserFontSet = new UserFontSet(this);
}
FontFaceSet::~FontFaceSet()
{
// Assert that we don't drop any FontFaceSet objects during a Servo traversal,
// since PostTraversalTask objects can hold raw pointers to FontFaceSets.
MOZ_ASSERT(!ServoStyleSet::IsInServoTraversal());
Disconnect();
for (auto it = mLoaders.Iter(); !it.Done(); it.Next()) {
it.Get()->GetKey()->Cancel();
}
}
JSObject*
FontFaceSet::WrapObject(JSContext* aContext, JS::Handle<JSObject*> aGivenProto)
{
return FontFaceSetBinding::Wrap(aContext, this, aGivenProto);
}
void
FontFaceSet::Disconnect()
{
RemoveDOMContentLoadedListener();
if (mDocument && mDocument->CSSLoader()) {
// We're null checking CSSLoader() since FontFaceSet::Disconnect() might be
// being called during unlink, at which time the loader amy already have
// been unlinked from the document.
mDocument->CSSLoader()->RemoveObserver(this);
}
}
void
FontFaceSet::RemoveDOMContentLoadedListener()
{
if (mDocument) {
mDocument->RemoveSystemEventListener(NS_LITERAL_STRING("DOMContentLoaded"),
this, false);
}
}
void
FontFaceSet::ParseFontShorthandForMatching(
const nsAString& aFont,
RefPtr<SharedFontList>& aFamilyList,
uint32_t& aWeight,
int32_t& aStretch,
uint8_t& aStyle,
ErrorResult& aRv)
{
nsCSSValue style;
nsCSSValue stretch;
nsCSSValue weight;
RefPtr<URLExtraData> url = ServoCSSParser::GetURLExtraData(mDocument);
if (!ServoCSSParser::ParseFontShorthandForMatching(
aFont, url, aFamilyList, style, stretch, weight)) {
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
return;
}
aWeight = weight.GetIntValue();
aStretch = stretch.GetIntValue();
aStyle = style.GetIntValue();
}
static bool
HasAnyCharacterInUnicodeRange(gfxUserFontEntry* aEntry,
const nsAString& aInput)
{
const char16_t* p = aInput.Data();
const char16_t* end = p + aInput.Length();
while (p < end) {
uint32_t c = UTF16CharEnumerator::NextChar(&p, end);
if (aEntry->CharacterInUnicodeRange(c)) {
return true;
}
}
return false;
}
void
FontFaceSet::FindMatchingFontFaces(const nsAString& aFont,
const nsAString& aText,
nsTArray<FontFace*>& aFontFaces,
ErrorResult& aRv)
{
RefPtr<SharedFontList> familyList;
uint32_t weight;
int32_t stretch;
uint8_t italicStyle;
ParseFontShorthandForMatching(aFont, familyList, weight, stretch, italicStyle,
aRv);
if (aRv.Failed()) {
return;
}
gfxFontStyle style;
style.style = italicStyle;
style.weight = weight;
style.stretch = stretch;
nsTArray<FontFaceRecord>* arrays[2];
arrays[0] = &mNonRuleFaces;
arrays[1] = &mRuleFaces;
// Set of FontFaces that we want to return.
nsTHashtable<nsPtrHashKey<FontFace>> matchingFaces;
for (const FontFamilyName& fontFamilyName : familyList->mNames) {
RefPtr<gfxFontFamily> family =
mUserFontSet->LookupFamily(fontFamilyName.mName);
if (!family) {
continue;
}
AutoTArray<gfxFontEntry*,4> entries;
bool needsBold;
family->FindAllFontsForStyle(style, entries, needsBold);
for (gfxFontEntry* e : entries) {
FontFace::Entry* entry = static_cast<FontFace::Entry*>(e);
if (HasAnyCharacterInUnicodeRange(entry, aText)) {
for (FontFace* f : entry->GetFontFaces()) {
matchingFaces.PutEntry(f);
}
}
}
}
// Add all FontFaces in matchingFaces to aFontFaces, in the order
// they appear in the FontFaceSet.
for (nsTArray<FontFaceRecord>* array : arrays) {
for (FontFaceRecord& record : *array) {
FontFace* f = record.mFontFace;
if (matchingFaces.Contains(f)) {
aFontFaces.AppendElement(f);
}
}
}
}
TimeStamp
FontFaceSet::GetNavigationStartTimeStamp()
{
TimeStamp navStart;
RefPtr<nsDOMNavigationTiming> timing(mDocument->GetNavigationTiming());
if (timing) {
navStart = timing->GetNavigationStartTimeStamp();
}
return navStart;
}
already_AddRefed<Promise>
FontFaceSet::Load(JSContext* aCx,
const nsAString& aFont,
const nsAString& aText,
ErrorResult& aRv)
{
FlushUserFontSet();
nsTArray<RefPtr<Promise>> promises;
nsTArray<FontFace*> faces;
FindMatchingFontFaces(aFont, aText, faces, aRv);
if (aRv.Failed()) {
return nullptr;
}
for (FontFace* f : faces) {
RefPtr<Promise> promise = f->Load(aRv);
if (aRv.Failed()) {
return nullptr;
}
if (!promises.AppendElement(promise, fallible)) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
}
nsIGlobalObject* globalObject = GetParentObject();
if (!globalObject) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
JS::Rooted<JSObject*> jsGlobal(aCx, globalObject->GetGlobalJSObject());
GlobalObject global(aCx, jsGlobal);
RefPtr<Promise> result = Promise::All(global, promises, aRv);
return result.forget();
}
bool
FontFaceSet::Check(const nsAString& aFont,
const nsAString& aText,
ErrorResult& aRv)
{
FlushUserFontSet();
nsTArray<FontFace*> faces;
FindMatchingFontFaces(aFont, aText, faces, aRv);
if (aRv.Failed()) {
return false;
}
for (FontFace* f : faces) {
if (f->Status() != FontFaceLoadStatus::Loaded) {
return false;
}
}
return true;
}
Promise*
FontFaceSet::GetReady(ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread());
if (!mReady) {
nsCOMPtr<nsIGlobalObject> global = GetParentObject();
mReady = Promise::Create(global, aRv);
if (!mReady) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (mResolveLazilyCreatedReadyPromise) {
mReady->MaybeResolve(this);
mResolveLazilyCreatedReadyPromise = false;
}
}
FlushUserFontSet();
return mReady;
}
FontFaceSetLoadStatus
FontFaceSet::Status()
{
FlushUserFontSet();
return mStatus;
}
#ifdef DEBUG
bool
FontFaceSet::HasRuleFontFace(FontFace* aFontFace)
{
for (size_t i = 0; i < mRuleFaces.Length(); i++) {
if (mRuleFaces[i].mFontFace == aFontFace) {
return true;
}
}
return false;
}
#endif
void
FontFaceSet::Add(FontFace& aFontFace, ErrorResult& aRv)
{
FlushUserFontSet();
if (aFontFace.IsInFontFaceSet(this)) {
return;
}
if (aFontFace.HasRule()) {
aRv.Throw(NS_ERROR_DOM_INVALID_MODIFICATION_ERR);
return;
}
aFontFace.AddFontFaceSet(this);
#ifdef DEBUG
for (const FontFaceRecord& rec : mNonRuleFaces) {
MOZ_ASSERT(rec.mFontFace != &aFontFace,
"FontFace should not occur in mNonRuleFaces twice");
}
#endif
FontFaceRecord* rec = mNonRuleFaces.AppendElement();
rec->mFontFace = &aFontFace;
rec->mSheetType = SheetType::Unknown; // unused for mNonRuleFaces
rec->mLoadEventShouldFire =
aFontFace.Status() == FontFaceLoadStatus::Unloaded ||
aFontFace.Status() == FontFaceLoadStatus::Loading;
mNonRuleFacesDirty = true;
MarkUserFontSetDirty();
mHasLoadingFontFacesIsDirty = true;
CheckLoadingStarted();
}
void
FontFaceSet::Clear()
{
FlushUserFontSet();
if (mNonRuleFaces.IsEmpty()) {
return;
}
for (size_t i = 0; i < mNonRuleFaces.Length(); i++) {
FontFace* f = mNonRuleFaces[i].mFontFace;
f->RemoveFontFaceSet(this);
}
mNonRuleFaces.Clear();
mNonRuleFacesDirty = true;
MarkUserFontSetDirty();
mHasLoadingFontFacesIsDirty = true;
CheckLoadingFinished();
}
bool
FontFaceSet::Delete(FontFace& aFontFace)
{
FlushUserFontSet();
if (aFontFace.HasRule()) {
return false;
}
bool removed = false;
for (size_t i = 0; i < mNonRuleFaces.Length(); i++) {
if (mNonRuleFaces[i].mFontFace == &aFontFace) {
mNonRuleFaces.RemoveElementAt(i);
removed = true;
break;
}
}
if (!removed) {
return false;
}
aFontFace.RemoveFontFaceSet(this);
mNonRuleFacesDirty = true;
MarkUserFontSetDirty();
mHasLoadingFontFacesIsDirty = true;
CheckLoadingFinished();
return true;
}
bool
FontFaceSet::HasAvailableFontFace(FontFace* aFontFace)
{
return aFontFace->IsInFontFaceSet(this);
}
bool
FontFaceSet::Has(FontFace& aFontFace)
{
FlushUserFontSet();
return HasAvailableFontFace(&aFontFace);
}
FontFace*
FontFaceSet::GetFontFaceAt(uint32_t aIndex)
{
FlushUserFontSet();
if (aIndex < mRuleFaces.Length()) {
return mRuleFaces[aIndex].mFontFace;
}
aIndex -= mRuleFaces.Length();
if (aIndex < mNonRuleFaces.Length()) {
return mNonRuleFaces[aIndex].mFontFace;
}
return nullptr;
}
uint32_t
FontFaceSet::Size()
{
FlushUserFontSet();
// Web IDL objects can only expose array index properties up to INT32_MAX.
size_t total = mRuleFaces.Length() + mNonRuleFaces.Length();
return std::min<size_t>(total, INT32_MAX);
}
already_AddRefed<FontFaceSetIterator>
FontFaceSet::Entries()
{
RefPtr<FontFaceSetIterator> it = new FontFaceSetIterator(this, true);
return it.forget();
}
already_AddRefed<FontFaceSetIterator>
FontFaceSet::Values()
{
RefPtr<FontFaceSetIterator> it = new FontFaceSetIterator(this, false);
return it.forget();
}
void
FontFaceSet::ForEach(JSContext* aCx,
FontFaceSetForEachCallback& aCallback,
JS::Handle<JS::Value> aThisArg,
ErrorResult& aRv)
{
JS::Rooted<JS::Value> thisArg(aCx, aThisArg);
for (size_t i = 0; i < Size(); i++) {
FontFace* face = GetFontFaceAt(i);
aCallback.Call(thisArg, *face, *face, *this, aRv);
if (aRv.Failed()) {
return;
}
}
}
void
FontFaceSet::RemoveLoader(nsFontFaceLoader* aLoader)
{
mLoaders.RemoveEntry(aLoader);
}
nsresult
FontFaceSet::StartLoad(gfxUserFontEntry* aUserFontEntry,
const gfxFontFaceSrc* aFontFaceSrc)
{
nsresult rv;
nsCOMPtr<nsIStreamLoader> streamLoader;
nsCOMPtr<nsILoadGroup> loadGroup(mDocument->GetDocumentLoadGroup());
gfxFontSrcPrincipal* principal = aUserFontEntry->GetPrincipal();
nsCOMPtr<nsIChannel> channel;
// Note we are calling NS_NewChannelWithTriggeringPrincipal() with both a
// node and a principal. This is because the document where the font is
// being loaded might have a different origin from the principal of the
// stylesheet that initiated the font load.
rv = NS_NewChannelWithTriggeringPrincipal(getter_AddRefs(channel),
aFontFaceSrc->mURI->get(),
mDocument,
principal ? principal->get() : nullptr,
nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS,
nsIContentPolicy::TYPE_FONT,
nullptr, // PerformanceStorage
loadGroup);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<nsFontFaceLoader> fontLoader =
new nsFontFaceLoader(aUserFontEntry, aFontFaceSrc->mURI->get(), this,
channel);
if (LOG_ENABLED()) {
LOG(("userfonts (%p) download start - font uri: (%s) "
"referrer uri: (%s)\n",
fontLoader.get(), aFontFaceSrc->mURI->GetSpecOrDefault().get(),
aFontFaceSrc->mReferrer
? aFontFaceSrc->mReferrer->GetSpecOrDefault().get()
: ""));
}
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
if (httpChannel) {
rv = httpChannel->SetReferrerWithPolicy(aFontFaceSrc->mReferrer,
mDocument->GetReferrerPolicy());
Unused << NS_WARN_IF(NS_FAILED(rv));
nsAutoCString accept("application/font-woff;q=0.9,*/*;q=0.8");
if (Preferences::GetBool(GFX_PREF_WOFF2_ENABLED)) {
accept.InsertLiteral("application/font-woff2;q=1.0,", 0);
}
rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
accept, false);
NS_ENSURE_SUCCESS(rv, rv);
// For WOFF and WOFF2, we should tell servers/proxies/etc NOT to try
// and apply additional compression at the content-encoding layer
if (aFontFaceSrc->mFormatFlags & (gfxUserFontSet::FLAG_FORMAT_WOFF |
gfxUserFontSet::FLAG_FORMAT_WOFF2)) {
rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Encoding"),
NS_LITERAL_CSTRING("identity"), false);
NS_ENSURE_SUCCESS(rv, rv);
}
}
nsCOMPtr<nsISupportsPriority> priorityChannel(do_QueryInterface(channel));
if (priorityChannel) {
priorityChannel->AdjustPriority(nsISupportsPriority::PRIORITY_HIGH);
}
rv = NS_NewStreamLoader(getter_AddRefs(streamLoader), fontLoader, fontLoader);
NS_ENSURE_SUCCESS(rv, rv);
mozilla::net::PredictorLearn(aFontFaceSrc->mURI->get(),
mDocument->GetDocumentURI(),
nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE,
loadGroup);
rv = channel->AsyncOpen2(streamLoader);
if (NS_FAILED(rv)) {
fontLoader->DropChannel(); // explicitly need to break ref cycle
}
if (NS_SUCCEEDED(rv)) {
mLoaders.PutEntry(fontLoader);
fontLoader->StartedLoading(streamLoader);
aUserFontEntry->SetLoader(fontLoader); // let the font entry remember the
// loader, in case we need to cancel it
}
return rv;
}
bool
FontFaceSet::UpdateRules(const nsTArray<nsFontFaceRuleContainer>& aRules)
{
MOZ_ASSERT(mUserFontSet);
// If there was a change to the mNonRuleFaces array, then there could
// have been a modification to the user font set.
bool modified = mNonRuleFacesDirty;
mNonRuleFacesDirty = false;
// reuse existing FontFace objects mapped to rules already
nsDataHashtable<nsPtrHashKey<RawServoFontFaceRule>, FontFace*> ruleFaceMap;
for (size_t i = 0, i_end = mRuleFaces.Length(); i < i_end; ++i) {
FontFace* f = mRuleFaces[i].mFontFace;
if (!f) {
continue;
}
ruleFaceMap.Put(f->GetRule(), f);
}
// The @font-face rules that make up the user font set have changed,
// so we need to update the set. However, we want to preserve existing
// font entries wherever possible, so that we don't discard and then
// re-download resources in the (common) case where at least some of the
// same rules are still present.
nsTArray<FontFaceRecord> oldRecords;
mRuleFaces.SwapElements(oldRecords);
// Remove faces from the font family records; we need to re-insert them
// because we might end up with faces in a different order even if they're
// the same font entries as before. (The order can affect font selection
// where multiple faces match the requested style, perhaps with overlapping
// unicode-range coverage.)
for (auto it = mUserFontSet->mFontFamilies.Iter(); !it.Done(); it.Next()) {
it.Data()->DetachFontEntries();
}
// Sometimes aRules has duplicate @font-face rules in it; we should make
// that not happen, but in the meantime, don't try to insert the same
// FontFace object more than once into mRuleFaces. We track which
// ones we've handled in this table.
nsTHashtable<nsPtrHashKey<RawServoFontFaceRule>> handledRules;
for (size_t i = 0, i_end = aRules.Length(); i < i_end; ++i) {
// Insert each FontFace objects for each rule into our list, migrating old
// font entries if possible rather than creating new ones; set modified to
// true if we detect that rule ordering has changed, or if a new entry is
// created.
RawServoFontFaceRule* rule = aRules[i].mRule;
if (!handledRules.EnsureInserted(rule)) {
// rule was already present in the hashtable
continue;
}
RefPtr<FontFace> f = ruleFaceMap.Get(rule);
if (!f.get()) {
f = FontFace::CreateForRule(GetParentObject(), this, rule);
}
InsertRuleFontFace(f, aRules[i].mSheetType, oldRecords, modified);
}
for (size_t i = 0, i_end = mNonRuleFaces.Length(); i < i_end; ++i) {
// Do the same for the non rule backed FontFace objects.
InsertNonRuleFontFace(mNonRuleFaces[i].mFontFace, modified);
}
// Remove any residual families that have no font entries (i.e., they were
// not defined at all by the updated set of @font-face rules).
for (auto it = mUserFontSet->mFontFamilies.Iter(); !it.Done(); it.Next()) {
if (it.Data()->GetFontList().IsEmpty()) {
it.Remove();
}
}
// If any FontFace objects for rules are left in the old list, note that the
// set has changed (even if the new set was built entirely by migrating old
// font entries).
if (oldRecords.Length() > 0) {
modified = true;
// Any in-progress loaders for obsolete rules should be cancelled,
// as the resource being downloaded will no longer be required.
// We need to explicitly remove any loaders here, otherwise the loaders
// will keep their "orphaned" font entries alive until they complete,
// even after the oldRules array is deleted.
//
// XXX Now that it is possible for the author to hold on to a rule backed
// FontFace object, we shouldn't cancel loading here; instead we should do
// it when the FontFace is GCed, if we can detect that.
size_t count = oldRecords.Length();
for (size_t i = 0; i < count; ++i) {
RefPtr<FontFace> f = oldRecords[i].mFontFace;
gfxUserFontEntry* userFontEntry = f->GetUserFontEntry();
if (userFontEntry) {
nsFontFaceLoader* loader = userFontEntry->GetLoader();
if (loader) {
loader->Cancel();
RemoveLoader(loader);
}
}
// Any left over FontFace objects should also cease being rule backed.
f->DisconnectFromRule();
}
}
if (modified) {
IncrementGeneration(true);
mHasLoadingFontFacesIsDirty = true;
CheckLoadingStarted();
CheckLoadingFinished();
}
// if local rules needed to be rebuilt, they have been rebuilt at this point
if (mUserFontSet->mRebuildLocalRules) {
mUserFontSet->mLocalRulesUsed = false;
mUserFontSet->mRebuildLocalRules = false;
}
if (LOG_ENABLED() && !mRuleFaces.IsEmpty()) {
LOG(("userfonts (%p) userfont rules update (%s) rule count: %d",
mUserFontSet.get(),
(modified ? "modified" : "not modified"),
(int)(mRuleFaces.Length())));
}
return modified;
}
static bool
HasLocalSrc(const nsCSSValue::Array *aSrcArr)
{
size_t numSrc = aSrcArr->Count();
for (size_t i = 0; i < numSrc; i++) {
if (aSrcArr->Item(i).GetUnit() == eCSSUnit_Local_Font) {
return true;
}
}
return false;
}
void
FontFaceSet::IncrementGeneration(bool aIsRebuild)
{
MOZ_ASSERT(mUserFontSet);
mUserFontSet->IncrementGeneration(aIsRebuild);
}
void
FontFaceSet::InsertNonRuleFontFace(FontFace* aFontFace,
bool& aFontSetModified)
{
nsAutoString fontfamily;
if (!aFontFace->GetFamilyName(fontfamily)) {
// If there is no family name, this rule cannot contribute a
// usable font, so there is no point in processing it further.
return;
}
// Just create a new font entry if we haven't got one already.
if (!aFontFace->GetUserFontEntry()) {
// XXX Should we be checking mUserFontSet->mLocalRulesUsed like
// InsertRuleFontFace does?
RefPtr<gfxUserFontEntry> entry =
FindOrCreateUserFontEntryFromFontFace(fontfamily, aFontFace,
SheetType::Doc);
if (!entry) {
return;
}
aFontFace->SetUserFontEntry(entry);
}
aFontSetModified = true;
mUserFontSet->AddUserFontEntry(fontfamily, aFontFace->GetUserFontEntry());
}
void
FontFaceSet::InsertRuleFontFace(FontFace* aFontFace, SheetType aSheetType,
nsTArray<FontFaceRecord>& aOldRecords,
bool& aFontSetModified)
{
nsAutoString fontfamily;
if (!aFontFace->GetFamilyName(fontfamily)) {
// If there is no family name, this rule cannot contribute a
// usable font, so there is no point in processing it further.
return;
}
bool remove = false;
size_t removeIndex;
// This is a rule backed FontFace. First, we check in aOldRecords; if
// the FontFace for the rule exists there, just move it to the new record
// list, and put the entry into the appropriate family.
for (size_t i = 0; i < aOldRecords.Length(); ++i) {
FontFaceRecord& rec = aOldRecords[i];
if (rec.mFontFace == aFontFace &&
rec.mSheetType == aSheetType) {
// if local rules were used, don't use the old font entry
// for rules containing src local usage
if (mUserFontSet->mLocalRulesUsed &&
mUserFontSet->mRebuildLocalRules) {
nsCSSValue val;
aFontFace->GetDesc(eCSSFontDesc_Src, val);
nsCSSUnit unit = val.GetUnit();
if (unit == eCSSUnit_Array && HasLocalSrc(val.GetArrayValue())) {
// Remove the old record, but wait to see if we successfully create a
// new user font entry below.
remove = true;
removeIndex = i;
break;
}
}
gfxUserFontEntry* entry = rec.mFontFace->GetUserFontEntry();
MOZ_ASSERT(entry, "FontFace should have a gfxUserFontEntry by now");
mUserFontSet->AddUserFontEntry(fontfamily, entry);
MOZ_ASSERT(!HasRuleFontFace(rec.mFontFace),
"FontFace should not occur in mRuleFaces twice");
mRuleFaces.AppendElement(rec);
aOldRecords.RemoveElementAt(i);
// note the set has been modified if an old rule was skipped to find
// this one - something has been dropped, or ordering changed
if (i > 0) {
aFontSetModified = true;
}
return;
}
}
// this is a new rule:
RefPtr<gfxUserFontEntry> entry =
FindOrCreateUserFontEntryFromFontFace(fontfamily, aFontFace, aSheetType);
if (!entry) {
return;
}
if (remove) {
// Although we broke out of the aOldRecords loop above, since we found
// src local usage, and we're not using the old user font entry, we still
// are adding a record to mRuleFaces with the same FontFace object.
// Remove the old record so that we don't have the same FontFace listed
// in both mRuleFaces and oldRecords, which would cause us to call
// DisconnectFromRule on a FontFace that should still be rule backed.
aOldRecords.RemoveElementAt(removeIndex);
}
FontFaceRecord rec;
rec.mFontFace = aFontFace;
rec.mSheetType = aSheetType;
rec.mLoadEventShouldFire =
aFontFace->Status() == FontFaceLoadStatus::Unloaded ||
aFontFace->Status() == FontFaceLoadStatus::Loading;
aFontFace->SetUserFontEntry(entry);
MOZ_ASSERT(!HasRuleFontFace(aFontFace),
"FontFace should not occur in mRuleFaces twice");
mRuleFaces.AppendElement(rec);
// this was a new rule and font entry, so note that the set was modified
aFontSetModified = true;
// Add the entry to the end of the list. If an existing userfont entry was
// returned by FindOrCreateUserFontEntryFromFontFace that was already stored
// on the family, gfxUserFontFamily::AddFontEntry(), which AddUserFontEntry
// calls, will automatically remove the earlier occurrence of the same
// userfont entry.
mUserFontSet->AddUserFontEntry(fontfamily, entry);
}
/* static */ already_AddRefed<gfxUserFontEntry>
FontFaceSet::FindOrCreateUserFontEntryFromFontFace(FontFace* aFontFace)
{
nsAutoString fontfamily;
if (!aFontFace->GetFamilyName(fontfamily)) {
// If there is no family name, this rule cannot contribute a
// usable font, so there is no point in processing it further.
return nullptr;
}
return FindOrCreateUserFontEntryFromFontFace(fontfamily, aFontFace,
SheetType::Doc);
}
/* static */ already_AddRefed<gfxUserFontEntry>
FontFaceSet::FindOrCreateUserFontEntryFromFontFace(const nsAString& aFamilyName,
FontFace* aFontFace,
SheetType aSheetType)
{
FontFaceSet* set = aFontFace->GetPrimaryFontFaceSet();
nsCSSValue val;
nsCSSUnit unit;
uint32_t weight = NS_FONT_WEIGHT_NORMAL;
int32_t stretch = NS_STYLE_FONT_STRETCH_NORMAL;
uint8_t italicStyle = NS_STYLE_FONT_STYLE_NORMAL;
uint32_t languageOverride = NO_FONT_LANGUAGE_OVERRIDE;
uint8_t fontDisplay = NS_FONT_DISPLAY_AUTO;
// set up weight
aFontFace->GetDesc(eCSSFontDesc_Weight, val);
unit = val.GetUnit();
if (unit == eCSSUnit_Integer || unit == eCSSUnit_Enumerated) {
weight = val.GetIntValue();
if (weight == 0) {
weight = NS_FONT_WEIGHT_NORMAL;
}
} else if (unit == eCSSUnit_Normal) {
weight = NS_FONT_WEIGHT_NORMAL;
} else {
NS_ASSERTION(unit == eCSSUnit_Null,
"@font-face weight has unexpected unit");
}
// set up stretch
aFontFace->GetDesc(eCSSFontDesc_Stretch, val);
unit = val.GetUnit();
if (unit == eCSSUnit_Enumerated) {
stretch = val.GetIntValue();