readline/terminal.go

96 lines
1.4 KiB
Go
Raw Normal View History

2015-09-20 18:14:29 +03:00
package readline
import (
"bufio"
"fmt"
"os"
"sync/atomic"
"syscall"
"golang.org/x/crypto/ssh/terminal"
)
type Terminal struct {
2015-09-22 13:16:24 +03:00
cfg *Config
2015-09-20 18:14:29 +03:00
state *terminal.State
outchan chan rune
closed int64
}
2015-09-22 13:16:24 +03:00
func NewTerminal(cfg *Config) (*Terminal, error) {
2015-09-20 18:14:29 +03:00
state, err := MakeRaw(syscall.Stdin)
if err != nil {
return nil, err
}
t := &Terminal{
2015-09-22 13:16:24 +03:00
cfg: cfg,
2015-09-20 18:14:29 +03:00
state: state,
outchan: make(chan rune),
}
go t.ioloop()
return t, nil
}
func (t *Terminal) Write(b []byte) (int, error) {
return os.Stdout.Write(b)
}
func (t *Terminal) Print(s string) {
fmt.Fprintf(os.Stdout, "%s", s)
}
func (t *Terminal) PrintRune(r rune) {
fmt.Fprintf(os.Stdout, "%c", r)
}
2015-09-22 13:16:24 +03:00
func (t *Terminal) Readline() *Operation {
return NewOperation(t, t.cfg)
2015-09-20 18:14:29 +03:00
}
func (t *Terminal) ReadRune() rune {
return <-t.outchan
}
func (t *Terminal) ioloop() {
buf := bufio.NewReader(os.Stdin)
isEscape := false
isEscapeEx := false
2015-09-20 18:14:29 +03:00
for {
r, _, err := buf.ReadRune()
if err != nil {
break
}
if isEscape {
isEscape = false
2015-09-23 06:46:56 +03:00
if r == CharEscapeEx {
isEscapeEx = true
continue
}
r = escapeKey(r)
} else if isEscapeEx {
isEscapeEx = false
r = escapeExKey(r)
2015-09-20 18:14:29 +03:00
}
switch r {
2015-09-23 06:46:56 +03:00
case CharInterrupt:
2015-09-20 18:14:29 +03:00
t.outchan <- r
goto exit
2015-09-23 06:46:56 +03:00
case CharEsc:
isEscape = true
2015-09-20 18:14:29 +03:00
default:
2015-09-23 06:46:56 +03:00
t.outchan <- r
2015-09-20 18:14:29 +03:00
}
}
exit:
}
func (t *Terminal) Close() error {
if atomic.SwapInt64(&t.closed, 1) != 0 {
return nil
}
return Restore(syscall.Stdin, t.state)
}