forked from jbensmann/mouseless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtual_keyboard.go
71 lines (64 loc) · 1.73 KB
/
virtual_keyboard.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
package main
import (
"github.com/bendahl/uinput"
log "github.com/sirupsen/logrus"
)
type VirtualKeyboard struct {
uinputKeyboard uinput.Keyboard
isPressed map[uint16]bool
pressedModifiers map[uint16]bool
triggeredKeys map[uint16][]uint16
}
func NewVirtualKeyboard() (*VirtualKeyboard, error) {
var err error
v := VirtualKeyboard{
isPressed: make(map[uint16]bool),
pressedModifiers: make(map[uint16]bool),
triggeredKeys: make(map[uint16][]uint16),
}
v.uinputKeyboard, err = uinput.CreateKeyboard("/dev/uinput", []byte("mouseless"))
if err != nil {
return nil, err
}
return &v, nil
}
func (v *VirtualKeyboard) PressKeys(triggeredByKey uint16, codes []uint16) {
v.triggeredKeys[triggeredByKey] = append(v.triggeredKeys[triggeredByKey], codes...)
// release previous modifiers
for c := range v.pressedModifiers {
v.releaseKey(c)
}
for i, c := range codes {
log.Debugf("Keyboard: pressing %v", c)
err := v.uinputKeyboard.KeyDown(int(c))
if err != nil {
log.Warnf("Keyboard: failed to press the key %v: %v", c, err)
}
v.isPressed[c] = true
if i < len(codes)-1 {
v.pressedModifiers[c] = true
}
}
}
func (v *VirtualKeyboard) releaseKey(code uint16) {
log.Debugf("Keyboard: releasing %v", code)
err := v.uinputKeyboard.KeyUp(int(code))
if err != nil {
log.Warnf("Keyboard: failed to release the key %v: %v", code, err)
}
delete(v.isPressed, code)
delete(v.pressedModifiers, code)
}
func (v *VirtualKeyboard) OriginalKeyUp(code uint16) {
if codes, ok := v.triggeredKeys[code]; ok {
for _, c := range codes {
if pressed, ok := v.isPressed[c]; ok && pressed {
v.releaseKey(c)
}
}
delete(v.triggeredKeys, code)
}
}
func (v *VirtualKeyboard) Close() {
v.uinputKeyboard.Close()
}