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("install"),
readline.PcItem("test"), readline.PcItem("test"),
), ),
readline.PcItem("sleep"),
) )
func main() { func main() {
@ -101,6 +102,9 @@ func main() {
}() }()
case line == "bye": case line == "bye":
goto exit goto exit
case line == "sleep":
log.Println("sleep 4 second")
time.Sleep(4 * time.Second)
case line == "": case line == "":
default: default:
log.Println("you said:", strconv.Quote(line)) 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) { func (o *Operation) Runes() ([]rune, error) {
o.t.EnterRawMode()
defer o.t.ExitRawMode()
o.buf.Refresh(nil) // print prompt o.buf.Refresh(nil) // print prompt
o.t.KickRead() o.t.KickRead()
r := <-o.outchan r := <-o.outchan
@ -268,6 +271,9 @@ func (o *Operation) Password(prompt string) ([]byte, error) {
if prompt != "" { if prompt != "" {
fmt.Fprintf(w, prompt) fmt.Fprintf(w, prompt)
} }
o.t.EnterRawMode()
defer o.t.ExitRawMode()
b, err := terminal.ReadPassword(int(os.Stdin.Fd())) b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprint(w, "\r\n") fmt.Fprint(w, "\r\n")
return b, err return b, err

View File

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