-
Notifications
You must be signed in to change notification settings - Fork 1
/
hotkey.go
49 lines (46 loc) · 906 Bytes
/
hotkey.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
package share_clipboard
import (
"fmt"
"github.com/juju/errors"
"golang.design/x/hotkey"
"strings"
)
// Translate eg: ctrl+shift+C
func translate(hotkey string) (mods []hotkey.Modifier, key hotkey.Key, err error) {
for _, ele := range strings.Split(hotkey, "+") {
e := strings.ToUpper(ele)
mod, ok1 := ModifierMap[e]
if ok1 {
mods = append(mods, mod)
}
k, ok2 := KeyMap[e]
if ok2 {
if key != 0 {
return nil, 0, fmt.Errorf("support one key only")
}
key = k
}
if !ok1 && !ok2 {
return nil, 0, fmt.Errorf("wrong key")
}
}
return mods, key, nil
}
func ListenHotKey(hk string, hook func()) error {
mods, key, err := translate(hk)
if err != nil {
return errors.Trace(err)
}
HK := hotkey.New(mods, key)
if err := HK.Register(); err != nil {
return errors.Trace(err)
}
go func() {
for {
<-HK.Keydown()
<-HK.Keyup()
hook()
}
}()
return nil
}