Skip to content
Myr

cursed_renderer.go

This file

Path

cursed_renderer.go

947 lines · 29.0 KiB · Go

Last changed by

feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626

History of this file

Take it

1package tea23import (4	"bytes"5	"fmt"6	"image/color"7	"io"8	"runtime"9	"strings"10	"sync"1112	"github.com/charmbracelet/colorprofile"13	uv "github.com/charmbracelet/ultraviolet"14	"github.com/charmbracelet/x/ansi"15	"github.com/lucasb-eyer/go-colorful"16)1718type cursedRenderer struct {19	w             io.Writer20	buf           bytes.Buffer // updates buffer to be flushed to [w]21	scr           *uv.TerminalRenderer22	cellbuf       uv.ScreenBuffer23	lastView      *View24	env           []string25	term          string // the terminal type $TERM26	width, height int27	mu            sync.Mutex28	profile       colorprofile.Profile29	logger        uv.Logger30	view          View31	hardTabs      bool // whether to use hard tabs to optimize cursor movements32	backspace     bool // whether to use backspace to optimize cursor movements33	mapnl         bool34	syncdUpdates  bool // whether to use synchronized output mode for updates35	starting      bool // indicates whether the renderer is starting after being stopped36	pendingErase  bool // an scr.Erase() is pending and hasn't been drained by flush yet37	noInput       bool // whether input is disabled, in which case keyboard enhancement queries are pointless38}3940var _ renderer = &cursedRenderer{}4142func newCursedRenderer(w io.Writer, env []string, width, height int) (s *cursedRenderer) {43	s = new(cursedRenderer)44	s.w = w45	s.env = env46	s.term = uv.Environ(env).Getenv("TERM")47	s.width, s.height = width, height // This needs to happen before [cursedRenderer.reset].48	s.cellbuf = uv.NewScreenBuffer(s.width, s.height)49	reset(s)50	return51}5253// setLogger sets the logger for the renderer.54func (s *cursedRenderer) setLogger(logger uv.Logger) {55	s.mu.Lock()56	s.logger = logger57	s.mu.Unlock()58}5960// setNoInput disables keyboard enhancement requests. When the program runs61// without input, the terminal's response to a keyboard enhancement query62// would arrive after the program has exited and leak into the shell.63func (s *cursedRenderer) setNoInput(noInput bool) {64	s.noInput = noInput65}6667// resetKeyboardEnhancements writes the sequences that reset keyboard68// enhancement protocols when switching between the main and alt screens.69// modifyOtherKeys has no stack, so it is reset in place; the Kitty keyboard70// stack is popped, but only if we previously pushed an entry (i.e. this is71// not the first render). With input disabled the keyboard protocol is never72// touched.73func (s *cursedRenderer) resetKeyboardEnhancements(buf *bytes.Buffer) {74	if s.noInput {75		return76	}77	_, _ = buf.WriteString(ansi.ResetModifyOtherKeys)78	if s.lastView != nil {79		_, _ = buf.WriteString(ansi.PopKittyKeyboard(1))80	}81}8283// setOptimizations sets the cursor movement optimizations.84func (s *cursedRenderer) setOptimizations(hardTabs, backspace, mapnl bool) {85	s.mu.Lock()86	s.hardTabs = hardTabs87	s.backspace = backspace88	s.mapnl = mapnl89	if s.hardTabs {90		s.scr.SetTabStops(s.width)91	} else {92		s.scr.SetTabStops(-1)93	}94	s.scr.SetBackspace(s.backspace)95	s.scr.SetMapNewline(s.mapnl)96	s.mu.Unlock()97}9899// start implements renderer.100func (s *cursedRenderer) start() {101	s.mu.Lock()102	defer s.mu.Unlock()103104	// Mark that we're starting. This is used to restore some state when105	// starting the renderer again after it was stopped.106	s.starting = true107108	if s.lastView == nil {109		return110	}111112	if s.lastView.AltScreen {113		enableAltScreen(s, true, true)114	}115	enableTextCursor(s, s.lastView.Cursor != nil)116	if s.lastView.Cursor != nil {117		if s.lastView.Cursor.Color != nil {118			col, ok := colorful.MakeColor(s.lastView.Cursor.Color)119			if ok {120				_, _ = s.scr.WriteString(ansi.SetCursorColor(col.Hex()))121			}122		}123		curStyle := encodeCursorStyle(s.lastView.Cursor.Shape, s.lastView.Cursor.Blink)124		if curStyle != 0 && curStyle != 1 {125			_, _ = s.scr.WriteString(ansi.SetCursorStyle(curStyle))126		}127	}128	if s.lastView.ForegroundColor != nil {129		col, ok := colorful.MakeColor(s.lastView.ForegroundColor)130		if ok {131			_, _ = s.scr.WriteString(ansi.SetForegroundColor(col.Hex()))132		}133	}134	if s.lastView.BackgroundColor != nil {135		col, ok := colorful.MakeColor(s.lastView.BackgroundColor)136		if ok {137			_, _ = s.scr.WriteString(ansi.SetBackgroundColor(col.Hex()))138		}139	}140	if !s.lastView.DisableBracketedPasteMode {141		_, _ = s.scr.WriteString(ansi.SetModeBracketedPaste)142	}143	if s.lastView.ReportFocus {144		_, _ = s.scr.WriteString(ansi.SetModeFocusEvent)145	}146	switch s.lastView.MouseMode {147	case MouseModeNone:148	case MouseModeCellMotion:149		_, _ = s.scr.WriteString(ansi.SetModeMouseButtonEvent + ansi.SetModeMouseExtSgr)150	case MouseModeAllMotion:151		_, _ = s.scr.WriteString(ansi.SetModeMouseAnyEvent + ansi.SetModeMouseExtSgr)152	}153	if s.lastView.WindowTitle != "" {154		_, _ = s.scr.WriteString(ansi.SetWindowTitle(s.lastView.WindowTitle))155	}156	if s.lastView.ProgressBar != nil {157		setProgressBar(s, s.lastView.ProgressBar)158	}159	if s.lastView.ProgramStatus != nil {160		setProgramStatus(s, nil, s.lastView.ProgramStatus)161	}162	if !s.noInput {163		// Enable modifyOtherKeys and Kitty keyboard protocol.164		// Both can coexist; terminals ignore what they don't support.165		_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)166167		kittyFlags := keyboardEnhancementsFlags(s.lastView.KeyboardEnhancements)168		// The entry was popped when the renderer was stopped, so push a fresh169		// one for the screen we're about to restore.170		_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))171	}172}173174// close implements renderer.175func (s *cursedRenderer) close() (err error) {176	s.mu.Lock()177	defer s.mu.Unlock()178179	// Exit the altScreen and show cursor before closing. It's important that180	// we don't change the [cursedRenderer] altScreen and cursorHidden states181	// so that we can restore them when we start the renderer again. This is182	// used when the user suspends the program and then resumes it.183	if lv := s.lastView; lv != nil { //nolint:nestif184		// NOTE: The Kitty keyboard specs specify that the terminal should have185		// two registries for the main and alt screens. We disable keyboard186		// enhancements whenever we enter/exit alt screen mode in187		// [cursedRenderer.flush].188		// Here, we pop the keyboard protocol of the last screen used189		// assuming the other screen is already popped when we switched190		// screens. With input disabled we never pushed an entry, so there is191		// nothing to pop.192		if !s.noInput {193			_, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)194			_, _ = s.buf.WriteString(ansi.PopKittyKeyboard(1))195		}196197		// Go to the bottom of the screen.198		// We need to go to the bottom of the screen regardless of whether199		// we're in alt screen mode or not to avoid leaving the cursor in the200		// middle in terminals that don't support alt screen mode.201		s.scr.MoveTo(0, s.cellbuf.Height()-1)202		_ = s.scr.Flush() // we need to flush to write the cursor movement203		if lv.AltScreen {204			enableAltScreen(s, false, true)205		} else {206			_, _ = s.scr.WriteString(ansi.EraseScreenBelow)207		}208		if lv.Cursor == nil {209			enableTextCursor(s, true)210		}211		if !lv.DisableBracketedPasteMode {212			_, _ = s.scr.WriteString(ansi.ResetModeBracketedPaste)213		}214		if lv.ReportFocus {215			_, _ = s.scr.WriteString(ansi.ResetModeFocusEvent)216		}217		switch lv.MouseMode {218		case MouseModeNone:219		case MouseModeCellMotion, MouseModeAllMotion:220			_, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent +221				ansi.ResetModeMouseAnyEvent +222				ansi.ResetModeMouseExtSgr)223		}224225		if lv.WindowTitle != "" {226			// Clear the window title if it was set.227			_, _ = s.scr.WriteString(ansi.SetWindowTitle(""))228		}229		if lc := lv.Cursor; lc != nil {230			curShape := encodeCursorStyle(lc.Shape, lc.Blink)231			if curShape != 0 && curShape != 1 {232				// Reset the cursor style to default if it was set to something other233				// blinking block.234				_, _ = s.scr.WriteString(ansi.SetCursorStyle(0))235			}236237			if lc.Color != nil {238				_, _ = s.scr.WriteString(ansi.ResetCursorColor)239			}240		}241242		if lv.BackgroundColor != nil {243			_, _ = s.scr.WriteString(ansi.ResetBackgroundColor)244		}245		if lv.ForegroundColor != nil {246			_, _ = s.scr.WriteString(ansi.ResetForegroundColor)247		}248		if lv.ProgressBar != nil && lv.ProgressBar.State != ProgressBarNone {249			_, _ = s.scr.WriteString(ansi.ResetProgressBar)250		}251		// Unlike the progress bar, the program status is left in place: done252		// and error reports should outlive the program, and terminals drop253		// working and blocked records when the process exits.254	}255256	if s.cellbuf.Method == ansi.GraphemeWidth {257		// Make sure to turn off Unicode mode (2027)258		_, _ = s.scr.WriteString(ansi.ResetModeUnicodeCore)259	}260261	if err := s.scr.Flush(); err != nil {262		return fmt.Errorf("bubbletea: error closing screen writer: %w", err)263	}264265	if s.buf.Len() > 0 {266		if s.logger != nil {267			s.logger.Printf("output: %q", s.buf.String())268		}269		if _, err := io.Copy(s.w, &s.buf); err != nil {270			return fmt.Errorf("bubbletea: error writing to screen: %w", err)271		}272		s.buf.Reset()273	}274275	x, y := s.scr.Position()276277	// We want to clear the renderer state but not the cursor position. This is278	// because we might be putting the tea process in the background, run some279	// other process, and then return to the tea process. We want to keep the280	// cursor position so that we can continue where we left off.281	reset(s)282	s.scr.SetPosition(x, y)283284	return nil285}286287// writeString implements renderer.288func (s *cursedRenderer) writeString(str string) (int, error) {289	s.mu.Lock()290	defer s.mu.Unlock()291292	return s.scr.WriteString(str) //nolint:wrapcheck293}294295// flush implements renderer.296func (s *cursedRenderer) flush(closing bool) error {297	s.mu.Lock()298	defer s.mu.Unlock()299300	view := s.view301	frameArea := uv.Rect(0, 0, s.width, s.height)302	if len(view.Content) == 0 {303		// If the component is nil, we should clear the screen buffer.304		frameArea.Max.Y = 0305	}306307	content := uv.NewStyledString(view.Content)308	if !view.AltScreen {309		// We need to resizes the screen based on the frame height and310		// terminal width. This is because the frame height can change based on311		// the content of the frame. For example, if the frame contains a list312		// of items, the height of the frame will be the number of items in the313		// list. This is different from the alt screen buffer, which has a314		// fixed height and width.315		frameHeight := content.Height()316		if frameHeight != frameArea.Dy() {317			frameArea.Max.Y = frameHeight318		}319	}320321	// Restore tab stops if we have tab optimizations enabled.322	if s.starting && s.hardTabs {323		_, _ = s.scr.WriteString(ansi.SetTabEvery8Columns)324	}325326	if !s.starting && !closing && !s.pendingErase && s.lastView != nil && viewEquals(s.lastView, &view) && frameArea == s.cellbuf.Bounds() {327		// No changes, nothing to do.328		return nil329	}330331	// We're no longer starting.332	s.starting = false333	s.pendingErase = false334335	if frameArea != s.cellbuf.Bounds() {336		s.scr.Erase() // Force a full redraw to avoid artifacts.337338		// We need to reset the touched lines buffer to match the new height.339		s.cellbuf.Touched = nil340341		// Resize the screen buffer to match the frame area. This is necessary342		// to ensure that the screen buffer is the same size as the frame area343		// and to avoid rendering issues when the frame area is smaller than344		// the screen buffer.345		s.cellbuf.Resize(frameArea.Dx(), frameArea.Dy())346	}347348	// Clear our screen buffer before copying the new frame into it to ensure349	// we erase any old content.350	s.cellbuf.Clear()351	content.Draw(s.cellbuf, s.cellbuf.Bounds())352353	// If the frame height is greater than the screen height, we drop the354	// lines from the top of the buffer.355	if frameHeight := frameArea.Dy(); frameHeight > s.height {356		s.cellbuf.Lines = s.cellbuf.Lines[frameHeight-s.height:]357	}358359	// Alt screen mode.360	shouldUpdateAltScreen := (s.lastView == nil && view.AltScreen) || (s.lastView != nil && s.lastView.AltScreen != view.AltScreen)361	if shouldUpdateAltScreen {362		// We want to enter/exit altscreen mode but defer writing the actual363		// sequences until we flush the rest of the updates. This is because we364		// control the cursor visibility and we need to ensure that happens365		// after entering/exiting alt screen mode. Some terminals have366		// different cursor visibility states for main and alt screen modes and367		// this ensures we handle that correctly.368		enableAltScreen(s, view.AltScreen, false)369	}370371	// bracketed paste mode.372	if s.lastView == nil || view.DisableBracketedPasteMode != s.lastView.DisableBracketedPasteMode {373		if !view.DisableBracketedPasteMode {374			_, _ = s.scr.WriteString(ansi.SetModeBracketedPaste)375		} else if s.lastView != nil {376			_, _ = s.scr.WriteString(ansi.ResetModeBracketedPaste)377		}378	}379380	// report focus events mode.381	if s.lastView == nil || s.lastView.ReportFocus != view.ReportFocus {382		if view.ReportFocus {383			_, _ = s.scr.WriteString(ansi.SetModeFocusEvent)384		} else if s.lastView != nil {385			_, _ = s.scr.WriteString(ansi.ResetModeFocusEvent)386		}387	}388389	// mouse events mode.390	if s.lastView == nil || view.MouseMode != s.lastView.MouseMode {391		switch view.MouseMode {392		case MouseModeNone:393			if s.lastView != nil && s.lastView.MouseMode != MouseModeNone {394				_, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent +395					ansi.ResetModeMouseAnyEvent +396					ansi.ResetModeMouseExtSgr)397			}398		case MouseModeCellMotion:399			if s.lastView != nil && s.lastView.MouseMode == MouseModeAllMotion {400				_, _ = s.scr.WriteString(ansi.ResetModeMouseAnyEvent)401			}402			_, _ = s.scr.WriteString(ansi.SetModeMouseButtonEvent + ansi.SetModeMouseExtSgr)403		case MouseModeAllMotion:404			if s.lastView != nil && s.lastView.MouseMode == MouseModeCellMotion {405				_, _ = s.scr.WriteString(ansi.ResetModeMouseButtonEvent)406			}407			_, _ = s.scr.WriteString(ansi.SetModeMouseAnyEvent + ansi.SetModeMouseExtSgr)408		}409	}410411	// Set window title.412	if s.lastView == nil || view.WindowTitle != s.lastView.WindowTitle {413		if s.lastView != nil || view.WindowTitle != "" {414			_, _ = s.scr.WriteString(ansi.SetWindowTitle(view.WindowTitle))415		}416	}417418	// kitty keyboard protocol. Skipped entirely when input is disabled: the419	// enhancements only affect keyboard input, and querying the terminal420	// would leave its response unconsumed, leaking into the shell after421	// the program exits.422	if !s.noInput && (s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||423		view.AltScreen != s.lastView.AltScreen) {424		// NOTE: We need to reset the keyboard protocol when switching425		// between main and alt screen. This is because the specs specify426		// two different states for the main and alt screen.427428		// Enable modifyOtherKeys and Kitty keyboard protocol.429		_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)430431		kittyFlags := keyboardEnhancementsFlags(view.KeyboardEnhancements)432		if s.lastView == nil || view.AltScreen != s.lastView.AltScreen {433			// First render or screen switch: the previous screen's entry434			// (if any) is popped below, so push a fresh one for this435			// screen.436			_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))437		} else {438			// Only the flags changed while the same screen stays active.439			// Update the topmost stack entry in place instead of popping440			// and re-pushing, so a keyboard change doesn't churn the441			// stack. Note that this overwrites whatever entry is currently442			// on top, which is normally ours.443			_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))444		}445		if !closing {446			// Request keyboard enhancements when they change447			_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)448		}449	}450451	// Set terminal colors.452	var (453		cc, lcc  color.Color454		lfg, lbg color.Color455	)456	if view.Cursor != nil {457		cc = view.Cursor.Color458	}459	if s.lastView != nil {460		if s.lastView.Cursor != nil {461			lcc = s.lastView.Cursor.Color462		}463		lfg = s.lastView.ForegroundColor464		lbg = s.lastView.BackgroundColor465	}466	for _, c := range []struct {467		newColor color.Color468		oldColor color.Color469		reset    string470		setter   func(string) string471	}{472		{newColor: cc, oldColor: lcc, reset: ansi.ResetCursorColor, setter: ansi.SetCursorColor},473		{newColor: view.ForegroundColor, oldColor: lfg, reset: ansi.ResetForegroundColor, setter: ansi.SetForegroundColor},474		{newColor: view.BackgroundColor, oldColor: lbg, reset: ansi.ResetBackgroundColor, setter: ansi.SetBackgroundColor},475	} {476		if c.newColor != c.oldColor {477			if c.newColor == nil {478				// Reset the color if it was set to nil.479				_, _ = s.scr.WriteString(c.reset)480			} else {481				// Set the color.482				col, ok := colorful.MakeColor(c.newColor)483				if ok {484					_, _ = s.scr.WriteString(c.setter(col.Hex()))485				}486			}487		}488	}489490	// Set cursor shape and blink if set.491	var ccStyle, lcStyle int492	var lcur *Cursor493	ccur := view.Cursor494	if lv := s.lastView; lv != nil {495		lcur = lv.Cursor496	}497	if ccur != nil {498		ccStyle = encodeCursorStyle(ccur.Shape, ccur.Blink)499	}500	if lcur != nil {501		lcStyle = encodeCursorStyle(lcur.Shape, lcur.Blink)502	}503	if ccStyle != lcStyle {504		_, _ = s.scr.WriteString(ansi.SetCursorStyle(ccStyle))505	}506507	// Render progress bar if it's changed.508	if (s.lastView == nil && view.ProgressBar != nil && view.ProgressBar.State != ProgressBarNone) ||509		(s.lastView != nil && (s.lastView.ProgressBar == nil) != (view.ProgressBar == nil)) ||510		(s.lastView != nil && s.lastView.ProgressBar != nil && view.ProgressBar != nil && *s.lastView.ProgressBar != *view.ProgressBar) {511		// Render or clear the progress bar if it was added or removed.512		setProgressBar(s, view.ProgressBar)513	}514515	// Report the program status if it's changed.516	var lps *ProgramStatus517	if s.lastView != nil {518		lps = s.lastView.ProgramStatus519	}520	if !programStatusEquals(lps, view.ProgramStatus) {521		setProgramStatus(s, lps, view.ProgramStatus)522	}523524	// Render and queue changes to the screen buffer.525	s.scr.Render(s.cellbuf.RenderBuffer)526527	if cur := view.Cursor; cur != nil {528		// MoveTo must come after [uv.TerminalRenderer.Render] because the529		// cursor position might get updated during rendering.530		s.scr.MoveTo(view.Cursor.X, view.Cursor.Y)531	} else if !view.AltScreen {532		// We don't want the cursor to be dangling at the end of the line in533		// inline mode because it can cause unwanted line wraps in some534		// terminals. So we move it to the beginning of the next line if535		// necessary.536		// This is only needed when the cursor is hidden because when it's537		// visible, we already set its position above.538		x, y := s.scr.Position()539		if x >= s.width-1 {540			s.scr.MoveTo(0, y)541		}542	}543544	if err := s.scr.Flush(); err != nil {545		return fmt.Errorf("bubbletea: error flushing screen writer: %w", err)546	}547548	// Check if we have any render updates to flush.549	hasUpdates := s.buf.Len() > 0550551	// Cursor visibility.552	didShowCursor := s.lastView != nil && s.lastView.Cursor != nil553	showCursor := view.Cursor != nil554	hideCursor := !showCursor555	shouldUpdateCursorVis := (s.lastView == nil || didShowCursor != showCursor) || shouldUpdateAltScreen556557	// Build final output buffer with synchronized output or hide/show cursor558	// updates. But first, enter/exit alt screen mode if needed.559	//560	// Here, we have two scenarios:561	// 1. Synchronized output updates are supported. In this case, we want to562	//    wrap all updates, unless it's just a cursor visibility change, in563	//    synchronized output mode. This is because synchronized output mode564	//    takes care of rendering the updates atomically. In the case of565	//    just a cursor visibility change, we don't need to enter566	//    synchronized output mode because it's just a single sequence to567	//    flush out to the terminal.568	//569	// 2. We don't have synchronized output updates support. In this case, and570	//    if the cursor is visible or should be visible, we wrap the updates571	//    with hide/show cursor sequences to try and mitigate cursor572	//    flickering. This is terminal dependent and may still result in573	//    flickering in some terminals. It's the best effort we can do instead574	//    of showing the cursor flying around the screen during updates.575576	var buf bytes.Buffer577	if shouldUpdateAltScreen {578		// We always reset keyboard enhancements when switching screens579		// because the terminal is expected to have two different keyboard580		// registries for main and alt screens.581		s.resetKeyboardEnhancements(&buf)582		if view.AltScreen {583			// Entering alt screen mode.584			buf.WriteString(ansi.SetModeAltScreenSaveCursor)585		} else {586			// Exiting alt screen mode.587			buf.WriteString(ansi.ResetModeAltScreenSaveCursor)588		}589	}590591	if s.syncdUpdates {592		if hasUpdates {593			// We have synchronized output updates enabled.594			buf.WriteString(ansi.SetModeSynchronizedOutput)595		}596		if shouldUpdateCursorVis && hideCursor {597			// Do we need to update the cursor visibility to hidden? If so, do598			// it here before writing any updates to the buffer.599			_, _ = buf.WriteString(ansi.ResetModeTextCursorEnable)600		}601	} else if (shouldUpdateCursorVis && hideCursor) || (hasUpdates && showCursor && didShowCursor) {602		_, _ = buf.WriteString(ansi.ResetModeTextCursorEnable)603	}604605	if hasUpdates {606		buf.Write(s.buf.Bytes())607	}608609	if s.syncdUpdates {610		if shouldUpdateCursorVis && showCursor {611			// Do we need to update the cursor visibility to visible? If so, do612			// it here after writing any updates to the buffer.613			_, _ = buf.WriteString(ansi.SetModeTextCursorEnable)614		}615		if hasUpdates {616			// Close synchronized output mode.617			buf.WriteString(ansi.ResetModeSynchronizedOutput)618		}619	} else if (shouldUpdateCursorVis && showCursor) || (hasUpdates && showCursor && didShowCursor) {620		_, _ = buf.WriteString(ansi.SetModeTextCursorEnable)621	}622623	// Reset internal screen renderer buffer.624	s.buf.Reset()625626	// If our updates flush buffer has content, write it to the output writer.627	if buf.Len() > 0 {628		if s.logger != nil {629			s.logger.Printf("output: %q", buf.String())630		}631		if _, err := io.Copy(s.w, &buf); err != nil {632			return fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)633		}634	}635636	s.lastView = &view637638	return nil639}640641// render implements renderer.642func (s *cursedRenderer) render(v View) {643	s.mu.Lock()644	defer s.mu.Unlock()645646	s.view = v647}648649// reset implements renderer.650func (s *cursedRenderer) reset() {651	s.mu.Lock()652	reset(s)653	s.mu.Unlock()654}655656func reset(s *cursedRenderer) {657	s.buf.Reset()658	scr := uv.NewTerminalRenderer(&s.buf, s.env)659	scr.SetColorProfile(s.profile)660	scr.SetRelativeCursor(true) // Always start in inline mode661	scr.SetFullscreen(false)    // Always start in inline mode662	if s.hardTabs {663		scr.SetTabStops(s.width)664	} else {665		scr.SetTabStops(-1)666	}667	scr.SetBackspace(s.backspace)668	scr.SetMapNewline(s.mapnl)669	scr.SetScrollOptim(runtime.GOOS != "windows") // disable scroll optimization on Windows due to bugs in some terminals670	s.scr = scr671}672673// setColorProfile implements renderer.674func (s *cursedRenderer) setColorProfile(p colorprofile.Profile) {675	s.mu.Lock()676	s.profile = p677	s.scr.SetColorProfile(p)678	s.mu.Unlock()679}680681// resize implements renderer.682func (s *cursedRenderer) resize(w, h int) {683	s.mu.Lock()684	// We need to mark the screen for clear to force a redraw. However, we685	// only do so if we're using alt screen or the width has changed.686	// That's because redrawing is expensive and we can avoid it if the687	// width hasn't changed in inline mode. On the other hand, when using688	// alt screen mode, we always want to redraw because some terminals689	// would scroll the screen and our content would be lost.690	s.scr.Erase()691	s.width, s.height = w, h692	s.scr.Resize(s.width, s.height)693	s.pendingErase = true694	s.mu.Unlock()695}696697// clearScreen implements renderer.698func (s *cursedRenderer) clearScreen() {699	s.mu.Lock()700	// Move the cursor to the top left corner of the screen and trigger a full701	// screen redraw.702	s.scr.MoveTo(0, 0)703	s.scr.Erase()704	s.pendingErase = true705	s.mu.Unlock()706}707708// enableAltScreen sets the alt screen mode.709// Note that this writes to the buffer directly if write is true.710func enableAltScreen(s *cursedRenderer, enable bool, write bool) {711	if enable {712		enterAltScreen(s, write)713	} else {714		exitAltScreen(s, write)715	}716}717718func enterAltScreen(s *cursedRenderer, write bool) {719	s.scr.SaveCursor()720	if write {721		s.buf.WriteString(ansi.SetModeAltScreenSaveCursor)722	}723	s.scr.SetFullscreen(true)724	s.scr.SetRelativeCursor(false)725	s.scr.Erase()726}727728func exitAltScreen(s *cursedRenderer, write bool) {729	s.scr.Erase()730	s.scr.SetRelativeCursor(true)731	s.scr.SetFullscreen(false)732	if write {733		s.buf.WriteString(ansi.ResetModeAltScreenSaveCursor)734	}735	s.scr.RestoreCursor()736}737738// enableTextCursor sets the text cursor mode.739func enableTextCursor(s *cursedRenderer, enable bool) {740	if enable {741		_, _ = s.scr.WriteString(ansi.SetModeTextCursorEnable)742	} else {743		_, _ = s.scr.WriteString(ansi.ResetModeTextCursorEnable)744	}745}746747// setSyncdUpdates implements renderer.748func (s *cursedRenderer) setSyncdUpdates(syncd bool) {749	s.mu.Lock()750	s.syncdUpdates = syncd751	s.mu.Unlock()752}753754// setWidthMethod implements renderer.755func (s *cursedRenderer) setWidthMethod(method ansi.Method) {756	s.mu.Lock()757	if method == ansi.GraphemeWidth {758		// Turn on Unicode mode (2027) for accurate grapheme width calculation.759		// This is needed for proper rendering of wide characters and emojis.760		_, _ = s.scr.WriteString(ansi.SetModeUnicodeCore)761	} else if s.cellbuf.Method == ansi.GraphemeWidth {762		// Turn off Unicode mode if we're switching away from grapheme width763		// calculation to avoid issues with some terminals that might still be764		// in Unicode mode and render characters incorrectly.765		_, _ = s.scr.WriteString(ansi.ResetModeUnicodeCore)766	}767	s.cellbuf.Method = method768	s.mu.Unlock()769}770771// insertAbove implements renderer.772func (s *cursedRenderer) insertAbove(str string) error {773	s.mu.Lock()774	defer s.mu.Unlock()775776	if len(str) == 0 {777		return nil778	}779780	var sb strings.Builder781	w, h := s.cellbuf.Width(), s.cellbuf.Height()782	_, y := s.scr.Position()783784	// We need to scroll the screen up by the number of lines in the queue.785	sb.WriteByte('\r')786	down := h - y - 1787	if down > 0 {788		sb.WriteString(ansi.CursorDown(down))789	}790791	lines := strings.Split(str, "\n")792	offset := len(lines)793	for _, line := range lines {794		lineWidth := ansi.StringWidth(line)795		if w > 0 && lineWidth > w {796			offset += (lineWidth / w)797		}798	}799800	// Scroll the screen up by the offset to make room for the new lines.801	sb.WriteString(strings.Repeat("\n", offset))802803	// XXX: Now go to the top of the screen, insert new lines, and write804	// the queued strings. It is important to use [Screen.moveCursor]805	// instead of [Screen.move] because we don't want to perform any checks806	// on the cursor position.807	up := offset + h - 1808	sb.WriteString(ansi.CursorUp(up))809	sb.WriteString(ansi.InsertLine(offset))810	for _, line := range lines {811		sb.WriteString(line)812		sb.WriteString(ansi.EraseLineRight)813		sb.WriteString("\r\n")814	}815816	s.scr.SetPosition(0, 0)817818	if s.logger != nil {819		s.logger.Printf("insert above: %q", sb.String())820	}821822	_, err := io.WriteString(s.w, sb.String())823	if err != nil {824		return fmt.Errorf("bubbletea: error writing insert above to the writer: %w", err)825	}826827	return nil828}829830// onMouse implements renderer.831func (s *cursedRenderer) onMouse(m MouseMsg) Cmd {832	var onMouse func(MouseMsg) Cmd833	s.mu.Lock()834	if s.lastView != nil {835		onMouse = s.lastView.OnMouse836	}837	s.mu.Unlock()838	if onMouse != nil {839		return onMouse(m)840	}841	return nil842}843844func setProgressBar(s *cursedRenderer, pb *ProgressBar) {845	if pb == nil {846		_, _ = s.scr.WriteString(ansi.ResetProgressBar)847		return848	}849850	var seq string851	switch pb.State {852	case ProgressBarNone:853		seq = ansi.ResetProgressBar854	case ProgressBarDefault:855		seq = ansi.SetProgressBar(pb.Value)856	case ProgressBarError:857		seq = ansi.SetErrorProgressBar(pb.Value)858	case ProgressBarIndeterminate:859		seq = ansi.SetIndeterminateProgressBar860	case ProgressBarWarning:861		seq = ansi.SetWarningProgressBar(pb.Value)862	}863	if seq != "" {864		_, _ = s.scr.WriteString(seq)865	}866}867868func programStatusEquals(a, b *ProgramStatus) bool {869	if a == nil || b == nil {870		return a == b871	}872	return *a == *b873}874875// setProgramStatus reports cur to the terminal. When cur is nil, or addresses876// a different record than prev, the record of prev is cleared first.877func setProgramStatus(s *cursedRenderer, prev, cur *ProgramStatus) {878	if prev != nil && (cur == nil || cur.ID != prev.ID) {879		_, _ = s.scr.WriteString(ansi.ClearProgramStatusID(prev.ID))880	}881	if cur != nil {882		_, _ = s.scr.WriteString(ansi.SetProgramStatus(*cur))883	}884}885886func viewEquals(a, b *View) bool {887	if a == nil || b == nil {888		return false889	}890891	if !programStatusEquals(a.ProgramStatus, b.ProgramStatus) {892		return false893	}894895	if a.Content != b.Content ||896		a.AltScreen != b.AltScreen ||897		a.DisableBracketedPasteMode != b.DisableBracketedPasteMode ||898		a.ReportFocus != b.ReportFocus ||899		a.MouseMode != b.MouseMode ||900		a.WindowTitle != b.WindowTitle ||901		a.ForegroundColor != b.ForegroundColor ||902		a.BackgroundColor != b.BackgroundColor ||903		a.KeyboardEnhancements != b.KeyboardEnhancements {904		return false905	}906907	if (a.Cursor == nil) != (b.Cursor == nil) {908		return false909	}910	if a.Cursor != nil && b.Cursor != nil {911		if a.Cursor.X != b.Cursor.X ||912			a.Cursor.Y != b.Cursor.Y ||913			a.Cursor.Shape != b.Cursor.Shape ||914			a.Cursor.Blink != b.Cursor.Blink ||915			a.Cursor.Color != b.Cursor.Color {916			return false917		}918	}919920	if (a.ProgressBar == nil) != (b.ProgressBar == nil) {921		return false922	}923	if a.ProgressBar != nil && b.ProgressBar != nil {924		if *a.ProgressBar != *b.ProgressBar {925			return false926		}927	}928929	return true930}931932func keyboardEnhancementsFlags(ke KeyboardEnhancements) int {933	flags := 1 // always enable basic key disambiguation934	if ke.ReportEventTypes {935		flags |= ansi.KittyReportEventTypes936	}937	if ke.ReportAlternateKeys {938		flags |= ansi.KittyReportAlternateKeys939	}940	if ke.ReportAllKeysAsEscapeCodes {941		flags |= ansi.KittyReportAllKeysAsEscapeCodes942	}943	if ke.ReportAssociatedText {944		flags |= ansi.KittyReportAssociatedKeys945	}946	return flags947}