-
Notifications
You must be signed in to change notification settings - Fork 22
/
samsa-core.js
2512 lines (2087 loc) · 80.7 KB
/
samsa-core.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
/*
samsa-core.js
Pre-GitHub version history
2019-10-18 glyf parsing in node & browser
2019-10-18 TVTs parsing in node & browser
2019-10-18 Tons of refactoring working nicely (tvts is much clearer structure than old gvd)
2019-10-19 avar seems to be working now
2019-10-20 Finally got gvar decompiling for all fonts I throw at it. Just need to do the fake glyph.points for composites and we’re done.
Minification:
- https://www.npmjs.com/package/uglify-es // this version of uglify is ES6 compatible, earlier versions were not
- uglifyjs samsa-core.js > samsa-core.min.js
*/
// TODO:
// - rename it SamsaCONFIG
// - pass the actual config object along with the font
let CONFIG = {
isNode: (typeof module !== 'undefined' && module.exports),
outFileDefault: "samsa-out.ttf",
instantiation: {
method: "default", // sets apple overlap bit
// method: "dummy-fvar", // does not set apple overlap bit
// method: "no-overlap-bit", // does not set apple overlap bit
skipTables: ["gvar","fvar","cvar","avar","STAT","MVAR","HVAR","VVAR","DSIG"],
ignoreIUP: false,
},
defaultGlyph: [
"A", "a", "Alpha", "alpha", "afii10017", "A-cy", "afii10065", "a-cy", "zero", // PostScript names: Latin, Russian, Cyrillic (or should we use the cmap? because some fonts lack ps names)
],
sfnt: {
maxNumTables: 100,
maxSize: 10000000,
},
glyf: {
overlapSimple: true,
bufferSize: 500000, // for writing to files (ignored for in-memory instantiation)
},
name: {
maxSize: 50000,
},
deltas: {
round: true,
},
postscriptNames: [".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"],
};
if (CONFIG.isNode) {
// mappings from DataView methods to Buffer methods
Buffer.prototype.getUint32 = Buffer.prototype.readUInt32BE;
Buffer.prototype.getInt32 = Buffer.prototype.readInt32BE;
Buffer.prototype.getUint16 = Buffer.prototype.readUInt16BE;
Buffer.prototype.getInt16 = Buffer.prototype.readInt16BE;
Buffer.prototype.getUint8 = Buffer.prototype.readUInt8;
Buffer.prototype.getInt8 = Buffer.prototype.readInt8;
Buffer.prototype.setUint32 = function (p,v) {this.writeUInt32BE(v,p);}
Buffer.prototype.setInt32 = function (p,v) {this.writeInt32BE(v,p);}
Buffer.prototype.setUint16 = function (p,v) {this.writeUInt16BE(v,p);}
Buffer.prototype.setInt16 = function (p,v) {this.writeInt16BE(v,p);}
Buffer.prototype.setUint8 = function (p,v) {this.writeUInt8(v,p);}
Buffer.prototype.setInt8 = function (p,v) {this.writeInt8(v,p);}
// add new Buffer methods
Buffer.prototype.getTag = function (p) {
var tag = "";
var p_end = p + 4; // global
var ch;
while (p < p_end)
{
ch = this.readUInt8(p++);
if (ch >= 32 && ch < 126) // valid chars in tag data type https://www.microsoft.com/typography/otspec/otff.htm
tag += String.fromCharCode(ch);
}
return tag.length == 4 ? tag : false;
}
Buffer.prototype.getF2DOT14 = function (p) {
return this.getInt16(p) / 16384.0; /* signed */
}
}
let fonts = [];
let glyph = {
font: undefined,
endPts: [],
points: [],
deltas: []
};
let newGlyph;
function getStringFromData (data, p0, length)
{
// TODO: add a Pascal and C modes to use in parsing "post" table (use length = undefined for C, -1 for Pascal)
var str = "";
var p = p0;
while (p - p0 < length) {
str += String.fromCharCode(data.getUint8(p++));
}
return str;
}
// TODO: get rid of this!
function uint8ToBase64(buffer) {
var binary = '';
var len = buffer.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(buffer[i]);
}
return window.btoa( binary );
}
//////////////////////////////////
// fvsToCSS()
//////////////////////////////////
function fvsToCSS(fvs) {
// transforms an fvs object into a string suitable for font-variation-settings
// - simple transormation, it doesn’t perform any checks to see if the axes are in a font or if settings are beyond axis ranges
// - examples:
// {"wght": 655, "wdth": 77, "FOOB": 12345} => '"wght" 655,"wdth" 77,"FOOB" 12345'
// {} => 'normal'
let fvsCSS = [];
Object.keys(fvs).forEach(tag => {
fvsCSS.push(`"${tag}" ${fvs[tag]}`);
});
return fvsCSS.length ? fvsCSS.join() : "normal";
}
DataView.prototype.getTag = function (p) {
let ch, tag = "";
const p_end = p + 4;
while (p < p_end) {
ch = this.getUint8(p++);
if (ch >= 32 && ch < 126) // valid chars in tag data type https://www.microsoft.com/typography/otspec/otff.htm
tag += String.fromCharCode(ch);
}
return tag.length == 4 ? tag : false;
}
DataView.prototype.getF2DOT14 = function (p) {
return this.getInt16(p) / 16384.0; // signed
}
function copyBytes(source, target, zs, zt, n) {
// copies n bytes from source (starting at zs) to target (starting at zt)
// - source and target are typically DataView, but they can be any TypedArray
const src = new Uint8Array(source.buffer, source.byteOffset + zs, n);
const tgt = new Uint8Array(target.buffer, target.byteOffset + zt, n);
for (let i=0; i < n; i++)
tgt[i] = src[i]; // this seems to be the quickest way to copy between two ArrayBuffers, see benchmark at https://www.measurethat.net/Benchmarks/Show/7537/0/copy-arraybuffer-dataview-vs-uint8arrayset-vs-float64ar
}
// TODO make SamsaVFInstance a proper object
function SamsaVFInstance (init) {
}
// TODO: make SamsaVFGlyph a proper object
function SamsaVFGlyph (init) {
this.points = [];
// methods
this.toSVG = function (asText = false) {
let svg = "";
// normal case
if (this.bezierOrder == 2) {
}
return svg;
};
this.toTTX = function () {
// return the glyf table and/or gvar table, depending on options
let ttx = {};
ttx.glyf = "...";
ttx.gvar = "...";
return ttx;
};
this.toGLIF = function () {
// UFO GLIF
// if you want GLIF data for non-default masters, then make an instance and use the glyph from that
};
this.toJSON = function () {
// remove circular object references
};
this.toCubic = function () {
this.bezierOrder = 3;
};
// might be nice to get binary and hex versions of TTF data, per glyph, although we are normally writing to a stream
this.toBinaryTTF = function () {
};
}
function SamsaFont (init, config) {
// initialize config, and update it with updates passed to constructor
this.config = CONFIG;
if (config) {
Object.keys(config).forEach(k => this.config[k] = config[k] );
}
// general properties
this.dateCreated = new Date();
this.date = init.date;
this.arrayBuffer = init.arrayBuffer;
this.url = init.url; // for browser using a VF on a server
this.callback = init.callback;
this.data = undefined;
this.fontFamily = init.fontFamily;
this.instances = [];
this.axes = [];
this.instances = [];
this.errors = [];
this.glyphs = [];
this.glyphOffsets = [];
this.glyphSizes = [];
this.tupleOffsets = [];
this.tupleSizes = [];
this.avar = [];
// node-dependent properties
if (this.config.isNode) {
this.inFile = init.inFile;
if (!init.outFile)
this.outFile = this.config.outFileDefault;
}
this.path = init.inFile || this.url;
this.filename = this.path.substr(this.path.lastIndexOf("/")+1); // works nicely even when there are no slashes in the name because of the -1 return :)
this.filesize = init.filesize;
// methods
//////////////////////////////////
// load()
//////////////////////////////////
this.load = () => {
if (this.config.isNode) {
// open the font file
try {
this.fd = config.fs.openSync (this.inFile, "r");
}
catch (error) {
this.errors.push(error);
quit(this);
}
this.stat = config.fs.fstatSync(this.fd);
this.filesize = this.stat.size;
this.date = this.stat.birthtimeMs;
this.parse();
}
else if (this.url) {
let oReq = new XMLHttpRequest();
oReq.open("GET", this.url, true);
oReq.responseType = "arraybuffer";
oReq.font = this;
oReq.onload = function(oEvent) {
oReq.font.data = new DataView(this.response);
oReq.font.filesize = oReq.font.data.byteLength;
oReq.font.parse();
};
oReq.send();
}
}
//////////////////////////////////
// parse()
//////////////////////////////////
this.parse = () => {
let font = this;
let data = this.data;
let config = this.config;
let table;
let p=p_=0; // data pointers
let node = this.config.isNode;
let fd = this.fd;
let read, write;
if (node) {
read = this.config.fs.readSync;
write = this.config.fs.writeSync;
}
/////////////////////////////////////////////////////////////////////////////////
// sfnt first 12 bytes
if (node) {
data = Buffer.alloc(12);
read (fd, data, 0, 12, 0);
}
font.fingerprint = data.getUint32(0);
switch (font.fingerprint) {
case 0x00010000: // normal TrueType
case 0x74727565: // 'true' (as in Skia.ttf)
font.flavor = "truetype";
break;
case 0x4f54544f: // 'OTTO' (as in OpenType OTF fonts)
font.flavor = "cff";
break;
default:
font.errors.push ("Invalid first 4 bytes of the file. Must be one of: 0x00010000, 0x74727565, 0x4f54544f");
break;
}
if (!font.errors.length)
{
font.numTables = data.getUint16(4);
if (font.numTables > config.sfnt.maxNumTables)
font.errors.push (`numTables (${font.numTables}) exceeds config.sfnt.maxNumTables (${config.sfnt.maxNumTables})`);
else {
/////////////////////////////////////////////////////////////////////////////////
// get sfnt table directory
font.tableDirectory = [];
font.tables = {};
if (node) {
p = 0;
data = Buffer.alloc(16 * font.numTables);
read (fd, data, 0, 16 * font.numTables, 12);
}
else
p = 12;
for (var t=0; t<font.numTables; t++) {
var tag = data.getTag (p);
if (!tag) {
font.errors.push ("Tag value is invalid");
break;
}
font.tables[tag] = font.tableDirectory[t] = {
id: t,
tag: tag,
checkSum: data.getUint32(p+4),
offset: data.getUint32(p+8),
length: data.getUint32(p+12),
};
p += 16;
}
}
}
// parse the short sfnt tables
// - maxp must be first
// - avar must precede fvar (because of normalizing code in fvar parsing)
// - name must precede fvar
// - name must precede STAT
// - gvar isn’t short, but we only parse its header here
["maxp", "hhea", "head", "hmtx", "OS/2", "post", "name", "avar", "fvar", "gvar", "STAT", "loca"].forEach(tag => {
if (font.tables[tag])
font.parseSmallTable(tag);
});
// parse glyf table: all glyphs!
if (!node) {
for (let g=0; g < font.numGlyphs; g++) {
font.glyphs[g] = font.parseGlyph(g); // glyf data
font.glyphs[g].tvts = font.parseTvts(g); // gvar data
// delete glyph if this is a big file, to save memory
// - which of these is better?
// font.glyphs[g] = undefined;
// delete font.glyphs[g]
}
}
// glyf end
// we parsed the font, get a timestamp
font.dateParsed = new Date();
font.callback(font);
}
//////////////////////////////////
// parseSmallTable()
//////////////////////////////////
this.parseSmallTable = tag => {
let font = this;
let data;
let tableOffset, p=p_=0; // data pointers
let config = this.config;
let table = {};
let node = this.config.isNode;
let fd, read, write;
if (node) {
fd = this.fd;
read = this.config.fs.readSync;
write = this.config.fs.writeSync;
}
// set up data and pointers
if (node) {
data = Buffer.alloc(font.tables[tag].length);
read (fd, data, 0, font.tables[tag].length, font.tables[tag].offset);
p = tableOffset = 0;
}
else {
data = this.data;
p = tableOffset = font.tables[tag].offset;
}
// switch by tag to process each table
switch (tag) {
case "maxp":
table.version = data.getUint32(p), p+=4;
table.numGlyphs = data.getUint16(p), p+=2;
font.numGlyphs = table.numGlyphs;
break;
case "hhea":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.ascender = data.getInt16(p), p+=2;
table.descender = data.getInt16(p), p+=2;
table.lineGap = data.getInt16(p), p+=2;
table.advanceWidthMax = data.getUint16(p), p+=2;
table.minLeftSideBearing = data.getInt16(p), p+=2;
table.minRightSideBearing = data.getInt16(p), p+=2;
table.xMaxExtent = data.getInt16(p), p+=2;
table.caretSlopeRise = data.getInt16(p), p+=2;
table.caretSlopeRun = data.getInt16(p), p+=2;
table.caretOffset = data.getInt16(p), p+=2;
p+=8;
table.metricDataFormat = data.getInt16(p), p+=2;
table.numberOfHMetrics = data.getUint16(p), p+=2;
break;
case "head":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.fontRevision = data.getUint32(p), p+=4;
table.checkSumAdjustment = data.getUint32(p), p+=4;
table.magicNumber = data.getUint32(p), p+=4;
table.flags = data.getUint16(p), p+=2;
table.unitsPerEm = data.getUint16(p), p+=2;
p += 8;
p += 8;
table.xMin = data.getInt16(p), p+=2;
table.yMin = data.getInt16(p), p+=2;
table.xMax = data.getInt16(p), p+=2;
table.yMax = data.getInt16(p), p+=2;
table.macStyle = data.getUint16(p), p+=2;
table.lowestRecPPEM = data.getUint16(p), p+=2;
table.fontDirectionHint = data.getInt16(p), p+=2;
table.indexToLocFormat = data.getUint16(p), p+=2;
table.glyphDataFormat = data.getUint16(p), p+=2;
font.unitsPerEm = table.unitsPerEm;
break;
case "hmtx":
font.widths = [];
if (font.tables['hhea'].data.numberOfHMetrics < 1)
font.errors.push ("hhea: numberOfHMetrics must be >=1.")
for (let m=0; m<font.numGlyphs; m++) {
if (m < font.tables['hhea'].data.numberOfHMetrics) {
font.widths[m] = data.getUint16(p), p+=2;
p+=2; // skip lsb
}
else
font.widths[m] = font.widths[m-1];
}
break;
case "OS/2":
table.version = data.getUint16(p), p+=2;
table.xAvgCharWidth = data.getInt16(p), p+=2;
table.usWeightClass = data.getUint16(p), p+=2;
table.usWidthClass = data.getUint16(p), p+=2;
table.fsType = data.getUint16(p), p+=2;
table.ySubscriptXSize = data.getInt16(p), p+=2;
table.ySubscriptYSize = data.getInt16(p), p+=2;
table.ySubscriptXOffset = data.getInt16(p), p+=2;
table.ySubscriptYOffset = data.getInt16(p), p+=2;
table.ySuperscriptXSize = data.getInt16(p), p+=2;
table.ySuperscriptYSize = data.getInt16(p), p+=2;
table.ySuperscriptXOffset = data.getInt16(p), p+=2;
table.ySuperscriptYOffset = data.getInt16(p), p+=2;
table.yStrikeoutSize = data.getInt16(p), p+=2;
table.yStrikeoutPosition = data.getInt16(p), p+=2;
table.sFamilyClass = data.getInt16(p), p+=2;
table.panose = [data.getUint8(p), data.getUint8(p+1), data.getUint8(p+2), data.getUint8(p+3), data.getUint8(p+4), data.getUint8(p+5), data.getUint8(p+6), data.getUint8(p+7), data.getUint8(p+8), data.getUint8(p+9)];
p+=10;
table.ulUnicodeRange1 = data.getUint32(p), p+=4;
table.ulUnicodeRange2 = data.getUint32(p), p+=4;
table.ulUnicodeRange3 = data.getUint32(p), p+=4;
table.ulUnicodeRange4 = data.getUint32(p), p+=4;
table.achVendID = getStringFromData (data, p, 4), p+=4;
table.fsSelection = data.getUint16(p), p+=2;
table.usFirstCharIndex = data.getUint16(p), p+=2;
table.usLastCharIndex = data.getUint16(p), p+=2;
table.sTypoAscender = data.getInt16(p), p+=2;
table.sTypoDescender = data.getInt16(p), p+=2;
table.sTypoLineGap = data.getInt16(p), p+=2;
table.usWinAscent = data.getUint16(p), p+=2;
table.usWinDescent = data.getUint16(p), p+=2;
break;
case "name":
table.format = data.getUint16(p), p+=2;
table.count = data.getUint16(p), p+=2;
table.stringOffset = data.getUint16(p), p+=2;
table.nameRecords = [];
font.names = [];
for (let n=0; n < table.count; n++) {
let nameRecord = {};
let str = "";
let nameRecordStart, nameRecordEnd;
nameRecord.platformID = data.getUint16(p), p+=2;
nameRecord.encodingID = data.getUint16(p), p+=2;
nameRecord.languageID = data.getUint16(p), p+=2;
nameRecord.nameID = data.getUint16(p), p+=2;
nameRecord.length = data.getUint16(p), p+=2;
nameRecord.offset = data.getUint16(p), p+=2;
nameRecordStart = tableOffset + table.stringOffset + nameRecord.offset;
nameRecordEnd = nameRecordStart + nameRecord.length;
if (nameRecordEnd > tableOffset + font.tables['name'].length) // safety check
continue;
p_ = p;
p = nameRecordStart;
switch (nameRecord.platformID)
{
case 1:
if (nameRecord.languageID == 0)
// TODO: treat 1,0 strings as MacRoman
if (nameRecord.encodingID == 0)
{
while (p < nameRecordEnd)
str += String.fromCharCode(data.getUint8(p)), p++;
nameRecord.string = str;
}
break;
case 3:
if (nameRecord.languageID == 0x0409)
{
switch (nameRecord.encodingID)
{
case 0:
case 1:
while (p < nameRecordEnd)
str += String.fromCharCode(data.getUint16(p)), p+=2;
nameRecord.string = str;
break;
case 10:
while (p < nameRecordEnd) {
// this obtains the Unicode index for codes >= 0x10000
str += (String.fromCharCode(data.getUint16(p))), p+=2;
}
nameRecord.string = str;
break; // the sample text in the 2016 Zycon uses this to store an Emoji string
// TODO: hmm, it’s the same code, because we store them like this in UTF-8
}
}
}
// set up working name strings that might be taken from Windows (3) or Macintosh (1) strings
// the Windows strings will overwrite the Mac strings, as nameRecords are sorted by platformID as well as nameID
if (nameRecord.hasOwnProperty('string'))
font.names[nameRecord.nameID] = str; // sparse array
table.nameRecords.push(nameRecord);
p = p_; // restore pointer ready for the next nameRecord
}
break;
case "post":
font.glyphNames = []; // store the names separately because the glyph often has not been loaded
table.format = data.getUint32(p+0);
font.italicAngle = data.getInt32(p+4) / 65536;
// most fonts are format 2
if (table.format == 0x00020000) {
// parse names data
p = tableOffset + 32 + 2 + 2 * font.numGlyphs; // jump past header and glyphNameIndex array
let extraNames = [];
while (p < tableOffset + font.tables['post'].length) {
let str="", len=data.getUint8(p++); // Pascal style strings: first byte is length, the rest is the string
while (len--) {
str += String.fromCharCode(data.getUint8(p++));
}
extraNames.push(str);
}
// parse glyphNameIndex array
p = tableOffset + 32; // jump past header
p += 2;
for (let g=0; g<font.numGlyphs; g++) {
let gni = data.getUint16(p + g*2);
font.glyphNames[g] = gni < 258 ? config.postscriptNames[gni] : extraNames[gni-258];
}
}
break;
case "loca":
let shortOffsets = (font.tables['head'].data.indexToLocFormat == 0);
font.glyphOffsets[0] = 0;
for (let g=0; g < font.numGlyphs; g++) {
if (shortOffsets)
font.glyphOffsets[g+1] = 2 * data.getUint16(tableOffset + 2 * (g+1));
else
font.glyphOffsets[g+1] = data.getUint32(tableOffset + 4 * (g+1));
font.glyphSizes[g] = font.glyphOffsets[g+1] - font.glyphOffsets[g];
}
break;
case "fvar":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.offsetToAxesArray = data.getUint16(p), p+=2;
table.countSizePairs = data.getUint16(p), p+=2;
table.axisCount = data.getUint16(p), p+=2;
table.axisSize = data.getUint16(p), p+=2;
table.instanceCount = data.getUint16(p), p+=2;
table.instanceSize = data.getUint16(p), p+=2;
// build axes
font.axes = [];
font.axisTagToId = {}; // TODO: better as an object where each property has value as the axis array item? and add id as an axis property
for (let a=0; a<table.axisCount; a++)
{
let axis = { id: a };
axis.tag = getStringFromData (data, p, 4), p+=4;
axis.min = data.getInt32(p)/65536, p+=4;
axis.default = data.getInt32(p)/65536, p+=4;
axis.max = data.getInt32(p)/65536, p+=4;
axis.flags = data.getUint16(p), p+=2;
if (axis.flags & 0x0001)
axis.hidden = true;
axis.axisNameID = data.getUint16(p), p+=2;
axis.name = font.names[axis.axisNameID];
if (axis.name === undefined)
axis.name = axis.tag; // for fonts without name table, e.g. optimized webfonts
font.axes.push(axis);
font.axisTagToId[axis.tag] = a;
}
// build instances
// - insert default instance as well as the instances in the fvar table
font.instances = [];
for (let i=0; i<table.instanceCount+1; i++) { // +1 allows for default instance
let instance = {
id: i,
glyphs: [],
tuple:[],
fvs: {},
static: null, // if this is instantiated as a static font, this can point to the data or url
};
if (i>0) {
instance.subfamilyNameID = data.getUint16(p), p+=2;
p+=2; // skip over flags
}
font.axes.forEach((axis, a) => {
instance.tuple[a] = axis.default;
if (i==0)
instance.tuple[a] = axis.default; // user-facing value
else
instance.tuple[a] = data.getInt32(p)/65536, p+=4; // user-facing value
instance.fvs[axis.tag] = instance.tuple[a];
instance.tuple[a] = font.axisNormalize(axis, instance.tuple[a]);
});
if (i==0) {
instance.name = "Default";
instance.type = "default"; // one of default, named, stat, custom
}
else {
if (table.instanceSize == table.axisCount * 4 + 6)
instance.postScriptNameID = data.getUint16(p), p+=2;
instance.name = font.names[instance.subfamilyNameID]; // name table must already be parsed! (TODO: fallback if no name table)
instance.type = "named"; // one of default, named, stat, custom
}
font.instances.push(instance);
}
font.axisCount = table.axisCount;
break;
case "avar":
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
if (!(table.majorVersion === 1 && table.minorVersion === 0))
break;
p+=2
table.axisCount = data.getUint16(p), p+=2;
for (let a=0; a<table.axisCount; a++) { // not font.axisCount, because we have not yet parsed fvar
font.avar[a] = [];
let positionMapCount = data.getUint16(p); p+=2; // TODO: if positionMapCount==3 (NOOP), don’t store anything
for (let m=0; m<positionMapCount; m++) {
font.avar[a][m] = [data.getF2DOT14(p), data.getF2DOT14(p+2)], p+=4; // = [<fromCoordinate>,<toCoordinate>]
}
}
break;
case "gvar":
// NOTE: this only parses the table header!
// the main data, tuple variation tables for each glyph, is processed in SamsaVF_parseTvts()
table.majorVersion = data.getUint16(p), p+=2;
table.minorVersion = data.getUint16(p), p+=2;
table.axisCount = data.getUint16(p), p+=2;
table.sharedTupleCount = data.getUint16(p), p+=2;
table.offsetToSharedTuples = data.getUint32(p), p+=4;
table.glyphCount = data.getUint16(p), p+=2;
table.flags = data.getUint16(p), p+=2;
table.offsetToData = data.getUint32(p), p+=4;
table.sizeofTuple = table.axisCount * 2; // sizeof (F2DOT14)
//table.sizeofOffset = (table.flags & 0x01) ? 4 : 2;
// get sharedTuples array - working nicely!
table.sharedTuples = [];
let ps = tableOffset + table.offsetToSharedTuples;
for (let t=0; t < table.sharedTupleCount; t++) {
let tuple = [];
for (var a=0; a<table.axisCount; a++)
tuple.push(data.getF2DOT14(ps)), ps+=2;
table.sharedTuples.push (tuple);
}
// store tvt offsets: we create an index into the tuple store for each glyph
font.tupleOffsets[0] = 0;
for (let g=0; g < font.numGlyphs; g++) {
if (table.flags & 0x01) // offsets are Offset32
font.tupleOffsets[g+1] = data.getUint32(tableOffset + 20 + 4 * (g+1));
else // offsets are 2*Offset16
font.tupleOffsets[g+1] = 2 * data.getUint16(tableOffset + 20 + 2 * (g+1));
font.tupleSizes[g] = font.tupleOffsets[g+1] - font.tupleOffsets[g];
}
font.sharedTuples = table.sharedTuples;
break;
case "STAT":
table.majorVersion = data.getUint16(p+0);
table.minorVersion = data.getUint16(p+2);
let designAxisSize = data.getUint16(p+4);
table.designAxisCount = data.getUint16(p+6);
let designAxesOffset = data.getUint32(p+8);
table.axisValueCount = data.getUint16(p+12);
let offsetToAxisValueOffsets = data.getUint32(p+14);
if (table.majorVersion >= 1 && table.minorVersion >= 1) {
table.elidedFallbackNameID = data.getUint16(p+18);
}
table.designAxes = [];
table.designAxesSorted = [];
table.axisValueTables = [];
// parse designAxes
for (let a=0; a<table.designAxisCount; a++) {
p = tableOffset + designAxesOffset + a*designAxisSize;
let designAxis = {
designAxisID: a, // in case we are enumerating a sorted array
tag: data.getTag(p),
nameID: data.getUint16(p+4),
axisOrdering: data.getUint16(p+6),
};
table.designAxes.push(designAxis);
table.designAxesSorted[designAxis.axisOrdering] = designAxis;
}
// parse axisValueTables
for (let a=0; a<table.axisValueCount; a++) {
p = tableOffset + offsetToAxisValueOffsets + 2*a;
let axisValueOffset = data.getUint16(p);
p = tableOffset + offsetToAxisValueOffsets + axisValueOffset;
let format = data.getUint16(p);
if (format < 1 || format > 4)
continue;
let axisValueTable = {
format: format,
axisIndex: data.getUint16(p+2),
flags: data.getUint16(p+4),
nameID: data.getUint16(p+6),
};
if (axisValueTable.format >= 1 && axisValueTable.format <= 3) {
axisValueTable.value = data.getInt32(p+8)/65536;
}
if (axisValueTable.format == 2) {
axisValueTable.min = data.getInt32(p+12)/65536;
axisValueTable.max = data.getInt32(p+16)/65536;
}
else if (axisValueTable.format == 3) {
axisValueTable.linkedValue = data.getInt32(p+12)/65536;
}
else if (axisValueTable.format == 4) {
axisValueTable.axisCount = axisValueTable.axisIndex;
axisValueTable.axisIndex = []; // now array, not numeric
axisValueTable.value = []; // now array, not numeric
p += 8;
for (let a=0; a < axisValueTable.axisCount; a++) {
axisValueTable.axisIndex.push(data.getUint16(p+a*6));
axisValueTable.value.push(data.getInt32(p+a*6+2)/65536);
}
}
table.axisValueTables.push(axisValueTable);
}
break;
}
font.tables[tag].data = table;
}
//////////////////////////////////
// parseGlyph()
//////////////////////////////////
this.parseGlyph = g => {
// parse glyph g from the given font
let font = this;
let node = this.config.isNode;
let data, p;
let offset = font.glyphOffsets[g];
let size = font.glyphSizes[g];
let pt;
let glyph = {
font: font,
name: font.glyphNames[g],
id: g,
numPoints: 0,
numContours: 0,
instructionLength: 0,
points: [],
endPts: [],
tvts: [], // tuple variable tables (see gvar spec)
};
let fd, read, write;
if (node) {
fd = this.fd;
read = this.config.fs.readSync;
write = this.config.fs.writeSync;
}
// set up data and pointers
if (node) {
data = Buffer.alloc(size);
// we should compare speeds for the best optmization
// - reading pieces of data from file when we need it
// - reading a whole glyph into memory, then parsing from memory
// - reading a block of data from the glyf table, loading more when needed, and parsing from memory
// - I think it was a bit faster when we loaded all glyphs in sequence, than the present case where we load a glyph and then its tvts
read (fd, data, 0, size, font.tables['glyf'].offset + offset);
p = 0;
}
else {
data = font.data;
p = font.tables['glyf'].offset + offset;
}
// non-printing glyph
if (size == 0) {
glyph.numContours = 0;
}
// printing glyph
else if (size > 0) {
glyph.numContours = data.getInt16(p), p+=2;
glyph.xMin = data.getInt16(p), p+=2;
glyph.yMin = data.getInt16(p), p+=2;
glyph.xMax = data.getInt16(p), p+=2;
glyph.yMax = data.getInt16(p), p+=2;
let flag, repeat=0, x_=0, y_=0, x, y, c, r;
// simple glyph
if (glyph.numContours > 0) {
// end points of each contour
for (c=0; c<glyph.numContours; c++)
glyph.endPts.push(data.getUint16(p)), p+=2;
glyph.numPoints = glyph.endPts[glyph.numContours -1] + 1;
// instructions
glyph.instructionLength = data.getUint16(p), p+=2;
p += glyph.instructionLength;
// flags
let flags = [];
for (pt=0; pt<glyph.numPoints; ) {
flag = data.getUint8(p), p++;
flags[pt++] = flag;
if (flag & 0x08) {
repeat = data.getUint8(p), p++;
for (r=0; r<repeat; r++)
flags[pt++] = flag;
}
}
// points
if (flags.length == glyph.numPoints) {
flags.forEach(function (flag, pt) {
switch (flag & 0x12) { // x
case 0x00: x = x_ + data.getInt16(p); p+=2; break;
case 0x02: x = x_ - data.getUint8(p); p++; break;
case 0x10: x = x_; break;
case 0x12: x = x_ + data.getUint8(p); p++; break;
}
glyph.points[pt] = [x_ = x];
});
flags.forEach(function (flag, pt) {
switch (flag & 0x24) { // y
case 0x00: y = y_ + data.getInt16(p), p+=2; break;
case 0x04: y = y_ - data.getUint8(p), p++; break;
case 0x20: y = y_; break;
case 0x24: y = y_ + data.getUint8(p), p++; break;
}
glyph.points[pt].push(y_ = y, flag & 0x01);
});
}
}
// composite glyph
// - we DO add points for composite glyphs: one per component (they are the x and y offsets), and the 4 extra metrics points
// - when we process these glyphs, we look at glyph.numContours and glyph.points, but NOT glyph.numPoints