vendor/github.com/charmbracelet/bubbletea/standard_renderer.go

755 lines · 19992 bytes

  1package tea
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"io"
  7	"strings"
  8	"sync"
  9	"time"
 10
 11	"github.com/charmbracelet/x/ansi"
 12	"github.com/muesli/ansi/compressor"
 13)
 14
 15const (
 16	// defaultFramerate specifies the maximum interval at which we should
 17	// update the view.
 18	defaultFPS = 60
 19	maxFPS     = 120
 20)
 21
 22// standardRenderer is a framerate-based terminal renderer, updating the view
 23// at a given framerate to avoid overloading the terminal emulator.
 24//
 25// In cases where very high performance is needed the renderer can be told
 26// to exclude ranges of lines, allowing them to be written to directly.
 27type standardRenderer struct {
 28	mtx *sync.Mutex
 29	out io.Writer
 30
 31	buf                bytes.Buffer
 32	queuedMessageLines []string
 33	framerate          time.Duration
 34	ticker             *time.Ticker
 35	done               chan struct{}
 36	lastRender         string
 37	linesRendered      int
 38	useANSICompressor  bool
 39	once               sync.Once
 40
 41	// cursor visibility state
 42	cursorHidden bool
 43
 44	// essentially whether or not we're using the full size of the terminal
 45	altScreenActive bool
 46
 47	// whether or not we're currently using bracketed paste
 48	bpActive bool
 49
 50	// reportingFocus whether reporting focus events is enabled
 51	reportingFocus bool
 52
 53	// renderer dimensions; usually the size of the window
 54	width  int
 55	height int
 56
 57	// lines explicitly set not to render
 58	ignoreLines map[int]struct{}
 59}
 60
 61// newRenderer creates a new renderer. Normally you'll want to initialize it
 62// with os.Stdout as the first argument.
 63func newRenderer(out io.Writer, useANSICompressor bool, fps int) renderer {
 64	if fps < 1 {
 65		fps = defaultFPS
 66	} else if fps > maxFPS {
 67		fps = maxFPS
 68	}
 69	r := &standardRenderer{
 70		out:                out,
 71		mtx:                &sync.Mutex{},
 72		done:               make(chan struct{}),
 73		framerate:          time.Second / time.Duration(fps),
 74		useANSICompressor:  useANSICompressor,
 75		queuedMessageLines: []string{},
 76	}
 77	if r.useANSICompressor {
 78		r.out = &compressor.Writer{Forward: out}
 79	}
 80	return r
 81}
 82
 83// start starts the renderer.
 84func (r *standardRenderer) start() {
 85	if r.ticker == nil {
 86		r.ticker = time.NewTicker(r.framerate)
 87	} else {
 88		// If the ticker already exists, it has been stopped and we need to
 89		// reset it.
 90		r.ticker.Reset(r.framerate)
 91	}
 92
 93	// Since the renderer can be restarted after a stop, we need to reset
 94	// the done channel and its corresponding sync.Once.
 95	r.once = sync.Once{}
 96
 97	go r.listen()
 98}
 99
100// stop permanently halts the renderer, rendering the final frame.
101func (r *standardRenderer) stop() {
102	// Stop the renderer before acquiring the mutex to avoid a deadlock.
103	r.once.Do(func() {
104		r.done <- struct{}{}
105	})
106
107	// flush locks the mutex
108	r.flush()
109
110	r.mtx.Lock()
111	defer r.mtx.Unlock()
112
113	r.execute(ansi.EraseEntireLine)
114	// Move the cursor back to the beginning of the line
115	r.execute("\r")
116
117	if r.useANSICompressor {
118		if w, ok := r.out.(io.WriteCloser); ok {
119			_ = w.Close()
120		}
121	}
122}
123
124// execute writes a sequence to the terminal.
125func (r *standardRenderer) execute(seq string) {
126	_, _ = io.WriteString(r.out, seq)
127}
128
129// kill halts the renderer. The final frame will not be rendered.
130func (r *standardRenderer) kill() {
131	// Stop the renderer before acquiring the mutex to avoid a deadlock.
132	r.once.Do(func() {
133		r.done <- struct{}{}
134	})
135
136	r.mtx.Lock()
137	defer r.mtx.Unlock()
138
139	r.execute(ansi.EraseEntireLine)
140	// Move the cursor back to the beginning of the line
141	r.execute("\r")
142}
143
144// listen waits for ticks on the ticker, or a signal to stop the renderer.
145func (r *standardRenderer) listen() {
146	for {
147		select {
148		case <-r.done:
149			r.ticker.Stop()
150			return
151
152		case <-r.ticker.C:
153			r.flush()
154		}
155	}
156}
157
158// flush renders the buffer.
159func (r *standardRenderer) flush() {
160	r.mtx.Lock()
161	defer r.mtx.Unlock()
162
163	if r.buf.Len() == 0 || r.buf.String() == r.lastRender {
164		// Nothing to do
165		return
166	}
167
168	// Output buffer
169	buf := &bytes.Buffer{}
170
171	newLines := strings.Split(r.buf.String(), "\n")
172
173	// If we know the output's height, we can use it to determine how many
174	// lines we can render. We drop lines from the top of the render buffer if
175	// necessary, as we can't navigate the cursor into the terminal's scrollback
176	// buffer.
177	if r.height > 0 && len(newLines) > r.height {
178		newLines = newLines[len(newLines)-r.height:]
179	}
180
181	numLinesThisFlush := len(newLines)
182	oldLines := strings.Split(r.lastRender, "\n")
183	skipLines := make(map[int]struct{})
184	flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive
185
186	// Clear any lines we painted in the last render.
187	if r.linesRendered > 0 {
188		for i := r.linesRendered - 1; i > 0; i-- {
189			// if we are clearing queued messages, we want to clear all lines, since
190			// printing messages allows for native terminal word-wrap, we
191			// don't have control over the queued lines
192			if flushQueuedMessages {
193				buf.WriteString(ansi.EraseEntireLine)
194			} else if (len(newLines) <= len(oldLines)) && (len(newLines) > i && len(oldLines) > i) && (newLines[i] == oldLines[i]) {
195				// If the number of lines we want to render hasn't increased and
196				// new line is the same as the old line we can skip rendering for
197				// this line as a performance optimization.
198				skipLines[i] = struct{}{}
199			} else if _, exists := r.ignoreLines[i]; !exists {
200				buf.WriteString(ansi.EraseEntireLine)
201			}
202
203			buf.WriteString(ansi.CursorUp1)
204		}
205
206		if _, exists := r.ignoreLines[0]; !exists {
207			// We need to return to the start of the line here to properly
208			// erase it. Going back the entire width of the terminal will
209			// usually be farther than we need to go, but terminal emulators
210			// will stop the cursor at the start of the line as a rule.
211			//
212			// We use this sequence in particular because it's part of the ANSI
213			// standard (whereas others are proprietary to, say, VT100/VT52).
214			// If cursor previous line (ESC[ + <n> + F) were better supported
215			// we could use that above to eliminate this step.
216			buf.WriteString(ansi.CursorLeft(r.width))
217			buf.WriteString(ansi.EraseEntireLine)
218		}
219	}
220
221	// Merge the set of lines we're skipping as a rendering optimization with
222	// the set of lines we've explicitly asked the renderer to ignore.
223	for k, v := range r.ignoreLines {
224		skipLines[k] = v
225	}
226
227	if flushQueuedMessages {
228		// Dump the lines we've queued up for printing
229		for _, line := range r.queuedMessageLines {
230			_, _ = buf.WriteString(line)
231			_, _ = buf.WriteString("\r\n")
232		}
233		// clear the queued message lines
234		r.queuedMessageLines = []string{}
235	}
236
237	// Paint new lines
238	for i := 0; i < len(newLines); i++ {
239		if _, skip := skipLines[i]; skip {
240			// Unless this is the last line, move the cursor down.
241			if i < len(newLines)-1 {
242				buf.WriteString(ansi.CursorDown1)
243			}
244		} else {
245			if i == 0 && r.lastRender == "" {
246				// On first render, reset the cursor to the start of the line
247				// before writing anything.
248				buf.WriteByte('\r')
249			}
250
251			line := newLines[i]
252
253			// Truncate lines wider than the width of the window to avoid
254			// wrapping, which will mess up rendering. If we don't have the
255			// width of the window this will be ignored.
256			//
257			// Note that on Windows we only get the width of the window on
258			// program initialization, so after a resize this won't perform
259			// correctly (signal SIGWINCH is not supported on Windows).
260			if r.width > 0 {
261				line = ansi.Truncate(line, r.width, "")
262			}
263
264			_, _ = buf.WriteString(line)
265
266			if i < len(newLines)-1 {
267				_, _ = buf.WriteString("\r\n")
268			}
269		}
270	}
271	r.linesRendered = numLinesThisFlush
272
273	// Make sure the cursor is at the start of the last line to keep rendering
274	// behavior consistent.
275	if r.altScreenActive {
276		// This case fixes a bug in macOS terminal. In other terminals the
277		// other case seems to do the job regardless of whether or not we're
278		// using the full terminal window.
279		buf.WriteString(ansi.MoveCursor(r.linesRendered, 0))
280	} else {
281		buf.WriteString(ansi.CursorLeft(r.width))
282	}
283
284	_, _ = r.out.Write(buf.Bytes())
285	r.lastRender = r.buf.String()
286	r.buf.Reset()
287}
288
289// write writes to the internal buffer. The buffer will be outputted via the
290// ticker which calls flush().
291func (r *standardRenderer) write(s string) {
292	r.mtx.Lock()
293	defer r.mtx.Unlock()
294	r.buf.Reset()
295
296	// If an empty string was passed we should clear existing output and
297	// rendering nothing. Rather than introduce additional state to manage
298	// this, we render a single space as a simple (albeit less correct)
299	// solution.
300	if s == "" {
301		s = " "
302	}
303
304	_, _ = r.buf.WriteString(s)
305}
306
307func (r *standardRenderer) repaint() {
308	r.lastRender = ""
309}
310
311func (r *standardRenderer) clearScreen() {
312	r.mtx.Lock()
313	defer r.mtx.Unlock()
314
315	r.execute(ansi.EraseEntireDisplay)
316	r.execute(ansi.MoveCursorOrigin)
317
318	r.repaint()
319}
320
321func (r *standardRenderer) altScreen() bool {
322	r.mtx.Lock()
323	defer r.mtx.Unlock()
324
325	return r.altScreenActive
326}
327
328func (r *standardRenderer) enterAltScreen() {
329	r.mtx.Lock()
330	defer r.mtx.Unlock()
331
332	if r.altScreenActive {
333		return
334	}
335
336	r.altScreenActive = true
337	r.execute(ansi.EnableAltScreenBuffer)
338
339	// Ensure that the terminal is cleared, even when it doesn't support
340	// alt screen (or alt screen support is disabled, like GNU screen by
341	// default).
342	//
343	// Note: we can't use r.clearScreen() here because the mutex is already
344	// locked.
345	r.execute(ansi.EraseEntireDisplay)
346	r.execute(ansi.MoveCursorOrigin)
347
348	// cmd.exe and other terminals keep separate cursor states for the AltScreen
349	// and the main buffer. We have to explicitly reset the cursor visibility
350	// whenever we enter AltScreen.
351	if r.cursorHidden {
352		r.execute(ansi.HideCursor)
353	} else {
354		r.execute(ansi.ShowCursor)
355	}
356
357	r.repaint()
358}
359
360func (r *standardRenderer) exitAltScreen() {
361	r.mtx.Lock()
362	defer r.mtx.Unlock()
363
364	if !r.altScreenActive {
365		return
366	}
367
368	r.altScreenActive = false
369	r.execute(ansi.DisableAltScreenBuffer)
370
371	// cmd.exe and other terminals keep separate cursor states for the AltScreen
372	// and the main buffer. We have to explicitly reset the cursor visibility
373	// whenever we exit AltScreen.
374	if r.cursorHidden {
375		r.execute(ansi.HideCursor)
376	} else {
377		r.execute(ansi.ShowCursor)
378	}
379
380	r.repaint()
381}
382
383func (r *standardRenderer) showCursor() {
384	r.mtx.Lock()
385	defer r.mtx.Unlock()
386
387	r.cursorHidden = false
388	r.execute(ansi.ShowCursor)
389}
390
391func (r *standardRenderer) hideCursor() {
392	r.mtx.Lock()
393	defer r.mtx.Unlock()
394
395	r.cursorHidden = true
396	r.execute(ansi.HideCursor)
397}
398
399func (r *standardRenderer) enableMouseCellMotion() {
400	r.mtx.Lock()
401	defer r.mtx.Unlock()
402
403	r.execute(ansi.EnableMouseCellMotion)
404}
405
406func (r *standardRenderer) disableMouseCellMotion() {
407	r.mtx.Lock()
408	defer r.mtx.Unlock()
409
410	r.execute(ansi.DisableMouseCellMotion)
411}
412
413func (r *standardRenderer) enableMouseAllMotion() {
414	r.mtx.Lock()
415	defer r.mtx.Unlock()
416
417	r.execute(ansi.EnableMouseAllMotion)
418}
419
420func (r *standardRenderer) disableMouseAllMotion() {
421	r.mtx.Lock()
422	defer r.mtx.Unlock()
423
424	r.execute(ansi.DisableMouseAllMotion)
425}
426
427func (r *standardRenderer) enableMouseSGRMode() {
428	r.mtx.Lock()
429	defer r.mtx.Unlock()
430
431	r.execute(ansi.EnableMouseSgrExt)
432}
433
434func (r *standardRenderer) disableMouseSGRMode() {
435	r.mtx.Lock()
436	defer r.mtx.Unlock()
437
438	r.execute(ansi.DisableMouseSgrExt)
439}
440
441func (r *standardRenderer) enableBracketedPaste() {
442	r.mtx.Lock()
443	defer r.mtx.Unlock()
444
445	r.execute(ansi.EnableBracketedPaste)
446	r.bpActive = true
447}
448
449func (r *standardRenderer) disableBracketedPaste() {
450	r.mtx.Lock()
451	defer r.mtx.Unlock()
452
453	r.execute(ansi.DisableBracketedPaste)
454	r.bpActive = false
455}
456
457func (r *standardRenderer) bracketedPasteActive() bool {
458	r.mtx.Lock()
459	defer r.mtx.Unlock()
460
461	return r.bpActive
462}
463
464func (r *standardRenderer) enableReportFocus() {
465	r.mtx.Lock()
466	defer r.mtx.Unlock()
467
468	r.execute(ansi.EnableReportFocus)
469	r.reportingFocus = true
470}
471
472func (r *standardRenderer) disableReportFocus() {
473	r.mtx.Lock()
474	defer r.mtx.Unlock()
475
476	r.execute(ansi.DisableReportFocus)
477	r.reportingFocus = false
478}
479
480func (r *standardRenderer) reportFocus() bool {
481	r.mtx.Lock()
482	defer r.mtx.Unlock()
483
484	return r.reportingFocus
485}
486
487// setWindowTitle sets the terminal window title.
488func (r *standardRenderer) setWindowTitle(title string) {
489	r.execute(ansi.SetWindowTitle(title))
490}
491
492// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea
493// renderer.
494func (r *standardRenderer) setIgnoredLines(from int, to int) {
495	// Lock if we're going to be clearing some lines since we don't want
496	// anything jacking our cursor.
497	if r.linesRendered > 0 {
498		r.mtx.Lock()
499		defer r.mtx.Unlock()
500	}
501
502	if r.ignoreLines == nil {
503		r.ignoreLines = make(map[int]struct{})
504	}
505	for i := from; i < to; i++ {
506		r.ignoreLines[i] = struct{}{}
507	}
508
509	// Erase ignored lines
510	if r.linesRendered > 0 {
511		buf := &bytes.Buffer{}
512
513		for i := r.linesRendered - 1; i >= 0; i-- {
514			if _, exists := r.ignoreLines[i]; exists {
515				buf.WriteString(ansi.EraseEntireLine)
516			}
517			buf.WriteString(ansi.CursorUp1)
518		}
519		buf.WriteString(ansi.MoveCursor(r.linesRendered, 0)) // put cursor back
520		_, _ = r.out.Write(buf.Bytes())
521	}
522}
523
524// clearIgnoredLines returns control of any ignored lines to the standard
525// Bubble Tea renderer. That is, any lines previously set to be ignored can be
526// rendered to again.
527func (r *standardRenderer) clearIgnoredLines() {
528	r.ignoreLines = nil
529}
530
531// insertTop effectively scrolls up. It inserts lines at the top of a given
532// area designated to be a scrollable region, pushing everything else down.
533// This is roughly how ncurses does it.
534//
535// To call this function use command ScrollUp().
536//
537// For this to work renderer.ignoreLines must be set to ignore the scrollable
538// region since we are bypassing the normal Bubble Tea renderer here.
539//
540// Because this method relies on the terminal dimensions, it's only valid for
541// full-window applications (generally those that use the alternate screen
542// buffer).
543//
544// This method bypasses the normal rendering buffer and is philosophically
545// different than the normal way we approach rendering in Bubble Tea. It's for
546// use in high-performance rendering, such as a pager that could potentially
547// be rendering very complicated ansi. In cases where the content is simpler
548// standard Bubble Tea rendering should suffice.
549func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {
550	r.mtx.Lock()
551	defer r.mtx.Unlock()
552
553	buf := &bytes.Buffer{}
554
555	buf.WriteString(ansi.SetScrollingRegion(topBoundary, bottomBoundary))
556	buf.WriteString(ansi.MoveCursor(topBoundary, 0))
557	buf.WriteString(ansi.InsertLine(len(lines)))
558	_, _ = buf.WriteString(strings.Join(lines, "\r\n"))
559	buf.WriteString(ansi.SetScrollingRegion(0, r.height))
560
561	// Move cursor back to where the main rendering routine expects it to be
562	buf.WriteString(ansi.MoveCursor(r.linesRendered, 0))
563
564	_, _ = r.out.Write(buf.Bytes())
565}
566
567// insertBottom effectively scrolls down. It inserts lines at the bottom of
568// a given area designated to be a scrollable region, pushing everything else
569// up. This is roughly how ncurses does it.
570//
571// To call this function use the command ScrollDown().
572//
573// See note in insertTop() for caveats, how this function only makes sense for
574// full-window applications, and how it differs from the normal way we do
575// rendering in Bubble Tea.
576func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {
577	r.mtx.Lock()
578	defer r.mtx.Unlock()
579
580	buf := &bytes.Buffer{}
581
582	buf.WriteString(ansi.SetScrollingRegion(topBoundary, bottomBoundary))
583	buf.WriteString(ansi.MoveCursor(bottomBoundary, 0))
584	_, _ = buf.WriteString("\r\n" + strings.Join(lines, "\r\n"))
585	buf.WriteString(ansi.SetScrollingRegion(0, r.height))
586
587	// Move cursor back to where the main rendering routine expects it to be
588	buf.WriteString(ansi.MoveCursor(r.linesRendered, 0))
589
590	_, _ = r.out.Write(buf.Bytes())
591}
592
593// handleMessages handles internal messages for the renderer.
594func (r *standardRenderer) handleMessages(msg Msg) {
595	switch msg := msg.(type) {
596	case repaintMsg:
597		// Force a repaint by clearing the render cache as we slide into a
598		// render.
599		r.mtx.Lock()
600		r.repaint()
601		r.mtx.Unlock()
602
603	case WindowSizeMsg:
604		r.mtx.Lock()
605		r.width = msg.Width
606		r.height = msg.Height
607		r.repaint()
608		r.mtx.Unlock()
609
610	case clearScrollAreaMsg:
611		r.clearIgnoredLines()
612
613		// Force a repaint on the area where the scrollable stuff was in this
614		// update cycle
615		r.mtx.Lock()
616		r.repaint()
617		r.mtx.Unlock()
618
619	case syncScrollAreaMsg:
620		// Re-render scrolling area
621		r.clearIgnoredLines()
622		r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary)
623		r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)
624
625		// Force non-scrolling stuff to repaint in this update cycle
626		r.mtx.Lock()
627		r.repaint()
628		r.mtx.Unlock()
629
630	case scrollUpMsg:
631		r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)
632
633	case scrollDownMsg:
634		r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)
635
636	case printLineMessage:
637		if !r.altScreenActive {
638			lines := strings.Split(msg.messageBody, "\n")
639			r.mtx.Lock()
640			r.queuedMessageLines = append(r.queuedMessageLines, lines...)
641			r.repaint()
642			r.mtx.Unlock()
643		}
644	}
645}
646
647// HIGH-PERFORMANCE RENDERING STUFF
648
649type syncScrollAreaMsg struct {
650	lines          []string
651	topBoundary    int
652	bottomBoundary int
653}
654
655// SyncScrollArea performs a paint of the entire region designated to be the
656// scrollable area. This is required to initialize the scrollable region and
657// should also be called on resize (WindowSizeMsg).
658//
659// For high-performance, scroll-based rendering only.
660func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {
661	return func() Msg {
662		return syncScrollAreaMsg{
663			lines:          lines,
664			topBoundary:    topBoundary,
665			bottomBoundary: bottomBoundary,
666		}
667	}
668}
669
670type clearScrollAreaMsg struct{}
671
672// ClearScrollArea deallocates the scrollable region and returns the control of
673// those lines to the main rendering routine.
674//
675// For high-performance, scroll-based rendering only.
676func ClearScrollArea() Msg {
677	return clearScrollAreaMsg{}
678}
679
680type scrollUpMsg struct {
681	lines          []string
682	topBoundary    int
683	bottomBoundary int
684}
685
686// ScrollUp adds lines to the top of the scrollable region, pushing existing
687// lines below down. Lines that are pushed out the scrollable region disappear
688// from view.
689//
690// For high-performance, scroll-based rendering only.
691func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {
692	return func() Msg {
693		return scrollUpMsg{
694			lines:          newLines,
695			topBoundary:    topBoundary,
696			bottomBoundary: bottomBoundary,
697		}
698	}
699}
700
701type scrollDownMsg struct {
702	lines          []string
703	topBoundary    int
704	bottomBoundary int
705}
706
707// ScrollDown adds lines to the bottom of the scrollable region, pushing
708// existing lines above up. Lines that are pushed out of the scrollable region
709// disappear from view.
710//
711// For high-performance, scroll-based rendering only.
712func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {
713	return func() Msg {
714		return scrollDownMsg{
715			lines:          newLines,
716			topBoundary:    topBoundary,
717			bottomBoundary: bottomBoundary,
718		}
719	}
720}
721
722type printLineMessage struct {
723	messageBody string
724}
725
726// Println prints above the Program. This output is unmanaged by the program and
727// will persist across renders by the Program.
728//
729// Unlike fmt.Println (but similar to log.Println) the message will be print on
730// its own line.
731//
732// If the altscreen is active no output will be printed.
733func Println(args ...interface{}) Cmd {
734	return func() Msg {
735		return printLineMessage{
736			messageBody: fmt.Sprint(args...),
737		}
738	}
739}
740
741// Printf prints above the Program. It takes a format template followed by
742// values similar to fmt.Printf. This output is unmanaged by the program and
743// will persist across renders by the Program.
744//
745// Unlike fmt.Printf (but similar to log.Printf) the message will be print on
746// its own line.
747//
748// If the altscreen is active no output will be printed.
749func Printf(template string, args ...interface{}) Cmd {
750	return func() Msg {
751		return printLineMessage{
752			messageBody: fmt.Sprintf(template, args...),
753		}
754	}
755}