forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
reader_windows.go
83 lines (69 loc) · 1.59 KB
/
reader_windows.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
//go:build windows
// +build windows
package prompt
import (
"errors"
"syscall"
"unicode/utf8"
"unsafe"
tty "github.com/mattn/go-tty"
)
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
// WindowsReader is a Reader implementation for Win32 console.
type WindowsReader struct {
tty *tty.TTY
}
// Open should be called before starting input
func (p *WindowsReader) Open() error {
t, err := tty.Open()
if err != nil {
return err
}
p.tty = t
return nil
}
// Close should be called after stopping input
func (p *WindowsReader) Close() error {
return p.tty.Close()
}
// Read returns byte array.
func (p *WindowsReader) Read(buff []byte) (int, error) {
var ev uint32
r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
if r0 == 0 {
return 0, err
}
if ev == 0 {
return 0, errors.New("EAGAIN")
}
r, err := p.tty.ReadRune()
if err != nil {
return 0, err
}
n := utf8.EncodeRune(buff[:], r)
for p.tty.Buffered() && n < len(buff) {
r, err := p.tty.ReadRune()
if err != nil {
break
}
n += utf8.EncodeRune(buff[n:], r)
}
return n, nil
}
// GetWinSize returns WinSize object to represent width and height of terminal.
func (p *WindowsReader) GetWinSize() *WinSize {
w, h, err := p.tty.Size()
if err != nil {
panic(err)
}
return &WinSize{
Row: uint16(h),
Col: uint16(w),
}
}
var _ Reader = &WindowsReader{}
// NewStdinReader returns Reader object to read from stdin.
func NewStdinReader() *WindowsReader {
return &WindowsReader{}
}