-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
fonts.js
3490 lines (3171 loc) · 121 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, FontType, FormatError, info,
isNum, isSpace, MissingDataException, readUint32, shadow, string32,
unreachable, warn
} from '../shared/util';
import {
CFF, CFFCharset, CFFCompiler, CFFHeader, CFFIndex, CFFParser, CFFPrivateDict,
CFFStandardStrings, CFFStrings, CFFTopDict
} from './cff_parser';
import { getDingbatsGlyphsUnicode, getGlyphsUnicode } from './glyphlist';
import {
getEncoding, MacRomanEncoding, StandardEncoding, SymbolSetEncoding,
ZapfDingbatsEncoding
} from './encodings';
import {
getGlyphMapForStandardFonts, getNonStdFontMap, getStdFontMap,
getSupplementalGlyphMapForArialBlack, getSupplementalGlyphMapForCalibri
} from './standard_fonts';
import {
getUnicodeForGlyph, getUnicodeRangeFor, mapSpecialUnicodeValues
} from './unicode';
import { FontRendererFactory } from './font_renderer';
import { Stream } from './stream';
import { Type1Parser } from './type1_parser';
// Unicode Private Use Area
var PRIVATE_USE_OFFSET_START = 0xE000;
var PRIVATE_USE_OFFSET_END = 0xF8FF;
var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
// PDF Glyph Space Units are one Thousandth of a TextSpace Unit
// except for Type 3 fonts
var PDF_GLYPH_SPACE_UNITS = 1000;
// Accented charactars are not displayed properly on Windows, using this flag
// to control analysis of seac charstrings.
var SEAC_ANALYSIS_ENABLED = false;
var FontFlags = {
FixedPitch: 1,
Serif: 2,
Symbolic: 4,
Script: 8,
Nonsymbolic: 32,
Italic: 64,
AllCap: 65536,
SmallCap: 131072,
ForceBold: 262144,
};
var MacStandardGlyphOrdering = [
'.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
function adjustWidths(properties) {
if (!properties.fontMatrix) {
return;
}
if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
return;
}
// adjusting width to fontMatrix scale
var scale = 0.001 / properties.fontMatrix[0];
var glyphsWidths = properties.widths;
for (var glyph in glyphsWidths) {
glyphsWidths[glyph] *= scale;
}
properties.defaultWidth *= scale;
}
function adjustToUnicode(properties, builtInEncoding) {
if (properties.hasIncludedToUnicodeMap) {
return; // The font dictionary has a `ToUnicode` entry.
}
if (properties.hasEncoding) {
return; // The font dictionary has an `Encoding` entry.
}
if (builtInEncoding === properties.defaultEncoding) {
return; // No point in trying to adjust `toUnicode` if the encodings match.
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
var toUnicode = [], glyphsUnicodeMap = getGlyphsUnicode();
for (var charCode in builtInEncoding) {
var glyphName = builtInEncoding[charCode];
var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
toUnicode[charCode] = String.fromCharCode(unicode);
}
}
properties.toUnicode.amend(toUnicode);
}
function getFontType(type, subtype) {
switch (type) {
case 'Type1':
return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
case 'CIDFontType0':
return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
FontType.CIDFONTTYPE0;
case 'OpenType':
return FontType.OPENTYPE;
case 'TrueType':
return FontType.TRUETYPE;
case 'CIDFontType2':
return FontType.CIDFONTTYPE2;
case 'MMType1':
return FontType.MMTYPE1;
case 'Type0':
return FontType.TYPE0;
default:
return FontType.UNKNOWN;
}
}
// Some bad PDF generators, e.g. Scribus PDF, include glyph names
// in a 'uniXXXX' format -- attempting to recover proper ones.
function recoverGlyphName(name, glyphsUnicodeMap) {
if (glyphsUnicodeMap[name] !== undefined) {
return name;
}
// The glyph name is non-standard, trying to recover.
var unicode = getUnicodeForGlyph(name, glyphsUnicodeMap);
if (unicode !== -1) {
for (var key in glyphsUnicodeMap) {
if (glyphsUnicodeMap[key] === unicode) {
return key;
}
}
}
info('Unable to recover a standard glyph name for: ' + name);
return name;
}
var Glyph = (function GlyphClosure() {
function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId,
isSpace, isInFont) {
this.fontChar = fontChar;
this.unicode = unicode;
this.accent = accent;
this.width = width;
this.vmetric = vmetric;
this.operatorListId = operatorListId;
this.isSpace = isSpace;
this.isInFont = isInFont;
}
Glyph.prototype.matchesForCache = function(fontChar, unicode, accent, width,
vmetric, operatorListId, isSpace,
isInFont) {
return this.fontChar === fontChar &&
this.unicode === unicode &&
this.accent === accent &&
this.width === width &&
this.vmetric === vmetric &&
this.operatorListId === operatorListId &&
this.isSpace === isSpace &&
this.isInFont === isInFont;
};
return Glyph;
})();
var ToUnicodeMap = (function ToUnicodeMapClosure() {
function ToUnicodeMap(cmap = []) {
// The elements of this._map can be integers or strings, depending on how
// `cmap` was created.
this._map = cmap;
}
ToUnicodeMap.prototype = {
get length() {
return this._map.length;
},
forEach(callback) {
for (var charCode in this._map) {
callback(charCode, this._map[charCode].charCodeAt(0));
}
},
has(i) {
return this._map[i] !== undefined;
},
get(i) {
return this._map[i];
},
charCodeOf(value) {
// `Array.prototype.indexOf` is *extremely* inefficient for arrays which
// are both very sparse and very large (see issue8372.pdf).
let map = this._map;
if (map.length <= 0x10000) {
return map.indexOf(value);
}
for (let charCode in map) {
if (map[charCode] === value) {
return (charCode | 0);
}
}
return -1;
},
amend(map) {
for (var charCode in map) {
this._map[charCode] = map[charCode];
}
},
};
return ToUnicodeMap;
})();
var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
function IdentityToUnicodeMap(firstChar, lastChar) {
this.firstChar = firstChar;
this.lastChar = lastChar;
}
IdentityToUnicodeMap.prototype = {
get length() {
return (this.lastChar + 1) - this.firstChar;
},
forEach(callback) {
for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
callback(i, i);
}
},
has(i) {
return this.firstChar <= i && i <= this.lastChar;
},
get(i) {
if (this.firstChar <= i && i <= this.lastChar) {
return String.fromCharCode(i);
}
return undefined;
},
charCodeOf(v) {
return (Number.isInteger(v) &&
v >= this.firstChar && v <= this.lastChar) ? v : -1;
},
amend(map) {
unreachable('Should not call amend()');
},
};
return IdentityToUnicodeMap;
})();
var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
function writeInt16(dest, offset, num) {
dest[offset] = (num >> 8) & 0xFF;
dest[offset + 1] = num & 0xFF;
}
function writeInt32(dest, offset, num) {
dest[offset] = (num >> 24) & 0xFF;
dest[offset + 1] = (num >> 16) & 0xFF;
dest[offset + 2] = (num >> 8) & 0xFF;
dest[offset + 3] = num & 0xFF;
}
function writeData(dest, offset, data) {
var i, ii;
if (data instanceof Uint8Array) {
dest.set(data, offset);
} else if (typeof data === 'string') {
for (i = 0, ii = data.length; i < ii; i++) {
dest[offset++] = data.charCodeAt(i) & 0xFF;
}
} else {
// treating everything else as array
for (i = 0, ii = data.length; i < ii; i++) {
dest[offset++] = data[i] & 0xFF;
}
}
}
function OpenTypeFileBuilder(sfnt) {
this.sfnt = sfnt;
this.tables = Object.create(null);
}
OpenTypeFileBuilder.getSearchParams =
function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
var maxPower2 = 1, log2 = 0;
while ((maxPower2 ^ entriesCount) > maxPower2) {
maxPower2 <<= 1;
log2++;
}
var searchRange = maxPower2 * entrySize;
return {
range: searchRange,
entry: log2,
rangeShift: entrySize * entriesCount - searchRange,
};
};
var OTF_HEADER_SIZE = 12;
var OTF_TABLE_ENTRY_SIZE = 16;
OpenTypeFileBuilder.prototype = {
toArray: function OpenTypeFileBuilder_toArray() {
var sfnt = this.sfnt;
// Tables needs to be written by ascendant alphabetic order
var tables = this.tables;
var tablesNames = Object.keys(tables);
tablesNames.sort();
var numTables = tablesNames.length;
var i, j, jj, table, tableName;
// layout the tables data
var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
var tableOffsets = [offset];
for (i = 0; i < numTables; i++) {
table = tables[tablesNames[i]];
var paddedLength = ((table.length + 3) & ~3) >>> 0;
offset += paddedLength;
tableOffsets.push(offset);
}
var file = new Uint8Array(offset);
// write the table data first (mostly for checksum)
for (i = 0; i < numTables; i++) {
table = tables[tablesNames[i]];
writeData(file, tableOffsets[i], table);
}
// sfnt version (4 bytes)
if (sfnt === 'true') {
// Windows hates the Mac TrueType sfnt version number
sfnt = string32(0x00010000);
}
file[0] = sfnt.charCodeAt(0) & 0xFF;
file[1] = sfnt.charCodeAt(1) & 0xFF;
file[2] = sfnt.charCodeAt(2) & 0xFF;
file[3] = sfnt.charCodeAt(3) & 0xFF;
// numTables (2 bytes)
writeInt16(file, 4, numTables);
var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
// searchRange (2 bytes)
writeInt16(file, 6, searchParams.range);
// entrySelector (2 bytes)
writeInt16(file, 8, searchParams.entry);
// rangeShift (2 bytes)
writeInt16(file, 10, searchParams.rangeShift);
offset = OTF_HEADER_SIZE;
// writing table entries
for (i = 0; i < numTables; i++) {
tableName = tablesNames[i];
file[offset] = tableName.charCodeAt(0) & 0xFF;
file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
// checksum
var checksum = 0;
for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
var quad = readUint32(file, j);
checksum = (checksum + quad) >>> 0;
}
writeInt32(file, offset + 4, checksum);
// offset
writeInt32(file, offset + 8, tableOffsets[i]);
// length
writeInt32(file, offset + 12, tables[tableName].length);
offset += OTF_TABLE_ENTRY_SIZE;
}
return file;
},
addTable: function OpenTypeFileBuilder_addTable(tag, data) {
if (tag in this.tables) {
throw new Error('Table ' + tag + ' already exists');
}
this.tables[tag] = data;
},
};
return OpenTypeFileBuilder;
})();
// Problematic Unicode characters in the fonts that needs to be moved to avoid
// issues when they are painted on the canvas, e.g. complex-script shaping or
// control/whitespace characters. The ranges are listed in pairs: the first item
// is a code of the first problematic code, the second one is the next
// non-problematic code. The ranges must be in sorted order.
var ProblematicCharRanges = new Int32Array([
// Control characters.
0x0000, 0x0020,
0x007F, 0x00A1,
0x00AD, 0x00AE,
// Chars that is used in complex-script shaping.
0x0600, 0x0780,
0x08A0, 0x10A0,
0x1780, 0x1800,
0x1C00, 0x1C50,
// General punctuation chars.
0x2000, 0x2010,
0x2011, 0x2012,
0x2028, 0x2030,
0x205F, 0x2070,
0x25CC, 0x25CD,
0x3000, 0x3001,
0x3164, 0x3165,
// Chars that is used in complex-script shaping.
0xAA60, 0xAA80,
// Unicode high surrogates.
0xD800, 0xE000,
// Specials Unicode block.
0xFFF0, 0x10000
]);
/**
* '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).
*
* For example to read a Type1 font and to attach it to the document:
* var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
* type1Font.bind();
*/
var Font = (function FontClosure() {
function Font(name, file, properties) {
var charCode;
this.name = name;
this.loadedName = properties.loadedName;
this.isType3Font = properties.isType3Font;
this.sizes = [];
this.missingFile = false;
this.glyphCache = Object.create(null);
this.isSerifFont = !!(properties.flags & FontFlags.Serif);
this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
var type = properties.type;
var subtype = properties.subtype;
this.type = type;
this.subtype = subtype;
this.fallbackName = (this.isMonospace ? 'monospace' :
(this.isSerifFont ? 'serif' : 'sans-serif'));
this.differences = properties.differences;
this.widths = properties.widths;
this.defaultWidth = properties.defaultWidth;
this.composite = properties.composite;
this.wideChars = properties.wideChars;
this.cMap = properties.cMap;
this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
this.fontMatrix = properties.fontMatrix;
this.bbox = properties.bbox;
this.defaultEncoding = properties.defaultEncoding;
this.toUnicode = properties.toUnicode;
this.fallbackToUnicode = properties.fallbackToUnicode || new ToUnicodeMap();
this.toFontChar = [];
if (properties.type === 'Type3') {
for (charCode = 0; charCode < 256; charCode++) {
this.toFontChar[charCode] = (this.differences[charCode] ||
properties.defaultEncoding[charCode]);
}
this.fontType = FontType.TYPE3;
return;
}
this.cidEncoding = properties.cidEncoding;
this.vertical = properties.vertical;
if (this.vertical) {
this.vmetrics = properties.vmetrics;
this.defaultVMetrics = properties.defaultVMetrics;
}
if (!file || file.isEmpty) {
if (file) {
// Some bad PDF generators will include empty font files,
// attempting to recover by assuming that no file exists.
warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
}
this.fallbackToSystemFont();
return;
}
// Some fonts might use wrong font types for Type1C or CIDFontType0C
if (subtype === 'Type1C') {
if (type !== 'Type1' && type !== 'MMType1') {
// Some TrueType fonts by mistake claim Type1C
if (isTrueTypeFile(file)) {
subtype = 'TrueType';
} else {
type = 'Type1';
}
} else if (isOpenTypeFile(file)) {
// Sometimes the type/subtype can be a complete lie (see issue7598.pdf).
subtype = 'OpenType';
}
}
if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
type = 'CIDFontType0';
}
// Some CIDFontType0C fonts by mistake claim CIDFontType0.
if (type === 'CIDFontType0') {
if (isType1File(file)) {
subtype = 'CIDFontType0';
} else if (isOpenTypeFile(file)) {
// Sometimes the type/subtype can be a complete lie (see issue6782.pdf).
subtype = 'OpenType';
} else {
subtype = 'CIDFontType0C';
}
}
if (subtype === 'OpenType' && type !== 'OpenType') {
type = 'OpenType';
}
try {
var data;
switch (type) {
case 'MMType1':
info('MMType1 font (' + name + '), falling back to Type1.');
/* falls through */
case 'Type1':
case 'CIDFontType0':
this.mimetype = 'font/opentype';
var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
new CFFFont(file, properties) :
new Type1Font(name, file, properties);
adjustWidths(properties);
// Wrap the CFF data inside an OTF font file
data = this.convert(name, cff, properties);
break;
case 'OpenType':
case 'TrueType':
case 'CIDFontType2':
this.mimetype = 'font/opentype';
// Repair the TrueType file. It is can be damaged in the point of
// view of the sanitizer
data = this.checkAndRepair(name, file, properties);
if (this.isOpenType) {
adjustWidths(properties);
type = 'OpenType';
}
break;
default:
throw new FormatError(`Font ${type} is not supported`);
}
} catch (e) {
if (!(e instanceof FormatError)) {
throw e;
}
warn(e);
this.fallbackToSystemFont();
return;
}
this.data = data;
this.fontType = getFontType(type, subtype);
// Transfer some properties again that could change during font conversion
this.fontMatrix = properties.fontMatrix;
this.widths = properties.widths;
this.defaultWidth = properties.defaultWidth;
this.toUnicode = properties.toUnicode;
this.encoding = properties.baseEncoding;
this.seacMap = properties.seacMap;
this.loading = true;
}
Font.getFontID = (function () {
var ID = 1;
return function Font_getFontID() {
return String(ID++);
};
})();
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) {
var value = (b0 << 8) + b1;
return value & (1 << 15) ? value - 0x10000 : value;
}
function int32(b0, b1, b2, b3) {
return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
}
function string16(value) {
return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
}
function safeString16(value) {
// clamp value to the 16-bit int range
value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
}
function isTrueTypeFile(file) {
var header = file.peekBytes(4);
return readUint32(header, 0) === 0x00010000;
}
function isTrueTypeCollectionFile(file) {
let header = file.peekBytes(4);
return bytesToString(header) === 'ttcf';
}
function isOpenTypeFile(file) {
var header = file.peekBytes(4);
return bytesToString(header) === 'OTTO';
}
function isType1File(file) {
var 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.
if (header[0] === 0x80 && header[1] === 0x01) { // pfb file header.
return true;
}
return false;
}
function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
var toFontChar = [], unicode;
for (var i = 0, ii = encoding.length; i < ii; i++) {
unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[i] = unicode;
}
}
for (var charCode in differences) {
unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[+charCode] = unicode;
}
}
return toFontChar;
}
/**
* Helper function for `adjustMapping`.
* @return {boolean}
*/
function isProblematicUnicodeLocation(code) {
// Using binary search to find a range start.
var i = 0, j = ProblematicCharRanges.length - 1;
while (i < j) {
var c = (i + j + 1) >> 1;
if (code < ProblematicCharRanges[c]) {
j = c - 1;
} else {
i = c;
}
}
// Even index means code in problematic range.
return !(i & 1);
}
/**
* Rebuilds the char code to glyph ID map by trying to replace the char codes
* with their unicode value. It also moves char codes that are in known
* problematic locations.
* @return {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, properties, missingGlyphs) {
var toUnicode = properties.toUnicode;
var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
var isIdentityUnicode =
properties.toUnicode instanceof IdentityToUnicodeMap;
var newMap = Object.create(null);
var toFontChar = [];
var usedFontCharCodes = [];
var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
for (var originalCharCode in charCodeToGlyphId) {
originalCharCode |= 0;
var glyphId = charCodeToGlyphId[originalCharCode];
// For missing glyphs don't create the mappings so the glyph isn't
// drawn.
if (missingGlyphs[glyphId]) {
continue;
}
var fontCharCode = originalCharCode;
// First try to map the value to a unicode position if a non identity map
// was created.
var hasUnicodeValue = false;
if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
hasUnicodeValue = true;
var unicode = toUnicode.get(fontCharCode);
// TODO: Try to map ligatures to the correct spot.
if (unicode.length === 1) {
fontCharCode = unicode.charCodeAt(0);
}
}
// Try to move control characters, special characters and already mapped
// characters to the private use area since they will not be drawn by
// canvas if left in their current position. Also, move characters if the
// font was symbolic and there is only an identity unicode map since the
// characters probably aren't in the correct position (fixes an issue
// with firefox and thuluthfont).
if ((usedFontCharCodes[fontCharCode] !== undefined ||
isProblematicUnicodeLocation(fontCharCode) ||
(isSymbolic && !hasUnicodeValue))) {
// Loop to try and find a free spot in the private use area.
do {
if (nextAvailableFontCharCode > PRIVATE_USE_OFFSET_END) {
warn('Ran out of space in font private use area.');
break;
}
fontCharCode = nextAvailableFontCharCode++;
if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
fontCharCode = 0xF020;
nextAvailableFontCharCode = fontCharCode + 1;
}
} while (usedFontCharCodes[fontCharCode] !== undefined);
}
newMap[fontCharCode] = glyphId;
toFontChar[originalCharCode] = fontCharCode;
usedFontCharCodes[fontCharCode] = true;
}
return {
toFontChar,
charCodeToGlyphId: newMap,
nextAvailableFontCharCode,
};
}
function getRanges(glyphs, numGlyphs) {
// Array.sort() sorts by characters, not numerically, so convert to an
// array of characters.
var codes = [];
for (var 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], });
}
// 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.
var ranges = [];
var length = codes.length;
for (var n = 0; n < length; ) { // eslint-disable-line space-in-parens
var start = codes[n].fontCharCode;
var codeIndices = [codes[n].glyphId];
++n;
var 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, numGlyphs) {
var ranges = getRanges(glyphs, numGlyphs);
var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
var cmap = '\x00\x00' + // version
string16(numTables) + // numTables
'\x00\x03' + // platformID
'\x00\x01' + // encodingID
string32(4 + numTables * 8); // start of the table record
var i, ii, j, jj;
for (i = ranges.length - 1; i >= 0; --i) {
if (ranges[i][0] <= 0xFFFF) {
break;
}
}
var bmpLength = i + 1;
if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
ranges[i][1] = 0xFFFE;
}
var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
var segCount = bmpLength + trailingRangesCount;
var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
// Fill up the 4 parallel arrays describing the segments.
var startCount = '';
var endCount = '';
var idDeltas = '';
var idRangeOffsets = '';
var glyphsIds = '';
var bias = 0;
var 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];
var contiguous = true;
for (j = 1, jj = codes.length; j < jj; ++j) {
if (codes[j] !== codes[j - 1] + 1) {
contiguous = false;
break;
}
}
if (!contiguous) {
var 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 {
var 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';
}
var format314 = '\x00\x00' + // language
string16(2 * segCount) +
string16(searchParams.range) +
string16(searchParams.entry) +
string16(searchParams.rangeShift) +
endCount + '\x00\x00' + startCount +
idDeltas + idRangeOffsets + glyphsIds;
var format31012 = '';
var 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];
var 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) {
var stream = new Stream(os2.data);
var version = stream.getUint16();
// TODO verify all OS/2 tables fields, but currently we validate only those
// that give us issues
stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
var selection = stream.getUint16();
if (version < 4 && (selection & 0x0300)) {
return false;
}
var firstChar = stream.getUint16();
var lastChar = stream.getUint16();
if (firstChar > lastChar) {
return false;
}
stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
var usWinAscent = stream.getUint16();
if (usWinAscent === 0) { // makes font unreadable by windows
return false;
}