/
cache.go
90 lines (70 loc) · 1.63 KB
/
cache.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
package fontcache
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
)
type Cache map[string]Styles
type Styles map[string]*truetype.Font
const fallbackId = "_fallback"
func New() Cache {
return make(Cache)
}
func (c Cache) Init(path string) {
filepath.Walk(path, c.loadFont)
}
func (c Cache) Get(name, style string) (*truetype.Font, error) {
var err error
if sm, ok := c[strings.ToLower(name)]; ok {
if f, ok := sm[strings.ToLower(style)]; ok {
return f, nil
}
err = errors.New(fmt.Sprintf("style %q not supported in font %q", style, name))
}
if s, ok := c[fallbackId]; ok {
return s[fallbackId], nil
}
if err == nil {
err = errors.New(fmt.Sprintf("font %q not found in cache", name))
}
return nil, err
}
func (c Cache) SetFallbackFont(name, style string) error {
if font, err := c.Get(name, style); err == nil {
s := make(Styles)
s[fallbackId] = font
c[fallbackId] = s
} else {
return err
}
return nil
}
func (c Cache) loadFont(path string, info os.FileInfo, err error) error {
// process ttf files only
if strings.ToLower(path[len(path)-4:]) != ".ttf" {
return nil
}
ttfBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
font, err := freetype.ParseFont(ttfBytes)
if err != nil {
log.Fatal(err)
}
name, style := strings.ToLower(font.Name(truetype.NameIDFontFamily)), strings.ToLower(font.Name(truetype.NameIDFontSubfamily))
if stylemap, ok := c[name]; !ok {
stylemap := make(Styles)
c[name] = stylemap
stylemap[style] = font
} else {
stylemap[style] = font
}
return nil
}