Compare commits

...

51 commits
v2.0.8 ... main

Author SHA1 Message Date
Drew Smirnoff
585149e50e
fix: drain terminal query replies before releasing the terminal (#1894)
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 19:01:53 +04:00
Meng Yan
b681f23559
fix(renderer): flush queued view before insert above (#1741)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Meng Yan <yanmxa@gmail.com>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:56:54 +04:00
jane michelle arc
9c6598361d
fix: return write errors from Program.Run (#1879)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:52:39 +04:00
Johnny Chen
bc55190481
fix: synchronize canceled input cleanup (#1876)
AI-assisted-by: Codex (GPT 6.1 sol)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:44:32 +04:00
draw me an elephant
7dd9c4c46e
fix: keep signal subscription alive through shutdown (#1853)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:38:53 +04:00
draw me an elephant
7ab4335dac
fix: don't panic on uncomparable color.Color values (#1852)
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:33:00 +04:00
Drew Smirnoff
38ddf5f58c
v2.1.2
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-18 12:44:36 +04:00
jane michelle arc
4853fdaaa0
fix(renderer): skip redraws when empty or tall views haven't changed (#1897) 2026-11-18 11:40:20 +04:00
jane michelle arc
8675fd8a85
fix: restore unicode mode on resume (#1896) 2026-11-18 11:31:36 +04:00
Morax
6b30ecf328
fix(renderer): use view height before first flush (#1766)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:45:21 +04:00
Gurdeep
94d45c807d
fix(renderer): prevent emitting stale frame on resize (#1856)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Gurdeep <gurdeepdalal05@gmail.com>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:39:48 +04:00
Ahmet Kamer Çivi
18d6fa3b34
fix: close trace file after program run (#1844)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:36:39 +04:00
Ahmet Kamer Çivi
1b8005fc10
fix: avoid terminal wait without input (#1829)
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:32:37 +04:00
Sanjay Santhanam
df137dee9a
fix: measure insertAbove lines with the active width method (#1861)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:30:31 +04:00
tianrking
b9e7454fd4
fix: make Quit a no-op before Run starts (#1840)
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:26:03 +04:00
draw me an elephant
13fb42d8ea
fix: close the TTY files opened for input when Run returns (#1855)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-12 17:25:49 +04:00
draw me an elephant
12b7b4d0eb
fix: restore terminal state on Run error paths (#1854)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-12 17:25:35 +04:00
Attila Fábián
56a2fe7fed
fix: close the replaced cancel reader on RestoreTerminal (#1821)
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:25:04 +04:00
Wu Shuwen
f3d74b724c
fix: ensure terminal state is restored after panics in Batch/Sequence commands (#1818)
Co-authored-by: TRAE AI Assistant <trae@bytedance.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:24:49 +04:00
Calvin Prewitt
73b79b3737
Provide the platform input/signal stubs on wasip1/wasip2 (#1767)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:24:26 +04:00
赵鑫亿
9806b0c763
fix(exec): clear View before releasing terminal for subprocess (#1762)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:23:45 +04:00
Ricardo-M-L
7a446b73f6
fix: avoid blocking prints after program exit (#1758)
Co-authored-by: Ricardo-M-L <XuthodoreveraynWX61@elvisfan.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:23:24 +04:00
Ricardo-M-L
418cada888
fix(logging): preserve Unicode prefix spacing (#1759)
Co-authored-by: Ricardo-M-L <XuthodoreveraynWX61@elvisfan.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:23:07 +04:00
Jack Walker
b3b8f982fe
test: stabilize view model golden output (#1752)
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:22:51 +04:00
Harjot Singh
bd09ae6834
fix: preserve exact-width lines printed above the view (#1888)
Co-authored-by: Drew Smirnoff <drew@charm.land>
2026-11-12 17:21:47 +04:00
陈志谦
55ba0f6de3
fix: allow Program.Run to be called again after the program exits (#1890)
Signed-off-by: simpleqt <2015900818@qq.com>
2026-11-12 17:21:35 +04:00
Drew Smirnoff
5982a61ef5
fix: data race with Kill() and Run() (#1774)
Signed-off-by: drew <me@andrinoff.com>
2026-11-12 17:11:18 +04:00
Viktor Danov
e4d617e7e0
perf(renderer): stop the frame ticker while nothing changes (#1832)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-09 14:55:22 +04:00
drew
67b4c7a8a2
v2.1.1
Signed-off-by: drew <me@andrinoff.com>
2026-10-28 14:18:02 +04:00
Drew Smirnoff
9c6c325f83
fix: ingnore implausible terminal resize reports (#1887)
Signed-off-by: drew <me@andrinoff.com>
2026-10-26 17:59:16 +04:00
drew
f9df43c4f2
v2.1.0
Signed-off-by: drew <me@andrinoff.com>
2026-10-08 21:38:55 +04:00
Drew Smirnoff
41bc626564
feat: OSC 7501 (#1841)
Signed-off-by: drew <me@andrinoff.com>
2026-10-08 21:36:08 +04:00
adam magued
96d69d2f7e
fix(tty): fall back to default dimensions when terminal size is 0x0 (#1836)
Co-authored-by: AdamMagued <adammagued.business@gmail.com>
2026-10-02 15:07:33 +04:00
Hsn
33f6a40ec0
docs: fix command and environment godoc examples (#1833) 2026-10-02 13:30:47 +04:00
陈志谦
ff51ba4c51
fix: prevent signal goroutine deadlock on shutdown (#1806) 2026-09-28 15:07:39 +04:00
drew
d5bfd5c2ff
v2.0.10
Signed-off-by: drew <me@andrinoff.com>
2026-09-24 12:06:39 +04:00
draw me an elephant
8b10e22689
fix: skip capability queries when input is disabled (#1801)
Co-authored-by: drew <me@andrinoff.com>
Signed-off-by: drew <me@andrinoff.com>
2026-09-24 12:05:48 +04:00
Drew Smirnoff
657aaae216
chore: bump go to 1.26.0 (#1807)
Signed-off-by: drew <me@andrinoff.com>
2026-09-17 12:08:29 +04:00
drew
73b6d91ac1
v2.0.9
Signed-off-by: drew <me@andrinoff.com>
2026-08-19 19:30:09 +04:00
deepakganesh78
0d3e281d14
fix: restore kitty keyboard stack on exit (#1750)
Co-authored-by: drew <me@andrinoff.com>
Signed-off-by: drew <me@andrinoff.com>
2026-08-19 15:56:33 +04:00
Ankit
930e18c966
fix: don't panic in ProgressBarState.String() for out-of-range values (#1748)
Co-authored-by: drew <me@andrinoff.com>
Signed-off-by: drew <me@andrinoff.com>
2026-08-19 12:21:01 +04:00
Drew Smirnoff
faf4dcf54a
fix: pendingErase in cursedRenderer (#1755)
Signed-off-by: drew <me@andrinoff.com>
2026-08-18 11:32:34 +04:00
Charm
351d2159f8
ci: sync dependabot config (#1763) 2026-08-12 17:36:40 -03:00
Ricardo-M-L
dc4b01750c
fix(key): map media record to ultraviolet code (#1757)
Co-authored-by: Ricardo-M-L <XuthodoreveraynWX61@elvisfan.com>
2026-08-11 16:43:12 +04:00
Kobi Hikri
708ee757a8
ci: fix examples workflow (#1734) 2026-08-10 15:55:28 +04:00
Bunlong Heng
1862dfba11
fix: assign MouseButton11 = uv.MouseButton11 (#1754) 2026-08-10 13:58:29 +04:00
Drew Smirnoff
0ef9fc90dc
fix: typo in doc (#1756)
Signed-off-by: drew <me@andrinoff.com>
2026-08-07 20:32:27 +04:00
Jason
af9a33e9c4
chore: remove deprecated windows note (#1695)
* remove deprecated windows note

* restart CI

---------

Co-authored-by: drew <me@andrinoff.com>
2026-08-06 16:20:53 +04:00
mhdna
882727b730
docs: fix links to tutorials & examples (#1645) 2026-08-06 16:20:16 +04:00
makoto-developer
6fb1f47b6c examples/sequence: fix milisecond typo in SleepPrintln
Rename the misspelled `milisecond` parameter to `millisecond`.

Signed-off-by: makoto-developer <72484465+makoto-developer@users.noreply.github.com>
2026-08-04 09:32:40 -04:00
Christian Rocha
d40db141fa docs: fix background color detection example in doc comment 2026-08-04 09:32:22 -04:00
59 changed files with 3684 additions and 237 deletions

View file

@ -4,10 +4,7 @@ updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "05:00"
timezone: "America/New_York"
interval: "monthly"
labels:
- "dependencies"
commit-message:
@ -25,10 +22,7 @@ updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "05:00"
timezone: "America/New_York"
interval: "monthly"
labels:
- "dependencies"
commit-message:
@ -42,10 +36,7 @@ updates:
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "05:00"
timezone: "America/New_York"
interval: "monthly"
labels:
- "dependencies"
commit-message:
@ -59,10 +50,7 @@ updates:
- package-ecosystem: "gomod"
directory: "/examples"
schedule:
interval: "weekly"
day: "monday"
time: "05:00"
timezone: "America/New_York"
interval: "monthly"
labels:
- "dependencies"
commit-message:
@ -76,10 +64,7 @@ updates:
- package-ecosystem: "gomod"
directory: "/tutorials"
schedule:
interval: "weekly"
day: "monday"
time: "05:00"
timezone: "America/New_York"
interval: "monthly"
labels:
- "dependencies"
commit-message:

View file

@ -3,15 +3,15 @@ name: examples
on:
push:
branches:
- 'master'
- 'main'
paths:
- '.github/workflows/examples.yml'
- './examples/go.mod'
- './examples/go.sum'
- './tutorials/go.mod'
- './tutorials/go.sum'
- './go.mod'
- './go.sum'
- 'examples/go.mod'
- 'examples/go.sum'
- 'tutorials/go.mod'
- 'tutorials/go.sum'
- 'go.mod'
- 'go.sum'
workflow_dispatch: {}
jobs:
@ -32,7 +32,7 @@ jobs:
- uses: stefanzweifel/git-auto-commit-action@v7
with:
commit_message: "chore: go mod tidy tutorials and examples"
branch: master
branch: main
commit_user_name: actions-user
commit_user_email: actions@github.com

View file

@ -98,6 +98,7 @@ The `tea.View` struct has fields for everything that used to be controlled by op
| `ForegroundColor` | Set the terminal foreground color |
| `BackgroundColor` | Set the terminal background color |
| `ProgressBar` | Show a native terminal progress bar |
| `ProgramStatus` | Report whether the program is working, waiting on the user, done, or failed (OSC 7501) |
| `KeyboardEnhancements` | Request keyboard enhancement features |
| `OnMouse` | Intercept mouse messages based on view content |

View file

@ -38,7 +38,8 @@ func SetClipboard(s string) Cmd {
type readClipboardMsg struct{}
// ReadClipboard produces a command that reads the system clipboard using OSC52.
// Note that OSC52 is not supported in all terminals.
// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable
// input, since the reply cannot be read otherwise.
func ReadClipboard() Msg {
return readClipboardMsg{}
}
@ -64,7 +65,8 @@ type readPrimaryClipboardMsg struct{}
// ReadPrimaryClipboard produces a command that reads the primary clipboard
// using OSC52. Primary clipboard selection is a feature present in X11 and
// Wayland only.
// Note that OSC52 is not supported in all terminals.
// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable
// input, since the reply cannot be read otherwise.
func ReadPrimaryClipboard() Msg {
return readPrimaryClipboardMsg{}
}

View file

@ -10,6 +10,7 @@ import (
type backgroundColorMsg struct{}
// RequestBackgroundColor is a command that requests the terminal background color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestBackgroundColor() Msg {
return backgroundColorMsg{}
}
@ -18,6 +19,7 @@ func RequestBackgroundColor() Msg {
type foregroundColorMsg struct{}
// RequestForegroundColor is a command that requests the terminal foreground color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestForegroundColor() Msg {
return foregroundColorMsg{}
}
@ -26,6 +28,7 @@ func RequestForegroundColor() Msg {
type cursorColorMsg struct{}
// RequestCursorColor is a command that requests the terminal cursor color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestCursorColor() Msg {
return cursorColorMsg{}
}
@ -49,20 +52,21 @@ func (e ForegroundColorMsg) IsDark() bool {
// emitted when the program requests the terminal background color with the
// [RequestBackgroundColor] Cmd.
//
// This is commonly used in [Update.Init] to get the terminal background color
// This is commonly used in [Model.Init] to get the terminal background color
// for style definitions. For that you'll want to call
// [BackgroundColorMsg.IsDark] to determine if the color is dark or light. For
// example:
//
// func (m Model) Init() (Model, Cmd) {
// return m, RequestBackgroundColor()
// func (m model) Init() Cmd {
// return RequestBackgroundColor
// }
//
// func (m Model) Update(msg Msg) (Model, Cmd) {
// func (m model) Update(msg Msg) (Model, Cmd) {
// switch msg := msg.(type) {
// case BackgroundColorMsg:
// m.styles = newStyles(msg.IsDark())
// }
// return m, nil
// }
type BackgroundColorMsg struct{ color.Color }

View file

@ -9,9 +9,9 @@ import (
//
// Example:
//
// func (m model) Init() (Model, Cmd) {
// return m, tea.Batch(someCommand, someOtherCommand)
// }
// func (m model) Init() tea.Cmd {
// return tea.Batch(someCommand, someOtherCommand)
// }
func Batch(cmds ...Cmd) Cmd {
return compactCmds[BatchMsg](cmds)
}

View file

@ -31,8 +31,12 @@ type cursedRenderer struct {
hardTabs bool // whether to use hard tabs to optimize cursor movements
backspace bool // whether to use backspace to optimize cursor movements
mapnl bool
syncdUpdates bool // whether to use synchronized output mode for updates
starting bool // indicates whether the renderer is starting after being stopped
syncdUpdates bool // whether to use synchronized output mode for updates
starting bool // indicates whether the renderer is starting after being stopped
pendingErase bool // an scr.Erase() is pending and hasn't been drained by flush yet
viewStale bool // a resize occurred and we are waiting for render() to supply the new View
noInput bool // whether input is disabled, in which case keyboard enhancement queries are pointless
onQuery func() // called when a terminal query is written, see [Program.noteQuery]
}
var _ renderer = &cursedRenderer{}
@ -55,6 +59,29 @@ func (s *cursedRenderer) setLogger(logger uv.Logger) {
s.mu.Unlock()
}
// setNoInput disables keyboard enhancement requests. When the program runs
// without input, the terminal's response to a keyboard enhancement query
// would arrive after the program has exited and leak into the shell.
func (s *cursedRenderer) setNoInput(noInput bool) {
s.noInput = noInput
}
// resetKeyboardEnhancements writes the sequences that reset keyboard
// enhancement protocols when switching between the main and alt screens.
// modifyOtherKeys has no stack, so it is reset in place; the Kitty keyboard
// stack is popped, but only if we previously pushed an entry (i.e. this is
// not the first render). With input disabled the keyboard protocol is never
// touched.
func (s *cursedRenderer) resetKeyboardEnhancements(buf *bytes.Buffer) {
if s.noInput {
return
}
_, _ = buf.WriteString(ansi.ResetModifyOtherKeys)
if s.lastView != nil {
_, _ = buf.WriteString(ansi.PopKittyKeyboard(1))
}
}
// setOptimizations sets the cursor movement optimizations.
func (s *cursedRenderer) setOptimizations(hardTabs, backspace, mapnl bool) {
s.mu.Lock()
@ -80,6 +107,11 @@ func (s *cursedRenderer) start() {
// starting the renderer again after it was stopped.
s.starting = true
// close disables Unicode mode; restore it for negotiated grapheme widths.
if s.cellbuf.Method == ansi.GraphemeWidth {
_, _ = s.scr.WriteString(ansi.SetModeUnicodeCore)
}
if s.lastView == nil {
return
}
@ -131,12 +163,19 @@ func (s *cursedRenderer) start() {
if s.lastView.ProgressBar != nil {
setProgressBar(s, s.lastView.ProgressBar)
}
// Enable modifyOtherKeys and Kitty keyboard protocol.
// Both can coexist; terminals ignore what they don't support.
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
if s.lastView.ProgramStatus != nil {
setProgramStatus(s, nil, s.lastView.ProgramStatus)
}
if !s.noInput {
// Enable modifyOtherKeys and Kitty keyboard protocol.
// Both can coexist; terminals ignore what they don't support.
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
kittyFlags := keyboardEnhancementsFlags(s.lastView.KeyboardEnhancements)
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
kittyFlags := keyboardEnhancementsFlags(s.lastView.KeyboardEnhancements)
// The entry was popped when the renderer was stopped, so push a fresh
// one for the screen we're about to restore.
_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))
}
}
// close implements renderer.
@ -153,10 +192,14 @@ func (s *cursedRenderer) close() (err error) {
// two registries for the main and alt screens. We disable keyboard
// enhancements whenever we enter/exit alt screen mode in
// [cursedRenderer.flush].
// Here, we reset the keyboard protocol of the last screen used
// assuming the other screen is already reset when we switched screens.
_, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = s.buf.WriteString(ansi.KittyKeyboard(0, 1))
// Here, we pop the keyboard protocol of the last screen used
// assuming the other screen is already popped when we switched
// screens. With input disabled we never pushed an entry, so there is
// nothing to pop.
if !s.noInput {
_, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = s.buf.WriteString(ansi.PopKittyKeyboard(1))
}
// Go to the bottom of the screen.
// We need to go to the bottom of the screen regardless of whether
@ -212,6 +255,9 @@ func (s *cursedRenderer) close() (err error) {
if lv.ProgressBar != nil && lv.ProgressBar.State != ProgressBarNone {
_, _ = s.scr.WriteString(ansi.ResetProgressBar)
}
// Unlike the progress bar, the program status is left in place: done
// and error reports should outlive the program, and terminals drop
// working and blocked records when the process exits.
}
if s.cellbuf.Method == ansi.GraphemeWidth {
@ -245,6 +291,14 @@ func (s *cursedRenderer) close() (err error) {
return nil
}
// query writes a terminal query and reports it to onQuery.
func (s *cursedRenderer) query(seq string) {
_, _ = s.scr.WriteString(seq)
if s.onQuery != nil {
s.onQuery()
}
}
// writeString implements renderer.
func (s *cursedRenderer) writeString(str string) (int, error) {
s.mu.Lock()
@ -254,10 +308,19 @@ func (s *cursedRenderer) writeString(str string) (int, error) {
}
// flush implements renderer.
func (s *cursedRenderer) flush(closing bool) error {
func (s *cursedRenderer) flush(closing bool) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.flushLocked(closing)
}
// flushLocked is [cursedRenderer.flush] for callers that hold s.mu.
func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
if !closing && s.viewStale {
return false, nil
}
view := s.view
frameArea := uv.Rect(0, 0, s.width, s.height)
if len(view.Content) == 0 {
@ -279,18 +342,27 @@ func (s *cursedRenderer) flush(closing bool) error {
}
}
// An empty screen buffer has zero width as well as zero height.
if frameArea.Dy() == 0 {
frameArea.Max.X = 0
}
// Restore tab stops if we have tab optimizations enabled.
if s.starting && s.hardTabs {
_, _ = s.scr.WriteString(ansi.SetTabEvery8Columns)
}
if !s.starting && !closing && s.lastView != nil && viewEquals(s.lastView, &view) && frameArea == s.cellbuf.Bounds() {
// Oversized inline frames retain only the rows that fit on the screen.
held := frameArea
held.Max.Y = min(held.Max.Y, s.height)
if !s.starting && !closing && !s.pendingErase && s.lastView != nil && viewEquals(s.lastView, &view) && held == s.cellbuf.Bounds() {
// No changes, nothing to do.
return nil
return false, nil
}
// We're no longer starting.
s.starting = false
s.pendingErase = false
if frameArea != s.cellbuf.Bounds() {
s.scr.Erase() // Force a full redraw to avoid artifacts.
@ -375,9 +447,12 @@ func (s *cursedRenderer) flush(closing bool) error {
}
}
// kitty keyboard protocol
if s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||
view.AltScreen != s.lastView.AltScreen {
// kitty keyboard protocol. Skipped entirely when input is disabled: the
// enhancements only affect keyboard input, and querying the terminal
// would leave its response unconsumed, leaking into the shell after
// the program exits.
if !s.noInput && (s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||
view.AltScreen != s.lastView.AltScreen) {
// NOTE: We need to reset the keyboard protocol when switching
// between main and alt screen. This is because the specs specify
// two different states for the main and alt screen.
@ -386,10 +461,22 @@ func (s *cursedRenderer) flush(closing bool) error {
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
kittyFlags := keyboardEnhancementsFlags(view.KeyboardEnhancements)
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
if s.lastView == nil || view.AltScreen != s.lastView.AltScreen {
// First render or screen switch: the previous screen's entry
// (if any) is popped below, so push a fresh one for this
// screen.
_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))
} else {
// Only the flags changed while the same screen stays active.
// Update the topmost stack entry in place instead of popping
// and re-pushing, so a keyboard change doesn't churn the
// stack. Note that this overwrites whatever entry is currently
// on top, which is normally ours.
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
}
if !closing {
// Request keyboard enhancements when they change
_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)
s.query(ansi.RequestKittyKeyboard)
}
}
@ -418,7 +505,7 @@ func (s *cursedRenderer) flush(closing bool) error {
{newColor: view.ForegroundColor, oldColor: lfg, reset: ansi.ResetForegroundColor, setter: ansi.SetForegroundColor},
{newColor: view.BackgroundColor, oldColor: lbg, reset: ansi.ResetBackgroundColor, setter: ansi.SetBackgroundColor},
} {
if c.newColor != c.oldColor {
if !colorEqual(c.newColor, c.oldColor) {
if c.newColor == nil {
// Reset the color if it was set to nil.
_, _ = s.scr.WriteString(c.reset)
@ -457,6 +544,15 @@ func (s *cursedRenderer) flush(closing bool) error {
setProgressBar(s, view.ProgressBar)
}
// Report the program status if it's changed.
var lps *ProgramStatus
if s.lastView != nil {
lps = s.lastView.ProgramStatus
}
if !programStatusEquals(lps, view.ProgramStatus) {
setProgramStatus(s, lps, view.ProgramStatus)
}
// Render and queue changes to the screen buffer.
s.scr.Render(s.cellbuf.RenderBuffer)
@ -478,7 +574,7 @@ func (s *cursedRenderer) flush(closing bool) error {
}
if err := s.scr.Flush(); err != nil {
return fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
return true, fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
}
// Check if we have any render updates to flush.
@ -511,11 +607,10 @@ func (s *cursedRenderer) flush(closing bool) error {
var buf bytes.Buffer
if shouldUpdateAltScreen {
// We always disable keyboard enhancements when switching screens
// We always reset keyboard enhancements when switching screens
// because the terminal is expected to have two different keyboard
// registries for main and alt screens.
_, _ = buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = buf.WriteString(ansi.KittyKeyboard(0, 1))
s.resetKeyboardEnhancements(&buf)
if view.AltScreen {
// Entering alt screen mode.
buf.WriteString(ansi.SetModeAltScreenSaveCursor)
@ -566,13 +661,13 @@ func (s *cursedRenderer) flush(closing bool) error {
s.logger.Printf("output: %q", buf.String())
}
if _, err := io.Copy(s.w, &buf); err != nil {
return fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
return true, fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
}
}
s.lastView = &view
return nil
return true, nil
}
// render implements renderer.
@ -581,6 +676,7 @@ func (s *cursedRenderer) render(v View) {
defer s.mu.Unlock()
s.view = v
s.viewStale = false
}
// reset implements renderer.
@ -627,6 +723,8 @@ func (s *cursedRenderer) resize(w, h int) {
s.scr.Erase()
s.width, s.height = w, h
s.scr.Resize(s.width, s.height)
s.pendingErase = true
s.viewStale = true
s.mu.Unlock()
}
@ -637,6 +735,19 @@ func (s *cursedRenderer) clearScreen() {
// screen redraw.
s.scr.MoveTo(0, 0)
s.scr.Erase()
s.pendingErase = true
s.mu.Unlock()
}
// clearView implements renderer.
func (s *cursedRenderer) clearView() {
s.mu.Lock()
// Blank the view content so the next flush writes nothing to the output.
// Terminal mode flags such as AltScreen are preserved so that the screen
// mode is restored correctly when the program resumes after the subprocess
// exits (see close and start). See issue #431.
s.view.Content = ""
s.view.Cursor = nil
s.mu.Unlock()
}
@ -712,9 +823,31 @@ func (s *cursedRenderer) insertAbove(str string) error {
return nil
}
// render only queues the latest view; the frame ticker draws it later, so
// a print can arrive before the view the program just returned is on the
// terminal. Draw that view first, so the lines go above what is actually
// on screen: scrolling with the old frame's geometry can move rows of the
// old frame into the scrollback, and a view that leaves the alt screen
// hasn't left it yet, so the lines would be printed on the alt screen and
// lost. A view that enters the alt screen is left for later: until then,
// the lines are still printed on the normal screen, where they persist.
if !s.view.AltScreen {
if _, err := s.flushLocked(false); err != nil {
return fmt.Errorf("bubbletea: error flushing before insert above: %w", err)
}
}
var sb strings.Builder
w, h := s.cellbuf.Width(), s.cellbuf.Height()
_, y := s.scr.Position()
// Before the first flush, the cell buffer still has the terminal height
// rather than the height of the current inline view.
if s.lastView == nil && !s.view.AltScreen {
h = uv.NewStyledString(s.view.Content).Height()
if y < 0 {
y = 0
}
}
// We need to scroll the screen up by the number of lines in the queue.
sb.WriteByte('\r')
@ -726,9 +859,14 @@ func (s *cursedRenderer) insertAbove(str string) error {
lines := strings.Split(str, "\n")
offset := len(lines)
for _, line := range lines {
lineWidth := ansi.StringWidth(line)
// Measure with the active screen buffer's width method: when the
// terminal doesn't enable Unicode-core mode the buffer stays on
// WcWidth, and grapheme semantics would count a different number of
// wrapped lines than the renderer. See
// https://github.com/charmbracelet/bubbletea/issues/1802.
lineWidth := s.cellbuf.WidthMethod().StringWidth(line)
if w > 0 && lineWidth > w {
offset += (lineWidth / w)
offset += (lineWidth - 1) / w
}
}
@ -743,8 +881,8 @@ func (s *cursedRenderer) insertAbove(str string) error {
sb.WriteString(ansi.CursorUp(up))
sb.WriteString(ansi.InsertLine(offset))
for _, line := range lines {
sb.WriteString(line)
sb.WriteString(ansi.EraseLineRight)
sb.WriteString(line)
sb.WriteString("\r\n")
}
@ -800,19 +938,55 @@ func setProgressBar(s *cursedRenderer, pb *ProgressBar) {
}
}
func programStatusEquals(a, b *ProgramStatus) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}
// setProgramStatus reports cur to the terminal. When cur is nil, or addresses
// a different record than prev, the record of prev is cleared first.
func setProgramStatus(s *cursedRenderer, prev, cur *ProgramStatus) {
if prev != nil && (cur == nil || cur.ID != prev.ID) {
_, _ = s.scr.WriteString(ansi.ClearProgramStatusID(prev.ID))
}
if cur != nil {
_, _ = s.scr.WriteString(ansi.SetProgramStatus(*cur))
}
}
// colorEqual reports whether two colors are equal. Colors are compared by
// their RGBA values, which is all the terminal ever sees, rather than with ==,
// which panics on [color.Color] implementations whose dynamic type is
// uncomparable (e.g. a struct containing a slice). A nil color stays distinct
// from any other color so that resetting a color still works.
func colorEqual(a, b color.Color) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
ar, ag, ab, aa := a.RGBA()
br, bg, bb, ba := b.RGBA()
return ar == br && ag == bg && ab == bb && aa == ba
}
func viewEquals(a, b *View) bool {
if a == nil || b == nil {
return false
}
if !programStatusEquals(a.ProgramStatus, b.ProgramStatus) {
return false
}
if a.Content != b.Content ||
a.AltScreen != b.AltScreen ||
a.DisableBracketedPasteMode != b.DisableBracketedPasteMode ||
a.ReportFocus != b.ReportFocus ||
a.MouseMode != b.MouseMode ||
a.WindowTitle != b.WindowTitle ||
a.ForegroundColor != b.ForegroundColor ||
a.BackgroundColor != b.BackgroundColor ||
!colorEqual(a.ForegroundColor, b.ForegroundColor) ||
!colorEqual(a.BackgroundColor, b.BackgroundColor) ||
a.KeyboardEnhancements != b.KeyboardEnhancements {
return false
}
@ -825,7 +999,7 @@ func viewEquals(a, b *View) bool {
a.Cursor.Y != b.Cursor.Y ||
a.Cursor.Shape != b.Cursor.Shape ||
a.Cursor.Blink != b.Cursor.Blink ||
a.Cursor.Color != b.Cursor.Color {
!colorEqual(a.Cursor.Color, b.Cursor.Color) {
return false
}
}

View file

@ -1,12 +1,161 @@
package tea
import (
"bytes"
"fmt"
"image/color"
"io"
"strings"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
)
func TestCursedRendererEnablesUnicodeModeForGraphemeWidth(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 10, 3)
r.start()
r.setWidthMethod(ansi.GraphemeWidth)
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), ansi.SetModeUnicodeCore) {
t.Fatalf("grapheme rendering did not enable Unicode mode; output %q", out.String())
}
}
func TestCursedRendererWcWidthDoesNotEnableUnicodeMode(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 10, 3)
r.start()
r.setWidthMethod(ansi.WcWidth)
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
if err := r.close(); err != nil {
t.Fatal(err)
}
if got := strings.Contains(out.String(), ansi.ResetModeUnicodeCore); got != false {
t.Fatalf("close reset Unicode mode = %v, want false; output %q", got, out.String())
}
// Discard shutdown output so only the resume sequence can satisfy the assertion.
out.Reset()
r.start()
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if got := strings.Contains(out.String(), ansi.SetModeUnicodeCore); got != false {
t.Fatalf("resume enabled Unicode mode = %v, want false; output %q", got, out.String())
}
}
func TestCursedRendererResumeRestoresUnicodeMode(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 10, 3)
r.start()
r.setWidthMethod(ansi.GraphemeWidth)
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
if err := r.close(); err != nil {
t.Fatal(err)
}
if got := strings.Contains(out.String(), ansi.ResetModeUnicodeCore); got != true {
t.Fatalf("close reset Unicode mode = %v, want true; output %q", got, out.String())
}
// Discard shutdown output so only the resume sequence can satisfy the assertion.
out.Reset()
r.start()
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if got := strings.Contains(out.String(), ansi.SetModeUnicodeCore); got != true {
t.Fatalf("resume enabled Unicode mode = %v, want true; output %q", got, out.String())
}
}
func TestCursedRendererSkipsUnchangedView(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 4, 3)
r.start()
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
if drawn, err := r.flush(false); err != nil || drawn || out.Len() != 0 {
t.Fatalf("unchanged view: drawn=%v, err=%v, output=%q", drawn, err, out.String())
}
}
func TestCursedRendererDrawsChangedEmptyAndTallViews(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
before, after View
}{
{"empty inline becomes nonempty", View{}, NewView("new")},
{"empty alt screen becomes nonempty", View{AltScreen: true}, View{Content: "new", AltScreen: true}},
{"tall inline changes visible rows", NewView("a\nb\nc\nd\ne"), NewView("a\nb\nx\ny\nz")},
} {
t.Run(tt.name, func(t *testing.T) {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 4, 3)
r.start()
r.render(tt.before)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
r.render(tt.after)
if drawn, err := r.flush(false); err != nil || !drawn || out.Len() == 0 {
t.Fatalf("changed view: drawn=%v, err=%v, output=%q", drawn, err, out.String())
}
})
}
}
func TestCursedRendererSkipsUnchangedEmptyAndTallViews(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
view View
}{
{"empty inline", View{}},
{"empty alt screen", View{AltScreen: true}},
{"tall inline", NewView("a\nb\nc\nd\ne\nf\ng")},
} {
t.Run(tt.name, func(t *testing.T) {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 4, 3)
r.start()
r.render(tt.view)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
// Measure only the second flush, after the initial frame is drawn.
out.Reset()
if drawn, err := r.flush(false); err != nil || drawn || out.Len() != 0 {
t.Fatalf("unchanged view: drawn=%v, err=%v, output=%q", drawn, err, out.String())
}
})
}
}
type mouseRaceModel struct {
i int
}
@ -78,3 +227,467 @@ func TestCursedRenderer_mouseVsFlush(t *testing.T) {
t.Fatal("program did not exit after Quit")
}
}
// uncomparableColor is a color.Color implementation whose dynamic type is
// uncomparable (it contains a slice), so comparing two values with == panics.
type uncomparableColor struct {
rgba color.RGBA
pad []int
}
func (c uncomparableColor) RGBA() (r, g, b, a uint32) {
return c.rgba.RGBA()
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1848
func TestCursedRenderer_uncomparableViewColors(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.start()
red := color.RGBA{R: 0xff, A: 0xff}
view := NewView("hello")
view.AltScreen = true
view.ForegroundColor = uncomparableColor{rgba: red, pad: []int{1}}
view.BackgroundColor = uncomparableColor{rgba: red, pad: []int{2}}
view.Cursor = &Cursor{Color: uncomparableColor{rgba: red, pad: []int{3}}}
// Render the same view twice. The second flush takes the viewEquals
// early-return path, which compares the color.Color interface values.
for range 2 {
r.render(view)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
}
}
// Colors are compared by value: the same color, whatever its type, doesn't
// redraw the view, while a different color or a reset does.
func TestCursedRenderer_viewColorChanges(t *testing.T) {
t.Parallel()
red := color.RGBA{R: 0xff, A: 0xff}
blue := color.RGBA{B: 0xff, A: 0xff}
for _, tt := range []struct {
name string
set func(*View, color.Color)
code string
reset string
}{
{"foreground", func(v *View, c color.Color) { v.ForegroundColor = c }, "10", "110"},
{"background", func(v *View, c color.Color) { v.BackgroundColor = c }, "11", "111"},
{"cursor", func(v *View, c color.Color) { v.Cursor = NewCursor(0, 0); v.Cursor.Color = c }, "12", "112"},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
render := func(c color.Color) bool {
t.Helper()
view := NewView("hello")
tt.set(&view, c)
r.render(view)
drew, err := r.flush(false)
if err != nil {
t.Fatal(err)
}
return drew
}
render(uncomparableColor{rgba: red, pad: []int{1}})
if want := "\x1b]" + tt.code + ";#ff0000\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing red color sequence %q in %q", want, out.String())
}
out.Reset()
if render(uncomparableColor{rgba: red, pad: []int{2}}) || out.Len() != 0 {
t.Fatalf("unchanged color redrew the view: %q", out.String())
}
if render(red) || out.Len() != 0 {
t.Fatalf("the same color of another type redrew the view: %q", out.String())
}
render(uncomparableColor{rgba: blue})
if want := "\x1b]" + tt.code + ";#0000ff\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing blue color sequence %q in %q", want, out.String())
}
out.Reset()
render(nil)
if want := "\x1b]" + tt.reset + "\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing color reset %q in %q", want, out.String())
}
})
}
}
func assertInOrder(t *testing.T, got string, wants ...string) {
t.Helper()
rest := got
for _, want := range wants {
idx := strings.Index(rest, want)
if idx < 0 {
t.Fatalf("expected %q to appear after the previous sequences in %q", want, got)
}
rest = rest[idx+len(want):]
}
}
func TestCursedRenderer_restoresKittyKeyboardStack(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.start()
view := NewView("hello")
view.KeyboardEnhancements.ReportEventTypes = true
pushMain := ansi.PushKittyKeyboard(keyboardEnhancementsFlags(view.KeyboardEnhancements))
pop := ansi.PopKittyKeyboard(1)
render := func(v View) {
t.Helper()
r.render(v)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
}
render(view)
// Stop the renderer (as on suspend or ExecProcess) and start it again:
// close pops the stack entry, start pushes it back.
if err := r.close(); err != nil {
t.Fatal(err)
}
r.start()
// Enter and leave the alt screen. The terminal keeps a separate Kitty
// keyboard stack per screen, so each screen gets its own push and pop.
view.AltScreen = true
render(view)
view.AltScreen = false
render(view)
if err := r.close(); err != nil {
t.Fatal(err)
}
got := out.String()
// The flags are pushed once per screen activation: the first flush,
// the flush after the renderer was restarted, and on each screen
// switch. start() itself does not write to [out].
if n := strings.Count(got, pushMain); n != 4 {
t.Fatalf("expected kitty keyboard protocol to be pushed 4 times with %q (%d times), got %q", pushMain, n, got)
}
// One pop per stop/start cycle and per screen switch: closing pops the
// current screen's entry, and switching screens pops the entry of the
// screen being left.
if n := strings.Count(got, pop); n != 4 {
t.Fatalf("expected kitty keyboard protocol to be popped 4 times with %q (%d times), got %q", pop, n, got)
}
// Every pop must come after a push: the stack is balanced when pushes
// and pops alternate. The resumed flush pushes twice in a row (once in
// start(), once in flush()), and both entries are popped afterwards.
assertInOrder(t, got,
pushMain, pop, // close pops the entry pushed by the first flush
pop, // entering the alt screen pops the resumed entry
pushMain, pop, // leaving the alt screen
pushMain, pop, // the resumed main screen entry and the final close
)
if strings.Contains(got, ansi.KittyKeyboard(0, 1)) {
t.Fatalf("expected kitty keyboard protocol not to be reset in-place with %q, got %q", ansi.KittyKeyboard(0, 1), got)
}
}
func TestCursedRenderer_updatesKittyKeyboardFlagsInPlace(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
render := func(v View) {
t.Helper()
r.render(v)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
}
view := NewView("hello")
render(view)
// Changing the enhancement flags without switching screens updates the
// current stack entry in place instead of pushing a new one.
changed := view
changed.KeyboardEnhancements.ReportEventTypes = true
render(changed)
wantUpdate := ansi.KittyKeyboard(keyboardEnhancementsFlags(changed.KeyboardEnhancements), 1)
got := out.String()
if !strings.Contains(got, wantUpdate) {
t.Fatalf("expected kitty keyboard flags to be updated in place with %q, got %q", wantUpdate, got)
}
assertInOrder(t, got,
ansi.PushKittyKeyboard(keyboardEnhancementsFlags(view.KeyboardEnhancements)),
wantUpdate,
)
if strings.Contains(got, ansi.PopKittyKeyboard(1)) {
t.Fatalf("expected kitty keyboard protocol not to be popped with %q, got %q", ansi.PopKittyKeyboard(1), got)
}
if n := strings.Count(got, ansi.PushKittyKeyboard(0)); n > 1 {
t.Fatalf("expected kitty keyboard protocol to be pushed once, got %d pushes in %q", n, got)
}
}
func TestCursedRenderer_insertAboveBeforeFirstFlush(t *testing.T) {
t.Parallel()
var output bytes.Buffer
renderer := newCursedRenderer(&output, []string{"TERM=xterm-256color"}, 80, 24)
renderer.render(NewView("footer"))
if err := renderer.insertAbove("startup"); err != nil {
t.Fatal(err)
}
// The one-line view is drawn first, then the line is inserted above it,
// making room for one line rather than for the terminal's height.
got := output.String()
frame := "\r" + ansi.EraseScreenBelow + "footer"
insert := "\r\n" + ansi.CursorUp(1) +
ansi.InsertLine(1) + ansi.EraseLineRight + "startup" + "\r\n"
if !strings.HasSuffix(got, frame+insert) {
t.Fatalf("unexpected insertAbove output:\nwant suffix: %q\n got: %q", frame+insert, got)
}
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1780
func TestCursedRenderer_resizeStaleFrame(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
// Render the initial frame at 80x24.
initialView := NewView("initial 80x24 content")
initialView.AltScreen = true
r.render(initialView)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
// Simulate window resize: resize() is called first, updating dimensions.
r.resize(100, 30)
// In the race window, the 60Hz ticker fires flush() BEFORE render() provides the new View.
// flush() must NOT output the stale initialView at the new 100x30 size.
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if out.Len() > 0 {
t.Fatalf("expected no output during stale resize race window, got %q", out.String())
}
// Now render() provides the new View matching the new 100x30 size.
newView := NewView("resized 100x30 content")
newView.AltScreen = true
r.render(newView)
// The subsequent flush() must draw the new view.
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "resized 100x30 content") {
t.Fatalf("expected output to contain resized view, got %q", out.String())
}
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1802
//
// insertAbove must measure wrapped lines with the active screen buffer's
// width method. When the terminal never answers the Unicode-core query the
// buffer stays on WcWidth, but insertAbove used grapheme semantics, so wide
// grapheme clusters inserted the wrong number of lines.
func TestCursedRenderer_insertAboveUsesActiveWidthMethod(t *testing.T) {
t.Parallel()
insertNewlines := func(method ansi.Method, s string) int {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 8, 4)
r.setWidthMethod(method)
if got := r.cellbuf.WidthMethod(); got != method {
t.Fatalf("expected width method %v, got %v", method, got)
}
if err := r.insertAbove(s); err != nil {
t.Fatal(err)
}
// One "\n" per inserted line, plus the trailing newline after each
// printed line.
return bytes.Count(out.Bytes(), []byte("\n"))
}
// "👨‍👩‍👧‍👦" is a single grapheme cluster (width 2) made of four wide
// codepoints (width 8), so the wrapped-line count differs per method.
// With an 8-column buffer: grapheme width 8 fits in 1 row, wcwidth 14
// wraps to 2 rows.
const line = "👨‍👩‍👧‍👦aaaaaa"
// WcWidth fallback: 1 line + (14-1)/8 extra -> 2 inserted lines, 3 newlines.
if got := insertNewlines(ansi.WcWidth, line); got != 3 {
t.Errorf("WcWidth: expected 3 newlines, got %d", got)
}
// GraphemeWidth (Unicode-core mode): 1 line + (8-1)/8 extra -> 1 inserted
// line, 2 newlines.
if got := insertNewlines(ansi.GraphemeWidth, line); got != 2 {
t.Errorf("GraphemeWidth: expected 2 newlines, got %d", got)
}
}
func TestCursedRenderer_insertAboveLineBoundaries(t *testing.T) {
t.Parallel()
const width = 40
tests := []struct {
name string
line string
rows int
}{
{name: "short", line: strings.Repeat("-", width-2) + "#", rows: 1},
{name: "exact width", line: strings.Repeat("-", width-1) + "#", rows: 1},
{name: "one cell over", line: strings.Repeat("-", width) + "#", rows: 2},
{name: "two exact rows", line: strings.Repeat("-", 2*width-1) + "#", rows: 2},
{name: "three exact rows", line: strings.Repeat("-", 3*width-1) + "#", rows: 3},
{name: "wide characters", line: strings.Repeat("界", width-1) + "-#", rows: 2},
{name: "styled", line: "\x1b[31m" + strings.Repeat("-", 2*width-1) + "#" + ansi.ResetStyle, rows: 2},
{name: "multiple lines", line: strings.Repeat("-", width-1) + "#\n" + strings.Repeat("-", 2*width-1) + "#", rows: 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, width, 2)
r.render(NewView("view\nview"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
r.scr.SetPosition(0, 0)
if err := r.insertAbove(tt.line); err != nil {
t.Fatal(err)
}
got := out.String()
prefix := "\r" + ansi.CursorDown(1) + strings.Repeat("\n", tt.rows) + ansi.CursorUp(tt.rows+1) + ansi.InsertLine(tt.rows)
if !strings.HasPrefix(got, prefix) {
t.Fatalf("expected room for %d terminal rows with prefix %q, got %q", tt.rows, prefix, got)
}
for _, line := range strings.Split(tt.line, "\n") {
if ansi.StringWidth(line)%width == 0 && strings.Contains(got, line+ansi.EraseLineRight) {
t.Fatalf("erasing at the right margin would delete the inserted line's last cell, got %q", got)
}
}
})
}
}
func TestCursedRenderer_insertAboveFlushesQueuedView(t *testing.T) {
var output bytes.Buffer
r := newCursedRenderer(
&output,
[]string{"TERM=xterm-256color", "TERM_PROGRAM=Apple_Terminal"},
80,
24,
)
r.render(NewView("stale frame\nstale row"))
if _, err := r.flush(false); err != nil {
t.Fatalf("flush initial view: %v", err)
}
output.Reset()
r.render(NewView("current frame"))
if err := r.insertAbove("committed block"); err != nil {
t.Fatalf("insert above: %v", err)
}
if r.lastView == nil || r.lastView.Content != "current frame" {
t.Fatalf("insertAbove did not flush the queued view: %#v", r.lastView)
}
written := output.String()
currentAt := strings.Index(written, "current frame")
committedAt := strings.Index(written, "committed block")
if currentAt < 0 || committedAt < 0 {
t.Fatalf("output missing markers (current=%d, committed=%d): %q", currentAt, committedAt, written)
}
if currentAt > committedAt {
t.Fatalf("inserted scrollback before flushing current frame: %q", written)
}
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1881
func TestCursedRenderer_insertAboveAfterLeavingAltScreen(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
alt := NewView("alt screen view")
alt.AltScreen = true
r.render(alt)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
// The update leaves the alt screen and prints a line before the next
// frame is drawn. The line must be printed on the normal screen, after
// leaving the alt screen, or it is lost with it.
r.render(NewView("inline view"))
if err := r.insertAbove("printed line"); err != nil {
t.Fatal(err)
}
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
got := out.String()
assertInOrder(t, got, ansi.SetModeAltScreenSaveCursor, ansi.ResetModeAltScreenSaveCursor, "inline view", "printed line")
if n := strings.Count(got, "printed line"); n != 1 {
t.Fatalf("expected the line to be printed once, got %d times in %q", n, got)
}
}
func TestCursedRenderer_insertAboveBeforeEnteringAltScreen(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.render(NewView("inline view"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
// The update enters the alt screen and prints a line before the next
// frame is drawn. The line is printed on the normal screen, before
// entering the alt screen, so it's still there after leaving it.
alt := NewView("alt screen view")
alt.AltScreen = true
r.render(alt)
if err := r.insertAbove("printed line"); err != nil {
t.Fatal(err)
}
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
assertInOrder(t, out.String(), "inline view", "printed line", ansi.SetModeAltScreenSaveCursor, "alt screen view")
}

View file

@ -23,6 +23,7 @@ type requestCursorPosMsg struct{}
// RequestCursorPosition is a command that requests the cursor position.
// The cursor position will be sent as a [CursorPositionMsg] message.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestCursorPosition() Msg {
return requestCursorPosMsg{}
}

View file

@ -18,8 +18,8 @@ haven't already read our tutorials on the basics of Bubble Tea and working with
commands, we recommend reading those first.
Find them at:
https://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands
https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics
https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands
https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics
*/
// sessionState is used to track which model is focused

View file

@ -1,6 +1,6 @@
module examples
go 1.25.8
go 1.26.7
replace charm.land/bubbletea/v2 => ../
@ -11,11 +11,11 @@ require (
charm.land/lipgloss/v2 v2.0.3
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/harmonica v0.2.0
github.com/charmbracelet/x/ansi v0.11.7
github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb
github.com/charmbracelet/x/term v0.2.2
github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776
github.com/lucasb-eyer/go-colorful v1.4.0
github.com/lucasb-eyer/go-colorful v1.4.1
github.com/segmentio/ksuid v1.0.4
)
@ -23,7 +23,7 @@ require (
github.com/alecthomas/chroma/v2 v2.14.0 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
@ -32,16 +32,16 @@ require (
github.com/dlclark/regexp2 v1.11.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/xo/terminfo v1.0.0 // indirect
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
golang.org/x/net v0.39.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.24.0 // indirect
)

View file

@ -22,10 +22,10 @@ github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7 h1:3FmWoGNWK4STvqg0O0Aeav2T7rodWJAPeF0QpH+8gFw=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7/go.mod h1:f/jRa757WUmaOZrbPspXymbg/GnbF+rwe4OLsG7aXYo=
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb h1:oTM8tZxV7FY0ehvYjFuICouuhzE08UZYNqUIp/lDQdY=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250602192518-9e722df69bbb/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
@ -54,10 +54,10 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
@ -68,8 +68,8 @@ github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=
github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
@ -79,9 +79,9 @@ golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=

View file

@ -0,0 +1,93 @@
package main
import (
"fmt"
"log"
"time"
tea "charm.land/bubbletea/v2"
)
type tickMsg struct{}
func tick() tea.Cmd {
return tea.Tick(200*time.Millisecond, func(time.Time) tea.Msg { return tickMsg{} })
}
var states = []tea.ProgramState{
tea.ProgramStateIdle,
tea.ProgramStateWorking,
tea.ProgramStateBlocked,
tea.ProgramStateDone,
tea.ProgramStateError,
}
var messages = map[tea.ProgramState]string{
tea.ProgramStateIdle: "Waiting for instructions",
tea.ProgramStateWorking: "Building the project",
tea.ProgramStateBlocked: "Deploy to production?",
tea.ProgramStateDone: "Build finished",
tea.ProgramStateError: "Build failed",
}
type model struct {
state int
progress int
supported bool
}
func (m model) Init() tea.Cmd {
return tea.Batch(tea.RequestProgramStatusSupport, tick())
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.ProgramStatusSupportMsg:
m.supported = true
case tickMsg:
if states[m.state] == tea.ProgramStateWorking {
m.progress = (m.progress + 5) % 105
}
return m, tick()
case tea.KeyPressMsg:
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "right", "l", "space":
m.state = (m.state + 1) % len(states)
m.progress = 0
case "left", "h":
m.state = (m.state + len(states) - 1) % len(states)
m.progress = 0
}
}
return m, nil
}
func (m model) View() tea.View {
state := states[m.state]
support := "no reply yet (unsupported, or behind tmux)"
if m.supported {
support = "supported"
}
v := tea.NewView(fmt.Sprintf(
"Program Status Protocol (OSC 7501): %s\n\nState: %s\nMessage: %s\n\nPress left/right to change state, q to quit.\n",
support, state, messages[state],
))
v.ProgramStatus = &tea.ProgramStatus{
State: state,
App: "program-status-example",
Kind: tea.ProgramStatusKindPermission,
Progress: m.progress,
HasProgress: state == tea.ProgramStateWorking,
Message: messages[state],
}
return v
}
func main() {
if _, err := tea.NewProgram(model{}).Run(); err != nil {
log.Fatalf("Error: %v", err)
}
}

View file

@ -43,10 +43,10 @@ func (m model) Init() tea.Cmd {
}
// print string after stopping for a certain period of time
func SleepPrintln(s string, milisecond int) tea.Cmd {
func SleepPrintln(s string, millisecond int) tea.Cmd {
printCmd := tea.Println(s)
return func() tea.Msg {
time.Sleep(time.Duration(milisecond) * time.Millisecond)
time.Sleep(time.Duration(millisecond) * time.Millisecond)
return printCmd()
}
}

View file

@ -100,6 +100,15 @@ func (c *osExecCommand) SetStderr(w io.Writer) {
// exec runs an ExecCommand and delivers the results to the program as a Msg.
func (p *Program) exec(c ExecCommand, fn ExecCallback) {
// Blank the current view before releasing the terminal so the renderer's
// final flush doesn't write the last View() output to stdout. Without
// this, the view content leaks to the terminal and persists after the
// subprocess exits. Terminal mode flags such as AltScreen are preserved so
// the screen mode is restored correctly when the program resumes. See #431.
if p.renderer != nil {
p.renderer.clearView()
}
if err := p.releaseTerminal(false); err != nil {
// If we can't release input, abort.
if fn != nil {

View file

@ -4,7 +4,9 @@ import (
"bytes"
"os/exec"
"runtime"
"strings"
"testing"
"time"
)
type execFinishedMsg struct{ err error }
@ -135,3 +137,120 @@ func TestTeaExecWithNilInput(t *testing.T) {
t.Fatalf("expected no error, got %v", m.err)
}
}
func TestReleaseTerminalWithNilInputDoesNotWait(t *testing.T) {
p := NewProgram(&testExecNoInputModel{}, WithInput(nil))
start := time.Now()
if err := p.ReleaseTerminal(); err != nil {
t.Fatal(err)
}
if elapsed := time.Since(start); elapsed >= 250*time.Millisecond {
t.Fatalf("ReleaseTerminal took %s without an input reader", elapsed)
}
}
// execLeakModel renders a distinctive marker from View() so a test can detect
// whether the renderer flushes the View to stdout when ExecProcess hands the
// terminal to a subprocess. Before the fix for #431, the renderer's final
// flush on releaseTerminal wrote the last View() output to stdout, where it
// persisted after the subprocess exited.
type execLeakModel struct {
done bool
altScreen bool
}
func (m *execLeakModel) Init() Cmd {
return ExecProcess(successExecCommand(), func(err error) Msg {
return execFinishedMsg{err}
})
}
func (m *execLeakModel) Update(msg Msg) (Model, Cmd) {
if _, ok := msg.(execFinishedMsg); ok {
m.done = true
return m, Quit
}
return m, nil
}
func (m *execLeakModel) View() View {
v := NewView("EXEC_MARKER")
if m.done {
v = NewView("QUIT_MARKER")
}
v.AltScreen = m.altScreen
return v
}
// TestExecProcessDoesNotLeakViewOutput is a regression test for #431: when
// ExecProcess runs a subprocess, the renderer must not flush the last View()
// to stdout. The program renders EXEC_MARKER until the subprocess finishes and
// QUIT_MARKER afterwards, so EXEC_MARKER may only ever reach stdout through
// the exec hand-off. WithFPS(1) makes the renderer's ticker fire once per
// second, so during this short test the only flushes are the ones performed
// when releasing the terminal for the subprocess and when shutting down, which
// keeps the assertion deterministic.
func TestExecProcessDoesNotLeakViewOutput(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
m := &execLeakModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithWindowSize(80, 24),
WithFPS(1),
)
if _, err := p.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
out := buf.String()
if strings.Contains(out, "EXEC_MARKER") {
t.Errorf("View output leaked to stdout before the subprocess ran; the renderer must not flush the last View() when handing the terminal to a subprocess (see #431)")
}
if !strings.Contains(out, "QUIT_MARKER") {
t.Errorf("expected the final View() (QUIT_MARKER) to be rendered on shutdown, got output: %q", out)
}
}
// TestExecProcessAltscreenNoLeak verifies the #431 fix also holds in alt screen
// mode and that the program leaves the terminal in a clean state. The fix
// preserves the AltScreen flag when blanking the view, so the screen mode is
// restored when the program resumes; every alt screen enter must therefore be
// paired with a leave.
func TestExecProcessAltscreenNoLeak(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
m := &execLeakModel{altScreen: true}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithWindowSize(80, 24),
WithFPS(1),
)
if _, err := p.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
out := buf.String()
if strings.Contains(out, "EXEC_MARKER") {
t.Errorf("alt screen View output leaked to stdout before the subprocess ran (see #431)")
}
const (
enterAlt = "\x1b[?1049h"
leaveAlt = "\x1b[?1049l"
)
enter := strings.Count(out, enterAlt)
leave := strings.Count(out, leaveAlt)
if enter == 0 {
t.Errorf("expected the program to enter the alt screen at least once, got output: %q", out)
}
if enter != leave {
t.Errorf("alt screen enter/leave unbalanced: enters=%d leaves=%d (output: %q)", enter, leave, out)
}
}

16
go.mod
View file

@ -2,17 +2,17 @@ module charm.land/bubbletea/v2
retract v2.0.0-beta1 // We add a "." after the "beta" in the version number.
go 1.25.0
go 1.26.0
require (
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7
github.com/charmbracelet/x/ansi v0.11.7
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4
github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f
github.com/charmbracelet/x/term v0.2.2
github.com/lucasb-eyer/go-colorful v1.4.0
github.com/lucasb-eyer/go-colorful v1.4.1
github.com/muesli/cancelreader v0.2.2
golang.org/x/sys v0.46.0
golang.org/x/sys v0.47.0
)
require (
@ -21,8 +21,8 @@ require (
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sync v0.21.0 // indirect
github.com/xo/terminfo v1.0.0 // indirect
golang.org/x/sync v0.22.0 // indirect
)

28
go.sum
View file

@ -2,10 +2,10 @@ github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWp
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7 h1:3FmWoGNWK4STvqg0O0Aeav2T7rodWJAPeF0QpH+8gFw=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7/go.mod h1:f/jRa757WUmaOZrbPspXymbg/GnbF+rwe4OLsG7aXYo=
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f h1:UytXHv0UxnsDFmL/7Z9Q5SBYPwSuRLXHbwx+6LycZ2w=
github.com/charmbracelet/x/exp/golden v0.0.0-20241212170349-ad4b7ae0f25f/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
@ -18,19 +18,19 @@ github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSE
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=

View file

@ -49,6 +49,8 @@ func (p *Program) translateInputEvent(e uv.Event) Msg {
return KeyboardEnhancementsMsg(e)
case uv.ModeReportEvent:
return ModeReportMsg(e)
case uv.ProgramStatusSupportEvent:
return ProgramStatusSupportMsg{}
}
return e
}

2
key.go
View file

@ -152,7 +152,7 @@ const (
KeyMediaRewind = uv.KeyMediaRewind
KeyMediaNext = uv.KeyMediaNext
KeyMediaPrev = uv.KeyMediaPrev
KeyMediaRecord
KeyMediaRecord = uv.KeyMediaRecord
KeyLowerVol = uv.KeyLowerVol
KeyRaiseVol = uv.KeyRaiseVol

View file

@ -6,6 +6,7 @@ import (
"log"
"os"
"unicode"
"unicode/utf8"
)
// LogToFile sets up default logging to log to a file. This is helpful as we
@ -42,8 +43,8 @@ func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File,
// Add a space after the prefix if a prefix is being specified and it
// doesn't already have a trailing space.
if len(prefix) > 0 {
finalChar := prefix[len(prefix)-1]
if !unicode.IsSpace(rune(finalChar)) {
finalRune, _ := utf8.DecodeLastRuneInString(prefix)
if !unicode.IsSpace(finalRune) {
prefix += " "
}
}

View file

@ -1,6 +1,7 @@
package tea
import (
"io"
"log"
"os"
"path/filepath"
@ -27,3 +28,34 @@ func TestLogToFile(t *testing.T) {
t.Fatalf("wrong log msg: %q", string(out))
}
}
func TestLogToFileWithPrefixSpacing(t *testing.T) {
tests := []struct {
name string
prefix string
want string
}{
{"empty", "", ""},
{"missing space", "prefix", "prefix "},
{"ASCII space", "prefix ", "prefix "},
{"non-breaking space", "prefix\u00a0", "prefix\u00a0"},
{"ideographic space", "prefix\u3000", "prefix\u3000"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logger := log.New(io.Discard, "", 0)
f, err := LogToFileWith(filepath.Join(t.TempDir(), "log.txt"), tt.prefix, logger)
if err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
if got := logger.Prefix(); got != tt.want {
t.Fatalf("prefix = %q; want %q", got, tt.want)
}
})
}
}

View file

@ -38,7 +38,7 @@ const (
MouseBackward = uv.MouseBackward
MouseForward = uv.MouseForward
MouseButton10 = uv.MouseButton10
MouseButton11
MouseButton11 = uv.MouseButton11
)
// MouseMsg represents a mouse message. This is a generic mouse message that

View file

@ -17,6 +17,9 @@ func (n nilRenderer) start() {}
// clearScreen implements renderer.
func (n nilRenderer) clearScreen() {}
// clearView implements renderer.
func (nilRenderer) clearView() {}
// insertAbove implements renderer.
func (n nilRenderer) insertAbove(string) error { return nil }
@ -27,7 +30,7 @@ func (n nilRenderer) resize(int, int) {}
func (n nilRenderer) setColorProfile(colorprofile.Profile) {}
// flush implements the Renderer interface.
func (nilRenderer) flush(bool) error { return nil }
func (nilRenderer) flush(bool) (bool, error) { return false, nil }
// close implements the Renderer interface.
func (nilRenderer) close() error { return nil }

View file

@ -37,6 +37,13 @@ func WithOutput(output io.Writer) ProgramOption {
// won't need to use this. To disable input entirely pass nil.
//
// p := NewProgram(model, WithInput(nil))
//
// Note that with input disabled, no terminal query is ever sent, since the
// reply could not be read: commands that expect a response, such as
// [RequestBackgroundColor], [RequestCursorPosition], [ReadClipboard], or
// [RequestTerminalVersion], are skipped, as is the startup capability probe.
// A model waiting on the reply message of any of those commands will never
// receive it.
func WithInput(input io.Reader) ProgramOption {
return func(p *Program) {
p.input = input
@ -54,7 +61,7 @@ func WithInput(input io.Reader) ProgramOption {
// var sess ssh.Session // ssh.Session is a type from the github.com/charmbracelet/ssh package
// pty, _, _ := sess.Pty()
// environ := append(sess.Environ(), "TERM="+pty.Term)
// p := tea.NewProgram(model, tea.WithEnvironment(environ)
// p := tea.NewProgram(model, tea.WithEnvironment(environ))
func WithEnvironment(env []string) ProgramOption {
return func(p *Program) {
p.environ = env

55
programstatus.go Normal file
View file

@ -0,0 +1,55 @@
package tea
import uv "github.com/charmbracelet/ultraviolet"
// ProgramStatus is a Program Status Protocol (OSC 7501) report. It tells the
// terminal whether the program is idle, working, waiting on the user, done,
// or failed, and why. Set it on [View.ProgramStatus].
//
// Support depends on the terminal. Terminals that don't support it ignore it.
//
// See: https://www.superlogical.com/rex/docs/build/program-status
type ProgramStatus = uv.ProgramStatus
// ProgramState is the state of a [ProgramStatus].
type ProgramState = uv.ProgramState
// ProgramStatusKind says what a blocked program waits for.
type ProgramStatusKind = uv.ProgramStatusKind
// Program states.
const (
ProgramStateIdle = uv.ProgramStateIdle
ProgramStateWorking = uv.ProgramStateWorking
ProgramStateDone = uv.ProgramStateDone
ProgramStateBlocked = uv.ProgramStateBlocked
ProgramStateError = uv.ProgramStateError
ProgramStateClear = uv.ProgramStateClear
)
// Program status kinds.
const (
ProgramStatusKindPermission = uv.ProgramStatusKindPermission
ProgramStatusKindQuestion = uv.ProgramStatusKindQuestion
ProgramStatusKindAuth = uv.ProgramStatusKindAuth
)
// ProgramStatusSupportMsg is sent when the terminal replies to
// [RequestProgramStatusSupport], meaning it supports the Program Status
// Protocol.
type ProgramStatusSupportMsg struct{}
// programStatusSupportMsg is an internal message that queries the terminal
// for Program Status Protocol support.
type programStatusSupportMsg struct{}
// RequestProgramStatusSupport is a command that asks the terminal whether it
// supports the Program Status Protocol (OSC 7501). A supporting terminal
// replies with a [ProgramStatusSupportMsg]. Terminals that don't support it
// never reply, so pick your own timeout. Use [WithInput] to enable input,
// since the reply cannot be read otherwise.
//
// Detection is optional: reports can be sent without it.
func RequestProgramStatusSupport() Msg {
return programStatusSupportMsg{}
}

88
programstatus_test.go Normal file
View file

@ -0,0 +1,88 @@
package tea
import (
"bytes"
"strings"
"testing"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
func TestCursedRenderer_programStatus(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.start()
step := func(name string, ps *ProgramStatus) string {
t.Helper()
out.Reset()
v := NewView("hello")
v.ProgramStatus = ps
r.render(v)
if _, err := r.flush(false); err != nil {
t.Fatalf("%s: %v", name, err)
}
return out.String()
}
working := &ProgramStatus{State: ProgramStateWorking, App: "tea", Message: "Building"}
if got := step("first", working); !strings.Contains(got, ansi.SetProgramStatus(*working)) {
t.Fatalf("first frame: missing report in %q", got)
}
same := *working
if got := step("unchanged", &same); strings.Contains(got, "7501") {
t.Fatalf("unchanged status was written again: %q", got)
}
changed := same
changed.Message = "Linking"
if got := step("changed", &changed); !strings.Contains(got, ansi.SetProgramStatus(changed)) {
t.Fatalf("changed status not written: %q", got)
}
child := &ProgramStatus{State: ProgramStateBlocked, ID: "job", Kind: ProgramStatusKindQuestion}
got := step("id change", child)
if strings.Contains(got, ansi.ClearProgramStatusID("job")) {
t.Fatalf("new record should not be cleared: %q", got)
}
assertInOrder(t, got, ansi.ClearProgramStatus, ansi.SetProgramStatus(*child))
if got := step("removed", nil); !strings.Contains(got, ansi.ClearProgramStatusID("job")) {
t.Fatalf("removed status not cleared: %q", got)
}
if got := step("invalid", &ProgramStatus{State: ProgramStateIdle, ID: "bad id"}); strings.Contains(got, "7501") {
t.Fatalf("invalid status was written: %q", got)
}
done := &ProgramStatus{State: ProgramStateDone, App: "tea"}
step("done", done)
out.Reset()
if err := r.close(); err != nil {
t.Fatal(err)
}
if got := out.String(); strings.Contains(got, "7501") {
t.Fatalf("close should leave the status in place, got %q", got)
}
// Resuming re-sends the last status.
out.Reset()
r.start()
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if got := out.String(); !strings.Contains(got, ansi.SetProgramStatus(*done)) {
t.Fatalf("restart did not restore the status: %q", got)
}
}
func TestTranslateProgramStatusSupport(t *testing.T) {
var p Program
if got := p.translateInputEvent(uv.ProgramStatusSupportEvent{}); got != (ProgramStatusSupportMsg{}) {
t.Fatalf("got %T, want ProgramStatusSupportMsg", got)
}
}

226
quit_lifecycle_test.go Normal file
View file

@ -0,0 +1,226 @@
package tea
import (
"context"
"io"
"sync/atomic"
"testing"
"time"
)
type quitLifecycleModel struct {
init func()
onUpdate func(Msg) Cmd
}
func (m quitLifecycleModel) Init() Cmd {
if m.init != nil {
m.init()
}
return nil
}
func (m quitLifecycleModel) Update(msg Msg) (Model, Cmd) {
if m.onUpdate != nil {
return m, m.onUpdate(msg)
}
return m, nil
}
func (quitLifecycleModel) View() View { return NewView("running") }
func awaitQuitLifecycle(t *testing.T, done <-chan struct{}, operation string) {
t.Helper()
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatalf("timed out waiting for %s", operation)
}
}
func TestProgramQuitUnstarted(t *testing.T) {
t.Parallel()
for _, model := range []Model{nil, quitLifecycleModel{}} {
t.Run("model", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
p := NewProgram(model, WithContext(ctx))
done := make(chan struct{})
go func() {
p.Quit()
p.Quit()
close(done)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, done, "unstarted Quit cleanup")
}()
awaitQuitLifecycle(t, done, "unstarted Quit")
if err := p.ctx.Err(); err != nil {
t.Fatalf("Quit canceled an unstarted program: %v", err)
}
})
}
}
func TestProgramQuitBeforeRunPreservesMessages(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
var received bool
m := quitLifecycleModel{onUpdate: func(msg Msg) Cmd {
if msg == "work" {
received = true
return Quit
}
return nil
}}
p := NewProgram(m, WithContext(ctx), WithInput(nil), WithOutput(io.Discard), WithoutRenderer())
done := make(chan struct{})
go func() {
p.Quit()
close(done)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, done, "pre-run Quit cleanup")
}()
awaitQuitLifecycle(t, done, "pre-run Quit")
go p.Send("work")
if _, err := p.Run(); err != nil {
t.Fatalf("Run after an unstarted Quit failed: %v", err)
}
if !received {
t.Fatal("unstarted Quit was queued and prevented later work")
}
p.Quit()
}
func TestProgramQuitDuringInitialization(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
initialized := make(chan struct{})
resumeInit := make(chan struct{})
m := quitLifecycleModel{init: func() {
close(initialized)
select {
case <-resumeInit:
case <-ctx.Done():
}
}}
p := NewProgram(m, WithContext(ctx), WithInput(nil), WithOutput(io.Discard), WithoutRenderer())
runDone := make(chan struct{})
var runErr error
go func() {
_, runErr = p.Run()
close(runDone)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, runDone, "initialization Run cleanup")
}()
awaitQuitLifecycle(t, initialized, "model initialization")
quitDone := make(chan struct{})
go func() {
p.Quit()
close(quitDone)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, quitDone, "initialization Quit cleanup")
}()
close(resumeInit)
awaitQuitLifecycle(t, quitDone, "Quit during initialization")
awaitQuitLifecycle(t, runDone, "graceful Run return")
if runErr != nil {
t.Fatalf("Quit during initialization failed: %v", runErr)
}
}
func TestProgramQuitRespectsFilter(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
var rejectQuit atomic.Bool
rejectQuit.Store(true)
filtered := make(chan struct{}, 1)
processed := make(chan struct{})
m := quitLifecycleModel{onUpdate: func(msg Msg) Cmd {
if msg == "work" {
close(processed)
}
return nil
}}
p := NewProgram(m, WithContext(ctx), WithInput(nil), WithOutput(io.Discard), WithoutRenderer(),
WithFilter(func(_ Model, msg Msg) Msg {
if _, ok := msg.(QuitMsg); ok && rejectQuit.Load() {
filtered <- struct{}{}
return nil
}
return msg
}))
runDone := make(chan struct{})
var runErr error
go func() {
_, runErr = p.Run()
close(runDone)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, runDone, "filtered Run cleanup")
}()
go p.Send("work")
awaitQuitLifecycle(t, processed, "active program")
p.Quit()
awaitQuitLifecycle(t, filtered, "rejected Quit")
if err := p.ctx.Err(); err != nil {
t.Fatalf("filtered Quit canceled the program: %v", err)
}
rejectQuit.Store(false)
p.Quit()
awaitQuitLifecycle(t, runDone, "accepted Quit")
if runErr != nil {
t.Fatalf("accepted Quit failed: %v", runErr)
}
}
func TestProgramSendBeforeRunStillWaits(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
var received bool
m := quitLifecycleModel{onUpdate: func(msg Msg) Cmd {
if msg == "work" {
received = true
return Quit
}
return nil
}}
p := NewProgram(m, WithContext(ctx), WithInput(nil), WithOutput(io.Discard), WithoutRenderer())
sending := make(chan struct{})
sent := make(chan struct{})
go func() {
close(sending)
p.Send("work")
close(sent)
}()
defer func() {
cancel()
awaitQuitLifecycle(t, sent, "Send cleanup")
}()
awaitQuitLifecycle(t, sending, "pre-run Send")
select {
case <-sent:
t.Fatal("Send returned before the program started")
case <-time.After(50 * time.Millisecond):
}
if _, err := p.Run(); err != nil {
t.Fatalf("Run with pre-start Send failed: %v", err)
}
awaitQuitLifecycle(t, sent, "delivered Send")
if !received {
t.Fatal("Send discarded the pre-start message")
}
}

View file

@ -25,8 +25,10 @@ type renderer interface {
// render renders a frame to the output.
render(View)
// flush flushes the renderer's buffer to the output.
flush(closing bool) error
// flush flushes the renderer's buffer to the output. It reports whether
// there was anything to draw, so the caller can tell an idle screen from
// an active one.
flush(closing bool) (bool, error)
// reset resets the renderer's state to its initial state.
reset()
@ -49,6 +51,13 @@ type renderer interface {
// clearScreen clears the screen.
clearScreen()
// clearView blanks the current view's content while preserving terminal
// mode flags such as AltScreen, so the next flush writes no View output to
// the terminal. It is used before handing the terminal to a subprocess
// (see Exec and ExecProcess) so the last View() does not leak to stdout
// and persist after the subprocess exits. See issue #431.
clearView()
// writeString writes a string to the renderer's output.
writeString(string) (int, error)

269
renderer_park_test.go Normal file
View file

@ -0,0 +1,269 @@
package tea
import (
"bytes"
"context"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
)
// These tests cover the renderer stopping its ticker while nothing changes.
// Once the ticker is stopped, a change only reaches the output if whatever
// made it woke the renderer, so each test parks the renderer first and then
// checks that the change is drawn.
// safeBuffer is an output that can be read while the program writes to it.
type safeBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *safeBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p) //nolint:wrapcheck
}
func (b *safeBuffer) Len() int {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Len()
}
// since returns everything written after the first n bytes.
func (b *safeBuffer) since(n int) string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()[n:]
}
// tickRenderer records when the renderer goroutine flushes, which happens
// once per tick of the frame ticker.
type tickRenderer struct {
renderer
mu sync.Mutex
ticks int
}
func (r *tickRenderer) flush(closing bool) (bool, error) {
if !closing {
r.mu.Lock()
r.ticks++
r.mu.Unlock()
}
return r.renderer.flush(closing)
}
// count returns the number of ticks so far.
func (r *tickRenderer) count() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.ticks
}
type setViewMsg func(*View)
type runCmdMsg struct{ cmd Cmd }
type parkModel struct{ view View }
func (m *parkModel) Init() Cmd { return nil }
func (m *parkModel) Update(msg Msg) (Model, Cmd) {
switch msg := msg.(type) {
case setViewMsg:
msg(&m.view)
case runCmdMsg:
return m, msg.cmd
}
return m, nil
}
func (m *parkModel) View() View { return m.view }
type parkHarness struct {
t *testing.T
p *Program
out *safeBuffer
r *tickRenderer
frame time.Duration
done chan struct{}
err error // valid once done is closed
}
func newParkHarness(t *testing.T, fps int, opts ...ProgramOption) *parkHarness {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
t.Cleanup(cancel)
h := &parkHarness{
t: t,
out: &safeBuffer{},
frame: time.Second / time.Duration(fps),
done: make(chan struct{}),
}
h.r = &tickRenderer{renderer: newCursedRenderer(h.out, nil, 80, 24)}
opts = append([]ProgramOption{
WithContext(ctx),
WithInput(&bytes.Buffer{}),
WithOutput(h.out),
WithFPS(fps),
WithWindowSize(80, 24),
}, opts...)
h.p = NewProgram(&parkModel{view: NewView("first")}, opts...)
h.p.renderer = h.r
go func() {
defer close(h.done)
_, h.err = h.p.Run()
}()
t.Cleanup(func() {
h.p.Kill()
<-h.done
})
return h
}
// waitParked waits until the renderer has stopped ticking.
func (h *parkHarness) waitParked() {
h.t.Helper()
// Parked means no tick for well over a frame. The ticker runs for about
// half a second of unchanged frames before it stops.
quiet := 6 * h.frame
deadline := time.Now().Add(10 * time.Second)
n := h.r.count()
for time.Now().Before(deadline) {
time.Sleep(quiet)
m := h.r.count()
if m == n && n > 0 {
return
}
n = m
}
h.t.Fatal("the renderer never stopped ticking")
}
// waitOutput waits until everything in want is written after mark and
// returns how long that took.
func (h *parkHarness) waitOutput(mark int, within time.Duration, want ...string) time.Duration {
h.t.Helper()
start := time.Now()
for {
got := h.out.since(mark)
missing := ""
for _, w := range want {
if !strings.Contains(got, w) {
missing = w
break
}
}
if missing == "" {
return time.Since(start)
}
if time.Since(start) > within {
h.t.Fatalf("%q not written within %v after waking a parked renderer; got %q", missing, within, got)
}
time.Sleep(time.Millisecond)
}
}
func (h *parkHarness) setView(fn func(*View)) {
h.p.Send(setViewMsg(fn))
}
// waitDone waits for Run to return.
func (h *parkHarness) waitDone() error {
h.t.Helper()
const within = 2 * time.Second
select {
case <-h.done:
return h.err
case <-time.After(within):
h.t.Fatalf("Run did not return within %v", within)
return nil
}
}
// nopExecCommand is an ExecCommand that does nothing.
type nopExecCommand struct{}
func (nopExecCommand) Run() error { return nil }
func (nopExecCommand) SetStdin(io.Reader) {}
func (nopExecCommand) SetStdout(io.Writer) {}
func (nopExecCommand) SetStderr(io.Writer) {}
func TestRendererStopsTickingWhenIdle(t *testing.T) {
t.Parallel()
h := newParkHarness(t, 60)
h.waitOutput(0, 5*time.Second, "first")
h.waitParked()
n := h.r.count()
time.Sleep(time.Second)
if ticks := h.r.count() - n; ticks != 0 {
t.Errorf("an idle program ticked %d times in a second, want 0", ticks)
}
}
// Every way of giving the renderer work must wake it.
func TestRendererWakes(t *testing.T) {
t.Parallel()
cmd := func(c Cmd) func(h *parkHarness) {
return func(h *parkHarness) { h.p.Send(runCmdMsg{c}) }
}
tests := []struct {
name string
do func(h *parkHarness)
want []string
}{
{"content", func(h *parkHarness) { h.setView(func(v *View) { v.Content = "second" }) }, []string{"second"}},
{"Println", cmd(Println("printed")), []string{"printed"}},
{"raw", cmd(Raw("\x1b]2;raw\x07")), []string{"\x1b]2;raw\x07"}},
{"exec", cmd(Exec(nopExecCommand{}, nil)), []string{ansi.SetModeBracketedPaste, "first"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
h := newParkHarness(t, 60)
h.waitOutput(0, 5*time.Second, "first")
h.waitParked()
mark := h.out.Len()
tc.do(h)
took := h.waitOutput(mark, 2*time.Second, tc.want...)
t.Logf("drawn %v after waking", took)
})
}
}
func TestRendererQuitWhileParked(t *testing.T) {
t.Parallel()
h := newParkHarness(t, 60)
h.waitParked()
mark := h.out.Len()
h.setView(func(v *View) { v.Content = "last" })
h.p.Quit()
if err := h.waitDone(); err != nil {
t.Errorf("Run returned %v, want nil", err)
}
if !strings.Contains(h.out.since(mark), "last") {
t.Error("final frame not drawn")
}
}

View file

@ -3,9 +3,7 @@ package tea
import "github.com/charmbracelet/x/ansi"
// WindowSizeMsg is used to report the terminal size. It's sent to Update once
// initially and then on every terminal resize. Note that Windows does not
// have support for reporting when resizes occur as it does not support the
// SIGWINCH signal.
// initially and then on every terminal resize.
type WindowSizeMsg struct {
Width int
Height int
@ -66,3 +64,18 @@ type ModeReportMsg struct {
// Value is the mode value.
Value ansi.ModeSetting
}
const (
maxWindowDimension = 4096
maxWindowCells = 1 << 20
)
func isPlausibleWindowSize(width, height int) bool {
if width < 0 || height < 0 {
return false
}
if width > maxWindowDimension || height > maxWindowDimension {
return false
}
return width*height <= maxWindowCells
}

View file

@ -138,6 +138,9 @@ func TestViewModel(t *testing.T) {
m := &testViewModel{testModel: &testModel{}}
p := NewProgram(m,
// Keep the renderer ticker from introducing intermediate frames into
// this golden-output test.
WithFPS(1),
// Set the initial window size for the program.
WithWindowSize(80, 24),
// Use ANSI256 to increase test coverage.
@ -205,3 +208,25 @@ func TestClearMsg(t *testing.T) {
})
}
}
func TestIsPlausibleWindowSize(t *testing.T) {
tests := []struct {
w, h int
want bool
}{
{80, 24, true},
{0, 0, true},
{500, 200, true},
{-1, 24, false},
{80, -1, false},
{5000, 1, false},
{23000, 23000, false},
{29000, 29000, false},
{2000, 2000, false},
}
for _, tt := range tests {
if got := isPlausibleWindowSize(tt.w, tt.h); got != tt.want {
t.Errorf("isPlausibleWindowSize(%d, %d) = %v, want %v", tt.w, tt.h, got, tt.want)
}
}
}

227
shutdown_input_test.go Normal file
View file

@ -0,0 +1,227 @@
package tea
import (
"context"
"errors"
"io"
"os"
"strings"
"testing"
"testing/synctest"
"time"
)
type shutdownInputReader struct {
cancelable bool
cancels int
closes int
}
func (*shutdownInputReader) Read([]byte) (int, error) { return 0, io.EOF }
func (r *shutdownInputReader) Cancel() bool { r.cancels++; return r.cancelable }
func (r *shutdownInputReader) Close() error { r.closes++; return nil }
func TestShutdownWaitsForCancelableInput(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "quit"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
p.readLoopDone = make(chan struct{})
stopped := make(chan struct{})
go func() { p.shutdown(kill); close(stopped) }()
synctest.Wait()
if r.cancels != 1 || r.closes != 0 {
t.Errorf("before read loop completion: cancel=%d close=%d", r.cancels, r.closes)
}
select {
case <-stopped:
t.Error("shutdown returned before the input loop finished")
default:
}
close(p.readLoopDone)
synctest.Wait()
<-stopped
if r.closes != 1 {
t.Errorf("close calls after input completion: got %d, want 1", r.closes)
}
p.shutdown(kill)
if r.cancels != 1 || r.closes != 1 {
t.Errorf("repeated shutdown: cancel=%d close=%d", r.cancels, r.closes)
}
})
})
}
}
func TestShutdownDefersCloseAfterInputTimeout(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "quit"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
done := make(chan struct{})
p.readLoopDone = done
stopped := make(chan struct{})
go func() { p.shutdown(kill); close(stopped) }()
synctest.Wait()
time.Sleep(time.Second)
synctest.Wait()
select {
case <-stopped:
default:
t.Error("shutdown did not retain its bounded wait")
}
if r.closes != 0 {
t.Errorf("reader closed while its input loop was still active: %d", r.closes)
}
// Cleanup must retain this reader, not follow a later field assignment.
replacement := &shutdownInputReader{}
p.cancelReader = replacement
p.readLoopDone = make(chan struct{})
close(done)
synctest.Wait()
if r.closes != 1 || replacement.closes != 0 {
t.Errorf("close calls: original=%d replacement=%d", r.closes, replacement.closes)
}
<-stopped
})
})
}
}
// A reader that shutdown closed must not be closed again when a later run
// replaces it: closing a cancel reader closes raw file descriptors, so a
// second close can close an unrelated file that reused the number.
func TestShutdownClosesInputOnce(t *testing.T) {
p := NewProgram(&testModel{}, WithInput(strings.NewReader("")), WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
p.readLoopDone = make(chan struct{})
close(p.readLoopDone)
p.shutdown(false)
if r.closes != 1 {
t.Fatalf("shutdown closed the reader %d times, want 1", r.closes)
}
// The next run starts a new reader in place of the closed one.
if err := p.initInputReader(false); err != nil {
t.Fatal(err)
}
if r.closes != 1 {
t.Errorf("starting a new reader closed the old one again: %d closes", r.closes)
}
p.shutdownInput()
}
func TestShutdownInputFallbacks(t *testing.T) {
for _, tc := range []struct {
name string
reader bool
cancelable bool
loop bool
finished bool
}{
{name: "no reader"},
{name: "uncancelable", reader: true, loop: true},
{name: "no input loop", reader: true, cancelable: true},
{name: "finished loop", reader: true, cancelable: true, loop: true, finished: true},
} {
t.Run(tc.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: tc.cancelable}
if tc.reader {
p.cancelReader = r
}
if tc.loop {
p.readLoopDone = make(chan struct{})
if tc.finished {
close(p.readLoopDone)
}
}
start := time.Now()
p.shutdown(true)
if time.Since(start) != 0 {
t.Error("input fallback unexpectedly waited")
}
if tc.reader && (r.cancels != 1 || r.closes != 1) {
t.Errorf("fallback cleanup: cancel=%d close=%d", r.cancels, r.closes)
}
})
})
}
}
type (
inputStartedMsg struct{}
inputShutdownModel struct{ ready chan struct{} }
)
func (m inputShutdownModel) Init() Cmd { return func() Msg { return inputStartedMsg{} } }
func (m inputShutdownModel) Update(msg Msg) (Model, Cmd) {
if _, ok := msg.(inputStartedMsg); ok {
close(m.ready)
}
return m, nil
}
func (inputShutdownModel) View() View { return NewView("ready") }
func TestProgramCanceledInput(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "context"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
// A real file exercises the native cancelreader rather than its no-op fallback.
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer reader.Close()
defer writer.Close()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
ready := make(chan struct{})
p := NewProgram(inputShutdownModel{ready}, WithContext(ctx), WithInput(reader), WithOutput(io.Discard), WithWindowSize(80, 24), WithoutSignalHandler())
result := make(chan error, 1)
go func() { _, err := p.Run(); result <- err }()
select {
case <-ready:
case <-time.After(5 * time.Second):
t.Fatal("event loop did not start")
}
if kill {
p.Kill()
} else {
cancel()
}
select {
case err = <-result:
case <-time.After(5 * time.Second):
t.Fatal("program did not stop")
}
if !errors.Is(err, ErrProgramKilled) {
t.Fatalf("unexpected error: %v", err)
}
if !kill && !errors.Is(err, context.Canceled) {
t.Fatalf("missing external cancellation: %v", err)
}
if _, err := reader.Stat(); err != nil {
t.Fatalf("borrowed input was closed: %v", err)
}
})
}
}

6
signals_other.go Normal file
View file

@ -0,0 +1,6 @@
//go:build wasip1 || wasip2
package tea
// listenForResize on WASI: no SIGWINCH; report immediately done.
func (p *Program) listenForResize(done chan struct{}) { close(done) }

123
signals_test.go Normal file
View file

@ -0,0 +1,123 @@
//go:build !windows
package tea
import (
"context"
"os"
"os/signal"
"syscall"
"testing"
"time"
)
// TestHandleSignalsReturnsAfterContextCancelDuringPendingSend is a
// regression test for the signal-goroutine deadlock on shutdown: a signal
// arriving while nobody reads p.msgs (the event loop already stopped) must
// not block the handler forever once the program context is canceled.
func TestHandleSignalsReturnsAfterContextCancelDuringPendingSend(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Register our own handler first so the SIGINT can never take down the
// test process before handleSignals registers its own.
ours := make(chan os.Signal, 1)
signal.Notify(ours, syscall.SIGINT)
defer signal.Stop(ours)
p := &Program{
ctx: ctx,
msgs: make(chan Msg), // unbuffered, no reader: simulates a stopped event loop
}
done := p.handleSignals()
time.Sleep(100 * time.Millisecond) // let the handler register its signal.Notify
if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {
t.Fatalf("failed to send SIGINT: %v", err)
}
select {
case <-ours:
case <-time.After(5 * time.Second):
t.Fatal("SIGINT was not delivered")
}
// Let the handler consume its copy of the signal and enter the send on
// p.msgs, where it would block forever before the fix.
time.Sleep(100 * time.Millisecond)
// Canceling the context (what shutdown does) must unblock the handler.
cancel()
select {
case <-done:
// The handler returned; shutdown can proceed.
case <-time.After(5 * time.Second):
t.Fatal("handleSignals did not return after context cancel: signal goroutine is deadlocked")
}
}
// TestHandleSignalsCatchesSecondSignalDuringShutdown is a regression test for
// https://github.com/charmbracelet/bubbletea/issues/1849: after a quit
// message is forwarded, the signal subscription must stay alive until the
// program finishes, so a second SIGINT during shutdown is caught instead of
// taking the runtime's default path and killing the process.
func TestHandleSignalsCatchesSecondSignalDuringShutdown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Register our own handler first so a SIGINT can never take down the
// test process, whether or not handleSignals is catching it.
ours := make(chan os.Signal, 2)
signal.Notify(ours, syscall.SIGINT)
defer signal.Stop(ours)
finished := make(chan struct{})
defer close(finished)
p := &Program{
ctx: ctx,
msgs: make(chan Msg),
finished: finished,
}
done := p.handleSignals()
time.Sleep(100 * time.Millisecond) // let the handler register its signal.Notify
// While the program runs, every signal is forwarded as an interrupt
// message, so a program that doesn't quit on the first one (for example
// because a filter dropped it) still gets the next one.
for i := range 2 {
if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {
t.Fatalf("failed to send SIGINT: %v", err)
}
<-ours
select {
case msg := <-p.msgs:
if _, ok := msg.(InterruptMsg); !ok {
t.Fatalf("expected InterruptMsg, got %T", msg)
}
case <-time.After(5 * time.Second):
t.Fatalf("SIGINT %d was not forwarded", i+1)
}
}
// Context cancellation (the start of shutdown) ends the handler.
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("handleSignals did not finish after context cancel")
}
// Release our own watcher so that whether SIGINT is still caught depends
// solely on the program's subscription. A second SIGINT during the
// shutdown window must still be caught (and dropped); if the program had
// already released its subscription it would take the runtime's default
// path and terminate this test process — so surviving is the assertion.
signal.Stop(ours)
if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {
t.Fatalf("failed to send second SIGINT: %v", err)
}
time.Sleep(200 * time.Millisecond)
}

415
tea.go
View file

@ -4,9 +4,9 @@
// both. It's been battle-tested in several large projects and is
// production-ready.
//
// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/master/tutorials
// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/main/tutorials
//
// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples
// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/main/examples
package tea
import (
@ -146,6 +146,20 @@ type View struct {
// progress bar section. Support depends on the terminal.
ProgressBar *ProgressBar
// ProgramStatus when not nil, reports the program status to the terminal
// using the Program Status Protocol (OSC 7501): whether the program is
// idle, working, waiting on the user, done, or failed. Support depends on
// the terminal.
//
// The status usually addresses the root record (empty ID). Changing it
// sends a new report, and setting it back to nil clears the record.
//
// The status is not cleared when the program exits, so done and error
// reports stay visible to the user. Report [ProgramStateDone],
// [ProgramStateError], or [ProgramStateIdle] before quitting rather than
// leaving a working or blocked status behind.
ProgramStatus *ProgramStatus
// AltScreen puts the program in the alternate screen buffer
// (i.e. the program goes into full window mode). Note that the altscreen will
// be automatically exited when the program quits.
@ -317,15 +331,23 @@ const (
ProgressBarWarning
)
// String return a human-readable value for the given [ProgressBarState].
// String returns a human-readable name for the given [ProgressBarState].
// Values outside the known range return "Unknown".
func (s ProgressBarState) String() string {
return [...]string{
"None",
"Default",
"Error",
"Indeterminate",
"Warning",
}[s]
switch s {
case ProgressBarNone:
return "None"
case ProgressBarDefault:
return "Default"
case ProgressBarError:
return "Error"
case ProgressBarIndeterminate:
return "Indeterminate"
case ProgressBarWarning:
return "Warning"
default:
return "Unknown"
}
}
// ProgressBar represents the terminal progress bar.
@ -336,7 +358,7 @@ func (s ProgressBarState) String() string {
type ProgressBar struct {
// State is the current state of the progress bar. It can be one of
// [ProgressBarNone], [ProgressBarDefault], [ProgressBarError],
// [ProgressBarIndeterminate], and [ProgressBarWarn].
// [ProgressBarIndeterminate], and [ProgressBarWarning].
State ProgressBarState
// Value is the current value of the progress bar. It should be between
// 0 and 100.
@ -500,8 +522,16 @@ type Program struct {
msgs chan Msg
errs chan error
writeErr error // first error writing to the output; guarded by writeErrMu
writeErrMu sync.Mutex
finished chan struct{}
runMu sync.Mutex
shutdownOnce sync.Once
started atomic.Bool
// ranOnce reports whether [Program.Run] has been called before, so its
// per-run state can be reinitialized on subsequent runs.
ranOnce bool
profile *colorprofile.Profile // the terminal color profile
@ -517,7 +547,8 @@ type Program struct {
// the environment variables for the program, defaults to os.Environ().
environ uv.Environ
// the program's logger for debugging.
logger uv.Logger
logger uv.Logger
tracePath string
// where to read inputs from, this will usually be os.Stdin.
input io.Reader
@ -528,18 +559,24 @@ type Program struct {
inputScanner *uv.TerminalReader
readLoopDone chan struct{}
// lastQuery is when a terminal query was last written, in Unix
// nanoseconds, or 0 once its reply has been read. See
// [Program.drainQueryReplies].
lastQuery atomic.Int64
// modes keeps track of terminal modes that have been enabled or disabled.
ignoreSignals uint32
// ticker is the ticker that will be used to write to the renderer.
ticker *time.Ticker
// once is used to stop the renderer.
once sync.Once
// rendererDone is used to stop the renderer.
rendererDone chan struct{}
// rendererWake wakes the renderer when it has stopped its ticker because
// nothing was changing. See [Program.startRenderer].
rendererWake chan struct{}
// Initial window size. Mainly used for testing.
width, height int
@ -597,7 +634,9 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
initialModel: model,
msgs: make(chan Msg),
errs: make(chan error, 1),
finished: make(chan struct{}),
rendererDone: make(chan struct{}),
rendererWake: make(chan struct{}, 1),
}
// Apply all options to the program.
@ -631,10 +670,7 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
tracePath, traceOk := os.LookupEnv("TEA_TRACE")
if traceOk && len(tracePath) > 0 {
// We have a trace filepath.
if f, err := os.OpenFile(tracePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600); err == nil {
p.logger = log.New(f, "bubbletea: ", log.LstdFlags|log.Lshortfile)
}
p.tracePath = tracePath
}
return p
@ -643,6 +679,11 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
func (p *Program) handleSignals() chan struct{} {
ch := make(chan struct{})
// Run sets finished before it starts the handlers. Read it here, not in
// the goroutine below, which may still be running when Run is called
// again and replaces it.
finished := p.finished
// Listen for SIGINT and SIGTERM.
//
// In most cases ^C will not send an interrupt because the terminal will be
@ -654,25 +695,34 @@ func (p *Program) handleSignals() chan struct{} {
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
defer func() {
signal.Stop(sig)
close(ch)
}()
defer signal.Stop(sig)
for {
select {
case <-p.ctx.Done():
// The program is shutting down: report the handler done so
// shutdown can proceed, but keep the signal subscription
// alive until Run returns. A second SIGINT/SIGTERM arriving
// while the terminal is being restored is then caught and
// dropped instead of taking the runtime's default path,
// which kills the process before the terminal is restored.
close(ch)
if finished != nil {
<-finished
}
return
case s := <-sig:
if atomic.LoadUint32(&p.ignoreSignals) == 0 {
switch s {
case syscall.SIGINT:
p.msgs <- InterruptMsg{}
default:
p.msgs <- QuitMsg{}
}
return
if atomic.LoadUint32(&p.ignoreSignals) != 0 {
continue
}
var msg Msg = QuitMsg{}
if s == syscall.SIGINT {
msg = InterruptMsg{}
}
select {
case p.msgs <- msg:
case <-p.ctx.Done():
}
}
}
@ -752,6 +802,10 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
case msg := <-p.msgs:
msg = p.translateInputEvent(msg)
if size, ok := msg.(WindowSizeMsg); ok && !isPlausibleWindowSize(size.Width, size.Height) {
continue
}
// Filter messages.
if p.filter != nil {
msg = p.filter(model, msg)
@ -808,35 +862,38 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
}
case readClipboardMsg:
p.execute(ansi.RequestSystemClipboard)
p.executeQuery(ansi.RequestSystemClipboard)
case setClipboardMsg:
p.execute(ansi.SetSystemClipboard(string(msg)))
case readPrimaryClipboardMsg:
p.execute(ansi.RequestPrimaryClipboard)
p.executeQuery(ansi.RequestPrimaryClipboard)
case setPrimaryClipboardMsg:
p.execute(ansi.SetPrimaryClipboard(string(msg)))
case backgroundColorMsg:
p.execute(ansi.RequestBackgroundColor)
p.executeQuery(ansi.RequestBackgroundColor)
case foregroundColorMsg:
p.execute(ansi.RequestForegroundColor)
p.executeQuery(ansi.RequestForegroundColor)
case cursorColorMsg:
p.execute(ansi.RequestCursorColor)
p.executeQuery(ansi.RequestCursorColor)
case programStatusSupportMsg:
p.executeQuery(ansi.RequestProgramStatusSupport)
case execMsg:
// NB: this blocks.
p.exec(msg.cmd, msg.fn)
case terminalVersion:
p.execute(ansi.RequestNameVersion)
p.executeQuery(ansi.RequestNameVersion)
case requestCapabilityMsg:
p.execute(ansi.RequestTermcap(string(msg)))
p.executeQuery(ansi.RequestTermcap(string(msg)))
case BatchMsg:
go p.execBatchMsg(msg)
@ -853,13 +910,13 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
go p.checkResize()
case requestCursorPosMsg:
p.execute(ansi.RequestCursorPositionReport)
p.executeQuery(ansi.RequestCursorPositionReport)
case RawMsg:
p.execute(fmt.Sprint(msg.Msg))
case printLineMessage:
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
p.keepWriteErr(p.renderer.insertAbove(msg.messageBody))
case clearScreenMsg:
p.renderer.clearScreen()
@ -886,6 +943,16 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
func (p *Program) render(model Model) {
if p.renderer != nil {
p.renderer.render(model.View()) // send view to renderer
p.wakeRenderer()
}
}
// wakeRenderer restarts the renderer's ticker if it was stopped because
// nothing was changing. It never blocks.
func (p *Program) wakeRenderer() {
select {
case p.rendererWake <- struct{}{}:
default:
}
}
@ -993,26 +1060,67 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
return nil, errors.New("bubbletea: InitialModel cannot be nil")
}
// Acquire runMu for the duration of initialization. Kill() will also
// acquire runMu before calling shutdown(), preventing data races between
// Run() writing to fields like p.handlers, p.renderer, and
// p.cancelReader and Kill() reading them.
p.runMu.Lock()
initialized := false
defer func() {
if !initialized {
p.runMu.Unlock()
}
}()
p.finished = make(chan struct{})
defer close(p.finished)
if p.tracePath != "" {
if f, err := os.OpenFile(p.tracePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600); err == nil {
defer f.Close() //nolint:errcheck
p.logger = log.New(f, "bubbletea: ", log.LstdFlags|log.Lshortfile)
}
}
// Initialize context and teardown channel.
//
// When a previous run already tore down its per-run state, recreate it so
// the Program can be run again. The context is only recreated after an
// actual run: replacing it unconditionally would swallow a
// [Program.Kill] issued before the program started, which works by
// cancelling the context created in NewProgram.
if p.ranOnce {
p.ctx, p.cancel = context.WithCancel(p.externalCtx)
p.errs = make(chan error, 1)
p.shutdownOnce = sync.Once{}
p.writeErrMu.Lock()
p.writeErr = nil
p.writeErrMu.Unlock()
}
p.ranOnce = true
p.handlers = channelHandlers{}
cmds := make(chan Cmd)
p.finished = make(chan struct{})
defer func() {
close(p.finished)
}()
defer p.cancel()
p.started.Store(true)
if p.disableInput {
p.input = nil
} else if p.input == nil {
p.input = os.Stdin
if !term.IsTerminal(os.Stdin.Fd()) {
ttyIn, _, err := OpenTTY()
ttyIn, ttyOut, err := OpenTTY()
if err != nil {
return p.initialModel, fmt.Errorf("bubbletea: error opening TTY: %w", err)
}
// Nothing else owns these files: close them when Run returns so
// each Run doesn't leak a /dev/tty fd (on Windows, CONIN$ and
// CONOUT$ handles).
defer func() {
_ = ttyIn.Close()
_ = ttyOut.Close()
}()
p.input = ttyIn
}
}
@ -1035,6 +1143,10 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Check if output is a TTY before entering raw mode, hiding the cursor and
// so on.
if err := p.initTerminal(); err != nil {
// The input may already be in raw mode at this point (on Windows it
// is made raw before the output console-mode setup), so restore the
// terminal before returning the error.
_ = p.restoreTerminalState()
return p.initialModel, err
}
@ -1044,10 +1156,11 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Set the initial size of the terminal.
w, h, err := term.GetSize(p.ttyOutput.Fd())
if err != nil {
_ = p.restoreTerminalState()
return p.initialModel, fmt.Errorf("bubbletea: error getting terminal size: %w", err)
}
width, height = w, h
width, height = p.fallbackDimensions(w, h)
}
p.width, p.height = width, height
@ -1065,6 +1178,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
p.height,
)
r.setLogger(p.logger)
r.setNoInput(p.disableInput)
// XXX: This breaks many things especially when we want the output
// to be compatible with terminals that are not necessary a TTY.
// This was originally done to work around a Wish emulated-pty
@ -1074,6 +1188,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// raw mode. See issue #1572.
mapNl := runtime.GOOS != "windows" && p.ttyInput == nil
r.setOptimizations(p.useHardTabs, p.useBackspace, mapNl)
r.onQuery = p.noteQuery
p.renderer = r
}
}
@ -1099,6 +1214,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
model := p.initialModel
if p.input != nil {
if err := p.initInputReader(false); err != nil {
_ = p.restoreTerminalState()
return model, err
}
}
@ -1110,7 +1226,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Query for synchronized updates support (mode 2026) and unicode core
// (mode 2027). If the terminal supports it, the renderer will enable
// it once we get the response.
p.execute(ansi.RequestModeSynchronizedOutput +
p.executeQuery(ansi.RequestModeSynchronizedOutput +
ansi.RequestModeUnicodeCore)
}
@ -1139,6 +1255,10 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Process commands.
p.handlers.add(p.handleCommands(cmds))
// Initialization is complete. Release the lock so Kill() can proceed.
p.runMu.Unlock()
initialized = true
// Run event loop, handle updates and draw.
var err error
model, err = p.eventLoop(model, cmds)
@ -1170,6 +1290,11 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Restore terminal state.
p.shutdown(killed)
if err == nil {
// Report a failure to write to the output, if there was one.
err = p.firstWriteErr()
}
return model, err
}
@ -1195,13 +1320,25 @@ func (p *Program) Send(msg Msg) {
// If the program is not running this will be a no-op, so it's safe to call
// if the program is unstarted or has already exited.
func (p *Program) Quit() {
if !p.started.Load() {
return
}
p.Send(Quit())
}
// Kill stops the program immediately and restores the former terminal state.
// The final render that you would normally see when quitting will be skipped.
// [program.Run] returns a [ErrProgramKilled] error.
//
// If [Program.Run] is concurrently initializing, Kill will wait for it to
// finish before performing shutdown. This prevents data races that could
// occur when Kill reads fields that Run is still setting up.
func (p *Program) Kill() {
// Wait for Run() to finish initializing before calling shutdown().
// This prevents data races between Run() writing to fields like
// p.handlers, p.renderer, and p.cancelReader and Kill() reading them.
p.runMu.Lock()
defer p.runMu.Unlock()
p.shutdown(true)
}
@ -1215,6 +1352,31 @@ func (p *Program) execute(seq string) {
p.mu.Lock()
_, _ = p.outputBuf.WriteString(seq)
p.mu.Unlock()
p.wakeRenderer()
}
// executeQuery writes a terminal query to the program output. Queries expect a
// reply on p.input, so when input is disabled the query is skipped: the
// program cannot read the response, and the terminal's reply would leak into
// the shell once the program exits (#1590).
//
// This covers every query that expects a reply, not just the startup
// capability probe: background, foreground, and cursor color requests, cursor
// position reports, clipboard reads, and terminal version and termcap
// queries.
func (p *Program) executeQuery(seq string) {
if p.disableInput {
return
}
p.noteQuery()
p.execute(seq)
}
// noteQuery records that a terminal query is about to be written, so its
// reply can be read before the terminal is handed back. See
// [Program.drainQueryReplies].
func (p *Program) noteQuery() {
p.lastQuery.Store(time.Now().UnixNano())
}
// flush flushes the output buffer to the program output.
@ -1236,6 +1398,27 @@ func (p *Program) flush() error {
return nil
}
// keepWriteErr remembers err as the error to return from [Program.Run] if it
// is the first error writing to the output. Later errors are dropped so they
// do not hide the first one.
func (p *Program) keepWriteErr(err error) {
if err == nil {
return
}
p.writeErrMu.Lock()
defer p.writeErrMu.Unlock()
if p.writeErr == nil {
p.writeErr = err
}
}
// firstWriteErr returns the first error kept by keepWriteErr.
func (p *Program) firstWriteErr() error {
p.writeErrMu.Lock()
defer p.writeErrMu.Unlock()
return p.writeErr
}
// shutdown performs operations to free up resources and restore the terminal
// to its original state.
func (p *Program) shutdown(kill bool) {
@ -1245,21 +1428,17 @@ func (p *Program) shutdown(kill bool) {
// Wait for all handlers to finish.
p.handlers.shutdown()
// Check if the cancel reader has been setup before waiting and closing.
if p.cancelReader != nil {
// Wait for input loop to finish.
if p.cancelReader.Cancel() {
if !kill {
p.waitForReadLoop()
}
}
_ = p.cancelReader.Close()
}
p.shutdownInput()
if p.renderer != nil {
p.stopRenderer(kill)
}
// Read the replies to queries that are still in flight, so they don't
// end up in the shell as typed input once the program exits. The
// program's context is already canceled, so give the drain its own.
_ = p.drainQueryReplies(context.Background())
_ = p.restoreTerminalState()
})
}
@ -1289,19 +1468,26 @@ func (p *Program) recoverFromPanic(r interface{}) {
}
}
// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and
// signals for the program to be killed and terminal restored to a usable state.
// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace,
// restores the terminal to a usable state, and signals the program to be killed.
func (p *Program) recoverFromGoPanic(r interface{}) {
p.recoverFromGoPanicWithStack(r, debug.Stack())
}
// recoverFromGoPanicWithStack is [Program.recoverFromGoPanic] with the stack
// captured at the panic site. The renderer ticker goroutine uses this because
// it must not block in [Program.shutdown].
func (p *Program) recoverFromGoPanicWithStack(r interface{}, trace []byte) {
select {
case p.errs <- ErrProgramPanic:
default:
}
p.cancel()
p.shutdown(true)
// We use "\r\n" to ensure the output is formatted even when restoring the
// terminal does not work or when raw mode is still active.
rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")
fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)
stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")
stack := strings.ReplaceAll(fmt.Sprintf("%s\n", trace), "\n", "\r\n")
fmt.Fprint(os.Stderr, stack)
if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {
f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))
@ -1324,10 +1510,9 @@ func (p *Program) releaseTerminal(reset bool) error {
atomic.StoreUint32(&p.ignoreSignals, 1)
if p.cancelReader != nil {
p.cancelReader.Cancel()
p.waitForReadLoop()
}
p.waitForReadLoop()
if p.renderer != nil {
p.stopRenderer(false)
if reset {
@ -1335,6 +1520,18 @@ func (p *Program) releaseTerminal(reset bool) error {
}
}
// Replies to queries we sent may still be in flight. Read them now, while
// the terminal is still in raw mode, so they don't end up as input for
// whoever gets the terminal next, e.g. an exec'd process. The program gets
// them once its event loop resumes.
if events := p.drainQueryReplies(p.ctx); len(events) > 0 {
go func() {
for _, ev := range events {
p.Send(ev)
}
}()
}
return p.restoreTerminalState()
}
@ -1369,10 +1566,11 @@ func (p *Program) RestoreTerminal() error {
// and will persist across renders by the Program.
//
// If the altscreen is active no output will be printed.
// If the program has already exited this is a no-op.
func (p *Program) Println(args ...any) {
p.msgs <- printLineMessage{
p.Send(printLineMessage{
messageBody: fmt.Sprint(args...),
}
})
}
// Printf prints above the Program. It takes a format template followed by
@ -1383,22 +1581,22 @@ func (p *Program) Println(args ...any) {
// its own line.
//
// If the altscreen is active no output will be printed.
// If the program has already exited this is a no-op.
func (p *Program) Printf(template string, args ...any) {
p.msgs <- printLineMessage{
p.Send(printLineMessage{
messageBody: fmt.Sprintf(template, args...),
}
})
}
// startRenderer starts the renderer.
func (p *Program) startRenderer() {
framerate := time.Second / time.Duration(p.fps)
if p.ticker == nil {
p.ticker = time.NewTicker(framerate)
} else {
// If the ticker already exists, it has been stopped and we need to
// reset it.
p.ticker.Reset(framerate)
}
// Stop ticking after about half a second of frames with nothing to draw.
idleFrames := max(p.fps/2, 1)
// Each run of the renderer gets its own ticker, so a goroutine that is
// still exiting can't stop the ticker of the next one.
ticker := time.NewTicker(framerate)
// Since the renderer can be restarted after a stop, we need to reset
// the done channel and its corresponding sync.Once.
@ -1407,20 +1605,74 @@ func (p *Program) startRenderer() {
// Start the renderer.
p.renderer.start()
go func() {
defer ticker.Stop()
var (
idle int // consecutive frames with nothing to draw
parked bool // whether the ticker is stopped
realign bool // whether the ticker runs a shortened interval
last time.Time // when the ticker last fired
)
for {
select {
case <-p.rendererDone:
p.ticker.Stop()
return
case <-p.ticker.C:
_ = p.flush()
_ = p.renderer.flush(false)
case <-p.rendererWake:
if !parked {
continue
}
// Resume on the same frame boundaries as if the ticker had
// never stopped, so frames are drawn exactly when they
// would have been.
parked, realign = false, true
ticker.Reset(framerate - time.Since(last)%framerate)
case last = <-ticker.C:
if realign {
realign = false
ticker.Reset(framerate)
}
drew, ok := p.flushFrame()
if !ok {
// The renderer panicked and the program is shutting
// down. Stop drawing and wait for stopRenderer.
<-p.rendererDone
return
}
if drew {
idle = 0
} else if idle++; idle >= idleFrames {
// Nothing is changing. Stop waking up every frame until
// there is something to draw, see [Program.wakeRenderer].
ticker.Stop()
parked = true
}
}
}
}()
}
// flushFrame writes the queued output and the current frame, and reports
// whether a frame was drawn. If the renderer panics, ok is false and the panic
// is recovered so the terminal still gets restored. The recovery runs on
// another goroutine: shutting down sends on rendererDone, which only the
// renderer goroutine calling flushFrame receives.
func (p *Program) flushFrame() (drew, ok bool) {
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
ok = false
go p.recoverFromGoPanicWithStack(r, debug.Stack())
}
}()
}
p.keepWriteErr(p.flush())
drew, err := p.renderer.flush(false)
p.keepWriteErr(err)
return drew, true
}
// stopRenderer stops the renderer.
// If kill is true, the renderer will be stopped immediately without flushing
// the last frame.
@ -1432,8 +1684,9 @@ func (p *Program) stopRenderer(kill bool) {
if !kill {
// flush locks the mutex
_ = p.renderer.flush(true)
_, err := p.renderer.flush(true)
p.keepWriteErr(err)
}
_ = p.renderer.close()
p.keepWriteErr(p.renderer.close())
}

View file

@ -6,11 +6,16 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
)
type ctxImplodeMsg struct {
@ -89,6 +94,28 @@ func TestTeaModel(t *testing.T) {
}
}
func TestProgramClosesTraceFile(t *testing.T) {
tracePath := filepath.Join(t.TempDir(), "trace.log")
t.Setenv("TEA_TRACE", tracePath)
p := NewProgram(quitModel{}, WithInput(nil), WithOutput(io.Discard), WithoutRenderer())
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
logger, ok := p.logger.(*log.Logger)
if !ok {
t.Fatalf("logger has type %T, want *log.Logger", p.logger)
}
traceFile, ok := logger.Writer().(*os.File)
if !ok {
t.Fatalf("trace writer has type %T, want *os.File", logger.Writer())
}
if _, err := traceFile.Write([]byte("x")); !errors.Is(err, os.ErrClosed) {
t.Fatalf("trace file remains open after Run: Write error = %v", err)
}
}
func TestTeaQuit(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
@ -222,6 +249,31 @@ func TestTeaWaitKill(t *testing.T) {
}
}
func TestKillDuringStartupRace(t *testing.T) {
t.Parallel()
for range 100 {
p := NewProgram(&testModel{},
WithInput(bytes.NewBuffer(nil)),
WithOutput(io.Discard),
WithoutSignals(),
)
done := make(chan struct{})
go func() {
_, _ = p.Run()
close(done)
}()
p.Kill()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("program did not stop")
}
}
}
func TestTeaWithFilter(t *testing.T) {
for _, preventCount := range []uint32{0, 1, 2} {
t.Run(fmt.Sprintf("prevent_%d", preventCount), func(t *testing.T) {
@ -533,6 +585,49 @@ func TestTeaSend(t *testing.T) {
p.Send(Quit())
}
func TestProgramPrintAfterExit(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
p := NewProgram(&testModel{},
WithInput(&in),
WithOutput(&buf),
)
go p.Send(Quit())
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
print func()
}{
{"Println", func() { p.Println("after exit") }},
{"Printf", func() { p.Printf("after %s", "exit") }},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
done := make(chan struct{})
go func() {
tt.print()
close(done)
}()
select {
case <-done:
case <-time.After(100 * time.Millisecond):
// Receive only after detecting the block. This releases the
// direct channel send used before this regression was fixed,
// so the test does not leak a goroutine against the old code.
<-p.msgs
<-done
t.Fatal("print blocked after the program exited")
}
})
}
}
func TestTeaNoRun(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
@ -545,6 +640,74 @@ func TestTeaNoRun(t *testing.T) {
)
}
// runTwiceModel waits for a WindowSizeMsg before quitting, and reports whether
// that message ever reached Update, so we can tell a real run from a
// torn-down one.
type runTwiceModel struct {
updated atomic.Bool
}
// Init returns no command on purpose: the program exits from Update once it
// has seen a WindowSizeMsg, so the quit is ordered after the observation
// rather than racing it.
func (m *runTwiceModel) Init() Cmd { return nil }
func (m *runTwiceModel) Update(msg Msg) (Model, Cmd) {
if _, ok := msg.(WindowSizeMsg); ok {
m.updated.Store(true)
return m, Quit
}
return m, nil
}
func (m *runTwiceModel) View() View { return NewView("hello") }
// TestTeaRunTwice is a regression test for running a Program a second time
// after the first Run returned. Run resets its per-run state (handlers,
// finished channel) at the top of every call, but before the fix the run
// context, error channel, and shutdown guard stayed behind: the second run
// tore down immediately with ErrProgramKilled and its shutdown was skipped,
// leaving the terminal state it changed unrestored.
func TestTeaRunTwice(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
m := &runTwiceModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
)
// The program quits from Update once it has observed a WindowSizeMsg, so
// every run returns on its own; a bounded wait keeps a genuinely broken
// run from hanging the test instead of failing it.
run := func(which string) {
t.Helper()
done := make(chan error, 1)
go func() {
_, err := p.Run()
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatalf("%s run: unexpected error: %v", which, err)
}
case <-time.After(30 * time.Second):
t.Fatalf("%s run: Run did not return; the program never observed a WindowSizeMsg", which)
}
}
run("first")
m.updated.Store(false)
run("second")
if !m.updated.Load() {
t.Error("second run never delivered messages to Update")
}
}
func TestTeaPanic(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
@ -612,6 +775,44 @@ func TestTeaGoroutinePanic(t *testing.T) {
}
}
// flushPanicRenderer panics on every non-closing flush, simulating a renderer
// crash inside the ticker goroutine started by startRenderer.
type flushPanicRenderer struct {
nilRenderer
}
func (flushPanicRenderer) flush(closing bool) (bool, error) {
if !closing {
panic("flushPanicRenderer")
}
return false, nil
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1848
func TestTeaRendererFlushPanic(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
m := &testModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithoutSignals(),
)
p.renderer = flushPanicRenderer{}
_, err := p.Run()
if !errors.Is(err, ErrProgramPanic) {
t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)
}
if !errors.Is(err, ErrProgramKilled) {
t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)
}
}
type benchModel struct {
t testing.TB
}
@ -669,3 +870,252 @@ func BenchmarkTeaRun(b *testing.B) {
_ = r.CloseWithError(io.EOF)
}
}
// quitModel quits as soon as it starts.
type quitModel struct{}
func (quitModel) Init() Cmd { return Quit }
func (quitModel) Update(Msg) (Model, Cmd) { return quitModel{}, nil }
func (quitModel) View() View { return NewView("") }
// TestTeaNoCapabilityQueryWithoutInput is a regression test for
// https://github.com/charmbracelet/gum/issues/1118: programs without input
// can't read the terminal's responses to capability queries, so the replies
// leak into the shell after the program exits. Don't send the queries when
// input is disabled.
func TestTeaNoCapabilityQueryWithoutInput(t *testing.T) {
t.Parallel()
query := ansi.RequestModeSynchronizedOutput + ansi.RequestModeUnicodeCore
env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}
for _, tt := range []struct {
name string
input io.Reader
want bool
}{
{name: "input disabled", input: nil, want: false},
{name: "input enabled", input: bytes.NewReader(nil), want: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(quitModel{},
WithInput(tt.input),
WithOutput(&buf),
WithEnvironment(env),
)
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
// The queued output may not have been flushed if the program
// exited before the first tick, so inspect it too. Reading
// p.outputBuf here is deliberate: it checks the buffered bytes
// that would have been flushed, without depending on flush
// timing (and it ties the test to the renderer's buffer, which
// is an intentional trade-off).
got := buf.String() + p.outputBuf.String()
if strings.Contains(got, query) != tt.want {
t.Fatalf("capability query present = %v, want %v; output: %q", !tt.want, tt.want, got)
}
})
}
}
// terminalQueryCmds lists every command that sends a terminal query whose
// reply must be read from the input reader.
var terminalQueryCmds = []Cmd{
RequestBackgroundColor,
RequestForegroundColor,
RequestCursorColor,
ReadClipboard,
ReadPrimaryClipboard,
RequestTerminalVersion,
RequestCapability("TN"),
RequestCursorPosition,
}
// queryModel issues every terminal query that needs a reply on the input
// reader, then quits once each one has been handled.
type queryModel struct {
handled int
}
func (queryModel) Init() Cmd {
return Batch(terminalQueryCmds...)
}
func (m queryModel) Update(msg Msg) (Model, Cmd) {
switch msg.(type) {
case backgroundColorMsg, foregroundColorMsg, cursorColorMsg,
readClipboardMsg, readPrimaryClipboardMsg, terminalVersion,
requestCapabilityMsg, requestCursorPosMsg:
// Each query is handled by an intermediate reader that turns the
// terminal's reply into a message, so Update only sees the request
// messages because the event loop passes them through after the
// intermediate reads. If that pass-through ever changes, this test
// will hang instead of quitting.
m.handled++
if m.handled == len(terminalQueryCmds) {
return m, Quit
}
}
return m, nil
}
func (queryModel) View() View { return NewView("") }
// TestTeaNoTerminalQueriesWithoutInput is a regression test for
// https://github.com/charmbracelet/gum/issues/1118: programs without input
// can't read the terminal's responses, so query replies leak into the shell
// after the program exits. No input-dependent query should be sent when input
// is disabled.
func TestTeaNoTerminalQueriesWithoutInput(t *testing.T) {
t.Parallel()
queries := []string{
ansi.RequestSystemClipboard,
ansi.RequestPrimaryClipboard,
ansi.RequestBackgroundColor,
ansi.RequestForegroundColor,
ansi.RequestCursorColor,
ansi.RequestNameVersion,
ansi.RequestTermcap("TN"),
ansi.RequestCursorPositionReport,
}
env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}
for _, tt := range []struct {
name string
input io.Reader
want bool
}{
{name: "input disabled", input: nil, want: false},
{name: "input enabled", input: bytes.NewReader(nil), want: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(queryModel{},
WithInput(tt.input),
WithOutput(&buf),
WithEnvironment(env),
)
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
// The queued output may not have been flushed if the program
// exited before the first tick, so inspect it too. Reading
// p.outputBuf here is deliberate: it checks the buffered bytes
// that would have been flushed, without depending on flush
// timing (and it ties the test to the renderer's buffer, which
// is an intentional trade-off).
got := buf.String() + p.outputBuf.String()
for _, query := range queries {
if strings.Contains(got, query) != tt.want {
t.Errorf("query %q present = %v, want %v; output: %q", query, !tt.want, tt.want, got)
}
}
})
}
}
// TestProgressBarStateStringOutOfRange is a regression test for
// https://github.com/charmbracelet/bubbletea/issues/1711: String panicked
// with an index-out-of-range error for any ProgressBarState outside the
// [ProgressBarNone, ProgressBarWarning] range. Since State is an exported
// field on ProgressBar, callers can assign such a value without going
// through NewProgressBar.
func TestProgressBarStateStringOutOfRange(t *testing.T) {
for _, s := range []ProgressBarState{-1, 5, 100} {
if got, want := s.String(), "Unknown"; got != want {
t.Errorf("ProgressBarState(%d).String() = %q, want %q", int(s), got, want)
}
}
for s := ProgressBarNone; s <= ProgressBarWarning; s++ {
if got := s.String(); got == "Unknown" {
t.Errorf("ProgressBarState(%d).String() = %q, want a known name", int(s), got)
}
}
}
type failWriter struct{}
func (failWriter) Write([]byte) (int, error) { return 0, errors.New("disk full") }
func TestTeaRunReturnsWriteError(t *testing.T) {
t.Parallel()
var in bytes.Buffer
in.Write([]byte("q"))
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
p := NewProgram(&testModel{},
WithContext(ctx),
WithInput(&in),
WithOutput(failWriter{}),
)
_, err := p.Run()
if err == nil {
t.Fatal("Run returned nil although every write to the output failed")
}
if !strings.Contains(err.Error(), "disk full") {
t.Fatalf("Run error does not wrap the write error: %v", err)
}
if errors.Is(err, ErrProgramKilled) {
t.Fatalf("a write error alone should not report a killed program: %v", err)
}
}
// helloQuitModel draws a line and quits as soon as it starts.
type helloQuitModel struct{ init Cmd }
func (m helloQuitModel) Init() Cmd { return m.init }
func (m helloQuitModel) Update(Msg) (Model, Cmd) { return m, nil }
func (helloQuitModel) View() View { return NewView("hello") }
// A write error belongs to the run it happened in: running the program again
// with a working output returns no error.
func TestTeaRunWriteErrorDoesNotCarryOver(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(helloQuitModel{init: Quit}, WithInput(nil), WithOutput(&buf), WithWindowSize(80, 24))
// Pretend an earlier run failed to write.
p.ranOnce = true
p.keepWriteErr(errors.New("disk full"))
if _, err := p.Run(); err != nil {
t.Fatalf("expected no error, got %v", err)
}
if !strings.Contains(buf.String(), "hello") {
t.Fatalf("expected the view to be written, got %q", buf.String())
}
}
// printFailWriter fails the writes that print a line above the program.
type printFailWriter struct{}
func (printFailWriter) Write(b []byte) (int, error) {
if bytes.Contains(b, []byte("printed line")) {
return 0, errors.New("broken pipe")
}
return len(b), nil
}
// Failing to print a line above the program is a write error too.
func TestTeaRunReturnsPrintWriteError(t *testing.T) {
t.Parallel()
m := helloQuitModel{init: Sequence(Println("printed line"), Quit)}
_, err := NewProgram(m, WithInput(nil), WithOutput(printFailWriter{})).Run()
if err == nil || !strings.Contains(err.Error(), "broken pipe") {
t.Fatalf("expected the print's write error, got %v", err)
}
}

View file

@ -5,7 +5,8 @@ package tea
type requestCapabilityMsg string
// RequestCapability is a command that requests the terminal to send its
// Termcap/Terminfo response for the given capability.
// Termcap/Terminfo response for the given capability. Use [WithInput] to
// enable input, since the reply cannot be read otherwise.
//
// Bubble Tea recognizes the following capabilities and will use them to
// upgrade the program's color profile:

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p]10;?]11;?]12;?
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p]10;?]11;?]12;?

View file

@ -1 +1 @@
[?25l [?2004h[>4;2m[=1;1usuccess[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l [?2004h[>4;2m[>1usuccess[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p]52;c;?]52;c;c3VjY2Vzcw==
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p]52;c;?]52;c;c3VjY2Vzcw==

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[>4m[=0;1u[?1049h[?25l[?2004h[>4;2m[=1;1usuccess[>4m[=0;1u[?1049l[?25h[?2004l[?2026$p[?2027$p
[>4m[?1049h[?25l[?2004h[>4;2m[>1usuccess[>4m[<1u[?1049l[?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u]11;#ffffff success[>4m[=0;1u [?25h[?2004l]111[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u]11;#ffffff success[>4m[<1u [?25h[?2004l]111[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?2004h[>4;2m[=1;1u[1 q success [?25h[>4m[=0;1u[?2004l[?2026$p[?2027$p
[?2004h[>4;2m[>1u[1 q success [?25h[>4m[<1u[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=3;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>3u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[?1003h[?1006h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p
[?25l[?2004h[?1003h[?1006h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[?1002h[?1006h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p
[?25l[?2004h[?1002h[?1006h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

181
tty.go
View file

@ -1,11 +1,14 @@
package tea
import (
"context"
"fmt"
"os"
"strconv"
"time"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
)
@ -32,7 +35,7 @@ func (p *Program) initTerminal() error {
// Bubble Tea program.
func (p *Program) restoreTerminalState() error {
// Flush queued commands.
_ = p.flush()
p.keepWriteErr(p.flush())
return p.restoreInput()
}
@ -59,6 +62,18 @@ func (p *Program) initInputReader(cancel bool) error {
p.waitForReadLoop()
}
// Close the reader we are about to replace, otherwise its resources (e.g.
// the epoll file descriptor on Linux) leak on every ReleaseTerminal and
// RestoreTerminal cycle. Only close it once its read loop has exited: if
// waitForReadLoop timed out, the loop may still be using it.
if p.cancelReader != nil && p.readLoopDone != nil {
select {
case <-p.readLoopDone:
_ = p.cancelReader.Close()
default:
}
}
term := p.environ.Getenv("TERM")
// Initialize the input reader.
@ -76,34 +91,182 @@ func (p *Program) initInputReader(cancel bool) error {
p.inputScanner = drv
p.readLoopDone = make(chan struct{})
go p.readLoop()
go p.readLoop(p.ctx, drv, p.readLoopDone, p.errs)
return nil
}
func (p *Program) readLoop() {
defer close(p.readLoopDone)
// readLoop streams input events to the program until ctx is done or reading
// fails. It takes the per-run state it uses as arguments rather than reading
// it from p: the loop can outlive [Program.shutdown], see
// [Program.shutdownInput], and must not race with a later run replacing it.
func (p *Program) readLoop(ctx context.Context, scanner *uv.TerminalReader, done chan struct{}, errs chan error) {
defer close(done)
if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {
if err := scanner.StreamEvents(ctx, p.msgs); err != nil {
select {
case <-p.ctx.Done():
case <-ctx.Done():
return
case p.errs <- err:
case errs <- err:
}
}
}
const inputReadLoopTimeout = 500 * time.Millisecond
// shutdownInput cancels input before closing the reader's resources. Keep the
// bounded shutdown for slow readers, but retain ownership of a reader that is
// still in use until its input loop has actually finished.
func (p *Program) shutdownInput() {
reader := p.cancelReader
if reader == nil {
return
}
// The reader is closed below, or later once its input loop finishes.
// Forget it so that a later run doesn't close it again: closing it closes
// raw file descriptors, and closing one twice can close an unrelated file
// that has since reused the number.
p.cancelReader = nil
if reader.Cancel() && p.readLoopDone != nil {
done := p.readLoopDone
timer := time.NewTimer(inputReadLoopTimeout)
defer timer.Stop()
select {
case <-done:
case <-timer.C:
go func() {
<-done
_ = reader.Close()
}()
return
}
}
_ = reader.Close()
}
// waitForReadLoop waits for the cancelReader to finish its read loop.
func (p *Program) waitForReadLoop() {
select {
case <-p.readLoopDone:
case <-time.After(500 * time.Millisecond): //nolint:mnd
case <-time.After(inputReadLoopTimeout):
// The read loop hangs, which means the input
// cancelReader's cancel function has returned true even
// though it was not able to cancel the read.
}
}
// queryDrainTimeout bounds how long [Program.drainQueryReplies] waits for the
// terminal to answer.
const queryDrainTimeout = 500 * time.Millisecond
// queryReplyWindow is how long after a query its reply may still be on its
// way. The input reader reads replies that arrive later than that.
const queryReplyWindow = time.Second
// drainQueryReplies reads the replies to terminal queries that may still be in
// flight after the input reader has stopped, and returns them. Otherwise they
// stay in the tty input queue for the next reader: a process started with
// [ExecProcess], or the shell once the program exits (#1590).
//
// It sends a Primary Device Attributes (DA1) request and reads input until
// the terminal answers it. Terminals answer requests in order, so by then
// every earlier reply has been read. Nothing is drained when the last query
// was sent long enough ago for its reply to have been read already.
func (p *Program) drainQueryReplies(ctx context.Context) []Msg {
last := p.lastQuery.Swap(0)
if last == 0 || time.Since(time.Unix(0, last)) > queryReplyWindow ||
p.ttyInput == nil || p.ttyOutput == nil || p.input == nil {
return nil
}
// Make sure the pending queries themselves have been written, followed by
// the DA1 request that marks the end of their replies.
p.mu.Lock()
_, _ = p.outputBuf.WriteString(ansi.RequestPrimaryDeviceAttributes)
p.mu.Unlock()
if err := p.flush(); err != nil {
p.keepWriteErr(err)
return nil
}
cr, err := uv.NewCancelReader(p.input)
if err != nil {
return nil
}
defer cr.Close() //nolint:errcheck
// Stop reading once the DA1 reply arrives, the timeout expires, or ctx is
// done.
ctx, cancel := context.WithTimeout(ctx, queryDrainTimeout)
defer cancel()
context.AfterFunc(ctx, func() { cr.Cancel() })
drv := uv.NewTerminalReader(cr, p.environ.Getenv("TERM"))
drv.SetLogger(p.logger)
eventc := make(chan uv.Event)
done := make(chan struct{})
go func() {
defer close(done)
_ = drv.StreamEvents(ctx, eventc)
}()
var events []Msg
for {
select {
case ev := <-eventc:
if _, ok := ev.(uv.PrimaryDeviceAttributesEvent); ok {
// Every earlier reply has been read.
cancel()
continue
}
events = append(events, ev)
case <-done:
return events
}
}
}
const (
defaultWidth = 80
defaultHeight = 24
)
// fallbackDimensions returns width and height, falling back to COLUMNS/LINES
// environment variables or 80x24 defaults when dimensions are non-positive.
func (p *Program) fallbackDimensions(width, height int) (int, int) {
if width <= 0 {
var cols string
if p != nil && p.environ != nil {
cols = p.environ.Getenv("COLUMNS")
} else {
cols = os.Getenv("COLUMNS")
}
if c, err := strconv.Atoi(cols); err == nil && c > 0 {
width = c
} else {
width = defaultWidth
}
}
if height <= 0 {
var lines string
if p != nil && p.environ != nil {
lines = p.environ.Getenv("LINES")
} else {
lines = os.Getenv("LINES")
}
if l, err := strconv.Atoi(lines); err == nil && l > 0 {
height = l
} else {
height = defaultHeight
}
}
return width, height
}
// checkResize detects the current size of the output and informs the program
// via a WindowSizeMsg.
func (p *Program) checkResize() {
@ -122,6 +285,8 @@ func (p *Program) checkResize() {
return
}
w, h = p.fallbackDimensions(w, h)
p.width, p.height = w, h
p.Send(WindowSizeMsg{Width: w, Height: h})
}

197
tty_drain_test.go Normal file
View file

@ -0,0 +1,197 @@
//go:build !windows
// +build !windows
package tea
import (
"bytes"
"io"
"os"
"sync"
"testing"
"time"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// fakeTerminal answers terminal queries written to it by writing the replies
// to the program's input, like a real terminal would.
type fakeTerminal struct {
mu sync.Mutex
out bytes.Buffer
input io.Writer
}
func (f *fakeTerminal) Write(b []byte) (int, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.out.Write(b)
if bytes.Contains(b, []byte(ansi.RequestModeSynchronizedOutput)) {
_, _ = io.WriteString(f.input, "\x1b[?2026;2$y")
}
if bytes.Contains(b, []byte(ansi.RequestPrimaryDeviceAttributes)) {
_, _ = io.WriteString(f.input, "\x1b[?62;22c")
}
return len(b), nil
}
func (f *fakeTerminal) String() string {
f.mu.Lock()
defer f.mu.Unlock()
return f.out.String()
}
func newDrainTestProgram(t *testing.T) (*Program, *os.File, *fakeTerminal) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = r.Close()
_ = w.Close()
})
ft := &fakeTerminal{input: w}
p := NewProgram(nil, WithInput(r), WithOutput(ft))
// Pretend input and output are a terminal; drainQueryReplies only runs
// for TTYs.
p.ttyInput = r
p.ttyOutput = w
return p, w, ft
}
// readAvailable returns what can be read from r within d.
func readAvailable(t *testing.T, r io.Reader, d time.Duration) string {
t.Helper()
ch := make(chan string, 1)
go func() {
buf := make([]byte, 256)
n, _ := r.Read(buf)
ch <- string(buf[:n])
}()
select {
case s := <-ch:
return s
case <-time.After(d):
return ""
}
}
// Replies to queries that arrive after the input reader is canceled must not
// be left in the tty input for the next reader, such as an exec'd process.
func TestDrainQueryReplies(t *testing.T) {
p, w, ft := newDrainTestProgram(t)
// The query is still buffered, as it is when ExecProcess is returned from
// Init before the renderer has flushed.
p.executeQuery(ansi.RequestModeSynchronizedOutput)
start := time.Now()
events := p.drainQueryReplies(t.Context())
if elapsed := time.Since(start); elapsed >= queryDrainTimeout {
t.Fatalf("drain did not stop at the DA1 reply, took %v", elapsed)
}
if !bytes.Contains([]byte(ft.String()), []byte(ansi.RequestPrimaryDeviceAttributes)) {
t.Fatalf("expected a DA1 request to be written, got %q", ft.String())
}
// The reply is returned, the DA1 reply is not.
if len(events) != 1 {
t.Fatalf("expected one reply, got %#v", events)
}
if ev, ok := events[0].(uv.ModeReportEvent); !ok || ev.Mode != ansi.ModeSynchronizedOutput {
t.Fatalf("expected a synchronized output mode report, got %#v", events[0])
}
// Nothing but what is typed afterwards is left for the next reader.
if _, err := io.WriteString(w, "abc"); err != nil {
t.Fatal(err)
}
if got := readAvailable(t, p.input, time.Second); got != "abc" {
t.Fatalf("expected next reader to get %q, got %q", "abc", got)
}
}
// Releasing the terminal hands the replies it read to the program.
func TestReleaseTerminalDeliversQueryReplies(t *testing.T) {
p, _, _ := newDrainTestProgram(t)
p.executeQuery(ansi.RequestModeSynchronizedOutput)
if err := p.releaseTerminal(false); err != nil {
t.Fatal(err)
}
select {
case msg := <-p.msgs:
if ev, ok := msg.(uv.ModeReportEvent); !ok || ev.Mode != ansi.ModeSynchronizedOutput {
t.Fatalf("expected a synchronized output mode report, got %#v", msg)
}
case <-time.After(time.Second):
t.Fatal("mode report was not delivered to the program")
}
}
// A program that quits right after it starts sends its queries during
// shutdown. Their replies must be read before the terminal is handed back to
// the shell, or the shell reads them as typed input.
//
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1590
func TestShutdownDrainsQueryReplies(t *testing.T) {
p, w, ft := newDrainTestProgram(t)
p.executeQuery(ansi.RequestModeSynchronizedOutput)
p.shutdown(false)
if !bytes.Contains([]byte(ft.String()), []byte(ansi.RequestPrimaryDeviceAttributes)) {
t.Fatalf("expected a DA1 request to be written, got %q", ft.String())
}
if _, err := io.WriteString(w, "abc"); err != nil {
t.Fatal(err)
}
if got := readAvailable(t, p.input, time.Second); got != "abc" {
t.Fatalf("expected the shell to get %q, got %q", "abc", got)
}
}
// Without outstanding queries there is nothing to drain, and no DA1 request
// is sent.
func TestDrainQueryRepliesNoPendingQuery(t *testing.T) {
p, _, ft := newDrainTestProgram(t)
p.drainQueryReplies(t.Context())
if out := ft.String(); out != "" {
t.Fatalf("expected no output, got %q", out)
}
}
// The reply to a query sent long ago has been read by the input reader
// already, so there's nothing to drain.
func TestDrainQueryRepliesOldQuery(t *testing.T) {
p, _, ft := newDrainTestProgram(t)
p.lastQuery.Store(time.Now().Add(-2 * queryReplyWindow).UnixNano())
p.drainQueryReplies(t.Context())
if out := ft.String(); out != "" {
t.Fatalf("expected no output, got %q", out)
}
}
// The renderer's keyboard enhancements query counts as a query.
func TestCursedRendererReportsQueries(t *testing.T) {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
var queries int
r.onQuery = func() { queries++ }
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if !bytes.Contains(out.Bytes(), []byte(ansi.RequestKittyKeyboard)) {
t.Fatalf("expected a keyboard enhancements query, got %q", out.String())
}
if queries != 1 {
t.Fatalf("expected the query to be reported once, got %d", queries)
}
}

91
tty_linux_test.go Normal file
View file

@ -0,0 +1,91 @@
//go:build linux
// +build linux
package tea
import (
"bytes"
"os"
"path/filepath"
"testing"
"time"
)
type readyMsg struct{}
type readyModel struct{ ready chan struct{} }
func (m readyModel) Init() Cmd { return func() Msg { return readyMsg{} } }
func (m readyModel) Update(msg Msg) (Model, Cmd) {
if _, ok := msg.(readyMsg); ok {
close(m.ready)
}
return m, nil
}
func (m readyModel) View() View { return NewView("") }
func countEpollFDs(t *testing.T) int {
t.Helper()
entries, err := os.ReadDir("/proc/self/fd")
if err != nil {
t.Skipf("cannot inspect file descriptors: %v", err)
}
var n int
for _, e := range entries {
target, err := os.Readlink(filepath.Join("/proc/self/fd", e.Name()))
if err == nil && target == "anon_inode:[eventpoll]" {
n++
}
}
return n
}
// Every ReleaseTerminal/RestoreTerminal cycle (Exec, suspend) replaces the
// input cancel reader. The replaced reader must be closed, or its epoll file
// descriptor leaks.
//
// Not parallel: it counts process-wide file descriptors.
func TestReleaseRestoreTerminalClosesCancelReader(t *testing.T) {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer r.Close() //nolint:errcheck
defer w.Close() //nolint:errcheck
m := readyModel{ready: make(chan struct{})}
var out bytes.Buffer
p := NewProgram(m, WithInput(r), WithOutput(&out))
done := make(chan struct{})
go func() {
defer close(done)
_, _ = p.Run()
}()
select {
case <-m.ready:
case <-time.After(5 * time.Second):
t.Fatal("program did not start")
}
before := countEpollFDs(t)
const cycles = 20
for i := range cycles {
if err := p.ReleaseTerminal(); err != nil {
t.Fatalf("release %d: %v", i, err)
}
if err := p.RestoreTerminal(); err != nil {
t.Fatalf("restore %d: %v", i, err)
}
}
after := countEpollFDs(t)
p.Quit()
<-done
if after > before {
t.Fatalf("epoll file descriptors grew by %d over %d release/restore cycles (before=%d, after=%d)",
after-before, cycles, before, after)
}
}

12
tty_other.go Normal file
View file

@ -0,0 +1,12 @@
//go:build wasip1 || wasip2
package tea
// initInput on WASI: there is no raw mode and no /dev/tty; the program
// runs with non-TTY (pipe) input, which Bubble Tea supports natively.
func (p *Program) initInput() (err error) { return nil }
// suspendSupported: no SIGTSTP or process groups on WASI.
const suspendSupported = false
func suspendProcess() {}

190
tty_test.go Normal file
View file

@ -0,0 +1,190 @@
package tea
import (
"bytes"
"testing"
)
type windowSizeModel struct {
windowSize WindowSizeMsg
quit bool
}
func (m *windowSizeModel) Init() Cmd {
return nil
}
func (m *windowSizeModel) Update(msg Msg) (Model, Cmd) {
switch msg := msg.(type) {
case WindowSizeMsg:
m.windowSize = msg
m.quit = true
return m, Quit
}
return m, nil
}
func (m *windowSizeModel) View() View {
return NewView("")
}
func TestFallbackDimensions(t *testing.T) {
t.Run("default fallback to 80x24", func(t *testing.T) {
t.Setenv("COLUMNS", "")
t.Setenv("LINES", "")
p := NewProgram(nil)
w, h := p.fallbackDimensions(0, 0)
if w != defaultWidth || h != defaultHeight {
t.Errorf("expected %dx%d, got %dx%d", defaultWidth, defaultHeight, w, h)
}
w, h = p.fallbackDimensions(-10, -5)
if w != defaultWidth || h != defaultHeight {
t.Errorf("expected %dx%d, got %dx%d", defaultWidth, defaultHeight, w, h)
}
})
t.Run("preserve positive dimensions", func(t *testing.T) {
p := NewProgram(nil)
w, h := p.fallbackDimensions(120, 40)
if w != 120 || h != 40 {
t.Errorf("expected 120x40, got %dx%d", w, h)
}
})
t.Run("mixed non-positive dimensions", func(t *testing.T) {
t.Setenv("COLUMNS", "")
t.Setenv("LINES", "")
p := NewProgram(nil)
w, h := p.fallbackDimensions(0, 50)
if w != defaultWidth || h != 50 {
t.Errorf("expected %dx50, got %dx%d", defaultWidth, w, h)
}
w, h = p.fallbackDimensions(100, 0)
if w != 100 || h != defaultHeight {
t.Errorf("expected 100x%d, got %dx%d", defaultHeight, w, h)
}
})
t.Run("fallback to COLUMNS and LINES from os env", func(t *testing.T) {
t.Setenv("COLUMNS", "132")
t.Setenv("LINES", "43")
p := NewProgram(nil)
w, h := p.fallbackDimensions(0, 0)
if w != 132 || h != 43 {
t.Errorf("expected 132x43, got %dx%d", w, h)
}
})
t.Run("fallback to COLUMNS and LINES from program environment", func(t *testing.T) {
t.Setenv("COLUMNS", "200")
t.Setenv("LINES", "100")
p := NewProgram(nil, WithEnvironment([]string{"COLUMNS=150", "LINES=60"}))
w, h := p.fallbackDimensions(0, 0)
if w != 150 || h != 60 {
t.Errorf("expected 150x60, got %dx%d", w, h)
}
})
t.Run("program environment without COLUMNS and LINES falls back to 80x24 skipping os env", func(t *testing.T) {
t.Setenv("COLUMNS", "200")
t.Setenv("LINES", "100")
p := NewProgram(nil, WithEnvironment([]string{"OTHER_VAR=1"}))
w, h := p.fallbackDimensions(0, 0)
if w != defaultWidth || h != defaultHeight {
t.Errorf("expected %dx%d, got %dx%d", defaultWidth, defaultHeight, w, h)
}
})
t.Run("invalid or non-positive COLUMNS and LINES fall back to defaults", func(t *testing.T) {
t.Setenv("COLUMNS", "invalid")
t.Setenv("LINES", "-10")
p := NewProgram(nil)
w, h := p.fallbackDimensions(0, 0)
if w != defaultWidth || h != defaultHeight {
t.Errorf("expected %dx%d, got %dx%d", defaultWidth, defaultHeight, w, h)
}
t.Setenv("COLUMNS", "0")
t.Setenv("LINES", "0")
w, h = p.fallbackDimensions(0, 0)
if w != defaultWidth || h != defaultHeight {
t.Errorf("expected %dx%d, got %dx%d", defaultWidth, defaultHeight, w, h)
}
})
}
func TestProgramNonTTYDimensions(t *testing.T) {
t.Run("non-tty output does not receive fallback dimensions", func(t *testing.T) {
t.Setenv("COLUMNS", "110")
t.Setenv("LINES", "35")
var buf bytes.Buffer
var in bytes.Buffer
m := &windowSizeModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
)
if _, err := p.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if m.windowSize.Width != 0 || m.windowSize.Height != 0 {
t.Errorf("expected WindowSizeMsg 0x0 for non-TTY output, got %dx%d",
m.windowSize.Width, m.windowSize.Height)
}
})
t.Run("non-tty output with program environment does not receive fallback dimensions", func(t *testing.T) {
var buf bytes.Buffer
var in bytes.Buffer
m := &windowSizeModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithEnvironment([]string{"COLUMNS=150", "LINES=60"}),
)
if _, err := p.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if m.windowSize.Width != 0 || m.windowSize.Height != 0 {
t.Errorf("expected WindowSizeMsg 0x0 for non-TTY output, got %dx%d",
m.windowSize.Width, m.windowSize.Height)
}
})
t.Run("non-tty output preserves WithWindowSize when specified", func(t *testing.T) {
var buf bytes.Buffer
var in bytes.Buffer
m := &windowSizeModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithWindowSize(120, 50),
)
if _, err := p.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if m.windowSize.Width != 120 || m.windowSize.Height != 50 {
t.Errorf("expected WindowSizeMsg 120x50, got %dx%d",
m.windowSize.Width, m.windowSize.Height)
}
})
}

View file

@ -10,7 +10,7 @@ By the way, the non-annotated source code for this program is available
[on GitHub][tut-source].
[elm]: https://guide.elm-lang.org/architecture/
[tut-source]: https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics
[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics
## Enough! Let’s get to it.
@ -216,8 +216,8 @@ look at the [Command Tutorial][cmd]. It’s pretty simple.
There are also several [Bubble Tea examples][examples] available and, of course,
there are [Go Docs][docs].
[cmd]: http://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands/
[examples]: http://github.com/charmbracelet/bubbletea/tree/master/examples
[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/
[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples
[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc
## Additional Resources

View file

@ -6,7 +6,7 @@ understanding of [the first tutorial][basics].
You can find the non-annotated version of this program [on GitHub][source].
[basics]: https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics
[basics]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics
[source]: https://github.com/charmbracelet/bubbletea/blob/master/tutorials/commands/main.go
## Let’s Go!
@ -222,7 +222,7 @@ And, of course, check out the [Go Docs][docs].
[bubbles]: https://github.com/charmbracelet/bubbles
[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc
[examples]: https://github.com/charmbracelet/bubbletea/tree/master/examples
[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples
## Additional Resources

View file

@ -16,7 +16,8 @@ type terminalVersion struct{}
// RequestTerminalVersion is a command that queries the terminal for its
// version using XTVERSION. Note that some terminals may not support this
// command.
// command. Use [WithInput] to enable input, since the reply cannot be read
// otherwise.
func RequestTerminalVersion() Msg {
return terminalVersion{}
}