/
glyphs.go
352 lines (301 loc) · 8.97 KB
/
glyphs.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
// SPDX-License-Identifier: Unlicense OR BSD-3-Clause
package font
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"image/jpeg"
"image/png"
"github.com/go-text/typesetting/opentype/api"
"github.com/go-text/typesetting/opentype/loader"
"github.com/go-text/typesetting/opentype/tables"
"golang.org/x/image/tiff"
)
type contourPoint struct {
api.SegmentPoint
isOnCurve bool
isEndPoint bool // this point is the last of the current contour
isExplicit bool // this point is referenced, i.e., explicit deltas specified */
}
func (c *contourPoint) translate(x, y float32) {
c.X += x
c.Y += y
}
func (c *contourPoint) transform(matrix [4]float32) {
px := c.X*matrix[0] + c.Y*matrix[2]
c.Y = c.X*matrix[1] + c.Y*matrix[3]
c.X = px
}
const (
phantomLeft = iota
phantomRight
phantomTop
phantomBottom
phantomCount
)
const maxCompositeNesting = 20 // protect against malicious fonts
// use the `glyf` table to fetch the contour points,
// applying variation if needed.
// for composite, recursively calls itself; allPoints includes phantom points and will be at least of length 4
func (f *Face) getPointsForGlyph(gid tables.GlyphID, currentDepth int, allPoints *[]contourPoint /* OUT */) {
// adapted from harfbuzz/src/hb-ot-glyf-table.hh
if currentDepth > maxCompositeNesting || int(gid) >= len(f.glyf) {
return
}
g := f.glyf[gid]
var points []contourPoint
if data, ok := g.Data.(tables.SimpleGlyph); ok {
points = getContourPoints(data) // fetch the "real" points
} else { // zeros values are enough
points = make([]contourPoint, pointNumbersCount(g))
}
// init phantom point
points = append(points, make([]contourPoint, phantomCount)...)
phantoms := points[len(points)-phantomCount:]
hDelta := float32(g.XMin - getSideBearing(gid, f.hmtx))
vOrig := float32(g.YMax + getSideBearing(gid, f.vmtx))
hAdv := float32(f.getBaseAdvance(gid, f.hmtx, false))
vAdv := float32(f.getBaseAdvance(gid, f.vmtx, true))
phantoms[phantomLeft].X = hDelta
phantoms[phantomRight].X = hAdv + hDelta
phantoms[phantomTop].Y = vOrig
phantoms[phantomBottom].Y = vOrig - vAdv
if f.isVar() {
f.gvar.applyDeltasToPoints(gid, f.Coords, points)
}
switch data := g.Data.(type) {
case tables.SimpleGlyph:
*allPoints = append(*allPoints, points...)
case tables.CompositeGlyph:
for compIndex, item := range data.Glyphs {
// recurse on component
var compPoints []contourPoint
f.getPointsForGlyph(item.GlyphIndex, currentDepth+1, &compPoints)
LC := len(compPoints)
if LC < phantomCount { // in case of max depth reached
return
}
/* Copy phantom points from component if USE_MY_METRICS flag set */
if item.HasUseMyMetrics() {
copy(phantoms, compPoints[LC-phantomCount:])
}
/* Apply component transformation & translation */
transformPoints(&item, compPoints)
/* Apply translation from gvar */
tx, ty := points[compIndex].X, points[compIndex].Y
for i := range compPoints {
compPoints[i].translate(tx, ty)
}
if item.IsAnchored() {
p1, p2 := item.ArgsAsIndices()
if p1 < len(*allPoints) && p2 < LC {
tx, ty := (*allPoints)[p1].X-compPoints[p2].X, (*allPoints)[p1].Y-compPoints[p2].Y
for i := range compPoints {
compPoints[i].translate(tx, ty)
}
}
}
*allPoints = append(*allPoints, compPoints[0:LC-phantomCount]...)
}
*allPoints = append(*allPoints, phantoms...)
default: // no data for the glyph
*allPoints = append(*allPoints, phantoms...)
}
// apply at top level
if currentDepth == 0 {
/* Undocumented rasterizer behavior:
* Shift points horizontally by the updated left side bearing */
tx := -phantoms[phantomLeft].X
for i := range *allPoints {
(*allPoints)[i].translate(tx, 0)
}
}
}
// does not includes phantom points
func pointNumbersCount(g tables.Glyph) int {
switch g := g.Data.(type) {
case tables.SimpleGlyph:
return len(g.Points)
case tables.CompositeGlyph:
/* pseudo component points for each component in composite glyph */
return len(g.Glyphs)
}
return 0
}
// return all the contour points, without phantoms
func getContourPoints(sg tables.SimpleGlyph) []contourPoint {
const flagOnCurve = 1 << 0 // 0x0001
points := make([]contourPoint, len(sg.Points))
for _, end := range sg.EndPtsOfContours {
points[end].isEndPoint = true
}
for i, p := range sg.Points {
points[i].X, points[i].Y = float32(p.X), float32(p.Y)
points[i].isOnCurve = p.Flag&flagOnCurve != 0
}
return points
}
func extentsFromPoints(allPoints []contourPoint) (ext api.GlyphExtents) {
truePoints := allPoints[:len(allPoints)-phantomCount]
if len(truePoints) == 0 {
// zero extent for the empty glyph
return ext
}
minX, minY := truePoints[0].X, truePoints[0].Y
maxX, maxY := minX, minY
for _, p := range truePoints {
minX = minF(minX, p.X)
minY = minF(minY, p.Y)
maxX = maxF(maxX, p.X)
maxY = maxF(maxY, p.Y)
}
ext.XBearing = minX
ext.YBearing = maxY
ext.Width = maxX - minX
ext.Height = minY - maxY
return ext
}
// walk through the contour points of the given glyph to compute its extends and its phantom points
// As an optimization, if `computeExtents` is false, the extents computation is skipped (a zero value is returned).
func (f *Face) getGlyfPoints(gid tables.GlyphID, computeExtents bool) (ext api.GlyphExtents, ph [phantomCount]contourPoint) {
if int(gid) >= len(f.glyf) {
return
}
var allPoints []contourPoint
f.getPointsForGlyph(gid, 0, &allPoints)
copy(ph[:], allPoints[len(allPoints)-phantomCount:])
if computeExtents {
ext = extentsFromPoints(allPoints)
}
return ext, ph
}
func min16(a, b int16) int16 {
if a < b {
return a
}
return b
}
func max16(a, b int16) int16 {
if a > b {
return a
}
return b
}
func minC(a, b VarCoord) VarCoord {
if a < b {
return a
}
return b
}
func maxC(a, b VarCoord) VarCoord {
if a > b {
return a
}
return b
}
func minF(a, b float32) float32 {
if a < b {
return a
}
return b
}
func maxF(a, b float32) float32 {
if a > b {
return a
}
return b
}
func transformPoints(c *tables.CompositeGlyphPart, points []contourPoint) {
var transX, transY float32
if !c.IsAnchored() {
arg1, arg2 := c.ArgsAsTranslation()
transX, transY = float32(arg1), float32(arg2)
}
scale := c.Scale
// shortcut identity transform
if transX == 0 && transY == 0 && scale == [4]float32{1, 0, 0, 1} {
return
}
if c.IsScaledOffsets() {
for i := range points {
points[i].translate(transX, transY)
points[i].transform(scale)
}
} else {
for i := range points {
points[i].transform(scale)
points[i].translate(transX, transY)
}
}
}
func getGlyphExtents(g tables.Glyph, metrics tables.Hmtx, gid gID) api.GlyphExtents {
var extents api.GlyphExtents
/* Undocumented rasterizer behavior: shift glyph to the left by (lsb - xMin), i.e., xMin = lsb */
/* extents.XBearing = hb_min (glyph_header.xMin, glyph_header.xMax); */
extents.XBearing = float32(getSideBearing(gid, metrics))
extents.YBearing = float32(max16(g.YMin, g.YMax))
extents.Width = float32(max16(g.XMin, g.XMax) - min16(g.XMin, g.XMax))
extents.Height = float32(min16(g.YMin, g.YMax) - max16(g.YMin, g.YMax))
return extents
}
// sbix
var (
dupe = loader.MustNewTag("dupe")
// tagPNG identifies bitmap glyph with png format
tagPNG = loader.MustNewTag("png ")
// tagTIFF identifies bitmap glyph with tiff format
tagTIFF = loader.MustNewTag("tiff")
// tagJPG identifies bitmap glyph with jpg format
tagJPG = loader.MustNewTag("jpg ")
)
// strikeGlyph return the data for [glyph], or a zero value if not found.
func strikeGlyph(b *tables.Strike, glyph gID, recursionLevel int) tables.BitmapGlyphData {
const maxRecursionLevel = 8
if int(glyph) >= len(b.GlyphDatas) {
return tables.BitmapGlyphData{}
}
out := b.GlyphDatas[glyph]
if out.GraphicType == dupe {
if len(out.Data) < 2 || recursionLevel > maxRecursionLevel {
return tables.BitmapGlyphData{}
}
glyph = gID(binary.BigEndian.Uint16(out.Data))
return strikeGlyph(b, glyph, recursionLevel+1)
}
return out
}
// decodeBitmapConfig parse the data to find the width and height
func decodeBitmapConfig(b tables.BitmapGlyphData) (width, height int, format api.BitmapFormat, err error) {
var config image.Config
switch b.GraphicType {
case tagPNG:
format = api.PNG
config, err = png.DecodeConfig(bytes.NewReader(b.Data))
case tagTIFF:
format = api.TIFF
config, err = tiff.DecodeConfig(bytes.NewReader(b.Data))
case tagJPG:
format = api.JPG
config, err = jpeg.DecodeConfig(bytes.NewReader(b.Data))
default:
err = fmt.Errorf("unsupported graphic type in sbix table: %s", b.GraphicType)
}
if err != nil {
return 0, 0, 0, err
}
return config.Width, config.Height, format, nil
}
// return the extents computed from the data
// should only be called on valid, non nil glyph data
func bitmapGlyphExtents(b tables.BitmapGlyphData) (out api.GlyphExtents, ok bool) {
width, height, _, err := decodeBitmapConfig(b)
if err != nil {
return out, false
}
out.XBearing = float32(b.OriginOffsetX)
out.YBearing = float32(height) + float32(b.OriginOffsetY)
out.Width = float32(width)
out.Height = -float32(height)
return out, true
}