-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
widget_button.go
122 lines (103 loc) · 2.23 KB
/
widget_button.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
package main
import (
"image"
"image/color"
"time"
)
// ButtonWidget is a simple widget displaying an icon and/or label.
type ButtonWidget struct {
*BaseWidget
icon image.Image
label string
fontsize float64
color color.Color
flatten bool
}
// NewButtonWidget returns a new ButtonWidget.
func NewButtonWidget(bw *BaseWidget, opts WidgetConfig) (*ButtonWidget, error) {
bw.setInterval(time.Duration(opts.Interval)*time.Millisecond, 0)
var icon, label string
_ = ConfigValue(opts.Config["icon"], &icon)
_ = ConfigValue(opts.Config["label"], &label)
var fontsize float64
_ = ConfigValue(opts.Config["fontsize"], &fontsize)
var color color.Color
_ = ConfigValue(opts.Config["color"], &color)
var flatten bool
_ = ConfigValue(opts.Config["flatten"], &flatten)
if color == nil {
color = DefaultColor
}
w := &ButtonWidget{
BaseWidget: bw,
label: label,
fontsize: fontsize,
color: color,
flatten: flatten,
}
if icon != "" {
if err := w.LoadImage(icon); err != nil {
return nil, err
}
}
return w, nil
}
// LoadImage loads an image from disk.
func (w *ButtonWidget) LoadImage(path string) error {
path, err := expandPath(w.base, path)
if err != nil {
return err
}
icon, err := loadImage(path)
if err != nil {
return err
}
w.SetImage(icon)
return nil
}
// SetImage updates the widget's icon.
func (w *ButtonWidget) SetImage(img image.Image) {
w.icon = img
if w.flatten {
w.icon = flattenImage(w.icon, w.color)
}
}
// Update renders the widget.
func (w *ButtonWidget) Update() error {
size := int(w.dev.Pixels)
margin := size / 18
height := size - (margin * 2)
img := image.NewRGBA(image.Rect(0, 0, size, size))
if w.label != "" {
iconsize := int((float64(height) / 3.0) * 2.0)
bounds := img.Bounds()
if w.icon != nil {
err := drawImage(img,
w.icon,
iconsize,
image.Pt(-1, margin))
if err != nil {
return err
}
bounds.Min.Y += iconsize + margin
bounds.Max.Y -= margin
}
drawString(img,
bounds,
ttfFont,
w.label,
w.dev.DPI,
w.fontsize,
w.color,
image.Pt(-1, -1))
} else if w.icon != nil {
err := drawImage(img,
w.icon,
height,
image.Pt(-1, -1))
if err != nil {
return err
}
}
return w.render(w.dev, img)
}