Skip to content
Myr

tea.go

This file

Path

tea.go

1,483 lines · 41.4 KiB · Go

Last changed by

feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626

History of this file

Take it

1// Package tea provides a framework for building rich terminal user interfaces2// based on the paradigms of The Elm Architecture. It's well-suited for simple3// and complex terminal applications, either inline, full-window, or a mix of4// both. It's been battle-tested in several large projects and is5// production-ready.6//7// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/main/tutorials8//9// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/main/examples10package tea1112import (13	"bytes"14	"context"15	"errors"16	"fmt"17	"image/color"18	"io"19	"log"20	"os"21	"os/signal"22	"runtime"23	"runtime/debug"24	"strconv"25	"strings"26	"sync"27	"sync/atomic"28	"syscall"29	"time"3031	"github.com/charmbracelet/colorprofile"32	uv "github.com/charmbracelet/ultraviolet"33	"github.com/charmbracelet/x/ansi"34	"github.com/charmbracelet/x/term"35	"github.com/muesli/cancelreader"36)3738// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.39var ErrProgramPanic = errors.New("program experienced a panic")4041// ErrProgramKilled is returned by [Program.Run] when the program gets killed.42var ErrProgramKilled = errors.New("program was killed")4344// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT45// signal, or when it receives a [InterruptMsg].46var ErrInterrupted = errors.New("program was interrupted")4748// Msg contain data from the result of a IO operation. Msgs trigger the update49// function and, henceforth, the UI.50type Msg = uv.Event5152// Model contains the program's state as well as its core functions.53type Model interface {54	// Init is the first function that will be called. It returns an optional55	// initial command. To not perform an initial command return nil.56	Init() Cmd5758	// Update is called when a message is received. Use it to inspect messages59	// and, in response, update the model and/or send a command.60	Update(Msg) (Model, Cmd)6162	// View renders the program's UI, which can be a string or a [Layer]. The63	// view is rendered after every Update.64	View() View65}6667// NewView is a helper function to create a new [View] with the given styled68// string. A styled string represents text with styles and hyperlinks encoded69// as ANSI escape codes.70//71// Example:72//73//	```go74//	v := tea.NewView("Hello, World!")75//	```76func NewView(s string) View {77	var view View78	view.SetContent(s)79	return view80}8182// View represents a terminal view that can be composed of multiple layers.83// It can also contain a cursor that will be rendered on top of the layers.84type View struct {85	// Content is the screen content of the view. It holds styled strings that86	// will be rendered to the terminal when the view is rendered.87	//88	// A styled string represents text with styles and hyperlinks encoded as89	// ANSI escape codes.90	//91	// Example:92	//93	//  ```go94	//  v := tea.NewView("Hello, World!")95	//  ```96	Content string9798	// OnMouse is an optional mouse message handler that can be used to99	// intercept mouse messages that depends on view content from last render.100	// It can be useful for implementing view-specific behavior without101	// breaking the unidirectional data flow of Bubble Tea.102	//103	// Example:104	//105	//  ```go106	//  content := "Hello, World!"107	//  v := tea.NewView(content)108	//  v.OnMouse = func(msg tea.MouseMsg) tea.Cmd {109	//      return func() tea.Msg {110	//        m := msg.Mouse()111	//        // Check if the mouse is within the bounds of "World!"112	//        start := strings.Index(content, "World!")113	//        end := start + len("World!")114	//        if m.Y == 0 && m.X >= start && m.X < end {115	//          // Mouse is over "World!"116	//          return MyCustomMsg{117	//            MouseMsg: msg,118	//          }119	//		  }120	//      }121	//    }122	//    return nil123	//  }124	//  return v125	//  ```126	OnMouse func(msg MouseMsg) Cmd127128	// Cursor represents the cursor position, style, and visibility on the129	// screen. When not nil, the cursor will be shown at the specified130	// position.131	Cursor *Cursor132133	// BackgroundColor when not nil, sets the terminal background color. Use134	// nil to reset to the terminal's default background color.135	BackgroundColor color.Color136137	// ForegroundColor when not nil, sets the terminal foreground color. Use138	// nil to reset to the terminal's default foreground color.139	ForegroundColor color.Color140141	// WindowTitle sets the terminal window title. Support depends on the142	// terminal.143	WindowTitle string144145	// ProgressBar when not nil, shows a progress bar in the terminal's146	// progress bar section. Support depends on the terminal.147	ProgressBar *ProgressBar148149	// ProgramStatus when not nil, reports the program status to the terminal150	// using the Program Status Protocol (OSC 7501): whether the program is151	// idle, working, waiting on the user, done, or failed. Support depends on152	// the terminal.153	//154	// The status usually addresses the root record (empty ID). Changing it155	// sends a new report, and setting it back to nil clears the record.156	//157	// The status is not cleared when the program exits, so done and error158	// reports stay visible to the user. Report [ProgramStateDone],159	// [ProgramStateError], or [ProgramStateIdle] before quitting rather than160	// leaving a working or blocked status behind.161	ProgramStatus *ProgramStatus162163	// AltScreen puts the program in the alternate screen buffer164	// (i.e. the program goes into full window mode). Note that the altscreen will165	// be automatically exited when the program quits.166	//167	// Example:168	//169	//	func (m model) View() tea.View {170	//	    v := tea.NewView("Hello, World!")171	//	    v.AltScreen = true172	//	    return v173	//	}174	//175	AltScreen bool176177	// ReportFocus enables reporting when the terminal gains and loses focus.178	// When this is enabled [FocusMsg] and [BlurMsg] messages will be sent to179	// your Update method.180	//181	// Note that while most terminals and multiplexers support focus reporting,182	// some do not. Also note that tmux needs to be configured to report focus183	// events.184	ReportFocus bool185186	// DisableBracketedPasteMode disables bracketed paste mode for this view.187	DisableBracketedPasteMode bool188189	// MouseMode sets the mouse mode for this view. It can be one of190	// [MouseModeNone], [MouseModeCellMotion], or [MouseModeAllMotion].191	MouseMode MouseMode192193	// KeyboardEnhancements describes what keyboard enhancement features Bubble194	// Tea should request from the terminal.195	//196	// Bubble Tea supports requesting the following keyboard enhancement features:197	//   - ReportEventTypes: requests the terminal to report key repeat and198	//     release events.199	//200	// If the terminal supports any of these features, your program will201	// receive  a [KeyboardEnhancementsMsg] that indicates which features are202	// available.203	KeyboardEnhancements KeyboardEnhancements204}205206// KeyboardEnhancements describes the requested keyboard enhancement features.207// If the terminal supports any of them, it will respond with a208// [KeyboardEnhancementsMsg] that indicates which features are supported.209210// KeyboardEnhancements defines different keyboard enhancement features that211// can be requested from the terminal.212213// KeyboardEnhancements defines different keyboard enhancement features that214// can be requested from the terminal.215//216// By default, Bubble Tea requests basic key disambiguation features from the217// terminal. If the terminal supports keyboard enhancements, or any of its218// additional features, it will respond with a [KeyboardEnhancementsMsg] that219// indicates which features are supported.220//221// Example:222//223//	```go224//	func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {225//	  switch msg := msg.(type) {226//	  case tea.KeyboardEnhancementsMsg:227//	    // We have basic key disambiguation support.228//	    // We can handle "shift+enter", "ctrl+i", etc.229//		m.keyboardEnhancements = msg230//		if msg.ReportEventTypes {231//		  // Even better! We can now handle key repeat and release events.232//		}233//	  case tea.KeyPressMsg:234//	    switch msg.String() {235//	    case "shift+enter":236//	      // Handle shift+enter237//	      // This would not be possible without keyboard enhancements.238//	    case "ctrl+j":239//	      // Handle ctrl+j240//	    }241//	  case tea.KeyReleaseMsg:242//	    // Whoa! A key was released!243//	  }244//245//	  return m, nil246//	}247//248//	func (m model) View() tea.View {249//	  v := tea.NewView("Press some keys!")250//	  // Request reporting key repeat and release events.251//	  v.KeyboardEnhancements.ReportEventTypes = true252//	  return v253//	}254//	```255type KeyboardEnhancements struct {256	// ReportEventTypes requests the terminal to report key repeat and release257	// events.258	// If supported, your program will receive [KeyReleaseMsg]s and259	// [KeyPressMsg] with the [Key.IsRepeat] field set indicating that this is260	// a it's part of a key repeat sequence.261	ReportEventTypes bool262263	// ReportAlternateKeys requests the terminal to report alternate key values264	// in addition to the main ones.265	// Note that only key events represented as escape codes will affected by266	// this enhancement.267	ReportAlternateKeys bool268269	// ReportAllKeysAsEscapeCodes requests the terminal to report all key270	// events, including plain text keys, as escape codes.271	// When this is enabled, text won't be sent as plain text but instead as272	// escape codes that encode the key value and modifiers.273	ReportAllKeysAsEscapeCodes bool274275	// ReportAssociatedText requests the terminal to report the text associated276	// with key events.277	// Note that this is an enhancement to278	// [KeyboardEnhancements.ReportAllKeysAsEscapeCodes] and only has an effect279	// if that is enabled.280	ReportAssociatedText bool281}282283// SetContent is a helper method to set the content of a [View] with a styled284// string. A styled string represents text with styles and hyperlinks encoded285// as ANSI escape codes.286//287// Example:288//289//	```go290//	var v tea.View291//	v.SetContent("Hello, World!")292//	```293func (v *View) SetContent(s string) {294	v.Content = s295}296297// MouseMode represents the mouse mode of a view.298type MouseMode int299300const (301	// MouseModeNone disables mouse events.302	MouseModeNone MouseMode = iota303304	// MouseModeCellMotion enables mouse click, release, and wheel events.305	// Mouse movement events are also captured if a mouse button is pressed306	// (i.e., drag events). Cell motion mode is better supported than all307	// motion mode.308	//309	// This will try to enable the mouse in extended mode (SGR), if that is not310	// supported by the terminal it will fall back to normal mode (X10).311	MouseModeCellMotion312313	// MouseModeAllMotion enables all mouse events, including click, release,314	// wheel, and movement events. You will receive mouse movement events even315	// when no buttons are pressed.316	//317	// This will try to enable the mouse in extended mode (SGR), if that is not318	// supported by the terminal it will fall back to normal mode (X10).319	MouseModeAllMotion320)321322// ProgressBarState represents the state of the progress bar.323type ProgressBarState int324325// Progress bar states.326const (327	ProgressBarNone ProgressBarState = iota328	ProgressBarDefault329	ProgressBarError330	ProgressBarIndeterminate331	ProgressBarWarning332)333334// String returns a human-readable name for the given [ProgressBarState].335// Values outside the known range return "Unknown".336func (s ProgressBarState) String() string {337	switch s {338	case ProgressBarNone:339		return "None"340	case ProgressBarDefault:341		return "Default"342	case ProgressBarError:343		return "Error"344	case ProgressBarIndeterminate:345		return "Indeterminate"346	case ProgressBarWarning:347		return "Warning"348	default:349		return "Unknown"350	}351}352353// ProgressBar represents the terminal progress bar.354//355// Support depends on the terminal.356//357// See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences358type ProgressBar struct {359	// State is the current state of the progress bar. It can be one of360	// [ProgressBarNone], [ProgressBarDefault], [ProgressBarError],361	// [ProgressBarIndeterminate], and [ProgressBarWarning].362	State ProgressBarState363	// Value is the current value of the progress bar. It should be between364	// 0 and 100.365	Value int366}367368// NewProgressBar returns a new progress bar with the given state and value.369// The value is ignored if the state is [ProgressBarNone] or370// [ProgressBarIndeterminate].371func NewProgressBar(state ProgressBarState, value int) *ProgressBar {372	return &ProgressBar{373		State: state,374		Value: min(max(value, 0), 100),375	}376}377378// Cursor represents a cursor on the terminal screen.379type Cursor struct {380	// Position is a [Position] that determines the cursor's position on the381	// screen relative to the top left corner of the frame.382	Position383384	// Color is a [color.Color] that determines the cursor's color.385	Color color.Color386387	// Shape is a [CursorShape] that determines the cursor's shape.388	Shape CursorShape389390	// Blink is a boolean that determines whether the cursor should blink.391	Blink bool392}393394// NewCursor returns a new cursor with the default settings and the given395// position.396func NewCursor(x, y int) *Cursor {397	return &Cursor{398		Position: Position{X: x, Y: y},399		Color:    nil,400		Shape:    CursorBlock,401		Blink:    true,402	}403}404405// Cmd is an IO operation that returns a message when it's complete. If it's406// nil it's considered a no-op. Use it for things like HTTP requests, timers,407// saving and loading from disk, and so on.408//409// Note that there's almost never a reason to use a command to send a message410// to another part of your program. That can almost always be done in the411// update function.412type Cmd func() Msg413414// channelHandlers manages the series of channels returned by various processes.415// It allows us to wait for those processes to terminate before exiting the416// program.417type channelHandlers struct {418	handlers []chan struct{}419	mu       sync.RWMutex420}421422// Adds a channel to the list of handlers. We wait for all handlers to terminate423// gracefully on shutdown.424func (h *channelHandlers) add(ch chan struct{}) {425	h.mu.Lock()426	h.handlers = append(h.handlers, ch)427	h.mu.Unlock()428}429430// shutdown waits for all handlers to terminate.431func (h *channelHandlers) shutdown() {432	var wg sync.WaitGroup433434	h.mu.RLock()435	defer h.mu.RUnlock()436437	for _, ch := range h.handlers {438		wg.Add(1)439		go func(ch chan struct{}) {440			<-ch441			wg.Done()442		}(ch)443	}444	wg.Wait()445}446447// Program is a terminal user interface.448type Program struct {449	// disableInput disables all input. This is useful for programs that450	// don't need input, like a progress bar or a spinner.451	disableInput bool452453	// disableSignalHandler disables the signal handler that Bubble Tea sets up454	// for Programs. This is useful if you want to handle signals yourself.455	disableSignalHandler bool456457	// disableCatchPanics disables the panic catching that Bubble Tea does by458	// default. If panic catching is disabled the terminal will be in a fairly459	// unusable state after a panic because Bubble Tea will not perform its usual460	// cleanup on exit.461	disableCatchPanics bool462463	// filter supplies an event filter that will be invoked before Bubble Tea464	// processes a tea.Msg. The event filter can return any tea.Msg which will465	// then get handled by Bubble Tea instead of the original event. If the466	// event filter returns nil, the event will be ignored and Bubble Tea will467	// not process it.468	//469	// As an example, this could be used to prevent a program from shutting470	// down if there are unsaved changes.471	//472	// Example:473	//474	//	func filter(m tea.Model, msg tea.Msg) tea.Msg {475	//		if _, ok := msg.(tea.QuitMsg); !ok {476	//			return msg477	//		}478	//479	//		model := m.(myModel)480	//		if model.hasChanges {481	//			return nil482	//		}483	//484	//		return msg485	//	}486	//487	//	p := tea.NewProgram(Model{});488	//	p.filter = filter489	//490	//	if _,err := p.Run(context.Background()); err != nil {491	//		fmt.Println("Error running program:", err)492	//		os.Exit(1)493	//	}494	filter func(Model, Msg) Msg495496	// fps sets a custom maximum fps at which the renderer should run. If less497	// than 1, the default value of 60 will be used. If over 120, the fps will498	// be capped at 120.499	fps int500501	// initialModel is the initial model for the program and is the only502	// required field when creating a new program.503	initialModel Model504505	// disableRenderer prevents the program from rendering to the terminal.506	// This can be useful for running daemon-like programs that don't require a507	// UI but still want to take advantage of Bubble Tea's architecture.508	disableRenderer bool509510	// handlers is a list of channels that need to be waited on before the511	// program can exit.512	handlers channelHandlers513514	// ctx is the programs's internal context for signalling internal teardown.515	// It is built and derived from the externalCtx in NewProgram().516	ctx    context.Context517	cancel context.CancelFunc518519	// externalCtx is a context that was passed in via WithContext, otherwise defaulting520	// to ctx.Background() (in case it was not), the internal context is derived from it.521	externalCtx context.Context522523	msgs         chan Msg524	errs         chan error525	finished     chan struct{}526	shutdownOnce sync.Once527528	profile *colorprofile.Profile // the terminal color profile529530	// where to send output, this will usually be os.Stdout.531	output    io.Writer532	outputBuf bytes.Buffer // buffer used to queue commands to be sent to the output533534	// ttyOutput is null if output is not a TTY.535	ttyOutput           term.File536	previousOutputState *term.State537	renderer            renderer538539	// the environment variables for the program, defaults to os.Environ().540	environ uv.Environ541	// the program's logger for debugging.542	logger uv.Logger543544	// where to read inputs from, this will usually be os.Stdin.545	input io.Reader546	// ttyInput is null if input is not a TTY.547	ttyInput              term.File548	previousTtyInputState *term.State549	cancelReader          cancelreader.CancelReader550	inputScanner          *uv.TerminalReader551	readLoopDone          chan struct{}552553	// modes keeps track of terminal modes that have been enabled or disabled.554	ignoreSignals uint32555556	// ticker is the ticker that will be used to write to the renderer.557	ticker *time.Ticker558559	// once is used to stop the renderer.560	once sync.Once561562	// rendererDone is used to stop the renderer.563	rendererDone chan struct{}564565	// Initial window size. Mainly used for testing.566	width, height int567568	// whether to use hard tabs to optimize cursor movements569	useHardTabs bool570	// whether to use backspace to optimize cursor movements571	useBackspace bool572573	mu sync.Mutex574}575576// Quit is a special command that tells the Bubble Tea program to exit.577func Quit() Msg {578	return QuitMsg{}579}580581// QuitMsg signals that the program should quit. You can send a [QuitMsg] with582// [Quit].583type QuitMsg struct{}584585// Suspend is a special command that tells the Bubble Tea program to suspend.586func Suspend() Msg {587	return SuspendMsg{}588}589590// SuspendMsg signals the program should suspend.591// This usually happens when ctrl+z is pressed on common programs, but since592// bubbletea puts the terminal in raw mode, we need to handle it in a593// per-program basis.594//595// You can send this message with [Suspend()].596type SuspendMsg struct{}597598// ResumeMsg can be listen to do something once a program is resumed back599// from a suspend state.600type ResumeMsg struct{}601602// InterruptMsg signals the program should suspend.603// This usually happens when ctrl+c is pressed on common programs, but since604// bubbletea puts the terminal in raw mode, we need to handle it in a605// per-program basis.606//607// You can send this message with [Interrupt()].608type InterruptMsg struct{}609610// Interrupt is a special command that tells the Bubble Tea program to611// interrupt.612func Interrupt() Msg {613	return InterruptMsg{}614}615616// NewProgram creates a new [Program].617func NewProgram(model Model, opts ...ProgramOption) *Program {618	p := &Program{619		initialModel: model,620		msgs:         make(chan Msg),621		errs:         make(chan error, 1),622		rendererDone: make(chan struct{}),623	}624625	// Apply all options to the program.626	for _, opt := range opts {627		opt(p)628	}629630	// A context can be provided with a ProgramOption, but if none was provided631	// we'll use the default background context.632	if p.externalCtx == nil {633		p.externalCtx = context.Background()634	}635	// Initialize context and teardown channel.636	p.ctx, p.cancel = context.WithCancel(p.externalCtx)637638	// if no output was set, set it to stdout639	if p.output == nil {640		p.output = os.Stdout641	}642643	// if no environment was set, set it to os.Environ()644	if p.environ == nil {645		p.environ = os.Environ()646	}647648	if p.fps < 1 {649		p.fps = defaultFPS650	} else if p.fps > maxFPS {651		p.fps = maxFPS652	}653654	tracePath, traceOk := os.LookupEnv("TEA_TRACE")655	if traceOk && len(tracePath) > 0 {656		// We have a trace filepath.657		if f, err := os.OpenFile(tracePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600); err == nil {658			p.logger = log.New(f, "bubbletea: ", log.LstdFlags|log.Lshortfile)659		}660	}661662	return p663}664665func (p *Program) handleSignals() chan struct{} {666	ch := make(chan struct{})667668	// Listen for SIGINT and SIGTERM.669	//670	// In most cases ^C will not send an interrupt because the terminal will be671	// in raw mode and ^C will be captured as a keystroke and sent along to672	// Program.Update as a KeyMsg. When input is not a TTY, however, ^C will be673	// caught here.674	//675	// SIGTERM is sent by unix utilities (like kill) to terminate a process.676	go func() {677		sig := make(chan os.Signal, 1)678		signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)679		defer func() {680			signal.Stop(sig)681			close(ch)682		}()683684		for {685			select {686			case <-p.ctx.Done():687				return688689			case s := <-sig:690				if atomic.LoadUint32(&p.ignoreSignals) == 0 {691					var msg Msg = QuitMsg{}692					if s == syscall.SIGINT {693						msg = InterruptMsg{}694					}695					select {696					case p.msgs <- msg:697					case <-p.ctx.Done():698					}699					return700				}701			}702		}703	}()704705	return ch706}707708// handleResize handles terminal resize events.709func (p *Program) handleResize() chan struct{} {710	ch := make(chan struct{})711712	if p.ttyOutput != nil {713		// Listen for window resizes.714		go p.listenForResize(ch)715	} else {716		close(ch)717	}718719	return ch720}721722// handleCommands runs commands in a goroutine and sends the result to the723// program's message channel.724func (p *Program) handleCommands(cmds chan Cmd) chan struct{} {725	ch := make(chan struct{})726727	go func() {728		defer close(ch)729730		for {731			select {732			case <-p.ctx.Done():733				return734735			case cmd := <-cmds:736				if cmd == nil {737					continue738				}739740				// Don't wait on these goroutines, otherwise the shutdown741				// latency would get too large as a Cmd can run for some time742				// (e.g. tick commands that sleep for half a second). It's not743				// possible to cancel them so we'll have to leak the goroutine744				// until Cmd returns.745				go func() {746					// Recover from panics.747					if !p.disableCatchPanics {748						defer func() {749							if r := recover(); r != nil {750								p.recoverFromPanic(r)751							}752						}()753					}754755					msg := cmd() // this can be long.756					p.Send(msg)757				}()758			}759		}760	}()761762	return ch763}764765// eventLoop is the central message loop. It receives and handles the default766// Bubble Tea messages, update the model and triggers redraws.767func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {768	for {769		select {770		case <-p.ctx.Done():771			return model, nil772773		case err := <-p.errs:774			return model, err775776		case msg := <-p.msgs:777			msg = p.translateInputEvent(msg)778779			// Filter messages.780			if p.filter != nil {781				msg = p.filter(model, msg)782			}783			if msg == nil {784				continue785			}786787			// Handle special internal messages.788			switch msg := msg.(type) {789			case QuitMsg:790				return model, nil791792			case InterruptMsg:793				return model, ErrInterrupted794795			case SuspendMsg:796				if suspendSupported {797					p.suspend()798				}799800			case CapabilityMsg:801				switch msg.Content {802				case "RGB", "Tc":803					if *p.profile != colorprofile.TrueColor {804						tc := colorprofile.TrueColor805						p.profile = &tc806						go p.Send(ColorProfileMsg{*p.profile})807					}808				}809810			case ModeReportMsg:811				switch msg.Mode {812				case ansi.ModeSynchronizedOutput:813					if msg.Value == ansi.ModeReset {814						// The terminal supports synchronized output and it's815						// currently disabled, so we can enable it on the renderer.816						p.renderer.setSyncdUpdates(true)817					}818				case ansi.ModeUnicodeCore:819					if msg.Value == ansi.ModeReset || msg.Value == ansi.ModeSet || msg.Value == ansi.ModePermanentlySet {820						p.renderer.setWidthMethod(ansi.GraphemeWidth)821					}822				}823824			case MouseMsg:825				switch msg.(type) {826				case MouseClickMsg, MouseReleaseMsg, MouseWheelMsg, MouseMotionMsg:827					// Only send mouse messages to the renderer if they are an828					// actual mouse event.829					if cmd := p.renderer.onMouse(msg); cmd != nil {830						go p.Send(cmd())831					}832				}833834			case readClipboardMsg:835				p.executeQuery(ansi.RequestSystemClipboard)836837			case setClipboardMsg:838				p.execute(ansi.SetSystemClipboard(string(msg)))839840			case readPrimaryClipboardMsg:841				p.executeQuery(ansi.RequestPrimaryClipboard)842843			case setPrimaryClipboardMsg:844				p.execute(ansi.SetPrimaryClipboard(string(msg)))845846			case backgroundColorMsg:847				p.executeQuery(ansi.RequestBackgroundColor)848849			case foregroundColorMsg:850				p.executeQuery(ansi.RequestForegroundColor)851852			case cursorColorMsg:853				p.executeQuery(ansi.RequestCursorColor)854855			case programStatusSupportMsg:856				p.executeQuery(ansi.RequestProgramStatusSupport)857858			case execMsg:859				// NB: this blocks.860				p.exec(msg.cmd, msg.fn)861862			case terminalVersion:863				p.executeQuery(ansi.RequestNameVersion)864865			case requestCapabilityMsg:866				p.executeQuery(ansi.RequestTermcap(string(msg)))867868			case BatchMsg:869				go p.execBatchMsg(msg)870				continue871872			case sequenceMsg:873				go p.execSequenceMsg(msg)874				continue875876			case WindowSizeMsg:877				p.renderer.resize(msg.Width, msg.Height)878879			case windowSizeMsg:880				go p.checkResize()881882			case requestCursorPosMsg:883				p.executeQuery(ansi.RequestCursorPositionReport)884885			case RawMsg:886				p.execute(fmt.Sprint(msg.Msg))887888			case printLineMessage:889				p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec890891			case clearScreenMsg:892				p.renderer.clearScreen()893894			case ColorProfileMsg:895				p.renderer.setColorProfile(msg.Profile)896			}897898			var cmd Cmd899			model, cmd = model.Update(msg) // run update900901			select {902			case <-p.ctx.Done():903				return model, nil904			case cmds <- cmd: // process command (if any)905			}906907			p.render(model) // render view908		}909	}910}911912// render renders the given view to the renderer.913func (p *Program) render(model Model) {914	if p.renderer != nil {915		p.renderer.render(model.View()) // send view to renderer916	}917}918919func (p *Program) execSequenceMsg(msg sequenceMsg) {920	if !p.disableCatchPanics {921		defer func() {922			if r := recover(); r != nil {923				p.recoverFromGoPanic(r)924			}925		}()926	}927928	// Execute commands one at a time, in order.929	for _, cmd := range msg {930		if cmd == nil {931			continue932		}933		msg := cmd()934		switch msg := msg.(type) {935		case BatchMsg:936			p.execBatchMsg(msg)937		case sequenceMsg:938			p.execSequenceMsg(msg)939		default:940			p.Send(msg)941		}942	}943}944945func (p *Program) execBatchMsg(msg BatchMsg) {946	if !p.disableCatchPanics {947		defer func() {948			if r := recover(); r != nil {949				p.recoverFromGoPanic(r)950			}951		}()952	}953954	// Execute commands one at a time.955	var wg sync.WaitGroup956	for _, cmd := range msg {957		if cmd == nil {958			continue959		}960		wg.Add(1)961		go func() {962			defer wg.Done()963964			if !p.disableCatchPanics {965				defer func() {966					if r := recover(); r != nil {967						p.recoverFromGoPanic(r)968					}969				}()970			}971972			msg := cmd()973			switch msg := msg.(type) {974			case BatchMsg:975				p.execBatchMsg(msg)976			case sequenceMsg:977				p.execSequenceMsg(msg)978			default:979				p.Send(msg)980			}981		}()982	}983984	wg.Wait() // wait for all commands from batch msg to finish985}986987// shouldQuerySynchronizedOutput determines whether the terminal should be988// queried for various capabilities.989//990// This function checks for terminals that are known to support mode 2026,991// while excluding SSH sessions which may be unreliable, unless it's a992// known-good terminal like Windows Terminal.993//994// The function returns true for:995//   - Terminals without TERM_PROGRAM set and not in SSH sessions996//   - Windows Terminal (WT_SESSION is set)997//   - Terminals with TERM_PROGRAM set (except Apple Terminal) and not in SSH sessions998//   - Specific terminal types: ghostty, wezterm, alacritty, kitty, rio999func shouldQuerySynchronizedOutput(environ uv.Environ) bool {1000	termType := environ.Getenv("TERM")1001	termProg, okTermProg := environ.LookupEnv("TERM_PROGRAM")1002	_, okSSHTTY := environ.LookupEnv("SSH_TTY")1003	_, okWTSession := environ.LookupEnv("WT_SESSION")10041005	return (!okTermProg && !okSSHTTY) ||1006		okWTSession ||1007		(okTermProg && !strings.Contains(termProg, "Apple") && !okSSHTTY) ||1008		strings.Contains(termType, "ghostty") ||1009		strings.Contains(termType, "wezterm") ||1010		strings.Contains(termType, "alacritty") ||1011		strings.Contains(termType, "kitty") ||1012		strings.Contains(termType, "rio")1013}10141015// Run initializes the program and runs its event loops, blocking until it gets1016// terminated by either [Program.Quit], [Program.Kill], or its signal handler.1017// Returns the final model.1018func (p *Program) Run() (returnModel Model, returnErr error) {1019	if p.initialModel == nil {1020		return nil, errors.New("bubbletea: InitialModel cannot be nil")1021	}10221023	// Initialize context and teardown channel.1024	p.handlers = channelHandlers{}1025	cmds := make(chan Cmd)10261027	p.finished = make(chan struct{})1028	defer func() {1029		close(p.finished)1030	}()10311032	defer p.cancel()10331034	if p.disableInput {1035		p.input = nil1036	} else if p.input == nil {1037		p.input = os.Stdin1038		if !term.IsTerminal(os.Stdin.Fd()) {1039			ttyIn, _, err := OpenTTY()1040			if err != nil {1041				return p.initialModel, fmt.Errorf("bubbletea: error opening TTY: %w", err)1042			}1043			p.input = ttyIn1044		}1045	}10461047	// Handle signals.1048	if !p.disableSignalHandler {1049		p.handlers.add(p.handleSignals())1050	}10511052	// Recover from panics.1053	if !p.disableCatchPanics {1054		defer func() {1055			if r := recover(); r != nil {1056				returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)1057				p.recoverFromPanic(r)1058			}1059		}()1060	}10611062	// Check if output is a TTY before entering raw mode, hiding the cursor and1063	// so on.1064	if err := p.initTerminal(); err != nil {1065		return p.initialModel, err1066	}10671068	// Get the initial window size.1069	width, height := p.width, p.height1070	if p.ttyOutput != nil {1071		// Set the initial size of the terminal.1072		w, h, err := term.GetSize(p.ttyOutput.Fd())1073		if err != nil {1074			return p.initialModel, fmt.Errorf("bubbletea: error getting terminal size: %w", err)1075		}10761077		width, height = p.fallbackDimensions(w, h)1078	}10791080	p.width, p.height = width, height1081	resizeMsg := WindowSizeMsg{Width: p.width, Height: p.height}10821083	if p.renderer == nil {1084		if p.disableRenderer {1085			p.renderer = &nilRenderer{}1086		} else {1087			// If no renderer is set use the cursed one.1088			r := newCursedRenderer(1089				p.output,1090				p.environ,1091				p.width,1092				p.height,1093			)1094			r.setLogger(p.logger)1095			r.setNoInput(p.disableInput)1096			// XXX: This breaks many things especially when we want the output1097			// to be compatible with terminals that are not necessary a TTY.1098			// This was originally done to work around a Wish emulated-pty1099			// issue where when a PTY session is detected, and we don't1100			// allocate a real PTY, the terminal settings (Termios and WinCon)1101			// don't change and the we end up working in cooked mode instead of1102			// raw mode. See issue #1572.1103			mapNl := runtime.GOOS != "windows" && p.ttyInput == nil1104			r.setOptimizations(p.useHardTabs, p.useBackspace, mapNl)1105			p.renderer = r1106		}1107	}11081109	// Get the color profile and send it to the program.1110	if p.profile == nil {1111		cp := colorprofile.Detect(p.output, p.environ)1112		p.profile = &cp1113	}11141115	// Set the color profile on the renderer and send it to the program.1116	p.renderer.setColorProfile(*p.profile)1117	go p.Send(ColorProfileMsg{*p.profile})11181119	// Send the initial size to the program.1120	go p.Send(resizeMsg)1121	p.renderer.resize(resizeMsg.Width, resizeMsg.Height)11221123	// Send the environment variables used by the program.1124	go p.Send(EnvMsg(p.environ))11251126	// Init the input reader and initial model.1127	model := p.initialModel1128	if p.input != nil {1129		if err := p.initInputReader(false); err != nil {1130			return model, err1131		}1132	}11331134	// Start the renderer.1135	p.startRenderer()11361137	if !p.disableRenderer && shouldQuerySynchronizedOutput(p.environ) {1138		// Query for synchronized updates support (mode 2026) and unicode core1139		// (mode 2027). If the terminal supports it, the renderer will enable1140		// it once we get the response.1141		p.executeQuery(ansi.RequestModeSynchronizedOutput +1142			ansi.RequestModeUnicodeCore)1143	}11441145	// Initialize the program.1146	initCmd := model.Init()1147	if initCmd != nil {1148		ch := make(chan struct{})1149		p.handlers.add(ch)11501151		go func() {1152			defer close(ch)11531154			select {1155			case cmds <- initCmd:1156			case <-p.ctx.Done():1157			}1158		}()1159	}11601161	// Render the initial view.1162	p.render(model)11631164	// Handle resize events.1165	p.handlers.add(p.handleResize())11661167	// Process commands.1168	p.handlers.add(p.handleCommands(cmds))11691170	// Run event loop, handle updates and draw.1171	var err error1172	model, err = p.eventLoop(model, cmds)11731174	if err == nil && len(p.errs) > 0 {1175		err = <-p.errs // Drain a leftover error in case eventLoop crashed.1176	}11771178	killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil1179	if killed {1180		if err == nil && p.externalCtx.Err() != nil {1181			// Return also as context error the cancellation of an external context.1182			// This is the context the user knows about and should be able to act on.1183			err = fmt.Errorf("%w: %w", ErrProgramKilled, p.externalCtx.Err())1184		} else if err == nil && p.ctx.Err() != nil {1185			// Return only that the program was killed (not the internal mechanism).1186			// The user does not know or need to care about the internal program context.1187			err = ErrProgramKilled1188		} else {1189			// Return that the program was killed and also the error that caused it.1190			err = fmt.Errorf("%w: %w", ErrProgramKilled, err)1191		}1192	} else {1193		// Graceful shutdown of the program (not killed):1194		// Ensure we rendered the final state of the model.1195		p.render(model)1196	}11971198	// Restore terminal state.1199	p.shutdown(killed)12001201	return model, err1202}12031204// Send sends a message to the main update function, effectively allowing1205// messages to be injected from outside the program for interoperability1206// purposes.1207//1208// If the program hasn't started yet this will be a blocking operation.1209// If the program has already been terminated this will be a no-op, so it's safe1210// to send messages after the program has exited.1211func (p *Program) Send(msg Msg) {1212	select {1213	case <-p.ctx.Done():1214	case p.msgs <- msg:1215	}1216}12171218// Quit is a convenience function for quitting Bubble Tea programs. Use it1219// when you need to shut down a Bubble Tea program from the outside.1220//1221// If you wish to quit from within a Bubble Tea program use the Quit command.1222//1223// If the program is not running this will be a no-op, so it's safe to call1224// if the program is unstarted or has already exited.1225func (p *Program) Quit() {1226	p.Send(Quit())1227}12281229// Kill stops the program immediately and restores the former terminal state.1230// The final render that you would normally see when quitting will be skipped.1231// [program.Run] returns a [ErrProgramKilled] error.1232func (p *Program) Kill() {1233	p.shutdown(true)1234}12351236// Wait waits/blocks until the underlying Program finished shutting down.1237func (p *Program) Wait() {1238	<-p.finished1239}12401241// execute writes the given sequence to the program output.1242func (p *Program) execute(seq string) {1243	p.mu.Lock()1244	_, _ = p.outputBuf.WriteString(seq)1245	p.mu.Unlock()1246}12471248// executeQuery writes a terminal query to the program output. Queries expect a1249// reply on p.input, so when input is disabled the query is skipped: the1250// program cannot read the response, and the terminal's reply would leak into1251// the shell once the program exits (#1590).1252//1253// This covers every query that expects a reply, not just the startup1254// capability probe: background, foreground, and cursor color requests, cursor1255// position reports, clipboard reads, and terminal version and termcap1256// queries.1257func (p *Program) executeQuery(seq string) {1258	if p.disableInput {1259		return1260	}1261	p.execute(seq)1262}12631264// flush flushes the output buffer to the program output.1265func (p *Program) flush() error {1266	p.mu.Lock()1267	defer p.mu.Unlock()12681269	if p.outputBuf.Len() == 0 {1270		return nil1271	}1272	if p.logger != nil {1273		p.logger.Printf("output: %q", p.outputBuf.String())1274	}1275	_, err := p.output.Write(p.outputBuf.Bytes())1276	p.outputBuf.Reset()1277	if err != nil {1278		return fmt.Errorf("error writing to output: %w", err)1279	}1280	return nil1281}12821283// shutdown performs operations to free up resources and restore the terminal1284// to its original state.1285func (p *Program) shutdown(kill bool) {1286	p.shutdownOnce.Do(func() {1287		p.cancel()12881289		// Wait for all handlers to finish.1290		p.handlers.shutdown()12911292		// Check if the cancel reader has been setup before waiting and closing.1293		if p.cancelReader != nil {1294			// Wait for input loop to finish.1295			if p.cancelReader.Cancel() {1296				if !kill {1297					p.waitForReadLoop()1298				}1299			}1300			_ = p.cancelReader.Close()1301		}13021303		if p.renderer != nil {1304			p.stopRenderer(kill)1305		}13061307		_ = p.restoreTerminalState()1308	})1309}13101311// recoverFromPanic recovers from a panic, prints the stack trace, and restores1312// the terminal to a usable state.1313func (p *Program) recoverFromPanic(r interface{}) {1314	select {1315	case p.errs <- ErrProgramPanic:1316	default:1317	}1318	p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore.1319	// We use "\r\n" to ensure the output is formatted even when restoring the1320	// terminal does not work or when raw mode is still active.1321	rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")1322	fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)1323	stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")1324	fmt.Fprint(os.Stderr, stack)1325	if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {1326		f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))1327		if err == nil {1328			defer f.Close()        //nolint:errcheck1329			fmt.Fprintln(f, rec)   //nolint:errcheck1330			fmt.Fprintln(f)        //nolint:errcheck1331			fmt.Fprintln(f, stack) //nolint:errcheck1332		}1333	}1334}13351336// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and1337// signals for the program to be killed and terminal restored to a usable state.1338func (p *Program) recoverFromGoPanic(r interface{}) {1339	select {1340	case p.errs <- ErrProgramPanic:1341	default:1342	}1343	p.cancel()1344	// We use "\r\n" to ensure the output is formatted even when restoring the1345	// terminal does not work or when raw mode is still active.1346	rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")1347	fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)1348	stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")1349	fmt.Fprint(os.Stderr, stack)1350	if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {1351		f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))1352		if err == nil {1353			defer f.Close()        //nolint:errcheck1354			fmt.Fprintln(f, rec)   //nolint:errcheck1355			fmt.Fprintln(f)        //nolint:errcheck1356			fmt.Fprintln(f, stack) //nolint:errcheck1357		}1358	}1359}13601361// ReleaseTerminal restores the original terminal state and cancels the input1362// reader. You can return control to the Program with RestoreTerminal.1363func (p *Program) ReleaseTerminal() error {1364	return p.releaseTerminal(false)1365}13661367func (p *Program) releaseTerminal(reset bool) error {1368	atomic.StoreUint32(&p.ignoreSignals, 1)1369	if p.cancelReader != nil {1370		p.cancelReader.Cancel()1371	}13721373	p.waitForReadLoop()13741375	if p.renderer != nil {1376		p.stopRenderer(false)1377		if reset {1378			p.renderer.reset()1379		}1380	}13811382	return p.restoreTerminalState()1383}13841385// RestoreTerminal reinitializes the Program's input reader, restores the1386// terminal to the former state when the program was running, and repaints.1387// Use it to reinitialize a Program after running ReleaseTerminal.1388func (p *Program) RestoreTerminal() error {1389	atomic.StoreUint32(&p.ignoreSignals, 0)13901391	if err := p.initTerminal(); err != nil {1392		return err1393	}1394	if p.input != nil {1395		if err := p.initInputReader(false); err != nil {1396			return err1397		}1398	}13991400	p.startRenderer()14011402	// If the output is a terminal, it may have been resized while another1403	// process was at the foreground, in which case we may not have received1404	// SIGWINCH. Detect any size change now and propagate the new size as1405	// needed.1406	go p.checkResize()14071408	// Flush queued commands.1409	return p.flush()1410}14111412// Println prints above the Program. This output is unmanaged by the program1413// and will persist across renders by the Program.1414//1415// If the altscreen is active no output will be printed.1416func (p *Program) Println(args ...any) {1417	p.msgs <- printLineMessage{1418		messageBody: fmt.Sprint(args...),1419	}1420}14211422// Printf prints above the Program. It takes a format template followed by1423// values similar to fmt.Printf. This output is unmanaged by the program and1424// will persist across renders by the Program.1425//1426// Unlike fmt.Printf (but similar to log.Printf) the message will be print on1427// its own line.1428//1429// If the altscreen is active no output will be printed.1430func (p *Program) Printf(template string, args ...any) {1431	p.msgs <- printLineMessage{1432		messageBody: fmt.Sprintf(template, args...),1433	}1434}14351436// startRenderer starts the renderer.1437func (p *Program) startRenderer() {1438	framerate := time.Second / time.Duration(p.fps)1439	if p.ticker == nil {1440		p.ticker = time.NewTicker(framerate)1441	} else {1442		// If the ticker already exists, it has been stopped and we need to1443		// reset it.1444		p.ticker.Reset(framerate)1445	}14461447	// Since the renderer can be restarted after a stop, we need to reset1448	// the done channel and its corresponding sync.Once.1449	p.once = sync.Once{}14501451	// Start the renderer.1452	p.renderer.start()1453	go func() {1454		for {1455			select {1456			case <-p.rendererDone:1457				p.ticker.Stop()1458				return14591460			case <-p.ticker.C:1461				_ = p.flush()1462				_ = p.renderer.flush(false)1463			}1464		}1465	}()1466}14671468// stopRenderer stops the renderer.1469// If kill is true, the renderer will be stopped immediately without flushing1470// the last frame.1471func (p *Program) stopRenderer(kill bool) {1472	// Stop the renderer before acquiring the mutex to avoid a deadlock.1473	p.once.Do(func() {1474		p.rendererDone <- struct{}{}1475	})14761477	if !kill {1478		// flush locks the mutex1479		_ = p.renderer.flush(true)1480	}14811482	_ = p.renderer.close()1483}