86 lines
1.4 KiB
Go
86 lines
1.4 KiB
Go
package tx
|
|
|
|
import "golang.org/x/term"
|
|
import "bufio"
|
|
import "fmt"
|
|
import "os"
|
|
|
|
type Terminal struct {
|
|
x *term.Terminal
|
|
file *os.File
|
|
input *bufio.Reader
|
|
fd int
|
|
prevState *term.State
|
|
}
|
|
|
|
func NewTerminal(input *os.File) (*Terminal, bool) {
|
|
if input == nil {
|
|
return nil, false
|
|
}
|
|
|
|
fd := int(input.Fd())
|
|
if !term.IsTerminal(fd) {
|
|
return nil, false
|
|
}
|
|
|
|
|
|
ret := Terminal{}
|
|
ret.file = input
|
|
ret.input = bufio.NewReader(input)
|
|
ret.fd = fd
|
|
ret.x = term.NewTerminal(input, "")
|
|
|
|
return &ret, true
|
|
}
|
|
|
|
func (t *Terminal) MakeRaw() error {
|
|
state, err := term.MakeRaw(t.fd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
t.prevState = state
|
|
return nil
|
|
}
|
|
|
|
func (t *Terminal) Restore() error {
|
|
if t.prevState == nil {
|
|
return nil
|
|
}
|
|
|
|
err := term.Restore(t.fd, t.prevState)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *Terminal) GetSize() (int, int, error) {
|
|
return term.GetSize(t.fd)
|
|
}
|
|
|
|
func (t *Terminal) ReadLine() (string, error) {
|
|
return t.x.ReadLine()
|
|
}
|
|
|
|
func (t *Terminal) ReadKey() (Key, int, error) {
|
|
r, size, err := t.input.ReadRune()
|
|
return Key(r), size, err
|
|
}
|
|
|
|
func (t *Terminal) Write(bts []byte) (int, error) {
|
|
return t.x.Write(bts)
|
|
}
|
|
|
|
func (t *Terminal) Printf(
|
|
format string, v ...any,
|
|
) (int, error) {
|
|
str := fmt.Sprintf(format, v...)
|
|
return t.Write([]byte(str))
|
|
}
|
|
|
|
func (t *Terminal) Print(v ...any) (int, error) {
|
|
str := fmt.Sprint(v...)
|
|
return t.Write([]byte(str))
|
|
}
|