-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt_posix.go
84 lines (76 loc) · 2.07 KB
/
prompt_posix.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
//go:build !windows
// +build !windows
package prompt
import (
"fmt"
"syscall"
"unsafe"
)
var (
escClearLine = "\x1B[2K"
escClearToEnd = "\x1B[0K"
escMoveUp = "\x1B[1A"
escMoveUpN = "\x1B[%dA"
escMoveDown = "\x1B[1B"
escMoveDownN = "\x1B[%dB"
escMoveLeft = "\x1B[1D"
escMoveRight = "\x1B[1C"
escMoveStart = "\x1B[G"
escMoveToCol = "\x1B[%dG"
escSavePos = "\x1B[s"
escRestorePos = "\x1B[u"
escBold = "\x1B[1m"
escRed = "\x1B[31m"
escReset = "\x1B[0m"
escShow = "\x1B[?25h"
escHide = "\x1B[?25l"
)
func TerminalSize() (int, int, error) {
data := struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}{}
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(syscall.Stdin), syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&data))); err != 0 {
return 0, 0, err
}
return int(data.Row), int(data.Col), nil
}
func MakeRawTerminal(hide bool) (func() error, error) {
if hide {
fmt.Printf(escHide)
}
oldState := syscall.Termios{}
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(syscall.Stdin), syscall.TCGETS, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
if hide {
fmt.Printf(escShow)
}
return nil, err
}
newState := syscall.Termios{}
newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG
// Because we are clearing canonical mode, we need to ensure VMIN & VTIME are
// set to the values we expect. This combination puts things in standard
// "blocking read" mode (see termios(3)).
newState.Cc[syscall.VMIN] = 1
newState.Cc[syscall.VTIME] = 0
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(syscall.Stdin), syscall.TCSETS, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
if hide {
fmt.Printf(escShow)
}
return nil, err
}
return func() error {
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(syscall.Stdin), syscall.TCSETS, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
if hide {
fmt.Printf(escShow)
}
return err
}
if hide {
fmt.Printf(escShow)
}
return nil
}, nil
}