119 lines
2 KiB
Go
119 lines
2 KiB
Go
package tx
|
|
|
|
import "golang.org/x/term"
|
|
import "surdeus.su/core/cli/aes"
|
|
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, error) {
|
|
if input == nil {
|
|
return nil, ErrNoInputProvided
|
|
}
|
|
|
|
fd := int(input.Fd())
|
|
if !term.IsTerminal(fd) {
|
|
return nil, ErrNotTerminal
|
|
}
|
|
|
|
ret := Terminal{}
|
|
ret.file = input
|
|
ret.input = bufio.NewReader(input)
|
|
ret.fd = fd
|
|
ret.x = term.NewTerminal(input, "")
|
|
|
|
return &ret, nil
|
|
}
|
|
|
|
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 {
|
|
t.DisableAltBuffer()
|
|
if t == nil || 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))
|
|
}
|
|
|
|
func (t *Terminal) MoveCursorRight(n int) {
|
|
t.Printf(aes.MoveCursorRightFormat, n)
|
|
}
|
|
|
|
func (t *Terminal) MoveCursorLeft(n int) {
|
|
t.Printf(aes.MoveCursorLeftFormat, n)
|
|
}
|
|
|
|
func (t *Terminal) MoveCursorUp(n int) {
|
|
t.Printf(aes.MoveCursorUpFormat, n)
|
|
}
|
|
|
|
func (t *Terminal) MoveCursorDown(n int) {
|
|
t.Printf(aes.MoveCursorDownFormat, n)
|
|
}
|
|
|
|
func (t *Terminal) NextLine(n int) {
|
|
t.Printf(
|
|
aes.MoveCursorToBeginOfNextLineDownFormat,
|
|
n,
|
|
)
|
|
}
|
|
|
|
func (t *Terminal) EnableAltBuffer() {
|
|
t.Printf("%s", aes.EnableAltBuffer)
|
|
}
|
|
|
|
func (t *Terminal) DisableAltBuffer() {
|
|
t.Printf("%s", aes.DisableAltBuffer)
|
|
}
|
|
|