-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
116 lines (102 loc) · 2.1 KB
/
input.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
package main
import (
"fmt"
"github.com/eiannone/keyboard"
"github.com/k0kubun/go-ansi"
"github.com/notwithering/memory"
)
func line(password bool) (string, error) {
if err := keyboard.Open(); err != nil {
return "", err
}
defer keyboard.Close()
var input []byte
var position int
var reprintFromPosition = func() {
var distance int = len(input[position:]) + 1
if password {
for range distance - 1 {
fmt.Print("*")
}
} else {
fmt.Print(string(input[position:]))
}
fmt.Print(" ")
ansi.CursorBack(distance)
}
for {
r, key, err := keyboard.GetKey()
if err != nil {
return "", err
}
switch key {
case keyboard.KeyEnter:
ansi.Print("\r\n")
if password {
defer memory.Zero(&input)
}
return string(input), nil
case keyboard.KeyArrowLeft:
if position > 0 {
position--
ansi.CursorBack(1)
}
case keyboard.KeyArrowRight:
if position < len(input) {
position++
ansi.CursorForward(1)
}
case keyboard.KeyBackspace, keyboard.KeyBackspace2:
if len(input) > 0 && position > 0 {
var inputBuf []byte
for i, r := range input {
if i != position-1 {
inputBuf = append(inputBuf, r)
}
}
input = inputBuf
position--
ansi.CursorBack(1)
reprintFromPosition()
}
case keyboard.KeyDelete:
if len(input) > 0 && position < len(input) {
var inputBuf []byte
for i, r := range input {
if i != position {
inputBuf = append(inputBuf, r)
}
}
input = inputBuf
reprintFromPosition()
}
case keyboard.KeyCtrlA:
ansi.CursorBack(position)
position = 0
case keyboard.KeyCtrlE:
for range len(input) - position {
ansi.CursorForward(1)
}
position = len(input)
// TODO: Add CTRL+U, CTRL+K, and CTRL+W
default:
if key == keyboard.KeySpace {
r = ' '
}
if r < ' ' || r > '~' {
continue
}
inputBuf := append(input, 0)
copy(inputBuf[position+1:], inputBuf[position:])
inputBuf[position] = byte(r)
input = inputBuf
if password {
fmt.Print("*")
} else {
fmt.Print(string(r))
}
position++
reprintFromPosition()
}
}
}