forked from jbensmann/mouseless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
311 lines (274 loc) · 7.4 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
package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"time"
evdev "github.com/gvalkov/golang-evdev"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
)
const version = "0.1.0"
const (
mouseLoopInterval = 20 * time.Millisecond
defaultConfigFile = ".config/mouseless/config.yaml"
)
var (
configFile string
config *Config
keyboardDevices []*KeyboardDevice
mouse *VirtualMouse
keyboard *VirtualKeyboard
tapHoldHandler *TapHoldHandler
currentLayer *Layer
toggleLayerKey *uint16
toggleLayerPrevious *Layer
)
var opts struct {
Version bool `short:"v" long:"version" description:"Show the version"`
Debug bool `short:"d" long:"debug" description:"Show verbose debug information"`
ConfigFile string `short:"c" long:"config" description:"The config file"`
}
func main() {
var err error
_, err = flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.Version {
fmt.Println(version)
os.Exit(0)
}
// init logging
log.SetOutput(os.Stdout)
if opts.Debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
listKeyboardDevices()
// if no config file is given, use the default one
configFile = opts.ConfigFile
if configFile == "" {
u, err := user.Current()
if err != nil {
exitError(err, "Failed to get the current user")
}
configFile = filepath.Join(u.HomeDir, defaultConfigFile)
}
log.Debugf("Using config file: %s", configFile)
loadConfig()
// init virtual mouse and keyboard
mouse, err = NewVirtualMouse()
if err != nil {
exitError(err, "Failed to init the virtual mouse")
}
defer mouse.Close()
keyboard, err = NewVirtualKeyboard()
if err != nil {
exitError(err, "Failed to init the virtual keyboard")
}
defer keyboard.Close()
tapHoldHandler = NewTapHoldHandler()
// init keyboard devices
for _, dev := range config.Devices {
kd := NewKeyboardDevice(dev, tapHoldHandler.InChannel())
keyboardDevices = append(keyboardDevices, kd)
go kd.ReadLoop()
}
if config.StartCommand != "" {
log.Debugf("Executing start command: %s", config.StartCommand)
cmd := exec.Command("sh", "-c", config.StartCommand)
err := cmd.Run()
if err != nil {
exitError(err, "Execution of start command failed")
}
}
mainLoop()
}
func loadConfig() {
var err error
config, err = readConfig(configFile)
if err != nil {
exitError(err, "Failed to read the config file")
}
// set initial layer
currentLayer = config.Layers[0]
log.Debugf("Switching to initial layer %s", currentLayer.Name)
}
func mainLoop() {
tapHoldHandler.StartProcessing()
mouseTimer := time.NewTimer(math.MaxInt64)
for {
// check if a key was pressed
var event *KeyboardEvent = nil
select {
case e := <-tapHoldHandler.OutChannel():
event = &e
case <-mouseTimer.C:
}
if event != nil {
handleKey(event)
}
// check if at least one device is opened
oneDeviceOpen := false
for _, device := range keyboardDevices {
if device.IsOpen() {
oneDeviceOpen = true
}
}
if !oneDeviceOpen {
log.Warnf("No keyboard device could be opened:")
for i, device := range keyboardDevices {
log.Warnf("Device %d: %s: %s", i+1, device.DeviceName(), device.LastOpenError())
}
time.Sleep(10 * time.Second)
}
// handle mouse movement and scrolling
moveSpeed := config.BaseMouseSpeed * mouseLoopInterval.Seconds()
scrollSpeed := config.BaseScrollSpeed * mouseLoopInterval.Seconds()
moveX := 0.0
moveY := 0.0
scrollX := 0.0
scrollY := 0.0
for code, binding := range currentLayer.Bindings {
if tapHoldHandler.IsKeyPressed(code) {
switch t := binding.(type) {
case SpeedBinding:
moveSpeed *= t.Speed
scrollSpeed *= t.Speed
case ScrollBinding:
scrollX += t.X
scrollY += t.Y
case MoveBinding:
moveX += t.X
moveY += t.Y
}
}
}
if moveX != 0 || moveY != 0 || scrollX != 0 || scrollY != 0 {
mouse.Scroll(scrollX*scrollSpeed, scrollY*scrollSpeed)
mouse.Move(moveX*moveSpeed, moveY*moveSpeed)
mouseTimer = time.NewTimer(mouseLoopInterval)
} else {
mouseTimer = time.NewTimer(math.MaxInt64)
}
}
}
// handleKey handles a single key event (press or release).
func handleKey(event *KeyboardEvent) {
binding, _ := currentLayer.Bindings[event.code]
// when no binding and pass through is enabled, insert a KeyBinding
if binding == nil && currentLayer.PassThrough {
binding = KeyBinding{KeyCombo: []uint16{event.code}}
}
// go back to the previous layer when toggleLayerKey is released
if toggleLayerKey != nil && *toggleLayerKey == event.code && !event.isPress {
if toggleLayerPrevious != nil {
currentLayer = toggleLayerPrevious
toggleLayerPrevious = nil
toggleLayerKey = nil
log.Debugf("Switching to layer %v", currentLayer.Name)
}
}
// inform the keyboard and mouse about key releases
if !event.isPress {
keyboard.OriginalKeyUp(event.code)
mouse.OriginalKeyUp(event.code)
}
executeBinding(event, binding)
// switch to first layer on escape
if event.code == evdev.KEY_ESC && event.isPress {
currentLayer = config.Layers[0]
log.Debugf("Switching to layer %v", currentLayer.Name)
}
}
// executeBinding does what needs to be done for the given binding.
// For some bindings there is nothing that needs to be done, e.g. for the speed
// and move bindings.
// For tap-hold bindings, either the tap or the hold binding is executed.
func executeBinding(event *KeyboardEvent, binding interface{}) {
log.Debugf("Executing %T: %+v", binding, binding)
switch t := binding.(type) {
case MultiBinding:
executeBinding(event, t.Binding1)
executeBinding(event, t.Binding2)
case TapHoldBinding:
if event.holdKey {
executeBinding(event, t.HoldBinding)
} else {
executeBinding(event, t.TapBinding)
}
case LayerBinding:
if event.isPress {
// if current layer is toggled, deactivate the toggle
if toggleLayerPrevious != nil {
toggleLayerPrevious = nil
toggleLayerKey = nil
}
for _, layer := range config.Layers {
if layer.Name == t.Layer {
log.Debugf("Switching to layer %v", layer.Name)
currentLayer = layer
break
}
}
}
case ToggleLayerBinding:
// only allow one toggle
if event.isPress && toggleLayerPrevious == nil {
for _, layer := range config.Layers {
if layer.Name == t.Layer {
log.Debugf("Switching to layer %v", layer.Name)
toggleLayerPrevious = currentLayer
toggleLayerKey = &event.code
currentLayer = layer
break
}
}
}
case ReloadConfigBinding:
if event.isPress {
loadConfig()
}
case KeyBinding:
if event.isPress {
keyboard.PressKeys(event.code, t.KeyCombo)
}
case ButtonBinding:
if event.isPress {
mouse.ButtonPress(event.code, t.Button)
}
case ExecBinding:
// exec
if event.isPress {
log.Debugf("Executing: %s", t.Command)
cmd := exec.Command("sh", "-c", t.Command)
err := cmd.Run()
if err != nil {
log.Warnf("Execution of command failed: %v", err)
}
}
}
}
// listKeyboardDevices lists all available keyboard input devices.
func listKeyboardDevices() {
devices, _ := evdev.ListInputDevices("/dev/input/by-path/*kbd*")
devices2, _ := evdev.ListInputDevices("/dev/input/by-id/*kbd*")
devices = append(devices, devices2...)
log.Debugf("Available keyboard devices:")
for _, dev := range devices {
log.Debugf("%s %s %s\n", dev.Fn, dev.Name, dev.Phys)
}
}
func exitError(err error, msg string) {
if err != nil {
log.Errorf(msg+": %v", err)
} else {
log.Error(msg)
}
os.Exit(1)
}