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 fileTake it
The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.
feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1–6why, one step back1// 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//docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b
line 7why, one step back7// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/main/tutorialsfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 8why, one step back8//docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b
line 9why, one step back9// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/main/examplesfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 10–12why, one step back10package tea1112import (Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 13why, one step back13 "bytes"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 14–16why, one step back14 "context"15 "errors"16 "fmt"Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 17why, one step back17 "image/color"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 18why, one step back18 "io"Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 19why, one step back19 "log"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 20–21why, one step back20 "os"21 "os/signal"fix(renderer): use mapNl optimization when not on Windows and no PTY input (#1615)Ayman Bagabasbefore adoptionf25595a
line 22why, one step back22 "runtime"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 23why, one step back23 "runtime/debug"Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 24–25why, one step back24 "strconv"25 "strings"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 26–28why, one step back26 "sync"27 "sync/atomic"28 "syscall"Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 29–33why, one step back29 "time"3031 "github.com/charmbracelet/colorprofile"32 uv "github.com/charmbracelet/ultraviolet"33 "github.com/charmbracelet/x/ansi"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 34–35why, one step back34 "github.com/charmbracelet/x/term"35 "github.com/muesli/cancelreader"Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 36–37why, one step back36)37chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 38–39why, one step back38// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.39var ErrProgramPanic = errors.New("program experienced a panic")Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 40why, one step back40feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
line 41why, one step back41// ErrProgramKilled is returned by [Program.Run] when the program gets killed.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 42why, one step back42var ErrProgramKilled = errors.New("program was killed")Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 43why, one step back43feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 44–46why, one step back44// 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")Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 47why, one step back47feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 48–49why, one step back48// Msg contain data from the result of a IO operation. Msgs trigger the update49// function and, henceforth, the UI.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 50–51why, one step back50type Msg = uv.Event51feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 52–56why, one step back52// 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() CmdMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 57why, one step back57feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 58–60why, one step back58 // 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)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 61–148why, one step back6162 // 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 *ProgressBar148feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626
lines 149–162why, one step back149 // 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 *ProgramStatus162Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 163–261why, one step back163 // 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 boolfeat: support extended keyboard enhancements (#1626)Ayman Bagabasbefore adoption05df5ae
lines 262–280why, one step back262263 // 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 boolMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 281–333why, one step back281}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)333fix: don't panic in ProgressBarState.String() for out-of-range values (#1748)Ankitbefore adoption930e18c
lines 334–335why, one step back334// String returns a human-readable name for the given [ProgressBarState].335// Values outside the known range return "Unknown".Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 336why, one step back336func (s ProgressBarState) String() string {fix: don't panic in ProgressBarState.String() for out-of-range values (#1748)Ankitbefore adoption930e18c
lines 337–350why, one step back337 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 }Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 351–360why, one step back351}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],fix: typo in doc (#1756)Drew Smirnoffbefore adoption0ef9fc9
line 361why, one step back361 // [ProgressBarIndeterminate], and [ProgressBarWarning].Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 362–413why, one step back362 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() Msg413feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 414–416why, one step back414// 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.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 417–421why, one step back417type channelHandlers struct {418 handlers []chan struct{}419 mu sync.RWMutex420}421feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 422–424why, one step back422// 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{}) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 425–429why, one step back425 h.mu.Lock()426 h.handlers = append(h.handlers, ch)427 h.mu.Unlock()428}429feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 430why, one step back430// shutdown waits for all handlers to terminate.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 431–438why, one step back431func (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)feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 439–442why, one step back439 go func(ch chan struct{}) {440 <-ch441 wg.Done()442 }(ch)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 443why, one step back443 }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 444why, one step back444 wg.Wait()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 445–446why, one step back445}446feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 447–448why, one step back447// Program is a terminal user interface.448type Program struct {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 449–493why, one step back449 // 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 // }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 494why, one step back494 filter func(Model, Msg) MsgMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 495–498why, one step back495496 // 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.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 499why, one step back499 fps intMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 500–575why, one step back500501 // 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}575feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 576–578why, one step back576// Quit is a special command that tells the Bubble Tea program to exit.577func Quit() Msg {578 return QuitMsg{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 579–580why, one step back579}580feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 581–582why, one step back581// QuitMsg signals that the program should quit. You can send a [QuitMsg] with582// [Quit].feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 583why, one step back583type QuitMsg struct{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 584why, one step back584feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 585–587why, one step back585// Suspend is a special command that tells the Bubble Tea program to suspend.586func Suspend() Msg {587 return SuspendMsg{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 588–589why, one step back588}589feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 590–591why, one step back590// SuspendMsg signals the program should suspend.591// This usually happens when ctrl+z is pressed on common programs, but sinceMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 592–594why, one step back592// bubbletea puts the terminal in raw mode, we need to handle it in a593// per-program basis.594//feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
line 595why, one step back595// You can send this message with [Suspend()].feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 596why, one step back596type SuspendMsg struct{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 597why, one step back597chore: fix some commentsyingshanghuangqiaobefore adoptionb6958d3
line 598why, one step back598// ResumeMsg can be listen to do something once a program is resumed backfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 599–600why, one step back599// from a suspend state.600type ResumeMsg struct{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 601why, one step back601feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 602–603why, one step back602// InterruptMsg signals the program should suspend.603// This usually happens when ctrl+c is pressed on common programs, but sinceMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 604–606why, one step back604// bubbletea puts the terminal in raw mode, we need to handle it in a605// per-program basis.606//feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 607–608why, one step back607// You can send this message with [Interrupt()].608type InterruptMsg struct{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 609why, one step back609feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 610–613why, one step back610// Interrupt is a special command that tells the Bubble Tea program to611// interrupt.612func Interrupt() Msg {613 return InterruptMsg{}Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 614–616why, one step back614}615616// NewProgram creates a new [Program].feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 617–620why, one step back617func NewProgram(model Model, opts ...ProgramOption) *Program {618 p := &Program{619 initialModel: model,620 msgs: make(chan Msg),Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 621–624why, one step back621 errs: make(chan error, 1),622 rendererDone: make(chan struct{}),623 }624feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 625–627why, one step back625 // Apply all options to the program.626 for _, opt := range opts {627 opt(p)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 628–629why, one step back628 }629feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 630–631why, one step back630 // A context can be provided with a ProgramOption, but if none was provided631 // we'll use the default background context.chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 632–633why, one step back632 if p.externalCtx == nil {633 p.externalCtx = context.Background()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 634–635why, one step back634 }635 // Initialize context and teardown channel.chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
line 636why, one step back636 p.ctx, p.cancel = context.WithCancel(p.externalCtx)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 637why, one step back637feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 638–640why, one step back638 // if no output was set, set it to stdout639 if p.output == nil {640 p.output = os.StdoutMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 641–642why, one step back641 }642feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 643–645why, one step back643 // if no environment was set, set it to os.Environ()644 if p.environ == nil {645 p.environ = os.Environ()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 646–661why, one step back646 }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 }661feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 662why, one step back662 return pMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 663–664why, one step back663}664feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 665why, one step back665func (p *Program) handleSignals() chan struct{} {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 666–667why, one step back666 ch := make(chan struct{})667feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 668why, one step back668 // Listen for SIGINT and SIGTERM.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 669why, one step back669 //feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 670–673why, one step back670 // 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.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 674why, one step back674 //feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 675why, one step back675 // SIGTERM is sent by unix utilities (like kill) to terminate a process.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 676why, one step back676 go func() {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 677–678why, one step back677 sig := make(chan os.Signal, 1)678 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 679why, one step back679 defer func() {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 680–681why, one step back680 signal.Stop(sig)681 close(ch)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 682–688why, one step back682 }()683684 for {685 select {686 case <-p.ctx.Done():687 return688feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
line 689why, one step back689 case s := <-sig:feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 690why, one step back690 if atomic.LoadUint32(&p.ignoreSignals) == 0 {fix: prevent signal goroutine deadlock on shutdown (#1806)陈志谦before adoptionff51ba4
lines 691–697why, one step back691 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():Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 698why, one step back698 }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 699why, one step back699 returnMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 700–707why, one step back700 }701 }702 }703 }()704705 return ch706}707feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 708–709why, one step back708// handleResize handles terminal resize events.709func (p *Program) handleResize() chan struct{} {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 710–712why, one step back710 ch := make(chan struct{})711712 if p.ttyOutput != nil {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 713–714why, one step back713 // Listen for window resizes.714 go p.listenForResize(ch)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 715why, one step back715 } else {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 716why, one step back716 close(ch)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 717–721why, one step back717 }718719 return ch720}721feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 722–724why, one step back722// 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{} {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 725–727why, one step back725 ch := make(chan struct{})726727 go func() {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 728why, one step back728 defer close(ch)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 729–734why, one step back729730 for {731 select {732 case <-p.ctx.Done():733 return734feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 735–737why, one step back735 case cmd := <-cmds:736 if cmd == nil {737 continueMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 738–739why, one step back738 }739feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 740–746why, one step back740 // 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.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 747why, one step back747 if !p.disableCatchPanics {chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 748–749why, one step back748 defer func() {749 if r := recover(); r != nil {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 750why, one step back750 p.recoverFromPanic(r)chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 751–752why, one step back751 }752 }()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 753–754why, one step back753 }754feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 755–756why, one step back755 msg := cmd() // this can be long.756 p.Send(msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 757–764why, one step back757 }()758 }759 }760 }()761762 return ch763}764feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 765–771why, one step back765// 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, nilMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 772why, one step back772feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 773why, one step back773 case err := <-p.errs:Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 774–775why, one step back774 return model, err775feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 776why, one step back776 case msg := <-p.msgs:Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 777–778why, one step back777 msg = p.translateInputEvent(msg)778feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 779–781why, one step back779 // Filter messages.780 if p.filter != nil {781 msg = p.filter(model, msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 782why, one step back782 }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 783why, one step back783 if msg == nil {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 784–786why, one step back784 continue785 }786feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 787why, one step back787 // Handle special internal messages.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 788why, one step back788 switch msg := msg.(type) {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 789why, one step back789 case QuitMsg:Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 790–791why, one step back790 return model, nil791feat(SIGINT): better handle interrupts (#1255)Carlos Alexandro Beckerbefore adoptioncb93959
lines 792–793why, one step back792 case InterruptMsg:793 return model, ErrInterruptedMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 794why, one step back794feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 795–797why, one step back795 case SuspendMsg:796 if suspendSupported {797 p.suspend()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 798–824why, one step back798 }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:feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 825why, one step back825 switch msg.(type) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 826–834why, one step back826 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:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 835why, one step back835 p.executeQuery(ansi.RequestSystemClipboard)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 836–840why, one step back836837 case setClipboardMsg:838 p.execute(ansi.SetSystemClipboard(string(msg)))839840 case readPrimaryClipboardMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 841why, one step back841 p.executeQuery(ansi.RequestPrimaryClipboard)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 842–846why, one step back842843 case setPrimaryClipboardMsg:844 p.execute(ansi.SetPrimaryClipboard(string(msg)))845846 case backgroundColorMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 847why, one step back847 p.executeQuery(ansi.RequestBackgroundColor)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 848–849why, one step back848849 case foregroundColorMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 850why, one step back850 p.executeQuery(ansi.RequestForegroundColor)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 851–852why, one step back851852 case cursorColorMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 853why, one step back853 p.executeQuery(ansi.RequestCursorColor)feat: OSC 7501 (#1841)Drew Smirnoffbefore adoption41bc626
lines 854–856why, one step back854855 case programStatusSupportMsg:856 p.executeQuery(ansi.RequestProgramStatusSupport)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 857why, one step back857feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 858–860why, one step back858 case execMsg:859 // NB: this blocks.860 p.exec(msg.cmd, msg.fn)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 861–862why, one step back861862 case terminalVersion:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 863why, one step back863 p.executeQuery(ansi.RequestNameVersion)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 864–865why, one step back864865 case requestCapabilityMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 866why, one step back866 p.executeQuery(ansi.RequestTermcap(string(msg)))Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 867–868why, one step back867868 case BatchMsg:Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 869why, one step back869 go p.execBatchMsg(msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 870–872why, one step back870 continue871872 case sequenceMsg:Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 873why, one step back873 go p.execSequenceMsg(msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 874–878why, one step back874 continue875876 case WindowSizeMsg:877 p.renderer.resize(msg.Width, msg.Height)878fix: handle setWindowTitleMsg and windowSizeMsg in eventLoopAyman Bagabasbefore adoption9edf69c
lines 879–880why, one step back879 case windowSizeMsg:880 go p.checkResize()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 881–882why, one step back881882 case requestCursorPosMsg:fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 883why, one step back883 p.executeQuery(ansi.RequestCursorPositionReport)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 884–897why, one step back884885 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 }897feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 898–899why, one step back898 var cmd Cmd899 model, cmd = model.Update(msg) // run updateMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 900–903why, one step back900901 select {902 case <-p.ctx.Done():903 return model, nilchore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
line 904why, one step back904 case cmds <- cmd: // process command (if any)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 905–918why, one step back905 }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}918Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 919why, one step back919func (p *Program) execSequenceMsg(msg sequenceMsg) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 920–927why, one step back920 if !p.disableCatchPanics {921 defer func() {922 if r := recover(); r != nil {923 p.recoverFromGoPanic(r)924 }925 }()926 }927Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 928why, one step back928 // Execute commands one at a time, in order.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 929–932why, one step back929 for _, cmd := range msg {930 if cmd == nil {931 continue932 }Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
lines 933–940why, one step back933 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)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 941–944why, one step back941 }942 }943}944Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 945why, one step back945func (p *Program) execBatchMsg(msg BatchMsg) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 946–953why, one step back946 if !p.disableCatchPanics {947 defer func() {948 if r := recover(); r != nil {949 p.recoverFromGoPanic(r)950 }951 }()952 }953Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 954why, one step back954 // Execute commands one at a time.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 955–961why, one step back955 var wg sync.WaitGroup956 for _, cmd := range msg {957 if cmd == nil {958 continue959 }960 wg.Add(1)961 go func() {Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 962why, one step back962 defer wg.Done()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 963–964why, one step back963964 if !p.disableCatchPanics {Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
lines 965–967why, one step back965 defer func() {966 if r := recover(); r != nil {967 p.recoverFromGoPanic(r)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 968–971why, one step back968 }969 }()970 }971Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 972why, one step back972 msg := cmd()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 973–974why, one step back973 switch msg := msg.(type) {974 case BatchMsg:Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 975why, one step back975 p.execBatchMsg(msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 976why, one step back976 case sequenceMsg:Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
lines 977–979why, one step back977 p.execSequenceMsg(msg)978 default:979 p.Send(msg)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 980–983why, one step back980 }981 }()982 }983Merge pull request #848 from wolfmagnate/fix-nested-cmd-orderAyman Bagabasbefore adoptionffa0502
line 984why, one step back984 wg.Wait() // wait for all commands from batch msg to finishMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 985–1014why, one step back985}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}1014feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1015–1017why, one step back1015// 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.chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
line 1018why, one step back1018func (p *Program) Run() (returnModel Model, returnErr error) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1019–1023why, one step back1019 if p.initialModel == nil {1020 return nil, errors.New("bubbletea: InitialModel cannot be nil")1021 }10221023 // Initialize context and teardown channel.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1024–1025why, one step back1024 p.handlers = channelHandlers{}1025 cmds := make(chan Cmd)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1026why, one step back1026chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 1027–1029why, one step back1027 p.finished = make(chan struct{})1028 defer func() {1029 close(p.finished)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1030–1031why, one step back1030 }()1031feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1032why, one step back1032 defer p.cancel()Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1033–1036why, one step back10331034 if p.disableInput {1035 p.input = nil1036 } else if p.input == nil {fix: check if os.Stdin is a terminal before opening the TTYAyman Bagabasbefore adoption66b7abd
lines 1037–1043why, one step back1037 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 = ttyInMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1044–1046why, one step back1044 }1045 }1046feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1047why, one step back1047 // Handle signals.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1048why, one step back1048 if !p.disableSignalHandler {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1049why, one step back1049 p.handlers.add(p.handleSignals())Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1050–1051why, one step back1050 }1051feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1052why, one step back1052 // Recover from panics.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1053–1055why, one step back1053 if !p.disableCatchPanics {1054 defer func() {1055 if r := recover(); r != nil {chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 1056–1057why, one step back1056 returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)1057 p.recoverFromPanic(r)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1058–1061why, one step back1058 }1059 }()1060 }1061feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1062–1063why, one step back1062 // Check if output is a TTY before entering raw mode, hiding the cursor and1063 // so on.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1064why, one step back1064 if err := p.initTerminal(); err != nil {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1065why, one step back1065 return p.initialModel, errMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1066–1076why, one step back1066 }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 }1076fix(tty): fall back to default dimensions when terminal size is 0x0 (#1836)adam maguedbefore adoption96d69d2
line 1077why, one step back1077 width, height = p.fallbackDimensions(w, h)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1078–1094why, one step back1078 }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)fix: restore kitty keyboard stack on exit (#1750)deepakganesh78before adoption0d3e281
line 1095why, one step back1095 r.setNoInput(p.disableInput)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1096–1101why, one step back1096 // 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 offix(renderer): use mapNl optimization when not on Windows and no PTY input (#1615)Ayman Bagabasbefore adoptionf25595a
lines 1102–1103why, one step back1102 // raw mode. See issue #1572.1103 mapNl := runtime.GOOS != "windows" && p.ttyInput == nilMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1104–1126why, one step back1104 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.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1127–1128why, one step back1127 model := p.initialModel1128 if p.input != nil {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1129–1136why, one step back1129 if err := p.initInputReader(false); err != nil {1130 return model, err1131 }1132 }11331134 // Start the renderer.1135 p.startRenderer()1136fix(tea): don't query for synchronized output if the renderer is disabledAyman Bagabasbefore adoption1ff0a47
line 1137why, one step back1137 if !p.disableRenderer && shouldQuerySynchronizedOutput(p.environ) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1138–1140why, one step back1138 // 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.fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
line 1141why, one step back1141 p.executeQuery(ansi.RequestModeSynchronizedOutput +Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1142–1163why, one step back1142 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)1163feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1164–1165why, one step back1164 // Handle resize events.1165 p.handlers.add(p.handleResize())Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1166why, one step back1166feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1167–1168why, one step back1167 // Process commands.1168 p.handlers.add(p.handleCommands(cmds))Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1169why, one step back1169feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1170why, one step back1170 // Run event loop, handle updates and draw.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1171–1173why, one step back1171 var err error1172 model, err = p.eventLoop(model, cmds)1173chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
line 1174why, one step back1174 if err == nil && len(p.errs) > 0 {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1175–1177why, one step back1175 err = <-p.errs // Drain a leftover error in case eventLoop crashed.1176 }1177chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 1178–1187why, one step back1178 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 = ErrProgramKilledMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1188why, one step back1188 } else {chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
lines 1189–1190why, one step back1189 // Return that the program was killed and also the error that caused it.1190 err = fmt.Errorf("%w: %w", ErrProgramKilled, err)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1191–1192why, one step back1191 }1192 } else {chore: merge pull request #1376 from desertwitch/stacked-patchesAyman Bagabasbefore adoption915f65d
line 1193why, one step back1193 // Graceful shutdown of the program (not killed):feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1194why, one step back1194 // Ensure we rendered the final state of the model.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1195–1197why, one step back1195 p.render(model)1196 }1197feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1198–1199why, one step back1198 // Restore terminal state.1199 p.shutdown(killed)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1200why, one step back1200feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1201why, one step back1201 return model, errMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1202–1203why, one step back1202}1203feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1204–1206why, one step back1204// Send sends a message to the main update function, effectively allowing1205// messages to be injected from outside the program for interoperability1206// purposes.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1207why, one step back1207//feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1208–1211why, one step back1208// 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) {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1212why, one step back1212 select {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1213–1214why, one step back1213 case <-p.ctx.Done():1214 case p.msgs <- msg:Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1215–1217why, one step back1215 }1216}1217feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1218–1219why, one step back1218// 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.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1220why, one step back1220//feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1221why, one step back1221// If you wish to quit from within a Bubble Tea program use the Quit command.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1222why, one step back1222//feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1223–1226why, one step back1223// 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())Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1227–1229why, one step back1227}12281229// Kill stops the program immediately and restores the former terminal state.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1230–1232why, one step back1230// The final render that you would normally see when quitting will be skipped.1231// [program.Run] returns a [ErrProgramKilled] error.1232func (p *Program) Kill() {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1233–1235why, one step back1233 p.shutdown(true)1234}1235feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1236–1238why, one step back1236// Wait waits/blocks until the underlying Program finished shutting down.1237func (p *Program) Wait() {1238 <-p.finishedMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1239–1245why, one step back1239}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()fix: skip capability queries when input is disabled (#1801)draw me an elephantbefore adoption8b10e22
lines 1246–1261why, one step back1246}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)Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1262–1279why, one step back1262}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 }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1280why, one step back1280 return nilMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1281–1393why, one step back1281}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 }fix: skip input reader restore when input is disabled (#1680)chaoliang yanbefore adoption074596e
lines 1394–1397why, one step back1394 if p.input != nil {1395 if err := p.initInputReader(false); err != nil {1396 return err1397 }Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1398–1411why, one step back1398 }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}1411feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1412–1413why, one step back1412// Println prints above the Program. This output is unmanaged by the program1413// and will persist across renders by the Program.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1414–1417why, one step back1414//1415// If the altscreen is active no output will be printed.1416func (p *Program) Println(args ...any) {1417 p.msgs <- printLineMessage{feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1418why, one step back1418 messageBody: fmt.Sprint(args...),Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1419–1421why, one step back1419 }1420}1421feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1422–1424why, one step back1422// 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.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1425why, one step back1425//feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 1426–1427why, one step back1426// Unlike fmt.Printf (but similar to log.Printf) the message will be print on1427// its own line.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1428–1431why, one step back1428//1429// If the altscreen is active no output will be printed.1430func (p *Program) Printf(template string, args ...any) {1431 p.msgs <- printLineMessage{feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1432why, one step back1432 messageBody: fmt.Sprintf(template, args...),Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 1433–1482why, one step back1433 }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()feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 1483why, one step back1483}