-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathkeyboard.go
187 lines (153 loc) · 2.27 KB
/
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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package keyboard
import (
"os"
"os/exec"
)
type bytes [3]byte
// KeyEvent contains data about a keyboard event
type KeyEvent struct {
Bytes bytes
Key int
Char string
}
const (
Tilde = iota + 96
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
)
const (
Escape = 27
Spacebar = 32
Hyphen = 45
Asterisk = 42
Plus = 43
Slash = 47
Dot = 46
)
const (
Zero = iota + 48
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
)
const (
ArrowUp = iota + 65
ArrowDown
ArrowRight
ArrowLeft
)
// used to hold the original stty state
var originalState string
func Parse(input bytes) KeyEvent {
event := KeyEvent{Bytes: input, Char: string(input[:])}
var code byte
// basic input codes
if input[1] == 0 && input[2] == 0 {
code = input[0]
// space bar
if code == Spacebar {
event.Key = Spacebar
}
// vanilla escape
if code == Escape {
event.Key = Escape
}
// Hyphen
if code == Hyphen {
event.Key = Hyphen
}
// Asterisk
if code == Asterisk {
event.Key = Asterisk
}
// Plus
if code == Plus {
event.Key = Plus
}
// Slash
if code == Slash {
event.Key = Slash
}
// Dot
if code == Dot {
event.Key = Dot
}
// number keys
if code >= 48 && code <= 57 {
event.Key = int(code)
}
// alphabet
if code >= 97 && code <= 122 {
event.Key = int(code)
}
return event
}
// arrow keys
if input[0] == Escape && input[1] == 91 {
code = input[2]
if code >= 65 && code <= 68 {
event.Key = int(code)
return event
}
}
return event
}
// fetches original state, sets up TTY for raw (unbuffered) input
func configure() error {
state, err := stty("-g")
if err != nil {
return err
}
originalState = state
// -echo: terminal doesn't echo typed characters back to the terminal
// -icanon: terminal doesn't interpret special characters (like backspace)
_, err = stty("-echo", "-icanon")
return err
}
// restores the TTY to the original state
func restore() error {
if _, err := stty("echo"); err != nil {
return err
}
_, err := stty(originalState)
return err
}
func stty(args ...string) (string, error) {
cmd := exec.Command("stty", args...)
cmd.Stdin = os.Stdin
out, err := cmd.Output()
if err != nil {
return "", err
}
return string(out), nil
}