forked from HACKERALERT/giu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputHandler.go
92 lines (74 loc) · 1.71 KB
/
InputHandler.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
package giu
// input menager is used to register a keyboard shortcuts in an app
import (
"github.com/Picocrypt/glfw/v3.3/glfw"
)
// store keyboard shortcuts
var shortcuts map[keyCombo]*callbacks
func init() {
shortcuts = make(map[keyCombo]*callbacks)
}
// ShortcutType represens a type of shortcut (global or local)
type ShortcutType bool
const (
// GlobalShortcut is registered for all the app
GlobalShortcut ShortcutType = true
// LocLShortcut is registered for current window only
LocalShortcut ShortcutType = false
)
type keyCombo struct {
key glfw.Key
modifier glfw.ModifierKey
}
type callbacks struct {
global func()
window func()
}
type Shortcut struct {
Key Key
Modifier Modifier
Callback func()
IsGlobal ShortcutType
}
func RegisterKeyboardShortcuts(s ...Shortcut) {
for _, shortcut := range s {
combo := keyCombo{glfw.Key(shortcut.Key), glfw.ModifierKey(shortcut.Modifier)}
cb, isRegistered := shortcuts[combo]
if !isRegistered {
cb = &callbacks{}
}
if shortcut.IsGlobal {
cb.global = shortcut.Callback
} else {
cb.window = shortcut.Callback
}
shortcuts[combo] = cb
}
}
func unregisterWindowShortcuts() {
for _, s := range shortcuts {
s.window = nil
}
}
func handler(key glfw.Key, mod glfw.ModifierKey, action glfw.Action) {
if action != glfw.Press {
return
}
for combo, cb := range shortcuts {
if combo.key != key || combo.modifier != mod {
continue
}
if cb.window != nil {
cb.window()
} else if cb.global != nil {
cb.global()
}
}
}
// WindowShortcut represents a window-level shortcut
// could be used as an argument to (*Window).RegisterKeyboardShortcuts
type WindowShortcut struct {
Key Key
Modifier Modifier
Callback func()
}