-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchart.go
134 lines (105 loc) · 2.45 KB
/
chart.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
package gopster
import (
"bytes"
"embed"
"errors"
"fmt"
"image/color"
"io"
"io/fs"
"github.com/tdewolff/canvas"
)
//go:embed resources
var resources embed.FS
var resourcesDir fs.FS
func init() {
var err error
resourcesDir, err = fs.Sub(resources, "resources")
if err != nil {
panic(err)
}
}
// ErrorChart is returned when a chart is misconfigured.
var ErrorChart = errors.New("gopster: error creating chart")
const (
maxSize = 3
defaultSize = 3
maxGap = 150
defaultGap = 20
titleMargin = 60
titlePt = 120.0
chartItemTitleMargin = 20
chartItemSize = 260.0
chartItemTitlePt = 60.0
mmToPixel = 3.7795275591
)
// Chart is a Topster chart.
type Chart struct {
title string
items []*chartItem
width int
height int
backgroundColor string
textColor string
showNumbers bool
showTitles bool
gap float64
background color.Color
color color.Color
family *canvas.FontFamily
titles []string
}
// NewChart creates a new chart with the given settings.
func NewChart(opts ...Option) (*Chart, error) {
c := &Chart{
items: make([]*chartItem, 0),
width: defaultSize,
height: defaultSize,
gap: defaultGap,
titles: make([]string, 0),
}
family := canvas.NewFontFamily("ubuntu-mono")
ubuntuMono, err := resourcesDir.Open("ubuntu-mono.ttf")
if err != nil {
return nil, err
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, ubuntuMono); err != nil {
return nil, err
}
if err := family.LoadFont(buf.Bytes(), 0, canvas.FontRegular); err != nil {
return nil, err
}
c.family = family
for _, o := range opts {
o(c)
}
if c.width <= 0 || c.width > maxSize {
return nil, fmt.Errorf("%w: width must be a number between 0 and %d", ErrorChart, maxSize)
}
if c.height <= 0 || c.height > maxSize {
return nil, fmt.Errorf("%w: height must be a number between 0 and %d", ErrorChart, maxSize)
}
if c.gap < 0 || c.gap > maxGap {
return nil, fmt.Errorf("%w: gap must be a number between 0 and %d", ErrorChart, maxGap)
}
if c.backgroundColor != "" {
bc, err := parseHexColor(c.backgroundColor)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrorChart, err)
}
c.background = bc
} else {
c.background = color.Black
}
if c.textColor != "" {
tc, err := parseHexColor(c.textColor)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrorChart, err)
}
c.color = tc
} else {
c.color = color.White
}
return c, nil
}