forked from muesli/deckmaster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeck.go
330 lines (284 loc) · 6.74 KB
/
deck.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
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
package main
import (
"fmt"
"image"
"image/draw"
"math"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/atotto/clipboard"
"github.com/godbus/dbus"
"github.com/muesli/streamdeck"
)
// Deck is a set of widgets.
type Deck struct {
File string
Background image.Image
Widgets []Widget
}
// LoadDeck loads a deck configuration.
func LoadDeck(dev *streamdeck.Device, base string, deck string) (*Deck, error) {
path, err := expandPath(base, deck)
if err != nil {
return nil, err
}
verbosef("Loading deck: %s", path)
dc, err := LoadConfig(path)
if err != nil {
return nil, err
}
d := Deck{
File: path,
}
if dc.Background != "" {
bgpath, err := expandPath(filepath.Dir(path), dc.Background)
if err != nil {
return nil, err
}
if err := d.loadBackground(dev, bgpath); err != nil {
return nil, err
}
}
keyMap := map[uint8]KeyConfig{}
for _, k := range dc.Keys {
keyMap[k.Index] = k
}
for i := uint8(0); i < dev.Keys; i++ {
bg := d.backgroundForKey(dev, i)
var w Widget
if k, found := keyMap[i]; found {
w, err = NewWidget(dev, filepath.Dir(path), k, bg)
if err != nil {
return nil, err
}
} else {
w = NewBaseWidget(dev, filepath.Dir(path), i, nil, nil, bg)
}
d.Widgets = append(d.Widgets, w)
}
return &d, nil
}
// loads a background image.
func (d *Deck) loadBackground(dev *streamdeck.Device, bg string) error {
f, err := os.Open(bg)
if err != nil {
return err
}
defer f.Close() //nolint:errcheck
background, _, err := image.Decode(f)
if err != nil {
return err
}
rows := int(dev.Rows)
cols := int(dev.Columns)
padding := int(dev.Padding)
pixels := int(dev.Pixels)
width := cols*pixels + (cols-1)*padding
height := rows*pixels + (rows-1)*padding
if background.Bounds().Dx() != width ||
background.Bounds().Dy() != height {
return fmt.Errorf("supplied background image has wrong dimensions, expected %dx%d pixels", width, height)
}
d.Background = background
return nil
}
// returns the background image for an individual key.
func (d Deck) backgroundForKey(dev *streamdeck.Device, key uint8) image.Image {
padding := int(dev.Padding)
pixels := int(dev.Pixels)
bg := image.NewRGBA(image.Rect(0, 0, pixels, pixels))
if d.Background != nil {
startx := int(key%dev.Columns) * (pixels + padding)
starty := int(key/dev.Columns) * (pixels + padding)
draw.Draw(bg, bg.Bounds(), d.Background, image.Point{startx, starty}, draw.Src)
}
return bg
}
// handles keypress with delay.
func emulateKeyPressWithDelay(keys string) {
kd := strings.Split(keys, "+")
emulateKeyPress(kd[0])
if len(kd) == 1 {
return
}
// optional delay
if delay, err := strconv.Atoi(strings.TrimSpace(kd[1])); err == nil {
time.Sleep(time.Duration(delay) * time.Millisecond)
}
}
// emulates a range of key presses.
func emulateKeyPresses(keys string) {
for _, kp := range strings.Split(keys, "/") {
emulateKeyPressWithDelay(kp)
}
}
// emulates a (multi-)key press.
func emulateKeyPress(keys string) {
if keyboard == nil {
fmt.Fprintln(os.Stderr, "Keyboard emulation is disabled!")
return
}
kk := strings.Split(keys, "-")
for i, k := range kk {
k = formatKeycodes(strings.TrimSpace(k))
kc, err := strconv.Atoi(k)
if err != nil {
fmt.Fprintf(os.Stderr, "%s is not a valid keycode: %s\n", k, err)
}
if i+1 < len(kk) {
_ = keyboard.KeyDown(kc)
defer keyboard.KeyUp(kc) //nolint:errcheck
} else {
_ = keyboard.KeyPress(kc)
}
}
}
// emulates a clipboard paste.
func emulateClipboard(text string) {
err := clipboard.WriteAll(text)
if err != nil {
fmt.Fprintf(os.Stderr, "Pasting to clipboard failed: %s\n", err)
}
// paste the string
emulateKeyPress("29-47") // ctrl-v
}
// executes a dbus method.
func executeDBusMethod(object, path, method, args string) {
call := dbusConn.Object(object, dbus.ObjectPath(path)).Call(method, 0, args)
if call.Err != nil {
fmt.Fprintf(os.Stderr, "dbus call failed: %s\n", call.Err)
}
}
// executes a command.
func executeCommand(cmd string) {
exp, err := expandPath("", cmd)
if err == nil {
cmd = exp
}
args := strings.Split(cmd, " ")
c := exec.Command(args[0], args[1:]...) //nolint:gosec
if *verbose {
c.Stdout = os.Stdout
c.Stderr = os.Stderr
}
if err := c.Start(); err != nil {
fmt.Fprintf(os.Stderr, "Command failed: %s\n", err)
return
}
if err := c.Wait(); err != nil {
fmt.Fprintf(os.Stderr, "Command failed: %s\n", err)
}
}
// triggerAction triggers an action.
func (d *Deck) triggerAction(dev *streamdeck.Device, index uint8, hold bool) {
for _, w := range d.Widgets {
if w.Key() != index {
continue
}
var a *ActionConfig
if hold {
a = w.ActionHold()
} else {
a = w.Action()
}
if a == nil {
w.TriggerAction(hold)
continue
}
if a.Deck != "" {
d, err := LoadDeck(dev, filepath.Dir(d.File), a.Deck)
if err != nil {
fmt.Fprintln(os.Stderr, "Can't load deck:", err)
return
}
if err := dev.Clear(); err != nil {
fatal(err)
return
}
deck = d
deck.updateWidgets()
}
if a.Keycode != "" {
emulateKeyPresses(a.Keycode)
}
if a.Paste != "" {
emulateClipboard(a.Paste)
}
if a.DBus.Method != "" {
executeDBusMethod(a.DBus.Object, a.DBus.Path, a.DBus.Method, a.DBus.Value)
}
if a.Exec != "" {
go executeCommand(a.Exec)
}
if a.Device != "" {
switch {
case a.Device == "sleep":
if err := dev.Sleep(); err != nil {
fatalf("error: %v\n", err)
}
case strings.HasPrefix(a.Device, "brightness"):
d.adjustBrightness(dev, strings.TrimPrefix(a.Device, "brightness"))
default:
fmt.Fprintln(os.Stderr, "Unrecognized special action:", a.Device)
}
}
}
}
// updateWidgets updates/repaints all the widgets.
func (d *Deck) updateWidgets() {
for _, w := range d.Widgets {
if !w.RequiresUpdate() {
continue
}
// fmt.Println("Repaint", w.Key())
if err := w.Update(); err != nil {
fatalf("error: %v", err)
}
}
}
// adjustBrightness adjusts the brightness.
func (d *Deck) adjustBrightness(dev *streamdeck.Device, value string) {
if len(value) == 0 {
fmt.Fprintln(os.Stderr, "No brightness value specified")
return
}
v := int64(math.MinInt64)
if len(value) > 1 {
nv, err := strconv.ParseInt(value[1:], 10, 64)
if err == nil {
v = nv
}
}
switch value[0] {
case '=': // brightness=[n]:
case '-': // brightness-[n]:
if v == math.MinInt64 {
v = 10
}
v = int64(*brightness) - v
case '+': // brightness+[n]:
if v == math.MinInt64 {
v = 10
}
v = int64(*brightness) + v
default:
v = math.MinInt64
}
if v == math.MinInt64 {
fmt.Fprintf(os.Stderr, "Could not grok the brightness from value '%s'\n", value)
return
}
if v < 1 {
v = 1
} else if v > 100 {
v = 100
}
if err := dev.SetBrightness(uint8(v)); err != nil {
fatalf("error: %v\n", err)
}
*brightness = uint(v)
}