-
Notifications
You must be signed in to change notification settings - Fork 3
/
sfnt.go
1070 lines (965 loc) · 31 KB
/
sfnt.go
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
package font
import (
"encoding/binary"
"fmt"
"math"
"sort"
"sync"
"time"
"github.com/tdewolff/parse/v2"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
// MaxCmapSegments is the maximum number of cmap segments that will be accepted.
const MaxCmapSegments = 20000
// Pather is an interface to append a glyph's path to canvas.Path.
type Pather interface {
MoveTo(float64, float64)
LineTo(float64, float64)
QuadTo(float64, float64, float64, float64)
CubeTo(float64, float64, float64, float64, float64, float64)
Close()
}
// Hinting specifies the type of hinting to use (none supported yes).
type Hinting int
// see Hinting
const (
NoHinting Hinting = iota
VerticalHinting
)
// SFNT is a parsed OpenType font.
type SFNT struct {
Length uint32
Version string
IsCFF, IsTrueType bool // only one can be true
Tables map[string][]byte
// required
Cmap *cmapTable
Head *headTable
Hhea *hheaTable
Hmtx *hmtxTable
Maxp *maxpTable
Name *nameTable
OS2 *os2Table
Post *postTable
// TrueType
Glyf *glyfTable
Loca *locaTable
// CFF
CFF *cffTable
// optional
Kern *kernTable
Vhea *vheaTable
Vmtx *vmtxTable
// TODO: SFNT tables
//Hdmx *hdmxTable
Gpos *gposgsubTable
Gsub *gposgsubTable
Jsft *jsftTable
//Gasp *gaspTable
//Base *baseTable
//Prep *baseTable
//Fpgm *baseTable
//Cvt *baseTable
}
// NumGlyphs returns the number of glyphs the font contains.
func (sfnt *SFNT) NumGlyphs() uint16 {
return sfnt.Maxp.NumGlyphs
}
// GlyphIndex returns the glyphID for a given rune. When the rune is not defined it returns 0.
func (sfnt *SFNT) GlyphIndex(r rune) uint16 {
return sfnt.Cmap.Get(r)
}
// GlyphName returns the name of the glyph. It returns an empty string when no name exists.
func (sfnt *SFNT) GlyphName(glyphID uint16) string {
if sfnt.IsCFF {
name, _ := sfnt.CFF.GlyphName(glyphID)
return name
}
return sfnt.Post.Get(glyphID)
}
// FindGlyphName returns the glyphID for a given glyph name. When the name is not defined it returns 0.
func (sfnt *SFNT) FindGlyphName(name string) uint16 {
if sfnt.IsCFF {
for glyphID, glyphName := range sfnt.CFF.charset {
if name == glyphName {
return uint16(glyphID)
}
}
return 0
}
glyphID, _ := sfnt.Post.Find(name)
return glyphID
}
// VerticalMetrics returns the ascender, descender, and line gap values. It returns the "win" values, or the "typo" values if OS/2.FsSelection.USE_TYPO_METRICS is set. If those are zero or not set, default to the "hhea" values.
func (sfnt *SFNT) VerticalMetrics() (uint16, uint16, uint16) {
// see https://learn.microsoft.com/en-us/typography/opentype/spec/recom#baseline-to-baseline-distances
var ascender, descender, lineGap uint16
if 0 < sfnt.Hhea.Ascender {
ascender = uint16(sfnt.Hhea.Ascender)
}
if sfnt.Hhea.Descender < 0 {
descender = uint16(-sfnt.Hhea.Descender)
}
if 0 < sfnt.Hhea.LineGap {
lineGap = uint16(sfnt.Hhea.LineGap)
}
if (sfnt.OS2.FsSelection & 0x0080) != 0 { // USE_TYPO_METRICS
if 0 < sfnt.OS2.STypoAscender && sfnt.OS2.STypoDescender < 0 {
ascender = uint16(sfnt.OS2.STypoAscender)
descender = uint16(-sfnt.OS2.STypoDescender)
if 0 < sfnt.OS2.STypoLineGap {
lineGap = uint16(sfnt.OS2.STypoLineGap)
} else {
lineGap = 0
}
}
} else {
if sfnt.OS2.UsWinAscent != 0 && sfnt.OS2.UsWinDescent != 0 {
ascender, descender = sfnt.OS2.UsWinAscent, sfnt.OS2.UsWinDescent
externalLeading := int(sfnt.Hhea.Ascender-sfnt.Hhea.Descender+sfnt.Hhea.LineGap) - int(sfnt.OS2.UsWinAscent+sfnt.OS2.UsWinDescent)
if 0 < externalLeading {
lineGap = uint16(externalLeading)
} else {
lineGap = 0
}
}
}
return ascender, descender, lineGap
}
// GlyphPath draws the glyph's contour as a path to the pather interface. It will use the specified ppem (pixels-per-EM) for hinting purposes. The path is draws to the (x,y) coordinate and scaled using the given scale factor.
func (sfnt *SFNT) GlyphPath(p Pather, glyphID, ppem uint16, x, y, scale float64, hinting Hinting) error {
if sfnt.IsTrueType {
return sfnt.Glyf.ToPath(p, glyphID, ppem, x, y, scale, hinting)
} else if sfnt.IsCFF {
return sfnt.CFF.ToPath(p, glyphID, ppem, x, y, scale, hinting)
}
return fmt.Errorf("only TrueType and CFF are supported")
}
// GlyphAdvance returns the (horizontal) advance width of the glyph.
func (sfnt *SFNT) GlyphAdvance(glyphID uint16) uint16 {
return sfnt.Hmtx.Advance(glyphID)
}
// GlyphVerticalAdvance returns the vertical advance width of the glyph.
func (sfnt *SFNT) GlyphVerticalAdvance(glyphID uint16) uint16 {
if sfnt.Vmtx == nil {
return sfnt.Head.UnitsPerEm
}
return sfnt.Vmtx.Advance(glyphID)
}
// GlyphBounds returns the bounding rectangle (xmin,ymin,xmax,ymax) of the glyph.
func (sfnt *SFNT) GlyphBounds(glyphID uint16) (int16, int16, int16, int16, error) {
if sfnt.IsTrueType {
contour, err := sfnt.Glyf.Contour(glyphID)
if err != nil {
return 0, 0, 0, 0, err
}
return contour.XMin, contour.YMin, contour.XMax, contour.YMax, nil
} else if sfnt.IsCFF {
p := &bboxPather{}
if err := sfnt.CFF.ToPath(p, glyphID, 0, 0, 0, 1.0, NoHinting); err != nil {
return 0, 0, 0, 0, err
}
return int16(p.XMin), int16(p.YMin), int16(math.Ceil(p.XMax)), int16(math.Ceil(p.YMax)), nil
}
return 0, 0, 0, 0, fmt.Errorf("only TrueType is supported")
}
// Kerning returns the kerning between two glyphs, i.e. the advance correction for glyph pairs.
func (sfnt *SFNT) Kerning(left, right uint16) int16 {
if sfnt.Kern == nil {
return 0
}
return sfnt.Kern.Get(left, right)
}
// ParseSFNT parses an OpenType file format (TTF, OTF, TTC). The index is used for font collections to select a single font.
func ParseSFNT(b []byte, index int) (*SFNT, error) {
return parseSFNT(b, index, false)
}
// ParseEmbeddedSFNT is like ParseSFNT but for embedded font files in PDFs. It allows font files with fewer required tables.
func ParseEmbeddedSFNT(b []byte, index int) (*SFNT, error) {
return parseSFNT(b, index, true)
}
func parseSFNT(b []byte, index int, embedded bool) (*SFNT, error) {
if len(b) < 12 || uint(math.MaxUint32) < uint(len(b)) {
return nil, ErrInvalidFontData
}
r := parse.NewBinaryReader(b)
sfntVersion := r.ReadString(4)
isCollection := sfntVersion == "ttcf"
if isCollection {
majorVersion := r.ReadUint16()
minorVersion := r.ReadUint16()
if majorVersion != 1 && majorVersion != 2 || minorVersion != 0 {
return nil, fmt.Errorf("bad TTC version")
}
numFonts := r.ReadUint32()
if index < 0 || numFonts <= uint32(index) {
return nil, fmt.Errorf("bad font index %d", index)
}
if r.Len() < 4*numFonts {
return nil, ErrInvalidFontData
}
_ = r.ReadBytes(uint32(4 * index))
offset := r.ReadUint32()
var length uint32
if uint32(index)+1 == numFonts {
length = uint32(len(b)) - offset
} else {
length = r.ReadUint32() - offset
}
if uint32(len(b))-8 < offset || uint32(len(b))-8-offset < length {
return nil, ErrInvalidFontData
}
r.Seek(offset)
sfntVersion = r.ReadString(4)
} else if index != 0 {
return nil, fmt.Errorf("bad font index %d", index)
}
if sfntVersion != "OTTO" && sfntVersion != "true" && binary.BigEndian.Uint32([]byte(sfntVersion)) != 0x00010000 {
return nil, fmt.Errorf("bad SFNT version")
}
numTables := r.ReadUint16()
_ = r.ReadUint16() // searchRange
_ = r.ReadUint16() // entrySelector
_ = r.ReadUint16() // rangeShift
if r.Len() < 16*uint32(numTables) { // can never exceed uint32 as numTables is uint16
return nil, ErrInvalidFontData
}
tables := make(map[string][]byte, numTables)
for i := 0; i < int(numTables); i++ {
tag := r.ReadString(4)
_ = r.ReadUint32() // checksum
offset := r.ReadUint32()
length := r.ReadUint32()
padding := (4 - length&3) & 3
if uint32(len(b)) <= offset || uint32(len(b))-offset < length || uint32(len(b))-offset-length < padding {
return nil, ErrInvalidFontData
}
if tag == "head" {
if length < 12 {
return nil, ErrInvalidFontData
}
// NOTE: checksum validation is disabled so as to parse broken fonts as best as possible
// to check checksum for head table, replace the overal checksum with zero and reset it at the end
//checksumAdjustment := binary.BigEndian.Uint32(b[offset+8:])
//binary.BigEndian.PutUint32(b[offset+8:], 0x00000000)
//if calcChecksum(b[offset:offset+length+padding]) != checksum {
// return nil, fmt.Errorf("%s: bad checksum", tag)
//} else if 0xB1B0AFBA-calcChecksum(b) != checksumAdjustment {
// return nil, fmt.Errorf("bad checksum")
//}
//binary.BigEndian.PutUint32(b[offset+8:], checksumAdjustment)
//} else if calcChecksum(b[offset:offset+length+padding]) != checksum {
// return nil, fmt.Errorf("%s: bad checksum", tag)
}
tables[tag] = b[offset : offset+length : offset+length]
}
sfnt := &SFNT{}
sfnt.Length = uint32(len(b))
sfnt.Version = sfntVersion
sfnt.IsCFF = sfntVersion == "OTTO"
sfnt.IsTrueType = sfntVersion == "true" || binary.BigEndian.Uint32([]byte(sfntVersion)) == 0x00010000
sfnt.Tables = tables
//if isCollection {
// sfnt.Data = sfnt.Write() // TODO: what is this?
//}
var requiredTables []string
if embedded {
// see Table 126 of the PDF32000 specification
if sfnt.IsTrueType {
requiredTables = []string{"glyf", "head", "hhea", "hmtx", "loca", "maxp"}
} else if sfnt.IsCFF {
requiredTables = []string{"cmap", "CFF "}
}
} else {
requiredTables = []string{"cmap", "head", "hhea", "hmtx", "maxp", "name", "post"} // OS/2 not required by TrueType
if sfnt.IsTrueType {
requiredTables = append(requiredTables, "glyf", "loca")
} else if sfnt.IsCFF {
_, hasCFF := tables["CFF "]
_, hasCFF2 := tables["CFF2"]
if !hasCFF && !hasCFF2 {
return nil, fmt.Errorf("CFF: missing table")
} else if hasCFF && hasCFF2 {
return nil, fmt.Errorf("CFF2: CFF table already exists")
}
}
}
for _, requiredTable := range requiredTables {
if _, ok := tables[requiredTable]; !ok {
return nil, fmt.Errorf("%s: missing table", requiredTable)
}
}
if embedded && sfnt.IsCFF {
if err := sfnt.parseCFF(); err != nil {
return nil, err
} else if err := sfnt.parseCmap(); err != nil {
return nil, err
}
return sfnt, nil
}
// required tables before parsing other tables
if err := sfnt.parseHead(); err != nil {
return nil, err
} else if err := sfnt.parseMaxp(); err != nil {
return nil, err
}
if sfnt.IsTrueType {
if err := sfnt.parseLoca(); err != nil {
return nil, err
}
}
tags := make([]string, 0, len(tables))
for tag := range tables {
tags = append(tags, tag)
}
sort.Strings(tags)
for _, tag := range tags {
var err error
switch tag {
case "CFF ":
err = sfnt.parseCFF()
case "CFF2":
err = sfnt.parseCFF2()
case "cmap":
err = sfnt.parseCmap()
case "glyf":
err = sfnt.parseGlyf()
//case "GPOS":
// err = sfnt.parseGPOS()
//case "GSUB":
// err = sfnt.parseGSUB()
case "hhea":
err = sfnt.parseHhea()
case "hmtx":
err = sfnt.parseHmtx()
case "kern":
err = sfnt.parseKern()
case "name":
err = sfnt.parseName()
case "OS/2":
err = sfnt.parseOS2()
case "post":
err = sfnt.parsePost()
case "vhea":
err = sfnt.parseVhea()
case "vmtx":
err = sfnt.parseVmtx()
}
if err != nil {
return nil, err
}
}
if sfnt.OS2 != nil && sfnt.OS2.Version <= 1 {
sfnt.estimateOS2()
}
return sfnt, nil
}
// Write writes out the SFNT file.
func (sfnt *SFNT) Write() []byte {
tags := make([]string, 0, len(sfnt.Tables))
for tag := range sfnt.Tables {
tags = append(tags, tag)
}
sort.Strings(tags)
// write header
w := parse.NewBinaryWriter([]byte{})
if sfnt.IsTrueType {
w.WriteUint32(0x00010000) // sfntVersion
} else if sfnt.IsCFF {
w.WriteString("OTTO") // sfntVersion
}
numTables := uint16(len(tags))
entrySelector := uint16(math.Log2(float64(numTables)))
searchRange := uint16(1 << (entrySelector + 4))
w.WriteUint16(numTables) // numTables
w.WriteUint16(searchRange) // searchRange
w.WriteUint16(entrySelector) // entrySelector
w.WriteUint16(numTables<<4 - searchRange) // rangeShift
// we'll write the table records at the end
w.WriteBytes(make([]byte, numTables<<4))
// write tables
var checksumAdjustmentPos uint32
offsets, lengths := make([]uint32, numTables), make([]uint32, numTables)
for i, tag := range tags {
offsets[i] = w.Len()
table := sfnt.Tables[tag]
if tag == "head" {
checksumAdjustmentPos = w.Len() + 8
w.WriteBytes(table[:8])
w.WriteUint32(0)
w.WriteBytes(table[12:28])
w.WriteInt64(int64(time.Now().UTC().Sub(time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)) / 1e9)) // modified
w.WriteBytes(table[36:])
} else {
w.WriteBytes(table)
}
lengths[i] = w.Len() - offsets[i]
padding := (4 - lengths[i]&3) & 3
for i := 0; i < int(padding); i++ {
w.WriteByte(0)
}
}
// add table record entries
buf := w.Bytes()
for i, tag := range tags {
pos := 12 + i<<4
copy(buf[pos:], []byte(tag))
padding := (4 - lengths[i]&3) & 3
checksum := calcChecksum(buf[offsets[i] : offsets[i]+lengths[i]+padding])
binary.BigEndian.PutUint32(buf[pos+4:], checksum)
binary.BigEndian.PutUint32(buf[pos+8:], offsets[i])
binary.BigEndian.PutUint32(buf[pos+12:], lengths[i])
}
binary.BigEndian.PutUint32(buf[checksumAdjustmentPos:], 0xB1B0AFBA-calcChecksum(buf))
return buf
}
////////////////////////////////////////////////////////////////
type headTable struct {
FontRevision uint32
Flags [16]bool
UnitsPerEm uint16
Created, Modified time.Time
XMin, YMin, XMax, YMax int16
MacStyle [16]bool
LowestRecPPEM uint16
FontDirectionHint int16
IndexToLocFormat int16
GlyphDataFormat int16
}
func (sfnt *SFNT) parseHead() error {
b, ok := sfnt.Tables["head"]
if !ok {
return fmt.Errorf("head: missing table")
} else if len(b) != 54 {
return fmt.Errorf("head: bad table")
}
sfnt.Head = &headTable{}
r := parse.NewBinaryReader(b)
majorVersion := r.ReadUint16()
minorVersion := r.ReadUint16()
if majorVersion != 1 && minorVersion != 0 {
return fmt.Errorf("head: bad version")
}
sfnt.Head.FontRevision = r.ReadUint32()
_ = r.ReadUint32() // checksumAdjustment
if r.ReadUint32() != 0x5F0F3CF5 { // magicNumber
return fmt.Errorf("head: bad magic version")
}
sfnt.Head.Flags = Uint16ToFlags(r.ReadUint16())
sfnt.Head.UnitsPerEm = r.ReadUint16()
created := r.ReadUint64()
modified := r.ReadUint64()
if math.MaxInt64 < created || math.MaxInt64 < modified {
return fmt.Errorf("head: created and/or modified dates too large")
}
sfnt.Head.Created = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Second * time.Duration(created))
sfnt.Head.Modified = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Second * time.Duration(modified))
sfnt.Head.XMin = r.ReadInt16()
sfnt.Head.YMin = r.ReadInt16()
sfnt.Head.XMax = r.ReadInt16()
sfnt.Head.YMax = r.ReadInt16()
sfnt.Head.MacStyle = Uint16ToFlags(r.ReadUint16())
sfnt.Head.LowestRecPPEM = r.ReadUint16()
sfnt.Head.FontDirectionHint = r.ReadInt16()
sfnt.Head.IndexToLocFormat = r.ReadInt16()
if sfnt.Head.IndexToLocFormat != 0 && sfnt.Head.IndexToLocFormat != 1 {
return fmt.Errorf("head: bad indexToLocFormat")
}
sfnt.Head.GlyphDataFormat = r.ReadInt16()
return nil
}
////////////////////////////////////////////////////////////////
type hheaTable struct {
Ascender int16
Descender int16
LineGap int16
AdvanceWidthMax uint16
MinLeftSideBearing int16
MinRightSideBearing int16
XMaxExtent int16
CaretSlopeRise int16
CaretSlopeRun int16
CaretOffset int16
MetricDataFormat int16
NumberOfHMetrics uint16
}
func (sfnt *SFNT) parseHhea() error {
if sfnt.Maxp == nil {
return fmt.Errorf("hhea: missing maxp table")
}
b, ok := sfnt.Tables["hhea"]
if !ok {
return fmt.Errorf("hhea: missing table")
} else if len(b) != 36 {
return fmt.Errorf("hhea: bad table")
}
sfnt.Hhea = &hheaTable{}
r := parse.NewBinaryReader(b)
majorVersion := r.ReadUint16()
minorVersion := r.ReadUint16()
if majorVersion != 1 && minorVersion != 0 {
return fmt.Errorf("hhea: bad version")
}
sfnt.Hhea.Ascender = r.ReadInt16()
sfnt.Hhea.Descender = r.ReadInt16()
sfnt.Hhea.LineGap = r.ReadInt16()
sfnt.Hhea.AdvanceWidthMax = r.ReadUint16()
sfnt.Hhea.MinLeftSideBearing = r.ReadInt16()
sfnt.Hhea.MinRightSideBearing = r.ReadInt16()
sfnt.Hhea.XMaxExtent = r.ReadInt16()
sfnt.Hhea.CaretSlopeRise = r.ReadInt16()
sfnt.Hhea.CaretSlopeRun = r.ReadInt16()
sfnt.Hhea.CaretOffset = r.ReadInt16()
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
sfnt.Hhea.MetricDataFormat = r.ReadInt16()
sfnt.Hhea.NumberOfHMetrics = r.ReadUint16()
if sfnt.Maxp.NumGlyphs < sfnt.Hhea.NumberOfHMetrics || sfnt.Hhea.NumberOfHMetrics == 0 {
return fmt.Errorf("hhea: bad numberOfHMetrics")
}
return nil
}
////////////////////////////////////////////////////////////////
type vheaTable struct {
Ascender int16
Descender int16
LineGap int16
AdvanceHeightMax int16
MinTopSideBearing int16
MinBottomSideBearing int16
YMaxExtent int16
CaretSlopeRise int16
CaretSlopeRun int16
CaretOffset int16
MetricDataFormat int16
NumberOfVMetrics uint16
}
func (sfnt *SFNT) parseVhea() error {
if sfnt.Maxp == nil {
return fmt.Errorf("vhea: missing maxp table")
}
b, ok := sfnt.Tables["vhea"]
if !ok {
return fmt.Errorf("vhea: missing table")
} else if len(b) != 36 {
return fmt.Errorf("vhea: bad table")
}
sfnt.Vhea = &vheaTable{}
r := parse.NewBinaryReader(b)
majorVersion := r.ReadUint16()
minorVersion := r.ReadUint16()
if majorVersion != 1 && minorVersion != 0 && minorVersion != 1 {
return fmt.Errorf("vhea: bad version")
}
sfnt.Vhea.Ascender = r.ReadInt16()
sfnt.Vhea.Descender = r.ReadInt16()
sfnt.Vhea.LineGap = r.ReadInt16()
sfnt.Vhea.AdvanceHeightMax = r.ReadInt16()
sfnt.Vhea.MinTopSideBearing = r.ReadInt16()
sfnt.Vhea.MinBottomSideBearing = r.ReadInt16()
sfnt.Vhea.YMaxExtent = r.ReadInt16()
sfnt.Vhea.CaretSlopeRise = r.ReadInt16()
sfnt.Vhea.CaretSlopeRun = r.ReadInt16()
sfnt.Vhea.CaretOffset = r.ReadInt16()
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
_ = r.ReadInt16() // reserved
sfnt.Vhea.MetricDataFormat = r.ReadInt16()
sfnt.Vhea.NumberOfVMetrics = r.ReadUint16()
if sfnt.Maxp.NumGlyphs < sfnt.Vhea.NumberOfVMetrics || sfnt.Vhea.NumberOfVMetrics == 0 {
return fmt.Errorf("vhea: bad numberOfVMetrics")
}
return nil
}
////////////////////////////////////////////////////////////////
type hmtxLongHorMetric struct {
AdvanceWidth uint16
LeftSideBearing int16
}
type hmtxTable struct {
HMetrics []hmtxLongHorMetric
LeftSideBearings []int16
}
func (hmtx *hmtxTable) LeftSideBearing(glyphID uint16) int16 {
if uint16(len(hmtx.HMetrics)) <= glyphID {
return hmtx.LeftSideBearings[glyphID-uint16(len(hmtx.HMetrics))]
}
return hmtx.HMetrics[glyphID].LeftSideBearing
}
func (hmtx *hmtxTable) Advance(glyphID uint16) uint16 {
if uint16(len(hmtx.HMetrics)) <= glyphID {
glyphID = uint16(len(hmtx.HMetrics)) - 1
}
return hmtx.HMetrics[glyphID].AdvanceWidth
}
func (sfnt *SFNT) parseHmtx() error {
// TODO: lazy parse
if sfnt.Hhea == nil {
return fmt.Errorf("hmtx: missing hhea table")
} else if sfnt.Maxp == nil {
return fmt.Errorf("hmtx: missing maxp table")
}
b, ok := sfnt.Tables["hmtx"]
length := 4*uint32(sfnt.Hhea.NumberOfHMetrics) + 2*uint32(sfnt.Maxp.NumGlyphs-sfnt.Hhea.NumberOfHMetrics)
if !ok {
return fmt.Errorf("hmtx: missing table")
} else if uint32(len(b)) != length {
return fmt.Errorf("hmtx: bad table")
}
sfnt.Hmtx = &hmtxTable{}
// numberOfHMetrics is smaller than numGlyphs
sfnt.Hmtx.HMetrics = make([]hmtxLongHorMetric, sfnt.Hhea.NumberOfHMetrics)
sfnt.Hmtx.LeftSideBearings = make([]int16, sfnt.Maxp.NumGlyphs-sfnt.Hhea.NumberOfHMetrics)
r := parse.NewBinaryReader(b)
for i := 0; i < int(sfnt.Hhea.NumberOfHMetrics); i++ {
sfnt.Hmtx.HMetrics[i].AdvanceWidth = r.ReadUint16()
sfnt.Hmtx.HMetrics[i].LeftSideBearing = r.ReadInt16()
}
for i := 0; i < int(sfnt.Maxp.NumGlyphs-sfnt.Hhea.NumberOfHMetrics); i++ {
sfnt.Hmtx.LeftSideBearings[i] = r.ReadInt16()
}
return nil
}
////////////////////////////////////////////////////////////////
type vmtxLongVerMetric struct {
AdvanceHeight uint16
TopSideBearing int16
}
type vmtxTable struct {
VMetrics []vmtxLongVerMetric
TopSideBearings []int16
}
func (vmtx *vmtxTable) TopSideBearing(glyphID uint16) int16 {
if uint16(len(vmtx.VMetrics)) <= glyphID {
return vmtx.TopSideBearings[glyphID-uint16(len(vmtx.VMetrics))]
}
return vmtx.VMetrics[glyphID].TopSideBearing
}
func (vmtx *vmtxTable) Advance(glyphID uint16) uint16 {
if uint16(len(vmtx.VMetrics)) <= glyphID {
glyphID = uint16(len(vmtx.VMetrics)) - 1
}
return vmtx.VMetrics[glyphID].AdvanceHeight
}
func (sfnt *SFNT) parseVmtx() error {
// TODO: lazy parse
if sfnt.Vhea == nil {
return fmt.Errorf("vmtx: missing vhea table")
} else if sfnt.Maxp == nil {
return fmt.Errorf("vmtx: missing maxp table")
}
b, ok := sfnt.Tables["vmtx"]
length := 4*uint32(sfnt.Vhea.NumberOfVMetrics) + 2*uint32(sfnt.Maxp.NumGlyphs-sfnt.Vhea.NumberOfVMetrics)
if !ok {
return fmt.Errorf("vmtx: missing table")
} else if uint32(len(b)) != length {
return fmt.Errorf("vmtx: bad table")
}
sfnt.Vmtx = &vmtxTable{}
// numberOfVMetrics is smaller than numGlyphs
sfnt.Vmtx.VMetrics = make([]vmtxLongVerMetric, sfnt.Vhea.NumberOfVMetrics)
sfnt.Vmtx.TopSideBearings = make([]int16, sfnt.Maxp.NumGlyphs-sfnt.Vhea.NumberOfVMetrics)
r := parse.NewBinaryReader(b)
for i := 0; i < int(sfnt.Vhea.NumberOfVMetrics); i++ {
sfnt.Vmtx.VMetrics[i].AdvanceHeight = r.ReadUint16()
sfnt.Vmtx.VMetrics[i].TopSideBearing = r.ReadInt16()
}
for i := 0; i < int(sfnt.Maxp.NumGlyphs-sfnt.Vhea.NumberOfVMetrics); i++ {
sfnt.Vmtx.TopSideBearings[i] = r.ReadInt16()
}
return nil
}
////////////////////////////////////////////////////////////////
type maxpTable struct {
NumGlyphs uint16
MaxPoints uint16
MaxContours uint16
MaxCompositePoints uint16
MaxCompositeContours uint16
MaxZones uint16
MaxTwilightPoints uint16
MaxStorage uint16
MaxFunctionDefs uint16
MaxInstructionDefs uint16
MaxStackElements uint16
MaxSizeOfInstructions uint16
MaxComponentElements uint16
MaxComponentDepth uint16
}
func (sfnt *SFNT) parseMaxp() error {
b, ok := sfnt.Tables["maxp"]
if !ok {
return fmt.Errorf("maxp: missing table")
}
sfnt.Maxp = &maxpTable{}
r := parse.NewBinaryReader(b)
version := binary.BigEndian.Uint32(r.ReadBytes(4))
sfnt.Maxp.NumGlyphs = r.ReadUint16()
if version == 0x00005000 && !sfnt.IsTrueType && len(b) == 6 {
return nil
} else if version == 0x00010000 && !sfnt.IsCFF && len(b) == 32 {
sfnt.Maxp.MaxPoints = r.ReadUint16()
sfnt.Maxp.MaxContours = r.ReadUint16()
sfnt.Maxp.MaxCompositePoints = r.ReadUint16()
sfnt.Maxp.MaxCompositeContours = r.ReadUint16()
sfnt.Maxp.MaxZones = r.ReadUint16()
sfnt.Maxp.MaxTwilightPoints = r.ReadUint16()
sfnt.Maxp.MaxStorage = r.ReadUint16()
sfnt.Maxp.MaxFunctionDefs = r.ReadUint16()
sfnt.Maxp.MaxInstructionDefs = r.ReadUint16()
sfnt.Maxp.MaxStackElements = r.ReadUint16()
sfnt.Maxp.MaxSizeOfInstructions = r.ReadUint16()
sfnt.Maxp.MaxComponentElements = r.ReadUint16()
sfnt.Maxp.MaxComponentDepth = r.ReadUint16()
return nil
}
return fmt.Errorf("maxp: bad table")
}
////////////////////////////////////////////////////////////////
type nameRecord struct {
Platform PlatformID
Encoding EncodingID
Language uint16
Name NameID
Value []byte
}
func (record nameRecord) String() string {
var decoder *encoding.Decoder
if record.Platform == PlatformUnicode || record.Platform == PlatformWindows {
decoder = unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewDecoder()
} else if record.Platform == PlatformMacintosh && record.Encoding == EncodingMacintoshRoman {
decoder = charmap.Macintosh.NewDecoder()
}
s, _, err := transform.String(decoder, string(record.Value))
if err == nil {
return s
}
return string(record.Value)
}
type nameLangTagRecord struct {
Value []byte
}
func (record nameLangTagRecord) String() string {
decoder := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewDecoder()
s, _, err := transform.String(decoder, string(record.Value))
if err == nil {
return s
}
return string(record.Value)
}
type nameTable struct {
NameRecord []nameRecord
LangTag []nameLangTagRecord
}
func (t *nameTable) Get(name NameID) []nameRecord {
records := []nameRecord{}
for _, record := range t.NameRecord {
if record.Name == name {
records = append(records, record)
}
}
return records
}
func (sfnt *SFNT) parseName() error {
// TODO: lazy parse
b, ok := sfnt.Tables["name"]
if !ok {
return fmt.Errorf("name: missing table")
} else if len(b) < 6 {
return fmt.Errorf("name: bad table")
}
sfnt.Name = &nameTable{}
r := parse.NewBinaryReader(b)
version := r.ReadUint16()
if version != 0 && version != 1 {
return fmt.Errorf("name: bad version")
}
count := r.ReadUint16()
storageOffset := r.ReadUint16()
if uint32(len(b)) < 6+12*uint32(count) || uint16(len(b)) < storageOffset {
return fmt.Errorf("name: bad table")
}
sfnt.Name.NameRecord = make([]nameRecord, count)
for i := 0; i < int(count); i++ {
sfnt.Name.NameRecord[i].Platform = PlatformID(r.ReadUint16())
sfnt.Name.NameRecord[i].Encoding = EncodingID(r.ReadUint16())
sfnt.Name.NameRecord[i].Language = r.ReadUint16()
sfnt.Name.NameRecord[i].Name = NameID(r.ReadUint16())
length := r.ReadUint16()
offset := r.ReadUint16()
if uint16(len(b))-storageOffset < offset || uint16(len(b))-storageOffset-offset < length {
return fmt.Errorf("name: bad table")
}
sfnt.Name.NameRecord[i].Value = b[storageOffset+offset : storageOffset+offset+length]
}
if version == 1 {
if uint32(len(b)) < 6+12*uint32(count)+2 {
return fmt.Errorf("name: bad table")
}
langTagCount := r.ReadUint16()
if uint32(len(b)) < 6+12*uint32(count)+2+4*uint32(langTagCount) {
return fmt.Errorf("name: bad table")
}
sfnt.Name.LangTag = make([]nameLangTagRecord, langTagCount)
for i := 0; i < int(langTagCount); i++ {
length := r.ReadUint16()
offset := r.ReadUint16()
if uint16(len(b))-storageOffset < offset || uint16(len(b))-storageOffset-offset < length {
return fmt.Errorf("name: bad table")
}
sfnt.Name.LangTag[i].Value = b[storageOffset+offset : storageOffset+offset+length]
}
}
if r.Pos() != uint32(storageOffset) {
return fmt.Errorf("name: bad storageOffset")
}
return nil
}
////////////////////////////////////////////////////////////////
type postTable struct {
ItalicAngle float64
UnderlinePosition int16
UnderlineThickness int16
IsFixedPitch uint32
MinMemType42 uint32
MaxMemType42 uint32
MinMemType1 uint32
MaxMemType1 uint32
// version 2
NumGlyphs uint16
glyphNameIndex []uint16
stringData [][]byte
nameMap map[string]uint16
once sync.Once
}
func (post *postTable) Get(glyphID uint16) string {
if len(post.glyphNameIndex) <= int(glyphID) {
return ""
}
index := post.glyphNameIndex[glyphID]
if index < 258 {
return macintoshGlyphNames[index]
} else if len(post.stringData) <= int(index)-258 {
return ""
}
return string(post.stringData[index-258])
}
func (post *postTable) Find(name string) (uint16, bool) {
post.once.Do(func() {
post.nameMap = make(map[string]uint16, len(post.glyphNameIndex))
for glyphID, index := range post.glyphNameIndex {
if index < 258 {
post.nameMap[macintoshGlyphNames[index]] = uint16(glyphID)
} else if int(index)-258 < len(post.stringData) {
post.nameMap[string(post.stringData[index-258])] = uint16(glyphID)
}
}
})
glyphID, ok := post.nameMap[name] // returns 0 if not found
return glyphID, ok
}
func (sfnt *SFNT) parsePost() error {
if sfnt.Maxp == nil {
return fmt.Errorf("post: missing maxp table")
}
b, ok := sfnt.Tables["post"]
if !ok {
return fmt.Errorf("post: missing table")
} else if len(b) < 32 {
return fmt.Errorf("post: bad table")
}
_, isCFF2 := sfnt.Tables["CFF2"]
sfnt.Post = &postTable{}
r := parse.NewBinaryReader(b)
version := r.ReadUint32()
sfnt.Post.ItalicAngle = float64(r.ReadInt32()) / (1 << 16)
sfnt.Post.UnderlinePosition = r.ReadInt16()
sfnt.Post.UnderlineThickness = r.ReadInt16()
sfnt.Post.IsFixedPitch = r.ReadUint32()
sfnt.Post.MinMemType42 = r.ReadUint32()
sfnt.Post.MaxMemType42 = r.ReadUint32()
sfnt.Post.MinMemType1 = r.ReadUint32()
sfnt.Post.MaxMemType1 = r.ReadUint32()
if version == 0x00010000 && sfnt.IsTrueType && len(b) == 32 {
sfnt.Post.glyphNameIndex = make([]uint16, 258)
for i := 0; i < 258; i++ {
sfnt.Post.glyphNameIndex[i] = uint16(i)
}
return nil
} else if version == 0x00020000 && (sfnt.IsTrueType || isCFF2) && 34 <= len(b) {
// can be used for TrueType and CFF2 fonts, we check for this in the CFF table
sfnt.Post.NumGlyphs = r.ReadUint16()
if sfnt.Post.NumGlyphs != sfnt.Maxp.NumGlyphs {
return fmt.Errorf("post: numGlyphs does not match maxp table numGlyphs")
} else if uint32(len(b)) < 34+2*uint32(sfnt.Post.NumGlyphs) {