-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.go
312 lines (261 loc) · 6.55 KB
/
main.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
package main
import (
"errors"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/bendahl/uinput"
"github.com/godbus/dbus"
"github.com/mitchellh/go-homedir"
"github.com/muesli/streamdeck"
)
var (
// Version contains the application version number. It's set via ldflags
// when building.
Version = ""
// CommitSHA contains the SHA of the commit that this application was built
// against. It's set via ldflags when building.
CommitSHA = ""
deck *Deck
dbusConn *dbus.Conn
keyboard uinput.Keyboard
shutdown = make(chan error)
xorg *Xorg
recentWindows []Window
deckFile = flag.String("deck", "main.deck", "path to deck config file")
device = flag.String("device", "", "which device to use (serial number)")
brightness = flag.Uint("brightness", 80, "brightness in percent")
sleep = flag.String("sleep", "", "sleep timeout")
verbose = flag.Bool("verbose", false, "verbose output")
version = flag.Bool("version", false, "display version")
)
const (
fadeDuration = 250 * time.Millisecond
longPressDuration = 350 * time.Millisecond
)
func fatal(v ...interface{}) {
go func() { shutdown <- errors.New(fmt.Sprint(v...)) }()
}
func fatalf(format string, a ...interface{}) {
go func() { shutdown <- fmt.Errorf(format, a...) }()
}
func verbosef(format string, a ...interface{}) {
if !*verbose {
return
}
fmt.Printf(format+"\n", a...)
}
func expandPath(base, path string) (string, error) {
var err error
path, err = homedir.Expand(path)
if err != nil {
return "", err
}
if base == "" {
return path, nil
}
if !filepath.IsAbs(path) {
path = filepath.Join(base, path)
}
return filepath.Abs(path)
}
func eventLoop(dev *streamdeck.Device, tch chan interface{}) error {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
var keyStates sync.Map
keyTimestamps := make(map[uint8]time.Time)
kch, err := dev.ReadKeys()
if err != nil {
return err
}
for {
select {
case <-time.After(100 * time.Millisecond):
deck.updateWidgets()
case k, ok := <-kch:
if !ok {
if err = dev.Open(); err != nil {
return err
}
continue
}
var state bool
if ks, ok := keyStates.Load(k.Index); ok {
state = ks.(bool)
}
keyStates.Store(k.Index, k.Pressed)
if state && !k.Pressed {
// key was released
if time.Since(keyTimestamps[k.Index]) < longPressDuration {
verbosef("Triggering short action for key %d", k.Index)
deck.triggerAction(dev, k.Index, false)
}
}
if !state && k.Pressed {
// key was pressed
go func() {
// launch timer to observe keystate
time.Sleep(longPressDuration)
if state, ok := keyStates.Load(k.Index); ok && state.(bool) {
// key still pressed
verbosef("Triggering long action for key %d", k.Index)
deck.triggerAction(dev, k.Index, true)
}
}()
}
keyTimestamps[k.Index] = time.Now()
case e := <-tch:
switch event := e.(type) {
case WindowClosedEvent:
handleWindowClosed(event)
case ActiveWindowChangedEvent:
handleActiveWindowChanged(dev, event)
}
case err := <-shutdown:
return err
case <-hup:
verbosef("Received SIGHUP, reloading configuration...")
nd, err := LoadDeck(dev, ".", deck.File)
if err != nil {
verbosef("The new configuration is not valid, keeping the current one.")
fmt.Fprintf(os.Stderr, "Configuration Error: %s\n", err)
continue
}
deck = nd
deck.updateWidgets()
case <-sigs:
fmt.Println("Shutting down...")
return nil
}
}
}
func closeDevice(dev *streamdeck.Device) {
if err := dev.Reset(); err != nil {
fmt.Fprintln(os.Stderr, "Unable to reset Stream Deck")
}
if err := dev.Close(); err != nil {
fmt.Fprintln(os.Stderr, "Unable to close Stream Deck")
}
}
func initDevice() (*streamdeck.Device, error) {
d, err := streamdeck.Devices()
if err != nil {
return nil, err
}
if len(d) == 0 {
return nil, fmt.Errorf("no Stream Deck devices found")
}
dev := d[0]
if len(*device) > 0 {
found := false
for _, v := range d {
if v.Serial == *device {
dev = v
found = true
break
}
}
if !found {
fmt.Fprintln(os.Stderr, "Can't find device. Available devices:")
for _, v := range d {
fmt.Fprintf(os.Stderr, "Serial %s (%d buttons)\n", v.Serial, dev.Keys)
}
os.Exit(1)
}
}
if err := dev.Open(); err != nil {
return nil, err
}
ver, err := dev.FirmwareVersion()
if err != nil {
return &dev, err
}
verbosef("Found device with serial %s (%d buttons, firmware %s)",
dev.Serial, dev.Keys, ver)
if err := dev.Reset(); err != nil {
return &dev, err
}
if *brightness > 100 {
*brightness = 100
}
if err = dev.SetBrightness(uint8(*brightness)); err != nil {
return &dev, err
}
dev.SetSleepFadeDuration(fadeDuration)
if len(*sleep) > 0 {
timeout, err := time.ParseDuration(*sleep)
if err != nil {
return &dev, err
}
dev.SetSleepTimeout(timeout)
}
return &dev, nil
}
func run() error {
// initialize device
dev, err := initDevice()
if dev != nil {
defer closeDevice(dev)
}
if err != nil {
return fmt.Errorf("Unable to initialize Stream Deck: %s", err)
}
// initialize dbus connection
dbusConn, err = dbus.SessionBus()
if err != nil {
return fmt.Errorf("Unable to connect to dbus: %s", err)
}
// initialize xorg connection and track window focus
tch := make(chan interface{})
xorg, err = Connect(os.Getenv("DISPLAY"))
if err == nil {
defer xorg.Close()
xorg.TrackWindows(tch, time.Second)
} else {
fmt.Fprintf(os.Stderr, "Could not connect to X server: %s\n", err)
fmt.Fprintln(os.Stderr, "Tracking window manager will be disabled!")
}
// initialize virtual keyboard
keyboard, err = uinput.CreateKeyboard("/dev/uinput", []byte("Deckmaster"))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not create virtual input device (/dev/uinput): %s\n", err)
fmt.Fprintln(os.Stderr, "Emulating keyboard events will be disabled!")
} else {
defer keyboard.Close() //nolint:errcheck
}
// load deck
deck, err = LoadDeck(dev, ".", *deckFile)
if err != nil {
return fmt.Errorf("Can't load deck: %s", err)
}
deck.updateWidgets()
return eventLoop(dev, tch)
}
func main() {
flag.Parse()
if *version {
if len(CommitSHA) > 7 {
CommitSHA = CommitSHA[:7]
}
if Version == "" {
Version = "(built from source)"
}
fmt.Printf("deckmaster %s", Version)
if len(CommitSHA) > 0 {
fmt.Printf(" (%s)", CommitSHA)
}
fmt.Println()
os.Exit(0)
}
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}