-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathkeyboard.go
83 lines (75 loc) · 1.76 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
package main
import (
"bytes"
"github.com/pkg/term"
)
// KeyType describes a key
type KeyType uint16
// Key holds the input value from terminal stream
type Key struct {
Value []byte
Type KeyType
}
// Key constants
const (
Enter KeyType = iota + 1
Esc
Space
Tab
CtrlA
CtrlB
CtrlC
Delete
CtrlBackslash
Backspace
UpArrow
DownArrow
LeftArrow
RightArrow
)
func pollKeyEvents() Key {
t, err := term.Open("/dev/tty")
if err != nil {
return Key{}
}
term.RawMode(t)
buff := make([]byte, 2048)
size, err := t.Read(buff)
t.Restore()
t.Close()
if err != nil {
return Key{}
}
switch {
case bytes.Equal(buff[0:size], []byte{13}) || bytes.Equal(buff[0:size], []byte{10}):
return Key{Type: Enter}
case bytes.Equal(buff[0:size], []byte{27}):
return Key{Type: Esc}
case bytes.Equal(buff[0:size], []byte{32}):
return Key{Type: Space}
case bytes.Equal(buff[0:size], []byte{9}):
return Key{Type: Tab}
case bytes.Equal(buff[0:size], []byte{1}):
return Key{Type: CtrlA}
case bytes.Equal(buff[0:size], []byte{2}):
return Key{Type: CtrlB}
case bytes.Equal(buff[0:size], []byte{3}):
return Key{Type: CtrlC}
case bytes.Equal(buff[0:size], []byte{28}):
return Key{Type: CtrlBackslash}
case bytes.Equal(buff[0:size], []byte{8}) || bytes.Equal(buff[0:size], []byte{127}):
return Key{Type: Backspace}
case bytes.Equal(buff[0:size], []byte{27, 91, 51, 126}):
return Key{Type: Delete}
case bytes.Equal(buff[0:size], []byte{27, 91, 65}):
return Key{Type: UpArrow}
case bytes.Equal(buff[0:size], []byte{27, 91, 66}):
return Key{Type: DownArrow}
case bytes.Equal(buff[0:size], []byte{27, 91, 67}):
return Key{Type: RightArrow}
case bytes.Equal(buff[0:size], []byte{27, 91, 68}):
return Key{Type: LeftArrow}
default:
return Key{Value: buff[0:size]}
}
}