forked from cocoabits/MASShortcut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo_bindings.go
72 lines (65 loc) · 1.69 KB
/
go_bindings.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
// +build darwin
package masshortcut
// #cgo CFLAGS: -x objective-c -framework Cocoa -framework CoreFoundation -framework Carbon -framework AppKit
// #cgo LDFLAGS: -framework Cocoa -framework CoreFoundation -framework Carbon -framework AppKit
// #import "./MASShortcutMonitor.h"
// void CHotkeyCallback(int Keys, int Modifiers);
// void register_shortcut(int Keys, int Modifiers);
import "C"
import (
"sync"
"unsafe"
)
var (
cbMap = map[string]func(){}
currentShortcuts = []string{}
currentShortcutLock = sync.Mutex{}
)
// Creates a hash.
func hashgen(Keys, Modifiers int) string {
a := make([]byte, 16)
for i, v := range *(*[8]byte)(unsafe.Pointer(&Keys)) {
a[i] = v
}
for i, v := range *(*[8]byte)(unsafe.Pointer(&Modifiers)) {
a[i+8] = v
}
return string(a)
}
// CHotkeyCallback is the hotkey callback for the shortcuts.
//export CHotkeyCallback
func CHotkeyCallback(CKeys, CModifiers C.int) {
Keys := int(CKeys)
Modifiers := int(CModifiers)
s, ok := cbMap[hashgen(Keys, Modifiers)]
if !ok {
return
}
go s()
}
// RegisterShortcut is used to register a shortcut.
func RegisterShortcut(Keys, Modifiers int, Callback func()) {
currentShortcutLock.Lock()
includes := false
hash := hashgen(Keys, Modifiers)
for _, v := range currentShortcuts {
if v == hash {
includes = true
break
}
}
if !includes {
currentShortcuts = append(currentShortcuts, hash)
}
cbMap[hash] = Callback
currentShortcutLock.Unlock()
if !includes {
C.register_shortcut(C.int(Keys), C.int(Modifiers))
}
}
// UnregisterShortcuts is used to unregister all of the shortcuts.
func UnregisterShortcuts() {
currentShortcutLock.Lock()
cbMap = map[string]func(){}
currentShortcutLock.Unlock()
}