aboutsummaryrefslogtreecommitdiff
path: root/bdf/bdf.go
blob: c02e31e22da68e18fb5ebb6767ac0a0ac378a744 (plain)
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
package bdf

import (
	"bufio"
	"encoding/hex"
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"io"
	"strconv"
)

// glyph is a singular bitmap glyph to be used as a mask, assumed to directly
// correspond to a rune. A zero value is also valid and drawable.
type glyph struct {
	// Coordinates are relative to the origin, on the baseline.
	// The ascent is thus negative, unlike the usual model.
	bounds  image.Rectangle
	bitmap  []byte
	advance int
}

// ColorModel implements image.Image.
func (g *glyph) ColorModel() color.Model { return color.Alpha16Model }

// Bounds implements image.Image.
func (g *glyph) Bounds() image.Rectangle { return g.bounds }

// At implements image.Image. This is going to be somewhat slow.
func (g *glyph) At(x, y int) color.Color {
	x -= g.bounds.Min.X
	y -= g.bounds.Min.Y

	dx, dy := g.bounds.Dx(), g.bounds.Dy()
	if x < 0 || y < 0 || x >= dx || y >= dy {
		return color.Transparent
	}

	stride, offset, bit := (dx+7)/8, x/8, byte(1<<uint(7-x%8))
	if g.bitmap[y*stride+offset]&bit == 0 {
		return color.Transparent
	}
	return color.Opaque
}

// -----------------------------------------------------------------------------

// Font represents a particular bitmap font.
type Font struct {
	Name     string
	glyphs   map[rune]glyph
	fallback glyph
}

// FindGlyph returns the best glyph to use for the given rune.
// The returned boolean indicates whether a fallback has been used.
func (f *Font) FindGlyph(r rune) (glyph, bool) {
	if g, ok := f.glyphs[r]; ok {
		return g, true
	}
	return f.fallback, false
}

// DrawString draws the specified text string onto dst horizontally along
// the baseline starting at dp, using black color.
func (f *Font) DrawString(dst draw.Image, dp image.Point, s string) {
	for _, r := range s {
		g, _ := f.FindGlyph(r)
		draw.DrawMask(dst, g.bounds.Add(dp),
			image.Black, image.ZP, &g, g.bounds.Min, draw.Over)
		dp.X += g.advance
	}
}

// BoundString measures the text's bounds when drawn along the X axis
// for the baseline. Also returns the total advance.
func (f *Font) BoundString(s string) (image.Rectangle, int) {
	var (
		bounds image.Rectangle
		dot    image.Point
	)
	for _, r := range s {
		g, _ := f.FindGlyph(r)
		bounds = bounds.Union(g.bounds.Add(dot))
		dot.X += g.advance
	}
	return bounds, dot.X
}

// -----------------------------------------------------------------------------

func latin1ToUTF8(latin1 []byte) string {
	buf := make([]rune, len(latin1))
	for i, b := range latin1 {
		buf[i] = rune(b)
	}
	return string(buf)
}

// tokenize splits a BDF line into tokens. Quoted strings may start anywhere
// on the line. We only enforce that they must end somewhere.
func tokenize(s string) (tokens []string, err error) {
	token, quotes, escape := []rune{}, false, false
	for _, r := range s {
		switch {
		case escape:
			switch r {
			case '"':
				escape = false
				token = append(token, r)
			case ' ', '\t':
				quotes, escape = false, false
				tokens = append(tokens, string(token))
				token = nil
			default:
				quotes, escape = false, false
				token = append(token, r)
			}
		case quotes:
			switch r {
			case '"':
				escape = true
			default:
				token = append(token, r)
			}
		default:
			switch r {
			case '"':
				// We could also enable quote processing on demand,
				// so that it is only turned on in properties.
				if len(tokens) < 1 || tokens[0] != "COMMENT" {
					quotes = true
				} else {
					token = append(token, r)
				}
			case ' ', '\t':
				if len(token) > 0 {
					tokens = append(tokens, string(token))
					token = nil
				}
			default:
				token = append(token, r)
			}
		}
	}
	if quotes && !escape {
		return nil, fmt.Errorf("strings may not contain newlines")
	}
	if quotes || len(token) > 0 {
		tokens = append(tokens, string(token))
	}
	return tokens, nil
}

// -----------------------------------------------------------------------------

// bdfParser is a basic and rather lenient parser of
// Bitmap Distribution Format (BDF) files.
type bdfParser struct {
	scanner *bufio.Scanner // input reader
	line    int            // current line number
	tokens  []string       // tokens on the current line
	font    *Font          // glyph storage

	defaultBounds  image.Rectangle
	defaultAdvance int
	defaultChar    int
}

// readLine reads the next line and splits it into tokens.
// Panics on error, returns false if the end of file has been reached normally.
func (p *bdfParser) readLine() bool {
	p.line++
	if !p.scanner.Scan() {
		if err := p.scanner.Err(); err != nil {
			panic(err)
		}
		p.line--
		return false
	}

	var err error
	if p.tokens, err = tokenize(latin1ToUTF8(p.scanner.Bytes())); err != nil {
		panic(err)
	}

	// Eh, it would be nicer iteratively, this may overrun the stack.
	if len(p.tokens) == 0 {
		return p.readLine()
	}
	return true
}

func (p *bdfParser) readCharEncoding() int {
	if len(p.tokens) < 2 {
		panic("insufficient arguments")
	}
	if i, err := strconv.Atoi(p.tokens[1]); err != nil {
		panic(err)
	} else {
		return i // Some fonts even use -1 for things outside the encoding.
	}
}

func (p *bdfParser) parseProperties() {
	// The wording in the specification suggests that the argument
	// with the number of properties to follow isn't reliable.
	for p.readLine() && p.tokens[0] != "ENDPROPERTIES" {
		switch p.tokens[0] {
		case "DEFAULT_CHAR":
			p.defaultChar = p.readCharEncoding()
		}
	}
}

// XXX: Ignoring vertical advance since we only expect purely horizontal fonts.
func (p *bdfParser) readDwidth() int {
	if len(p.tokens) < 2 {
		panic("insufficient arguments")
	}
	if i, err := strconv.Atoi(p.tokens[1]); err != nil {
		panic(err)
	} else {
		return i
	}
}

func (p *bdfParser) readBBX() image.Rectangle {
	if len(p.tokens) < 5 {
		panic("insufficient arguments")
	}
	w, e1 := strconv.Atoi(p.tokens[1])
	h, e2 := strconv.Atoi(p.tokens[2])
	x, e3 := strconv.Atoi(p.tokens[3])
	y, e4 := strconv.Atoi(p.tokens[4])
	if e1 != nil || e2 != nil || e3 != nil || e4 != nil {
		panic("invalid arguments")
	}
	if w < 0 || h < 0 {
		panic("bounding boxes may not have negative dimensions")
	}
	return image.Rectangle{
		Min: image.Point{x, -(y + h)},
		Max: image.Point{x + w, -y},
	}
}

func (p *bdfParser) parseChar() {
	g := glyph{bounds: p.defaultBounds, advance: p.defaultAdvance}
	bitmap, rows, encoding := false, 0, -1
	for p.readLine() && p.tokens[0] != "ENDCHAR" {
		if bitmap {
			b, err := hex.DecodeString(p.tokens[0])
			if err != nil {
				panic(err)
			}
			if len(b) != (g.bounds.Dx()+7)/8 {
				panic("invalid bitmap data, width mismatch")
			}
			g.bitmap = append(g.bitmap, b...)
			rows++
		} else {
			switch p.tokens[0] {
			case "ENCODING":
				encoding = p.readCharEncoding()
			case "DWIDTH":
				g.advance = p.readDwidth()
			case "BBX":
				g.bounds = p.readBBX()
			case "BITMAP":
				bitmap = true
			}
		}
	}
	if rows != g.bounds.Dy() {
		panic("invalid bitmap data, height mismatch")
	}

	// XXX: We don't try to convert encodings, since we'd need x/text/encoding
	// for the conversion tables, though most fonts are at least going to use
	// supersets of ASCII. Use ISO10646-1 X11 fonts for proper Unicode support.
	if encoding >= 0 {
		p.font.glyphs[rune(encoding)] = g
	}
	if encoding == p.defaultChar {
		p.font.fallback = g
	}
}

// https://en.wikipedia.org/wiki/Glyph_Bitmap_Distribution_Format
// https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5005.BDF_Spec.pdf
func (p *bdfParser) parse() {
	if !p.readLine() || len(p.tokens) != 2 || p.tokens[0] != "STARTFONT" {
		panic("invalid header")
	}
	if p.tokens[1] != "2.1" && p.tokens[1] != "2.2" {
		panic("unsupported version number")
	}
	for p.readLine() && p.tokens[0] != "ENDFONT" {
		switch p.tokens[0] {
		case "FONT":
			if len(p.tokens) < 2 {
				panic("insufficient arguments")
			}
			p.font.Name = p.tokens[1]
		case "FONTBOUNDINGBOX":
			// There's no guarantee that this includes all BBXs.
			p.defaultBounds = p.readBBX()
		case "METRICSSET":
			if len(p.tokens) < 2 {
				panic("insufficient arguments")
			}
			if p.tokens[1] == "1" {
				panic("purely vertical fonts are unsupported")
			}
		case "DWIDTH":
			p.defaultAdvance = p.readDwidth()
		case "STARTPROPERTIES":
			p.parseProperties()
		case "STARTCHAR":
			p.parseChar()
		}
	}
	if p.font.Name == "" {
		panic("the font file doesn't contain the font's name")
	}
	if len(p.font.glyphs) == 0 {
		panic("the font file doesn't seem to contain any glyphs")
	}
}

func NewFromBDF(r io.Reader) (f *Font, err error) {
	p := bdfParser{
		scanner:     bufio.NewScanner(r),
		font:        &Font{glyphs: make(map[rune]glyph)},
		defaultChar: -1,
	}
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			if err, ok = r.(error); !ok {
				err = fmt.Errorf("%v", r)
			}
		}
		if err != nil {
			err = fmt.Errorf("line %d: %s", p.line, err)
		}
	}()

	p.parse()
	return p.font, nil
}