-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
InputHandler.go
111 lines (89 loc) · 2.38 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package giu
// input manager is used to register a keyboard shortcuts in an app.
// Shortcut represents a keyboard shortcut.
type Shortcut struct {
Key Key
Modifier Modifier
Callback func()
IsGlobal ShortcutType
}
// WindowShortcut represents a window-level shortcut
// could be used as an argument to (*Window).RegisterKeyboardShortcuts.
type WindowShortcut struct {
Key Key
Modifier Modifier
Callback func()
}
// ShortcutType represents a type of shortcut (global or local).
type ShortcutType bool
const (
// GlobalShortcut is registered for all the app.
GlobalShortcut ShortcutType = true
// LocalShortcut is registered for current window only.
LocalShortcut ShortcutType = false
)
// InputHandlerHandleCallback is a callback which is called when a shortcut is triggered.
type InputHandlerHandleCallback func(Key, Modifier, Action)
// InputHandler is an interface which needs to be implemented
// by user-defined input handlers.
type InputHandler interface {
// RegisterKeyboardShortcuts adds a specified shortcuts into input handler
RegisterKeyboardShortcuts(...Shortcut)
// UnregisterKeyboardShortcuts removes window shortcuts from input handler
UnregisterWindowShortcuts()
// Handle handles a shortcut
Handle(Key, Modifier, Action)
}
// --- Default implementation of giu input manager ---
var _ InputHandler = &inputHandler{}
func newInputHandler() *inputHandler {
return &inputHandler{
shortcuts: make(map[keyCombo]*callbacks),
}
}
type inputHandler struct {
shortcuts map[keyCombo]*callbacks
}
func (i *inputHandler) RegisterKeyboardShortcuts(s ...Shortcut) {
for _, shortcut := range s {
combo := keyCombo{shortcut.Key, shortcut.Modifier}
cb, isRegistered := i.shortcuts[combo]
if !isRegistered {
cb = &callbacks{}
}
if shortcut.IsGlobal {
cb.global = shortcut.Callback
} else {
cb.window = shortcut.Callback
}
i.shortcuts[combo] = cb
}
}
func (i *inputHandler) UnregisterWindowShortcuts() {
for _, s := range i.shortcuts {
s.window = nil
}
}
func (i *inputHandler) Handle(key Key, mod Modifier, a Action) {
if a != Press {
return
}
for combo, cb := range i.shortcuts {
if combo.key != key || combo.modifier != mod {
continue
}
if cb.window != nil {
cb.window()
} else if cb.global != nil {
cb.global()
}
}
}
type keyCombo struct {
key Key
modifier Modifier
}
type callbacks struct {
global func()
window func()
}