go-prompt/input_posix.go

78 lines
1.6 KiB
Go
Raw Normal View History

2017-08-16 03:22:38 +00:00
// +build !windows
2017-07-05 15:59:22 +00:00
package prompt
import (
"syscall"
2018-12-17 17:59:59 +00:00
"github.com/c-bata/go-prompt/internal/term"
2019-04-10 14:10:16 +00:00
"golang.org/x/sys/unix"
2017-07-05 15:59:22 +00:00
)
2018-02-12 10:12:31 +00:00
const maxReadBytes = 1024
// PosixParser is a ConsoleParser implementation for POSIX environment.
2018-02-12 10:12:31 +00:00
type PosixParser struct {
2017-07-05 15:59:22 +00:00
fd int
origTermios syscall.Termios
}
2018-02-13 16:14:22 +00:00
// Setup should be called before starting input
2018-02-12 10:12:31 +00:00
func (t *PosixParser) Setup() error {
2017-08-09 07:20:31 +00:00
// Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
if err := syscall.SetNonblock(t.fd, true); err != nil {
return err
}
2018-12-17 17:59:59 +00:00
if err := term.SetRaw(t.fd); err != nil {
2017-08-09 07:20:31 +00:00
return err
}
return nil
}
2018-02-13 16:14:22 +00:00
// TearDown should be called after stopping input
2018-02-12 10:12:31 +00:00
func (t *PosixParser) TearDown() error {
2017-08-09 07:20:31 +00:00
if err := syscall.SetNonblock(t.fd, false); err != nil {
return err
}
2018-12-17 17:59:59 +00:00
if err := term.Restore(); err != nil {
2017-08-09 07:20:31 +00:00
return err
}
return nil
2017-07-05 15:59:22 +00:00
}
2018-02-13 16:14:22 +00:00
// Read returns byte array.
2018-02-12 10:12:31 +00:00
func (t *PosixParser) Read() ([]byte, error) {
buf := make([]byte, maxReadBytes)
n, err := syscall.Read(t.fd, buf)
2018-02-12 10:12:31 +00:00
if err != nil {
return []byte{}, err
}
return buf[:n], nil
}
2018-02-13 16:14:22 +00:00
// GetWinSize returns WinSize object to represent width and height of terminal.
2018-02-12 10:12:31 +00:00
func (t *PosixParser) GetWinSize() *WinSize {
2019-04-10 14:10:16 +00:00
ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
if err != nil {
panic(err)
2017-07-05 15:59:22 +00:00
}
2017-07-14 01:51:19 +00:00
return &WinSize{
Row: ws.Row,
Col: ws.Col,
}
2017-07-05 15:59:22 +00:00
}
2018-02-12 10:12:31 +00:00
var _ ConsoleParser = &PosixParser{}
2017-07-16 18:53:23 +00:00
// NewStandardInputParser returns ConsoleParser object to read from stdin.
2018-02-12 10:12:31 +00:00
func NewStandardInputParser() *PosixParser {
in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
if err != nil {
panic(err)
}
2018-02-12 10:12:31 +00:00
return &PosixParser{
fd: in,
2017-07-16 18:53:23 +00:00
}
}