github.com/elves/elvish@v0.15.0/pkg/cli/term/reader.go (about)

     1  package term
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  )
     8  
     9  // Reader reads events from the terminal.
    10  type Reader interface {
    11  	// ReadEvent reads a single event from the terminal.
    12  	ReadEvent() (Event, error)
    13  	// ReadRawEvent reads a single raw event from the terminal. The concept of
    14  	// raw events is applicable where terminal events are represented as escape
    15  	// sequences sequences, such as most modern Unix terminal emulators. If
    16  	// the concept is not applicable, such as in the Windows console, it is
    17  	// equivalent to ReadEvent.
    18  	ReadRawEvent() (Event, error)
    19  	// Close releases resources associated with the Reader. Any outstanding
    20  	// ReadEvent or ReadRawEvent call will be aborted, returning ErrStopped.
    21  	Close()
    22  }
    23  
    24  // ErrStopped is returned by Reader when Close is called during a ReadEvent or
    25  // ReadRawEvent method.
    26  var ErrStopped = errors.New("stopped")
    27  
    28  var errTimeout = errors.New("timed out")
    29  
    30  type seqError struct {
    31  	msg string
    32  	seq string
    33  }
    34  
    35  func (err seqError) Error() string {
    36  	return fmt.Sprintf("%s: %q", err.msg, err.seq)
    37  }
    38  
    39  // NewReader creates a new Reader on the given terminal file.
    40  //
    41  // TODO: NewReader should return an error as well. Right now failure to
    42  // initialize Reader panics.
    43  func NewReader(f *os.File) Reader {
    44  	return newReader(f)
    45  }
    46  
    47  // IsReadErrorRecoverable returns whether an error returned by Reader is
    48  // recoverable.
    49  func IsReadErrorRecoverable(err error) bool {
    50  	if _, ok := err.(seqError); ok {
    51  		return true
    52  	}
    53  	return err == ErrStopped || err == errTimeout
    54  }