Skip to content

Commit a3b43b4

Browse files
authored
tinyfontgen-ttf: Bugfix/multiple fonts (#56)
* feat: add filename comment to index table output * feat: Add font duplicate check. * feat: sort runes before generating index table
1 parent 2f58061 commit a3b43b4

1 file changed

Lines changed: 23 additions & 8 deletions

File tree

cmd/tinyfontgen-ttf/main.go

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"log"
99
"os"
1010
"path/filepath"
11+
"sort"
1112
"strings"
1213

1314
"golang.org/x/image/font"
@@ -94,11 +95,13 @@ func main() {
9495

9596
func run(size, dpi int, fonts []string) error {
9697
type xx struct {
97-
Rune rune
98-
Index uint16
99-
Face font.Face
98+
Rune rune
99+
Index uint16
100+
Face font.Face
101+
Filename string
100102
}
101103
indexes := []xx{}
104+
seen := map[rune]string{}
102105

103106
for _, fontfile := range fonts {
104107
bb, err := ioutil.ReadFile(fontfile)
@@ -125,15 +128,25 @@ func run(size, dpi int, fonts []string) error {
125128
return err
126129
}
127130
if idx != 0 && (*all || runesMap[r]) {
131+
if first, ok := seen[r]; ok {
132+
fmt.Fprintf(os.Stderr,
133+
"warning: rune U+%04X (%c) already registered from %s, skipping from %s\n",
134+
r, r, filepath.Base(first), filepath.Base(fontfile))
135+
continue
136+
}
137+
seen[r] = fontfile
128138
indexes = append(indexes, xx{
129-
Rune: r,
130-
Index: uint16(idx),
131-
Face: face,
139+
Rune: r,
140+
Index: uint16(idx),
141+
Face: face,
142+
Filename: fontfile,
132143
})
133144
}
134145
}
135146
}
136-
147+
sort.Slice(indexes, func(i, j int) bool {
148+
return indexes[i].Rune < indexes[j].Rune
149+
})
137150
fontBuffer := [256]uint8{}
138151
font := Font{
139152
Glyphs: make([]Glyph, len(indexes)),
@@ -166,6 +179,7 @@ func run(size, dpi int, fonts []string) error {
166179
}
167180

168181
font.Glyphs[i].Rune = xxx.Rune
182+
font.Glyphs[i].Filename = filepath.Base(xxx.Filename)
169183
font.Glyphs[i].Width = uint8(img.Bounds().Max.X - img.Bounds().Min.X)
170184
font.Glyphs[i].Height = uint8(img.Bounds().Max.Y - img.Bounds().Min.Y)
171185
font.Glyphs[i].XAdvance = uint8(adv.Ceil())
@@ -207,6 +221,7 @@ type Glyph struct {
207221
XOffset int8
208222
YOffset int8
209223
Bitmaps []byte
224+
Filename string
210225
}
211226

212227
// Font is a struct that implements Fonter interface.
@@ -246,7 +261,7 @@ func (f Font) SaveTo(w io.Writer) {
246261
fmt.Fprintf(w, ` "\x%02X\x%02X\x%02X" + `, byte(x.Rune>>16), byte(x.Rune>>8), byte(x.Rune))
247262
fmt.Fprintf(w, `"\x%02X\x%02X\x%02X" + `, byte(offset>>16), byte(offset>>8), byte(offset))
248263
if x.Rune > 0 {
249-
fmt.Fprintf(w, `// %c`, x.Rune)
264+
fmt.Fprintf(w, `// %c %s`, x.Rune, x.Filename)
250265
} else {
251266
fmt.Fprintf(w, `//`)
252267
}

0 commit comments

Comments
 (0)