-
Notifications
You must be signed in to change notification settings - Fork 54
/
gfxFontUtils.cpp
1912 lines (1599 loc) · 64.7 KB
/
gfxFontUtils.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/ArrayUtils.h"
#include "mozilla/BinarySearch.h"
#include "gfxFontUtils.h"
#include "gfxFontEntry.h"
#include "gfxFontVariations.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/Preferences.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/Sprintf.h"
#include "mozilla/Unused.h"
#include "nsCOMPtr.h"
#include "nsIUUIDGenerator.h"
#include "mozilla/Encoding.h"
#include "harfbuzz/hb.h"
#include "plbase64.h"
#include "mozilla/Logging.h"
#ifdef XP_MACOSX
# include <CoreFoundation/CoreFoundation.h>
#endif
#define LOG(log, args) MOZ_LOG(gfxPlatform::GetLog(log), LogLevel::Debug, args)
#define UNICODE_BMP_LIMIT 0x10000
using namespace mozilla;
#pragma pack(1)
typedef struct {
AutoSwap_PRUint16 format;
AutoSwap_PRUint16 reserved;
AutoSwap_PRUint32 length;
AutoSwap_PRUint32 language;
AutoSwap_PRUint32 startCharCode;
AutoSwap_PRUint32 numChars;
} Format10CmapHeader;
typedef struct {
AutoSwap_PRUint16 format;
AutoSwap_PRUint16 reserved;
AutoSwap_PRUint32 length;
AutoSwap_PRUint32 language;
AutoSwap_PRUint32 numGroups;
} Format12CmapHeader;
typedef struct {
AutoSwap_PRUint32 startCharCode;
AutoSwap_PRUint32 endCharCode;
AutoSwap_PRUint32 startGlyphId;
} Format12Group;
#pragma pack()
void gfxSparseBitSet::Dump(const char* aPrefix, eGfxLog aWhichLog) const {
uint32_t numBlocks = mBlockIndex.Length();
for (uint32_t b = 0; b < numBlocks; b++) {
if (mBlockIndex[b] == NO_BLOCK) {
continue;
}
const Block* block = &mBlocks[mBlockIndex[b]];
const int BUFSIZE = 256;
char outStr[BUFSIZE];
int index = 0;
index += snprintf(&outStr[index], BUFSIZE - index, "%s u+%6.6x [", aPrefix,
(b * BLOCK_SIZE_BITS));
for (int i = 0; i < 32; i += 4) {
for (int j = i; j < i + 4; j++) {
uint8_t bits = block->mBits[j];
uint8_t flip1 = ((bits & 0xaa) >> 1) | ((bits & 0x55) << 1);
uint8_t flip2 = ((flip1 & 0xcc) >> 2) | ((flip1 & 0x33) << 2);
uint8_t flipped = ((flip2 & 0xf0) >> 4) | ((flip2 & 0x0f) << 4);
index += snprintf(&outStr[index], BUFSIZE - index, "%2.2x", flipped);
}
if (i + 4 != 32) index += snprintf(&outStr[index], BUFSIZE - index, " ");
}
Unused << snprintf(&outStr[index], BUFSIZE - index, "]");
LOG(aWhichLog, ("%s", outStr));
}
}
nsresult gfxFontUtils::ReadCMAPTableFormat10(const uint8_t* aBuf,
uint32_t aLength,
gfxSparseBitSet& aCharacterMap) {
// Ensure table is large enough that we can safely read the header
NS_ENSURE_TRUE(aLength >= sizeof(Format10CmapHeader),
NS_ERROR_GFX_CMAP_MALFORMED);
// Sanity-check header fields
const Format10CmapHeader* cmap10 =
reinterpret_cast<const Format10CmapHeader*>(aBuf);
NS_ENSURE_TRUE(uint16_t(cmap10->format) == 10, NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(uint16_t(cmap10->reserved) == 0, NS_ERROR_GFX_CMAP_MALFORMED);
uint32_t tablelen = cmap10->length;
NS_ENSURE_TRUE(tablelen >= sizeof(Format10CmapHeader) && tablelen <= aLength,
NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(cmap10->language == 0, NS_ERROR_GFX_CMAP_MALFORMED);
uint32_t numChars = cmap10->numChars;
NS_ENSURE_TRUE(
tablelen == sizeof(Format10CmapHeader) + numChars * sizeof(uint16_t),
NS_ERROR_GFX_CMAP_MALFORMED);
uint32_t charCode = cmap10->startCharCode;
NS_ENSURE_TRUE(charCode <= CMAP_MAX_CODEPOINT &&
charCode + numChars <= CMAP_MAX_CODEPOINT,
NS_ERROR_GFX_CMAP_MALFORMED);
// glyphs[] array immediately follows the subtable header
const AutoSwap_PRUint16* glyphs =
reinterpret_cast<const AutoSwap_PRUint16*>(cmap10 + 1);
for (uint32_t i = 0; i < numChars; ++i) {
if (uint16_t(*glyphs) != 0) {
aCharacterMap.set(charCode);
}
++charCode;
++glyphs;
}
aCharacterMap.Compact();
return NS_OK;
}
nsresult gfxFontUtils::ReadCMAPTableFormat12or13(
const uint8_t* aBuf, uint32_t aLength, gfxSparseBitSet& aCharacterMap) {
// Format 13 has the same structure as format 12, the only difference is
// the interpretation of the glyphID field. So we can share the code here
// that reads the table and just records character coverage.
// Ensure table is large enough that we can safely read the header
NS_ENSURE_TRUE(aLength >= sizeof(Format12CmapHeader),
NS_ERROR_GFX_CMAP_MALFORMED);
// Sanity-check header fields
const Format12CmapHeader* cmap12 =
reinterpret_cast<const Format12CmapHeader*>(aBuf);
NS_ENSURE_TRUE(
uint16_t(cmap12->format) == 12 || uint16_t(cmap12->format) == 13,
NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(uint16_t(cmap12->reserved) == 0, NS_ERROR_GFX_CMAP_MALFORMED);
uint32_t tablelen = cmap12->length;
NS_ENSURE_TRUE(tablelen >= sizeof(Format12CmapHeader) && tablelen <= aLength,
NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(cmap12->language == 0, NS_ERROR_GFX_CMAP_MALFORMED);
// Check that the table is large enough for the group array
const uint32_t numGroups = cmap12->numGroups;
NS_ENSURE_TRUE(
(tablelen - sizeof(Format12CmapHeader)) / sizeof(Format12Group) >=
numGroups,
NS_ERROR_GFX_CMAP_MALFORMED);
// The array of groups immediately follows the subtable header.
const Format12Group* group =
reinterpret_cast<const Format12Group*>(aBuf + sizeof(Format12CmapHeader));
// Check that groups are in correct order and do not overlap,
// and record character coverage in aCharacterMap.
uint32_t prevEndCharCode = 0;
for (uint32_t i = 0; i < numGroups; i++, group++) {
uint32_t startCharCode = group->startCharCode;
const uint32_t endCharCode = group->endCharCode;
NS_ENSURE_TRUE((prevEndCharCode < startCharCode || i == 0) &&
startCharCode <= endCharCode &&
endCharCode <= CMAP_MAX_CODEPOINT,
NS_ERROR_GFX_CMAP_MALFORMED);
// don't include a character that maps to glyph ID 0 (.notdef)
if (group->startGlyphId == 0) {
startCharCode++;
}
if (startCharCode <= endCharCode) {
aCharacterMap.SetRange(startCharCode, endCharCode);
}
prevEndCharCode = endCharCode;
}
aCharacterMap.Compact();
return NS_OK;
}
nsresult gfxFontUtils::ReadCMAPTableFormat4(const uint8_t* aBuf,
uint32_t aLength,
gfxSparseBitSet& aCharacterMap) {
enum {
OffsetFormat = 0,
OffsetLength = 2,
OffsetLanguage = 4,
OffsetSegCountX2 = 6
};
NS_ENSURE_TRUE(ReadShortAt(aBuf, OffsetFormat) == 4,
NS_ERROR_GFX_CMAP_MALFORMED);
uint16_t tablelen = ReadShortAt(aBuf, OffsetLength);
NS_ENSURE_TRUE(tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(tablelen > 16, NS_ERROR_GFX_CMAP_MALFORMED);
// This field should normally (except for Mac platform subtables) be zero
// according to the OT spec, but some buggy fonts have lang = 1 (which would
// be English for MacOS). E.g. Arial Narrow Bold, v. 1.1 (Tiger), Arial
// Unicode MS (see bug 530614). So accept either zero or one here; the error
// should be harmless.
NS_ENSURE_TRUE((ReadShortAt(aBuf, OffsetLanguage) & 0xfffe) == 0,
NS_ERROR_GFX_CMAP_MALFORMED);
uint16_t segCountX2 = ReadShortAt(aBuf, OffsetSegCountX2);
NS_ENSURE_TRUE(tablelen >= 16 + (segCountX2 * 4),
NS_ERROR_GFX_CMAP_MALFORMED);
const uint16_t segCount = segCountX2 / 2;
const uint16_t* endCounts = reinterpret_cast<const uint16_t*>(aBuf + 14);
const uint16_t* startCounts =
endCounts + 1 /* skip one uint16_t for reservedPad */ + segCount;
const uint16_t* idDeltas = startCounts + segCount;
const uint16_t* idRangeOffsets = idDeltas + segCount;
uint16_t prevEndCount = 0;
for (uint16_t i = 0; i < segCount; i++) {
const uint16_t endCount = ReadShortAt16(endCounts, i);
const uint16_t startCount = ReadShortAt16(startCounts, i);
const uint16_t idRangeOffset = ReadShortAt16(idRangeOffsets, i);
// sanity-check range
// This permits ranges to overlap by 1 character, which is strictly
// incorrect but occurs in Baskerville on OS X 10.7 (see bug 689087),
// and appears to be harmless in practice
NS_ENSURE_TRUE(startCount >= prevEndCount && startCount <= endCount,
NS_ERROR_GFX_CMAP_MALFORMED);
prevEndCount = endCount;
if (idRangeOffset == 0) {
// figure out if there's a code in the range that would map to
// glyph ID 0 (.notdef); if so, we need to skip setting that
// character code in the map
const uint16_t skipCode = 65536 - ReadShortAt16(idDeltas, i);
if (startCount < skipCode) {
aCharacterMap.SetRange(startCount,
std::min<uint16_t>(skipCode - 1, endCount));
}
if (skipCode < endCount) {
aCharacterMap.SetRange(std::max<uint16_t>(startCount, skipCode + 1),
endCount);
}
} else {
// Unused: self-documenting.
// const uint16_t idDelta = ReadShortAt16(idDeltas, i);
for (uint32_t c = startCount; c <= endCount; ++c) {
if (c == 0xFFFF) break;
const uint16_t* gdata =
(idRangeOffset / 2 + (c - startCount) + &idRangeOffsets[i]);
NS_ENSURE_TRUE(
(uint8_t*)gdata > aBuf && (uint8_t*)gdata < aBuf + aLength,
NS_ERROR_GFX_CMAP_MALFORMED);
// make sure we have a glyph
if (*gdata != 0) {
// The glyph index at this point is:
uint16_t glyph = ReadShortAt16(idDeltas, i) + *gdata;
if (glyph) {
aCharacterMap.set(c);
}
}
}
}
}
aCharacterMap.Compact();
return NS_OK;
}
nsresult gfxFontUtils::ReadCMAPTableFormat14(const uint8_t* aBuf,
uint32_t aLength,
UniquePtr<uint8_t[]>& aTable) {
enum {
OffsetFormat = 0,
OffsetTableLength = 2,
OffsetNumVarSelectorRecords = 6,
OffsetVarSelectorRecords = 10,
SizeOfVarSelectorRecord = 11,
VSRecOffsetVarSelector = 0,
VSRecOffsetDefUVSOffset = 3,
VSRecOffsetNonDefUVSOffset = 7,
SizeOfDefUVSTable = 4,
DefUVSOffsetStartUnicodeValue = 0,
DefUVSOffsetAdditionalCount = 3,
SizeOfNonDefUVSTable = 5,
NonDefUVSOffsetUnicodeValue = 0,
NonDefUVSOffsetGlyphID = 3
};
NS_ENSURE_TRUE(aLength >= OffsetVarSelectorRecords,
NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(ReadShortAt(aBuf, OffsetFormat) == 14,
NS_ERROR_GFX_CMAP_MALFORMED);
uint32_t tablelen = ReadLongAt(aBuf, OffsetTableLength);
NS_ENSURE_TRUE(tablelen <= aLength, NS_ERROR_GFX_CMAP_MALFORMED);
NS_ENSURE_TRUE(tablelen >= OffsetVarSelectorRecords,
NS_ERROR_GFX_CMAP_MALFORMED);
const uint32_t numVarSelectorRecords =
ReadLongAt(aBuf, OffsetNumVarSelectorRecords);
NS_ENSURE_TRUE(
(tablelen - OffsetVarSelectorRecords) / SizeOfVarSelectorRecord >=
numVarSelectorRecords,
NS_ERROR_GFX_CMAP_MALFORMED);
const uint8_t* records = aBuf + OffsetVarSelectorRecords;
for (uint32_t i = 0; i < numVarSelectorRecords;
i++, records += SizeOfVarSelectorRecord) {
const uint32_t varSelector = ReadUint24At(records, VSRecOffsetVarSelector);
const uint32_t defUVSOffset = ReadLongAt(records, VSRecOffsetDefUVSOffset);
const uint32_t nonDefUVSOffset =
ReadLongAt(records, VSRecOffsetNonDefUVSOffset);
NS_ENSURE_TRUE(varSelector <= CMAP_MAX_CODEPOINT &&
defUVSOffset <= tablelen - 4 &&
nonDefUVSOffset <= tablelen - 4,
NS_ERROR_GFX_CMAP_MALFORMED);
if (defUVSOffset) {
const uint32_t numUnicodeValueRanges = ReadLongAt(aBuf, defUVSOffset);
NS_ENSURE_TRUE((tablelen - defUVSOffset) / SizeOfDefUVSTable >=
numUnicodeValueRanges,
NS_ERROR_GFX_CMAP_MALFORMED);
const uint8_t* tables = aBuf + defUVSOffset + 4;
uint32_t prevEndUnicode = 0;
for (uint32_t j = 0; j < numUnicodeValueRanges;
j++, tables += SizeOfDefUVSTable) {
const uint32_t startUnicode =
ReadUint24At(tables, DefUVSOffsetStartUnicodeValue);
const uint32_t endUnicode =
startUnicode + tables[DefUVSOffsetAdditionalCount];
NS_ENSURE_TRUE((prevEndUnicode < startUnicode || j == 0) &&
endUnicode <= CMAP_MAX_CODEPOINT,
NS_ERROR_GFX_CMAP_MALFORMED);
prevEndUnicode = endUnicode;
}
}
if (nonDefUVSOffset) {
const uint32_t numUVSMappings = ReadLongAt(aBuf, nonDefUVSOffset);
NS_ENSURE_TRUE(
(tablelen - nonDefUVSOffset) / SizeOfNonDefUVSTable >= numUVSMappings,
NS_ERROR_GFX_CMAP_MALFORMED);
const uint8_t* tables = aBuf + nonDefUVSOffset + 4;
uint32_t prevUnicode = 0;
for (uint32_t j = 0; j < numUVSMappings;
j++, tables += SizeOfNonDefUVSTable) {
const uint32_t unicodeValue =
ReadUint24At(tables, NonDefUVSOffsetUnicodeValue);
NS_ENSURE_TRUE((prevUnicode < unicodeValue || j == 0) &&
unicodeValue <= CMAP_MAX_CODEPOINT,
NS_ERROR_GFX_CMAP_MALFORMED);
prevUnicode = unicodeValue;
}
}
}
aTable = MakeUnique<uint8_t[]>(tablelen);
memcpy(aTable.get(), aBuf, tablelen);
return NS_OK;
}
// For fonts with two format-4 tables, the first one (Unicode platform) is
// preferred on the Mac; on other platforms we allow the Microsoft-platform
// subtable to replace it.
#if defined(XP_MACOSX)
# define acceptableFormat4(p, e, k) \
(((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDMicrosoft && !(k)) || \
((p) == PLATFORM_ID_UNICODE))
# define acceptableUCS4Encoding(p, e, k) \
(((p) == PLATFORM_ID_MICROSOFT && \
(e) == EncodingIDUCS4ForMicrosoftPlatform) && \
(k) != 12 || \
((p) == PLATFORM_ID_UNICODE && ((e) != EncodingIDUVSForUnicodePlatform)))
#else
# define acceptableFormat4(p, e, k) \
(((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDMicrosoft) || \
((p) == PLATFORM_ID_UNICODE))
# define acceptableUCS4Encoding(p, e, k) \
((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDUCS4ForMicrosoftPlatform)
#endif
#define acceptablePlatform(p) \
((p) == PLATFORM_ID_UNICODE || (p) == PLATFORM_ID_MICROSOFT)
#define isSymbol(p, e) ((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDSymbol)
#define isUVSEncoding(p, e) \
((p) == PLATFORM_ID_UNICODE && (e) == EncodingIDUVSForUnicodePlatform)
uint32_t gfxFontUtils::FindPreferredSubtable(const uint8_t* aBuf,
uint32_t aBufLength,
uint32_t* aTableOffset,
uint32_t* aUVSTableOffset) {
enum {
OffsetVersion = 0,
OffsetNumTables = 2,
SizeOfHeader = 4,
TableOffsetPlatformID = 0,
TableOffsetEncodingID = 2,
TableOffsetOffset = 4,
SizeOfTable = 8,
SubtableOffsetFormat = 0
};
enum {
EncodingIDSymbol = 0,
EncodingIDMicrosoft = 1,
EncodingIDDefaultForUnicodePlatform = 0,
EncodingIDUCS4ForUnicodePlatform = 3,
EncodingIDUVSForUnicodePlatform = 5,
EncodingIDUCS4ForMicrosoftPlatform = 10
};
if (aUVSTableOffset) {
*aUVSTableOffset = 0;
}
if (!aBuf || aBufLength < SizeOfHeader) {
// cmap table is missing, or too small to contain header fields!
return 0;
}
// uint16_t version = ReadShortAt(aBuf, OffsetVersion); // Unused:
// self-documenting.
uint16_t numTables = ReadShortAt(aBuf, OffsetNumTables);
if (aBufLength < uint32_t(SizeOfHeader + numTables * SizeOfTable)) {
return 0;
}
// save the format we want here
uint32_t keepFormat = 0;
const uint8_t* table = aBuf + SizeOfHeader;
for (uint16_t i = 0; i < numTables; ++i, table += SizeOfTable) {
const uint16_t platformID = ReadShortAt(table, TableOffsetPlatformID);
if (!acceptablePlatform(platformID)) continue;
const uint16_t encodingID = ReadShortAt(table, TableOffsetEncodingID);
const uint32_t offset = ReadLongAt(table, TableOffsetOffset);
if (aBufLength - 2 < offset) {
// this subtable is not valid - beyond end of buffer
return 0;
}
const uint8_t* subtable = aBuf + offset;
const uint16_t format = ReadShortAt(subtable, SubtableOffsetFormat);
if (isSymbol(platformID, encodingID)) {
keepFormat = format;
*aTableOffset = offset;
break;
} else if (format == 4 &&
acceptableFormat4(platformID, encodingID, keepFormat)) {
keepFormat = format;
*aTableOffset = offset;
} else if ((format == 10 || format == 12 || format == 13) &&
acceptableUCS4Encoding(platformID, encodingID, keepFormat)) {
keepFormat = format;
*aTableOffset = offset;
if (platformID > PLATFORM_ID_UNICODE || !aUVSTableOffset ||
*aUVSTableOffset) {
break; // we don't want to try anything else when this format is
// available.
}
} else if (format == 14 && isUVSEncoding(platformID, encodingID) &&
aUVSTableOffset) {
*aUVSTableOffset = offset;
if (keepFormat == 10 || keepFormat == 12) {
break;
}
}
}
return keepFormat;
}
nsresult gfxFontUtils::ReadCMAP(const uint8_t* aBuf, uint32_t aBufLength,
gfxSparseBitSet& aCharacterMap,
uint32_t& aUVSOffset) {
uint32_t offset;
uint32_t format =
FindPreferredSubtable(aBuf, aBufLength, &offset, &aUVSOffset);
switch (format) {
case 4:
return ReadCMAPTableFormat4(aBuf + offset, aBufLength - offset,
aCharacterMap);
case 10:
return ReadCMAPTableFormat10(aBuf + offset, aBufLength - offset,
aCharacterMap);
case 12:
case 13:
return ReadCMAPTableFormat12or13(aBuf + offset, aBufLength - offset,
aCharacterMap);
default:
break;
}
return NS_ERROR_FAILURE;
}
#pragma pack(1)
typedef struct {
AutoSwap_PRUint16 format;
AutoSwap_PRUint16 length;
AutoSwap_PRUint16 language;
AutoSwap_PRUint16 segCountX2;
AutoSwap_PRUint16 searchRange;
AutoSwap_PRUint16 entrySelector;
AutoSwap_PRUint16 rangeShift;
AutoSwap_PRUint16 arrays[1];
} Format4Cmap;
typedef struct {
AutoSwap_PRUint16 format;
AutoSwap_PRUint32 length;
AutoSwap_PRUint32 numVarSelectorRecords;
typedef struct {
AutoSwap_PRUint24 varSelector;
AutoSwap_PRUint32 defaultUVSOffset;
AutoSwap_PRUint32 nonDefaultUVSOffset;
} VarSelectorRecord;
VarSelectorRecord varSelectorRecords[1];
} Format14Cmap;
typedef struct {
AutoSwap_PRUint32 numUVSMappings;
typedef struct {
AutoSwap_PRUint24 unicodeValue;
AutoSwap_PRUint16 glyphID;
} UVSMapping;
UVSMapping uvsMappings[1];
} NonDefUVSTable;
#pragma pack()
uint32_t gfxFontUtils::MapCharToGlyphFormat4(const uint8_t* aBuf,
uint32_t aLength, char16_t aCh) {
const Format4Cmap* cmap4 = reinterpret_cast<const Format4Cmap*>(aBuf);
uint16_t segCount = (uint16_t)(cmap4->segCountX2) / 2;
const AutoSwap_PRUint16* endCodes = &cmap4->arrays[0];
const AutoSwap_PRUint16* startCodes = &cmap4->arrays[segCount + 1];
const AutoSwap_PRUint16* idDelta = &startCodes[segCount];
const AutoSwap_PRUint16* idRangeOffset = &idDelta[segCount];
// Sanity-check that the fixed-size arrays don't exceed the buffer.
const uint8_t* const limit = aBuf + aLength;
if ((const uint8_t*)(&idRangeOffset[segCount]) > limit) {
return 0; // broken font, just bail out safely
}
// For most efficient binary search, we want to work on a range of segment
// indexes that is a power of 2 so that we can always halve it by shifting.
// So we find the largest power of 2 that is <= segCount.
// We will offset this range by segOffset so as to reach the end
// of the table, provided that doesn't put us beyond the target
// value from the outset.
uint32_t powerOf2 = mozilla::FindHighestBit(segCount);
uint32_t segOffset = segCount - powerOf2;
uint32_t idx = 0;
if (uint16_t(startCodes[segOffset]) <= aCh) {
idx = segOffset;
}
// Repeatedly halve the size of the range until we find the target group
while (powerOf2 > 1) {
powerOf2 >>= 1;
if (uint16_t(startCodes[idx + powerOf2]) <= aCh) {
idx += powerOf2;
}
}
if (aCh >= uint16_t(startCodes[idx]) && aCh <= uint16_t(endCodes[idx])) {
uint16_t result;
if (uint16_t(idRangeOffset[idx]) == 0) {
result = aCh;
} else {
uint16_t offset = aCh - uint16_t(startCodes[idx]);
const AutoSwap_PRUint16* glyphIndexTable =
(const AutoSwap_PRUint16*)((const char*)&idRangeOffset[idx] +
uint16_t(idRangeOffset[idx]));
if ((const uint8_t*)(glyphIndexTable + offset + 1) > limit) {
return 0; // broken font, just bail out safely
}
result = glyphIndexTable[offset];
}
// Note that this is unsigned 16-bit arithmetic, and may wrap around
// (which is required behavior per spec)
result += uint16_t(idDelta[idx]);
return result;
}
return 0;
}
uint32_t gfxFontUtils::MapCharToGlyphFormat10(const uint8_t* aBuf,
uint32_t aCh) {
const Format10CmapHeader* cmap10 =
reinterpret_cast<const Format10CmapHeader*>(aBuf);
uint32_t startChar = cmap10->startCharCode;
uint32_t numChars = cmap10->numChars;
if (aCh < startChar || aCh >= startChar + numChars) {
return 0;
}
const AutoSwap_PRUint16* glyphs =
reinterpret_cast<const AutoSwap_PRUint16*>(cmap10 + 1);
uint16_t glyph = glyphs[aCh - startChar];
return glyph;
}
uint32_t gfxFontUtils::MapCharToGlyphFormat12or13(const uint8_t* aBuf,
uint32_t aCh) {
// The only difference between formats 12 and 13 is the interpretation of
// the glyphId field. So the code here uses the same "Format12" structures,
// etc., to handle both subtable formats.
const Format12CmapHeader* cmap12 =
reinterpret_cast<const Format12CmapHeader*>(aBuf);
// We know that numGroups is within range for the subtable size
// because it was checked by ReadCMAPTableFormat12or13.
uint32_t numGroups = cmap12->numGroups;
// The array of groups immediately follows the subtable header.
const Format12Group* groups =
reinterpret_cast<const Format12Group*>(aBuf + sizeof(Format12CmapHeader));
// For most efficient binary search, we want to work on a range that
// is a power of 2 so that we can always halve it by shifting.
// So we find the largest power of 2 that is <= numGroups.
// We will offset this range by rangeOffset so as to reach the end
// of the table, provided that doesn't put us beyond the target
// value from the outset.
uint32_t powerOf2 = mozilla::FindHighestBit(numGroups);
uint32_t rangeOffset = numGroups - powerOf2;
uint32_t range = 0;
uint32_t startCharCode;
if (groups[rangeOffset].startCharCode <= aCh) {
range = rangeOffset;
}
// Repeatedly halve the size of the range until we find the target group
while (powerOf2 > 1) {
powerOf2 >>= 1;
if (groups[range + powerOf2].startCharCode <= aCh) {
range += powerOf2;
}
}
// Check if the character is actually present in the range and return
// the corresponding glyph ID. Here is where formats 12 and 13 interpret
// the startGlyphId (12) or glyphId (13) field differently
startCharCode = groups[range].startCharCode;
if (startCharCode <= aCh && groups[range].endCharCode >= aCh) {
return uint16_t(cmap12->format) == 12
? uint16_t(groups[range].startGlyphId) + aCh - startCharCode
: uint16_t(groups[range].startGlyphId);
}
// Else it's not present, so return the .notdef glyph
return 0;
}
namespace {
struct Format14CmapWrapper {
const Format14Cmap& mCmap14;
explicit Format14CmapWrapper(const Format14Cmap& cmap14) : mCmap14(cmap14) {}
uint32_t operator[](size_t index) const {
return mCmap14.varSelectorRecords[index].varSelector;
}
};
struct NonDefUVSTableWrapper {
const NonDefUVSTable& mTable;
explicit NonDefUVSTableWrapper(const NonDefUVSTable& table) : mTable(table) {}
uint32_t operator[](size_t index) const {
return mTable.uvsMappings[index].unicodeValue;
}
};
} // namespace
uint16_t gfxFontUtils::MapUVSToGlyphFormat14(const uint8_t* aBuf, uint32_t aCh,
uint32_t aVS) {
using mozilla::BinarySearch;
const Format14Cmap* cmap14 = reinterpret_cast<const Format14Cmap*>(aBuf);
size_t index;
if (!BinarySearch(Format14CmapWrapper(*cmap14), 0,
cmap14->numVarSelectorRecords, aVS, &index)) {
return 0;
}
const uint32_t nonDefUVSOffset =
cmap14->varSelectorRecords[index].nonDefaultUVSOffset;
if (!nonDefUVSOffset) {
return 0;
}
const NonDefUVSTable* table =
reinterpret_cast<const NonDefUVSTable*>(aBuf + nonDefUVSOffset);
if (BinarySearch(NonDefUVSTableWrapper(*table), 0, table->numUVSMappings, aCh,
&index)) {
return table->uvsMappings[index].glyphID;
}
return 0;
}
uint32_t gfxFontUtils::MapCharToGlyph(const uint8_t* aCmapBuf,
uint32_t aBufLength, uint32_t aUnicode,
uint32_t aVarSelector) {
uint32_t offset, uvsOffset;
uint32_t format =
FindPreferredSubtable(aCmapBuf, aBufLength, &offset, &uvsOffset);
uint32_t gid;
switch (format) {
case 4:
gid = aUnicode < UNICODE_BMP_LIMIT
? MapCharToGlyphFormat4(aCmapBuf + offset, aBufLength - offset,
char16_t(aUnicode))
: 0;
break;
case 10:
gid = MapCharToGlyphFormat10(aCmapBuf + offset, aUnicode);
break;
case 12:
case 13:
gid = MapCharToGlyphFormat12or13(aCmapBuf + offset, aUnicode);
break;
default:
NS_WARNING("unsupported cmap format, glyphs will be missing");
gid = 0;
}
if (aVarSelector && uvsOffset && gid) {
uint32_t varGID = gfxFontUtils::MapUVSToGlyphFormat14(
aCmapBuf + uvsOffset, aUnicode, aVarSelector);
if (!varGID) {
aUnicode = gfxFontUtils::GetUVSFallback(aUnicode, aVarSelector);
if (aUnicode) {
switch (format) {
case 4:
if (aUnicode < UNICODE_BMP_LIMIT) {
varGID = MapCharToGlyphFormat4(
aCmapBuf + offset, aBufLength - offset, char16_t(aUnicode));
}
break;
case 10:
varGID = MapCharToGlyphFormat10(aCmapBuf + offset, aUnicode);
break;
case 12:
case 13:
varGID = MapCharToGlyphFormat12or13(aCmapBuf + offset, aUnicode);
break;
}
}
}
if (varGID) {
gid = varGID;
}
// else the variation sequence was not supported, use default mapping
// of the character code alone
}
return gid;
}
void gfxFontUtils::ParseFontList(const nsACString& aFamilyList,
nsTArray<nsCString>& aFontList) {
const char kComma = ',';
// append each font name to the list
nsAutoCString fontname;
const char *p, *p_end;
aFamilyList.BeginReading(p);
aFamilyList.EndReading(p_end);
while (p < p_end) {
const char* nameStart = p;
while (++p != p_end && *p != kComma) /* nothing */
;
// pull out a single name and clean out leading/trailing whitespace
fontname = Substring(nameStart, p);
fontname.CompressWhitespace(true, true);
// append it to the list if it's not empty
if (!fontname.IsEmpty()) {
aFontList.AppendElement(fontname);
}
++p;
}
}
void gfxFontUtils::AppendPrefsFontList(const char* aPrefName,
nsTArray<nsCString>& aFontList) {
// get the list of single-face font families
nsAutoCString fontlistValue;
nsresult rv = Preferences::GetCString(aPrefName, fontlistValue);
if (NS_FAILED(rv)) {
return;
}
ParseFontList(fontlistValue, aFontList);
}
void gfxFontUtils::GetPrefsFontList(const char* aPrefName,
nsTArray<nsCString>& aFontList) {
aFontList.Clear();
AppendPrefsFontList(aPrefName, aFontList);
}
// produce a unique font name that is (1) a valid Postscript name and (2) less
// than 31 characters in length. Using AddFontMemResourceEx on Windows fails
// for names longer than 30 characters in length.
#define MAX_B64_LEN 32
nsresult gfxFontUtils::MakeUniqueUserFontName(nsAString& aName) {
nsCOMPtr<nsIUUIDGenerator> uuidgen =
do_GetService("@mozilla.org/uuid-generator;1");
NS_ENSURE_TRUE(uuidgen, NS_ERROR_OUT_OF_MEMORY);
nsID guid;
NS_ASSERTION(sizeof(guid) * 2 <= MAX_B64_LEN, "size of nsID has changed!");
nsresult rv = uuidgen->GenerateUUIDInPlace(&guid);
NS_ENSURE_SUCCESS(rv, rv);
char guidB64[MAX_B64_LEN] = {0};
if (!PL_Base64Encode(reinterpret_cast<char*>(&guid), sizeof(guid), guidB64))
return NS_ERROR_FAILURE;
// all b64 characters except for '/' are allowed in Postscript names, so
// convert / ==> -
char* p;
for (p = guidB64; *p; p++) {
if (*p == '/') *p = '-';
}
aName.AssignLiteral(u"uf");
aName.AppendASCII(guidB64);
return NS_OK;
}
// TrueType/OpenType table handling code
// need byte aligned structs
#pragma pack(1)
// name table stores set of name record structures, followed by
// large block containing all the strings. name record offset and length
// indicates the offset and length within that block.
// http://www.microsoft.com/typography/otspec/name.htm
struct NameRecordData {
uint32_t offset;
uint32_t length;
};
#pragma pack()
static bool IsValidSFNTVersion(uint32_t version) {
// normally 0x00010000, CFF-style OT fonts == 'OTTO' and Apple TT fonts =
// 'true' 'typ1' is also possible for old Type 1 fonts in a SFNT container but
// not supported
return version == 0x10000 || version == TRUETYPE_TAG('O', 'T', 'T', 'O') ||
version == TRUETYPE_TAG('t', 'r', 'u', 'e');
}
gfxUserFontType gfxFontUtils::DetermineFontDataType(const uint8_t* aFontData,
uint32_t aFontDataLength) {
// test for OpenType font data
// problem: EOT-Lite with 0x10000 length will look like TrueType!
if (aFontDataLength >= sizeof(SFNTHeader)) {
const SFNTHeader* sfntHeader =
reinterpret_cast<const SFNTHeader*>(aFontData);
uint32_t sfntVersion = sfntHeader->sfntVersion;
if (IsValidSFNTVersion(sfntVersion)) {
return GFX_USERFONT_OPENTYPE;
}
}
// test for WOFF or WOFF2
if (aFontDataLength >= sizeof(AutoSwap_PRUint32)) {
const AutoSwap_PRUint32* version =
reinterpret_cast<const AutoSwap_PRUint32*>(aFontData);
if (uint32_t(*version) == TRUETYPE_TAG('w', 'O', 'F', 'F')) {
return GFX_USERFONT_WOFF;
}
if (uint32_t(*version) == TRUETYPE_TAG('w', 'O', 'F', '2')) {
return GFX_USERFONT_WOFF2;
}
}
// tests for other formats here
return GFX_USERFONT_UNKNOWN;
}
static int DirEntryCmp(const void* aKey, const void* aItem) {
int32_t tag = *static_cast<const int32_t*>(aKey);
const TableDirEntry* entry = static_cast<const TableDirEntry*>(aItem);
return tag - int32_t(entry->tag);
}
/* static */
TableDirEntry* gfxFontUtils::FindTableDirEntry(const void* aFontData,
uint32_t aTableTag) {
const SFNTHeader* header = reinterpret_cast<const SFNTHeader*>(aFontData);
const TableDirEntry* dir = reinterpret_cast<const TableDirEntry*>(header + 1);
return static_cast<TableDirEntry*>(
bsearch(&aTableTag, dir, uint16_t(header->numTables),
sizeof(TableDirEntry), DirEntryCmp));
}
/* static */
hb_blob_t* gfxFontUtils::GetTableFromFontData(const void* aFontData,
uint32_t aTableTag) {
const TableDirEntry* dir = FindTableDirEntry(aFontData, aTableTag);
if (dir) {
return hb_blob_create(
reinterpret_cast<const char*>(aFontData) + dir->offset, dir->length,
HB_MEMORY_MODE_READONLY, nullptr, nullptr);
}
return nullptr;
}
nsresult gfxFontUtils::RenameFont(const nsAString& aName,
const uint8_t* aFontData,
uint32_t aFontDataLength,
FallibleTArray<uint8_t>* aNewFont) {
NS_ASSERTION(aNewFont, "null font data array");
uint64_t dataLength(aFontDataLength);
// new name table
static const uint32_t neededNameIDs[] = {NAME_ID_FAMILY, NAME_ID_STYLE,
NAME_ID_UNIQUE, NAME_ID_FULL,
NAME_ID_POSTSCRIPT};
// calculate new name table size
uint16_t nameCount = ArrayLength(neededNameIDs);
// leave room for null-terminator
uint32_t nameStrLength = (aName.Length() + 1) * sizeof(char16_t);