-
Notifications
You must be signed in to change notification settings - Fork 10k
/
fonts.js
3587 lines (3301 loc) · 111 KB
/
fonts.js
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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
assert,
bytesToString,
FONT_IDENTITY_MATRIX,
FormatError,
info,
shadow,
string32,
warn,
} from "../shared/util.js";
import { CFFCompiler, CFFParser } from "./cff_parser.js";
import {
FontFlags,
getVerticalPresentationForm,
MacStandardGlyphOrdering,
normalizeFontName,
recoverGlyphName,
SEAC_ANALYSIS_ENABLED,
} from "./fonts_utils.js";
import {
getCharUnicodeCategory,
getUnicodeForGlyph,
getUnicodeRangeFor,
mapSpecialUnicodeValues,
} from "./unicode.js";
import { getDingbatsGlyphsUnicode, getGlyphsUnicode } from "./glyphlist.js";
import {
getEncoding,
MacRomanEncoding,
StandardEncoding,
SymbolSetEncoding,
WinAnsiEncoding,
ZapfDingbatsEncoding,
} from "./encodings.js";
import {
getGlyphMapForStandardFonts,
getNonStdFontMap,
getSerifFonts,
getStdFontMap,
getSupplementalGlyphMapForArialBlack,
getSupplementalGlyphMapForCalibri,
} from "./standard_fonts.js";
import { IdentityToUnicodeMap, ToUnicodeMap } from "./to_unicode_map.js";
import { CFFFont } from "./cff_font.js";
import { FontRendererFactory } from "./font_renderer.js";
import { getFontBasicMetrics } from "./metrics.js";
import { GlyfTable } from "./glyf.js";
import { IdentityCMap } from "./cmap.js";
import { OpenTypeFileBuilder } from "./opentype_file_builder.js";
import { readUint32 } from "./core_utils.js";
import { Stream } from "./stream.js";
import { Type1Font } from "./type1_font.js";
// Unicode Private Use Areas:
const PRIVATE_USE_AREAS = [
[0xe000, 0xf8ff], // BMP (0)
[0x100000, 0x10fffd], // PUP (16)
];
// PDF Glyph Space Units are one Thousandth of a TextSpace Unit
// except for Type 3 fonts
const PDF_GLYPH_SPACE_UNITS = 1000;
const EXPORT_DATA_PROPERTIES = [
"ascent",
"bbox",
"black",
"bold",
"charProcOperatorList",
"composite",
"cssFontInfo",
"data",
"defaultVMetrics",
"defaultWidth",
"descent",
"fallbackName",
"fontMatrix",
"isInvalidPDFjsFont",
"isType3Font",
"italic",
"loadedName",
"mimetype",
"missingFile",
"name",
"remeasure",
"subtype",
"systemFontInfo",
"type",
"vertical",
];
const EXPORT_DATA_EXTRA_PROPERTIES = [
"cMap",
"defaultEncoding",
"differences",
"isMonospace",
"isSerifFont",
"isSymbolicFont",
"seacMap",
"toFontChar",
"toUnicode",
"vmetrics",
"widths",
];
function adjustWidths(properties) {
if (!properties.fontMatrix) {
return;
}
if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
return;
}
// adjusting width to fontMatrix scale
const scale = 0.001 / properties.fontMatrix[0];
const glyphsWidths = properties.widths;
for (const glyph in glyphsWidths) {
glyphsWidths[glyph] *= scale;
}
properties.defaultWidth *= scale;
}
function adjustTrueTypeToUnicode(properties, isSymbolicFont, nameRecords) {
if (properties.isInternalFont) {
return;
}
if (properties.hasIncludedToUnicodeMap) {
return; // The font dictionary has a `ToUnicode` entry.
}
if (properties.hasEncoding) {
return; // The font dictionary has an `Encoding` entry.
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
if (!isSymbolicFont) {
return; // A non-symbolic font should default to `StandardEncoding`.
}
if (nameRecords.length === 0) {
return;
}
// Try to infer if the fallback encoding should really be `WinAnsiEncoding`.
if (properties.defaultEncoding === WinAnsiEncoding) {
return;
}
for (const r of nameRecords) {
if (!isWinNameRecord(r)) {
return; // Not Windows, hence `WinAnsiEncoding` wouldn't make sense.
}
}
const encoding = WinAnsiEncoding;
const toUnicode = [],
glyphsUnicodeMap = getGlyphsUnicode();
for (const charCode in encoding) {
const glyphName = encoding[charCode];
if (glyphName === "") {
continue;
}
const unicode = glyphsUnicodeMap[glyphName];
if (unicode === undefined) {
continue;
}
toUnicode[charCode] = String.fromCharCode(unicode);
}
if (toUnicode.length > 0) {
properties.toUnicode.amend(toUnicode);
}
}
function adjustType1ToUnicode(properties, builtInEncoding) {
if (properties.isInternalFont) {
return;
}
if (properties.hasIncludedToUnicodeMap) {
return; // The font dictionary has a `ToUnicode` entry.
}
if (builtInEncoding === properties.defaultEncoding) {
return; // No point in trying to adjust `toUnicode` if the encodings match.
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
const toUnicode = [],
glyphsUnicodeMap = getGlyphsUnicode();
for (const charCode in builtInEncoding) {
if (properties.hasEncoding) {
if (
properties.baseEncodingName ||
properties.differences[charCode] !== undefined
) {
continue; // The font dictionary has an `Encoding`/`Differences` entry.
}
}
const glyphName = builtInEncoding[charCode];
const unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
toUnicode[charCode] = String.fromCharCode(unicode);
}
}
if (toUnicode.length > 0) {
properties.toUnicode.amend(toUnicode);
}
}
/**
* NOTE: This function should only be called at the *end* of font-parsing,
* after e.g. `adjustType1ToUnicode` has run, to prevent any issues.
*/
function amendFallbackToUnicode(properties) {
if (!properties.fallbackToUnicode) {
return;
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
const toUnicode = [];
for (const charCode in properties.fallbackToUnicode) {
if (properties.toUnicode.has(charCode)) {
continue; // The font dictionary has a `ToUnicode` entry.
}
toUnicode[charCode] = properties.fallbackToUnicode[charCode];
}
if (toUnicode.length > 0) {
properties.toUnicode.amend(toUnicode);
}
}
class Glyph {
constructor(
originalCharCode,
fontChar,
unicode,
accent,
width,
vmetric,
operatorListId,
isSpace,
isInFont
) {
this.originalCharCode = originalCharCode;
this.fontChar = fontChar;
this.unicode = unicode;
this.accent = accent;
this.width = width;
this.vmetric = vmetric;
this.operatorListId = operatorListId;
this.isSpace = isSpace;
this.isInFont = isInFont;
}
/**
* This property, which is only used by `PartialEvaluator.getTextContent`,
* is purposely made non-serializable.
* @type {Object}
*/
get category() {
return shadow(
this,
"category",
getCharUnicodeCategory(this.unicode),
/* nonSerializable = */ true
);
}
}
function int16(b0, b1) {
return (b0 << 8) + b1;
}
function writeSignedInt16(bytes, index, value) {
bytes[index + 1] = value;
bytes[index] = value >>> 8;
}
function signedInt16(b0, b1) {
const value = (b0 << 8) + b1;
return value & (1 << 15) ? value - 0x10000 : value;
}
function writeUint32(bytes, index, value) {
bytes[index + 3] = value & 0xff;
bytes[index + 2] = value >>> 8;
bytes[index + 1] = value >>> 16;
bytes[index] = value >>> 24;
}
function int32(b0, b1, b2, b3) {
return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
}
function string16(value) {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
assert(
typeof value === "number" && Math.abs(value) < 2 ** 16,
`string16: Unexpected input "${value}".`
);
}
return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
}
function safeString16(value) {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
assert(
typeof value === "number" && !Number.isNaN(value),
`safeString16: Unexpected input "${value}".`
);
}
// clamp value to the 16-bit int range
if (value > 0x7fff) {
value = 0x7fff;
} else if (value < -0x8000) {
value = -0x8000;
}
return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
}
function isTrueTypeFile(file) {
const header = file.peekBytes(4);
return (
readUint32(header, 0) === 0x00010000 || bytesToString(header) === "true"
);
}
function isTrueTypeCollectionFile(file) {
const header = file.peekBytes(4);
return bytesToString(header) === "ttcf";
}
function isOpenTypeFile(file) {
const header = file.peekBytes(4);
return bytesToString(header) === "OTTO";
}
function isType1File(file) {
const header = file.peekBytes(2);
// All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
if (header[0] === 0x25 && header[1] === 0x21) {
return true;
}
// ... obviously some fonts violate that part of the specification,
// please refer to the comment in |Type1Font| below (pfb file header).
if (header[0] === 0x80 && header[1] === 0x01) {
return true;
}
return false;
}
/**
* Compared to other font formats, the header in CFF files is not constant
* but contains version numbers. To reduce the possibility of misclassifying
* font files as CFF, it's recommended to check for other font formats first.
*/
function isCFFFile(file) {
const header = file.peekBytes(4);
if (
/* major version, [1, 255] */ header[0] >= 1 &&
/* minor version, [0, 255]; header[1] */
/* header size, [0, 255]; header[2] */
/* offset(0) size, [1, 4] */ header[3] >= 1 &&
header[3] <= 4
) {
return true;
}
return false;
}
function getFontFileType(file, { type, subtype, composite }) {
let fileType, fileSubtype;
if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) {
fileType = composite ? "CIDFontType2" : "TrueType";
} else if (isOpenTypeFile(file)) {
fileType = composite ? "CIDFontType2" : "OpenType";
} else if (isType1File(file)) {
if (composite) {
fileType = "CIDFontType0";
} else {
fileType = type === "MMType1" ? "MMType1" : "Type1";
}
} else if (isCFFFile(file)) {
if (composite) {
fileType = "CIDFontType0";
fileSubtype = "CIDFontType0C";
} else {
fileType = type === "MMType1" ? "MMType1" : "Type1";
fileSubtype = "Type1C";
}
} else {
warn("getFontFileType: Unable to detect correct font file Type/Subtype.");
fileType = type;
fileSubtype = subtype;
}
return [fileType, fileSubtype];
}
function applyStandardFontGlyphMap(map, glyphMap) {
for (const charCode in glyphMap) {
map[+charCode] = glyphMap[charCode];
}
}
function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
const toFontChar = [];
let unicode;
for (let i = 0, ii = encoding.length; i < ii; i++) {
unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[i] = unicode;
}
}
for (const charCode in differences) {
unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[+charCode] = unicode;
}
}
return toFontChar;
}
// Please refer to:
// - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html
function isMacNameRecord(r) {
return r.platform === 1 && r.encoding === 0 && r.language === 0;
}
// Please refer to:
// - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html
// - https://learn.microsoft.com/en-us/typography/opentype/spec/name#windows-language-ids
function isWinNameRecord(r) {
return r.platform === 3 && r.encoding === 1 && r.language === 0x409;
}
function convertCidString(charCode, cid, shouldThrow = false) {
switch (cid.length) {
case 1:
return cid.charCodeAt(0);
case 2:
return (cid.charCodeAt(0) << 8) | cid.charCodeAt(1);
}
const msg = `Unsupported CID string (charCode ${charCode}): "${cid}".`;
if (shouldThrow) {
throw new FormatError(msg);
}
warn(msg);
return cid;
}
/**
* Rebuilds the char code to glyph ID map by moving all char codes to the
* private use area. This is done to avoid issues with various problematic
* unicode areas where either a glyph won't be drawn or is deformed by a
* shaper.
* @returns {Object} Two properties:
* 'toFontChar' - maps original char codes(the value that will be read
* from commands such as show text) to the char codes that will be used in the
* font that we build
* 'charCodeToGlyphId' - maps the new font char codes to glyph ids
*/
function adjustMapping(charCodeToGlyphId, hasGlyph, newGlyphZeroId, toUnicode) {
const newMap = Object.create(null);
const toUnicodeExtraMap = new Map();
const toFontChar = [];
const usedGlyphIds = new Set();
let privateUseAreaIndex = 0;
const privateUseOffetStart = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
let nextAvailableFontCharCode = privateUseOffetStart;
let privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
const isInPrivateArea = code =>
(PRIVATE_USE_AREAS[0][0] <= code && code <= PRIVATE_USE_AREAS[0][1]) ||
(PRIVATE_USE_AREAS[1][0] <= code && code <= PRIVATE_USE_AREAS[1][1]);
for (const originalCharCode in charCodeToGlyphId) {
let glyphId = charCodeToGlyphId[originalCharCode];
// For missing glyphs don't create the mappings so the glyph isn't
// drawn.
if (!hasGlyph(glyphId)) {
continue;
}
if (nextAvailableFontCharCode > privateUseOffetEnd) {
privateUseAreaIndex++;
if (privateUseAreaIndex >= PRIVATE_USE_AREAS.length) {
warn("Ran out of space in font private use area.");
break;
}
nextAvailableFontCharCode = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
}
const fontCharCode = nextAvailableFontCharCode++;
if (glyphId === 0) {
glyphId = newGlyphZeroId;
}
// Fix for bug 1778484:
// The charcodes are moved into a private use area to fix some rendering
// issues (https://github.com/mozilla/pdf.js/pull/9340) but when printing
// to PDF the generated font will contain wrong chars. We can avoid that by
// adding the unicode to the cmap and the print backend will then map the
// glyph ids to the correct unicode.
let unicode = toUnicode.get(originalCharCode);
if (typeof unicode === "string") {
unicode = unicode.codePointAt(0);
}
if (unicode && !isInPrivateArea(unicode) && !usedGlyphIds.has(glyphId)) {
toUnicodeExtraMap.set(unicode, glyphId);
usedGlyphIds.add(glyphId);
}
newMap[fontCharCode] = glyphId;
toFontChar[originalCharCode] = fontCharCode;
}
return {
toFontChar,
charCodeToGlyphId: newMap,
toUnicodeExtraMap,
nextAvailableFontCharCode,
};
}
function getRanges(glyphs, toUnicodeExtraMap, numGlyphs) {
// Array.sort() sorts by characters, not numerically, so convert to an
// array of characters.
const codes = [];
for (const charCode in glyphs) {
// Remove an invalid glyph ID mappings to make OTS happy.
if (glyphs[charCode] >= numGlyphs) {
continue;
}
codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
}
if (toUnicodeExtraMap) {
for (const [unicode, glyphId] of toUnicodeExtraMap) {
if (glyphId >= numGlyphs) {
continue;
}
codes.push({ fontCharCode: unicode, glyphId });
}
}
// Some fonts have zero glyphs and are used only for text selection, but
// there needs to be at least one to build a valid cmap table.
if (codes.length === 0) {
codes.push({ fontCharCode: 0, glyphId: 0 });
}
codes.sort(function fontGetRangesSort(a, b) {
return a.fontCharCode - b.fontCharCode;
});
// Split the sorted codes into ranges.
const ranges = [];
const length = codes.length;
for (let n = 0; n < length; ) {
const start = codes[n].fontCharCode;
const codeIndices = [codes[n].glyphId];
++n;
let end = start;
while (n < length && end + 1 === codes[n].fontCharCode) {
codeIndices.push(codes[n].glyphId);
++end;
++n;
if (end === 0xffff) {
break;
}
}
ranges.push([start, end, codeIndices]);
}
return ranges;
}
function createCmapTable(glyphs, toUnicodeExtraMap, numGlyphs) {
const ranges = getRanges(glyphs, toUnicodeExtraMap, numGlyphs);
const numTables = ranges.at(-1)[1] > 0xffff ? 2 : 1;
let cmap =
"\x00\x00" + // version
string16(numTables) + // numTables
"\x00\x03" + // platformID
"\x00\x01" + // encodingID
string32(4 + numTables * 8); // start of the table record
let i, ii, j, jj;
for (i = ranges.length - 1; i >= 0; --i) {
if (ranges[i][0] <= 0xffff) {
break;
}
}
const bmpLength = i + 1;
if (ranges[i][0] < 0xffff && ranges[i][1] === 0xffff) {
ranges[i][1] = 0xfffe;
}
const trailingRangesCount = ranges[i][1] < 0xffff ? 1 : 0;
const segCount = bmpLength + trailingRangesCount;
const searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
// Fill up the 4 parallel arrays describing the segments.
let startCount = "";
let endCount = "";
let idDeltas = "";
let idRangeOffsets = "";
let glyphsIds = "";
let bias = 0;
let range, start, end, codes;
for (i = 0, ii = bmpLength; i < ii; i++) {
range = ranges[i];
start = range[0];
end = range[1];
startCount += string16(start);
endCount += string16(end);
codes = range[2];
let contiguous = true;
for (j = 1, jj = codes.length; j < jj; ++j) {
if (codes[j] !== codes[j - 1] + 1) {
contiguous = false;
break;
}
}
if (!contiguous) {
const offset = (segCount - i) * 2 + bias * 2;
bias += end - start + 1;
idDeltas += string16(0);
idRangeOffsets += string16(offset);
for (j = 0, jj = codes.length; j < jj; ++j) {
glyphsIds += string16(codes[j]);
}
} else {
const startCode = codes[0];
idDeltas += string16((startCode - start) & 0xffff);
idRangeOffsets += string16(0);
}
}
if (trailingRangesCount > 0) {
endCount += "\xFF\xFF";
startCount += "\xFF\xFF";
idDeltas += "\x00\x01";
idRangeOffsets += "\x00\x00";
}
const format314 =
"\x00\x00" + // language
string16(2 * segCount) +
string16(searchParams.range) +
string16(searchParams.entry) +
string16(searchParams.rangeShift) +
endCount +
"\x00\x00" +
startCount +
idDeltas +
idRangeOffsets +
glyphsIds;
let format31012 = "";
let header31012 = "";
if (numTables > 1) {
cmap +=
"\x00\x03" + // platformID
"\x00\x0A" + // encodingID
string32(4 + numTables * 8 + 4 + format314.length); // start of the table record
format31012 = "";
for (i = 0, ii = ranges.length; i < ii; i++) {
range = ranges[i];
start = range[0];
codes = range[2];
let code = codes[0];
for (j = 1, jj = codes.length; j < jj; ++j) {
if (codes[j] !== codes[j - 1] + 1) {
end = range[0] + j - 1;
format31012 +=
string32(start) + // startCharCode
string32(end) + // endCharCode
string32(code); // startGlyphID
start = end + 1;
code = codes[j];
}
}
format31012 +=
string32(start) + // startCharCode
string32(range[1]) + // endCharCode
string32(code); // startGlyphID
}
header31012 =
"\x00\x0C" + // format
"\x00\x00" + // reserved
string32(format31012.length + 16) + // length
"\x00\x00\x00\x00" + // language
string32(format31012.length / 12); // nGroups
}
return (
cmap +
"\x00\x04" + // format
string16(format314.length + 4) + // length
format314 +
header31012 +
format31012
);
}
function validateOS2Table(os2, file) {
file.pos = (file.start || 0) + os2.offset;
const version = file.getUint16();
// TODO verify all OS/2 tables fields, but currently we validate only those
// that give us issues
file.skip(60); // skipping type, misc sizes, panose, unicode ranges
const selection = file.getUint16();
if (version < 4 && selection & 0x0300) {
return false;
}
const firstChar = file.getUint16();
const lastChar = file.getUint16();
if (firstChar > lastChar) {
return false;
}
file.skip(6); // skipping sTypoAscender/Descender/LineGap
const usWinAscent = file.getUint16();
if (usWinAscent === 0) {
// makes font unreadable by windows
return false;
}
// OS/2 appears to be valid, resetting some fields
os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
return true;
}
function createOS2Table(properties, charstrings, override) {
override ||= {
unitsPerEm: 0,
yMax: 0,
yMin: 0,
ascent: 0,
descent: 0,
};
let ulUnicodeRange1 = 0;
let ulUnicodeRange2 = 0;
let ulUnicodeRange3 = 0;
let ulUnicodeRange4 = 0;
let firstCharIndex = null;
let lastCharIndex = 0;
let position = -1;
if (charstrings) {
for (let code in charstrings) {
code |= 0;
if (firstCharIndex > code || !firstCharIndex) {
firstCharIndex = code;
}
if (lastCharIndex < code) {
lastCharIndex = code;
}
position = getUnicodeRangeFor(code, position);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << (position - 32);
} else if (position < 96) {
ulUnicodeRange3 |= 1 << (position - 64);
} else if (position < 123) {
ulUnicodeRange4 |= 1 << (position - 96);
} else {
throw new FormatError(
"Unicode ranges Bits > 123 are reserved for internal usage"
);
}
}
if (lastCharIndex > 0xffff) {
// OS2 only supports a 16 bit int. The spec says if supplementary
// characters are used the field should just be set to 0xFFFF.
lastCharIndex = 0xffff;
}
} else {
// TODO
firstCharIndex = 0;
lastCharIndex = 255;
}
const bbox = properties.bbox || [0, 0, 0, 0];
const unitsPerEm =
override.unitsPerEm ||
(properties.fontMatrix
? 1 / Math.max(...properties.fontMatrix.slice(0, 4).map(Math.abs))
: 1000);
// if the font units differ to the PDF glyph space units
// then scale up the values
const scale = properties.ascentScaled
? 1.0
: unitsPerEm / PDF_GLYPH_SPACE_UNITS;
const typoAscent =
override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
let typoDescent =
override.descent || Math.round(scale * (properties.descent || bbox[1]));
if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
typoDescent = -typoDescent; // fixing incorrect descent
}
const winAscent = override.yMax || typoAscent;
const winDescent = -override.yMin || -typoDescent;
return (
"\x00\x03" + // version
"\x02\x24" + // xAvgCharWidth
"\x01\xF4" + // usWeightClass
"\x00\x05" + // usWidthClass
"\x00\x00" + // fstype (0 to let the font loads via font-face on IE)
"\x02\x8A" + // ySubscriptXSize
"\x02\xBB" + // ySubscriptYSize
"\x00\x00" + // ySubscriptXOffset
"\x00\x8C" + // ySubscriptYOffset
"\x02\x8A" + // ySuperScriptXSize
"\x02\xBB" + // ySuperScriptYSize
"\x00\x00" + // ySuperScriptXOffset
"\x01\xDF" + // ySuperScriptYOffset
"\x00\x31" + // yStrikeOutSize
"\x01\x02" + // yStrikeOutPosition
"\x00\x00" + // sFamilyClass
"\x00\x00\x06" +
String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
"\x00\x00\x00\x00\x00\x00" + // Panose
string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
"\x2A\x32\x31\x2A" + // achVendID
string16(properties.italicAngle ? 1 : 0) + // fsSelection
string16(firstCharIndex || properties.firstChar) + // usFirstCharIndex
string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
string16(typoAscent) + // sTypoAscender
string16(typoDescent) + // sTypoDescender
"\x00\x64" + // sTypoLineGap (7%-10% of the unitsPerEM value)
string16(winAscent) + // usWinAscent
string16(winDescent) + // usWinDescent
"\x00\x00\x00\x00" + // ulCodePageRange1 (Bits 0-31)
"\x00\x00\x00\x00" + // ulCodePageRange2 (Bits 32-63)
string16(properties.xHeight) + // sxHeight
string16(properties.capHeight) + // sCapHeight
string16(0) + // usDefaultChar
string16(firstCharIndex || properties.firstChar) + // usBreakChar
"\x00\x03"
); // usMaxContext
}
function createPostTable(properties) {
const angle = Math.floor(properties.italicAngle * 2 ** 16);
return (
"\x00\x03\x00\x00" + // Version number
string32(angle) + // italicAngle
"\x00\x00" + // underlinePosition
"\x00\x00" + // underlineThickness
string32(properties.fixedPitch ? 1 : 0) + // isFixedPitch
"\x00\x00\x00\x00" + // minMemType42
"\x00\x00\x00\x00" + // maxMemType42
"\x00\x00\x00\x00" + // minMemType1
"\x00\x00\x00\x00"
); // maxMemType1
}
function createPostscriptName(name) {
// See https://docs.microsoft.com/en-us/typography/opentype/spec/recom#name.
return name.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g, "").slice(0, 63);
}
function createNameTable(name, proto) {
if (!proto) {
proto = [[], []]; // no strings and unicode strings
}
const strings = [
proto[0][0] || "Original licence", // 0.Copyright
proto[0][1] || name, // 1.Font family
proto[0][2] || "Unknown", // 2.Font subfamily (font weight)
proto[0][3] || "uniqueID", // 3.Unique ID
proto[0][4] || name, // 4.Full font name
proto[0][5] || "Version 0.11", // 5.Version
proto[0][6] || createPostscriptName(name), // 6.Postscript name
proto[0][7] || "Unknown", // 7.Trademark
proto[0][8] || "Unknown", // 8.Manufacturer
proto[0][9] || "Unknown", // 9.Designer
];
// Mac want 1-byte per character strings while Windows want
// 2-bytes per character, so duplicate the names table
const stringsUnicode = [];
let i, ii, j, jj, str;
for (i = 0, ii = strings.length; i < ii; i++) {
str = proto[1][i] || strings[i];
const strBufUnicode = [];
for (j = 0, jj = str.length; j < jj; j++) {
strBufUnicode.push(string16(str.charCodeAt(j)));
}
stringsUnicode.push(strBufUnicode.join(""));
}
const names = [strings, stringsUnicode];
const platforms = ["\x00\x01", "\x00\x03"];
const encodings = ["\x00\x00", "\x00\x01"];
const languages = ["\x00\x00", "\x04\x09"];
const namesRecordCount = strings.length * platforms.length;
let nameTable =
"\x00\x00" + // format
string16(namesRecordCount) + // Number of names Record
string16(namesRecordCount * 12 + 6); // Storage
// Build the name records field
let strOffset = 0;
for (i = 0, ii = platforms.length; i < ii; i++) {
const strs = names[i];
for (j = 0, jj = strs.length; j < jj; j++) {
str = strs[j];
const nameRecord =
platforms[i] + // platform ID
encodings[i] + // encoding ID
languages[i] + // language ID
string16(j) + // name ID
string16(str.length) +
string16(strOffset);
nameTable += nameRecord;
strOffset += str.length;
}
}
nameTable += strings.join("") + stringsUnicode.join("");
return nameTable;
}
/**
* 'Font' is the class the outside world should use, it encapsulate all the font
* decoding logics whatever type it is (assuming the font type is supported).
*/
class Font {
constructor(name, file, properties) {
this.name = name;
this.psName = null;
this.mimetype = null;
this.disableFontFace = false;
this.loadedName = properties.loadedName;
this.isType3Font = properties.isType3Font;
this.missingFile = false;
this.cssFontInfo = properties.cssFontInfo;
this._charsCache = Object.create(null);
this._glyphCache = Object.create(null);
let isSerifFont = !!(properties.flags & FontFlags.Serif);
// Fallback to checking the font name, in order to improve text-selection,
// since the /Flags-entry is often wrong (fixes issue13845.pdf).
if (!isSerifFont && !properties.isSimulatedFlags) {
const baseName = name.replaceAll(/[,_]/g, "-").split("-", 1)[0],
serifFonts = getSerifFonts();
for (const namePart of baseName.split("+")) {
if (serifFonts[namePart]) {
isSerifFont = true;
break;
}
}
}
this.isSerifFont = isSerifFont;
this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
let { type, subtype } = properties;
this.type = type;
this.subtype = subtype;
this.systemFontInfo = properties.systemFontInfo;
const matches = name.match(/^InvalidPDFjsFont_(.*)_\d+$/);
this.isInvalidPDFjsFont = !!matches;
if (this.isInvalidPDFjsFont) {
this.fallbackName = matches[1];
} else if (this.isMonospace) {
this.fallbackName = "monospace";
} else if (this.isSerifFont) {
this.fallbackName = "serif";
} else {