only enter raw mode when calling Readline()

This commit is contained in:
Cheney 2015-11-09 11:20:26 +08:00
parent e870ba12fd
commit 5ee706df9b
3 changed files with 27 additions and 6 deletions

View File

@ -37,6 +37,7 @@ var completer = readline.NewPrefixCompleter(
readline.PcItem("install"),
readline.PcItem("test"),
),
readline.PcItem("sleep"),
)
func main() {
@ -101,6 +102,9 @@ func main() {
}()
case line == "bye":
goto exit
case line == "sleep":
log.Println("sleep 4 second")
time.Sleep(4 * time.Second)
case line == "":
default:
log.Println("you said:", strconv.Quote(line))

View File

@ -254,6 +254,9 @@ func (o *Operation) String() (string, error) {
}
func (o *Operation) Runes() ([]rune, error) {
o.t.EnterRawMode()
defer o.t.ExitRawMode()
o.buf.Refresh(nil) // print prompt
o.t.KickRead()
r := <-o.outchan
@ -268,6 +271,9 @@ func (o *Operation) Password(prompt string) ([]byte, error) {
if prompt != "" {
fmt.Fprintf(w, prompt)
}
o.t.EnterRawMode()
defer o.t.ExitRawMode()
b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprint(w, "\r\n")
return b, err

View File

@ -24,13 +24,8 @@ func NewTerminal(cfg *Config) (*Terminal, error) {
if err := cfg.Init(); err != nil {
return nil, err
}
state, err := MakeRaw(StdinFd)
if err != nil {
return nil, err
}
t := &Terminal{
cfg: cfg,
state: state,
kickChan: make(chan struct{}, 1),
outchan: make(chan rune),
stopChan: make(chan struct{}, 1),
@ -40,6 +35,22 @@ func NewTerminal(cfg *Config) (*Terminal, error) {
return t, nil
}
func (t *Terminal) EnterRawMode() (err error) {
t.state, err = MakeRaw(StdinFd)
return err
}
func (t *Terminal) ExitRawMode() (err error) {
if t.state == nil {
return
}
err = Restore(StdinFd, t.state)
if err == nil {
t.state = nil
}
return err
}
func (t *Terminal) Write(b []byte) (int, error) {
return t.cfg.Stdout.Write(b)
}
@ -137,5 +148,5 @@ func (t *Terminal) Close() error {
}
t.stopChan <- struct{}{}
t.wg.Wait()
return Restore(StdinFd, t.state)
return t.ExitRawMode()
}