| 19 | 19 |
// Writer is a buffered the writer that updates the terminal. The
|
| 20 | 20 |
// contents of writer will be flushed when Flush is called.
|
| 21 | 21 |
type Writer struct {
|
|
22 |
*bytes.Buffer
|
| 22 | 23 |
out io.Writer
|
| 23 | |
buf bytes.Buffer
|
| 24 | 24 |
fd int
|
| 25 | 25 |
terminal bool
|
| 26 | 26 |
termSize func(int) (int, int, error)
|
|
| 29 | 29 |
// New returns a new Writer with defaults.
|
| 30 | 30 |
func New(out io.Writer) *Writer {
|
| 31 | 31 |
w := &Writer{
|
| 32 | |
out: out,
|
|
32 |
Buffer: new(bytes.Buffer),
|
|
33 |
out: out,
|
| 33 | 34 |
termSize: func(_ int) (int, int, error) {
|
| 34 | 35 |
return -1, -1, ErrNotTTY
|
| 35 | 36 |
},
|
|
| 46 | 47 |
return w
|
| 47 | 48 |
}
|
| 48 | 49 |
|
| 49 | |
// Flush flushes the underlying buffer.
|
| 50 | |
func (w *Writer) Flush(lines int) error {
|
| 51 | |
_, err := w.buf.WriteTo(w.out)
|
| 52 | |
// some terminals interpret 'cursor up 0' as 'cursor up 1'
|
| 53 | |
if err == nil && lines > 0 {
|
| 54 | |
err = w.clearLines(lines)
|
| 55 | |
}
|
| 56 | |
return err
|
| 57 | |
}
|
| 58 | |
|
| 59 | |
// Write appends the contents of p to the underlying buffer.
|
| 60 | |
func (w *Writer) Write(p []byte) (n int, err error) {
|
| 61 | |
return w.buf.Write(p)
|
| 62 | |
}
|
| 63 | |
|
| 64 | |
// WriteString writes string to the underlying buffer.
|
| 65 | |
func (w *Writer) WriteString(s string) (n int, err error) {
|
| 66 | |
return w.buf.WriteString(s)
|
| 67 | |
}
|
| 68 | |
|
| 69 | |
// ReadFrom reads from the provided io.Reader and writes to the
|
| 70 | |
// underlying buffer.
|
| 71 | |
func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) {
|
| 72 | |
return w.buf.ReadFrom(r)
|
| 73 | |
}
|
| 74 | |
|
| 75 | 50 |
// GetTermSize returns WxH of underlying terminal.
|
| 76 | 51 |
func (w *Writer) GetTermSize() (width, height int, err error) {
|
| 77 | 52 |
return w.termSize(w.fd)
|
| 78 | 53 |
}
|
| 79 | 54 |
|
| 80 | |
func (w *Writer) ansiCuuAndEd(n int) error {
|
|
55 |
func ansiCuuAndEd(out io.Writer, n int) error {
|
| 81 | 56 |
buf := make([]byte, 8)
|
| 82 | 57 |
buf = strconv.AppendInt(buf[:copy(buf, escOpen)], int64(n), 10)
|
| 83 | |
_, err := w.buf.Write(append(buf, cuuAndEd...))
|
|
58 |
_, err := out.Write(append(buf, cuuAndEd...))
|
| 84 | 59 |
return err
|
| 85 | 60 |
}
|