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 // * Removed newline/bypass related code. No Windows support
22 // ESC is the ASCII code for escape character
25 // RefreshInterval is the default refresh interval to update the ui
26 var RefreshInterval = 10 * time.Millisecond
28 var overFlowHandled bool
32 // Out is the default output writer for the Writer
35 // FdWriter is a writer with a file descriptor.
36 type FdWriter interface {
41 // 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.
43 // Out is the writer to write to
46 // RefreshInterval is the time the UI sould refresh
47 RefreshInterval time.Duration
56 // New returns a new Writer with defaults
58 termWidth, _ = getTermSize()
60 overFlowHandled = true
64 RefreshInterval: RefreshInterval,
69 // clear the line and move the cursor up
70 var clear = fmt.Sprintf("%c[%dA%c[2K", ESC, 1, ESC)
72 func (w *Writer) clearLines() {
73 fmt.Fprint(w.Out, clear)
76 // 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.
77 // Any incomplete escape sequence at the end is considered complete for formatting purposes.
78 // An error is returned if the contents of the buffer cannot be written to the underlying output stream
79 func (w *Writer) Flush() (err error) {
81 // do nothing if buffer is empty
82 if len(w.buf.Bytes()) == 0 {
87 var currentLine bytes.Buffer
88 for _, b := range w.buf.Bytes() {
92 currentLine.Write([]byte{b})
93 if overFlowHandled && currentLine.Len() > termWidth {
98 _, err = w.Out.Write(w.buf.Bytes())
103 // Start starts the listener in a non-blocking manner
104 func (w *Writer) Start() {
105 w.ticker = time.NewTicker(w.RefreshInterval)
106 w.tdone = make(chan struct{})
107 w.Out.Write([]byte("\n"))
111 // Stop stops the listener that updates the terminal
112 func (w *Writer) Stop() {
117 // Listen listens for updates to the writer's buffer and flushes to the out provided. It blocks the runtime.
118 func (w *Writer) Listen() {
134 // Write save the contents of buf to the writer b. The only errors returned are ones encountered while writing to the underlying buffer.
135 func (w *Writer) Write(buf []byte) (n int, err error) {
138 n, err = w.buf.Write(buf)