1 // This is a fork of github.com/gosuri/uilive for NNCP project
2 // * It does not buffer all the writes, but resets the buffer
3 // just only for single latest line. Some terminals have
4 // huge CPU usage if so much data (as copied files progress)
6 // * By default it uses stderr
7 // * By default it uses 10ms refresh period
8 // * defer-s are removed for less CPU usage
9 // * By default it uses stderr
10 // * By default it uses stderr
11 // * By default it uses stderr
12 // * Removed newline/bypass related code. No Windows support
25 // ESC is the ASCII code for escape character
28 // RefreshInterval is the default refresh interval to update the ui
29 var RefreshInterval = 10 * time.Millisecond
31 var overFlowHandled bool
35 // Out is the default output writer for the Writer
38 // FdWriter is a writer with a file descriptor.
39 type FdWriter interface {
44 // Writer is a buffered the writer that updates the terminal. The contents of writer will be flushed on a timed interval or when Flush is called.
46 // Out is the writer to write to
49 // RefreshInterval is the time the UI sould refresh
50 RefreshInterval time.Duration
59 // New returns a new Writer with defaults
61 termWidth, _ = getTermSize()
63 overFlowHandled = true
67 RefreshInterval: RefreshInterval,
72 // clear the line and move the cursor up
73 var clear = fmt.Sprintf("%c[%dA%c[2K", ESC, 1, ESC)
75 func (w *Writer) clearLines() {
76 fmt.Fprint(w.Out, clear)
79 // Flush writes to the out and resets the buffer. It should be called after the last call to Write to ensure that any data buffered in the Writer is written to output.
80 // Any incomplete escape sequence at the end is considered complete for formatting purposes.
81 // An error is returned if the contents of the buffer cannot be written to the underlying output stream
82 func (w *Writer) Flush() (err error) {
84 // do nothing if buffer is empty
85 if len(w.buf.Bytes()) == 0 {
90 var currentLine bytes.Buffer
91 for _, b := range w.buf.Bytes() {
95 currentLine.Write([]byte{b})
96 if overFlowHandled && currentLine.Len() > termWidth {
101 _, err = w.Out.Write(w.buf.Bytes())
106 // Start starts the listener in a non-blocking manner
107 func (w *Writer) Start() {
108 w.ticker = time.NewTicker(w.RefreshInterval)
109 w.tdone = make(chan struct{}, 0)
110 w.Out.Write([]byte("\n"))
114 // Stop stops the listener that updates the terminal
115 func (w *Writer) Stop() {
120 // Listen listens for updates to the writer's buffer and flushes to the out provided. It blocks the runtime.
121 func (w *Writer) Listen() {
137 // Write save the contents of buf to the writer b. The only errors returned are ones encountered while writing to the underlying buffer.
138 func (w *Writer) Write(buf []byte) (n int, err error) {
141 n, err = w.buf.Write(buf)