Compare commits
1 commit
main
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e12b8ae73 |
23 changed files with 102 additions and 2554 deletions
6
.github/workflows/coverage.yml
vendored
6
.github/workflows/coverage.yml
vendored
|
|
@ -12,18 +12,18 @@ jobs:
|
|||
GO111MODULE: "on"
|
||||
steps:
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v6
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Coverage
|
||||
run: |
|
||||
go test -race -covermode=atomic -coverprofile=coverage.txt ./...
|
||||
|
||||
- uses: codecov/codecov-action@v6
|
||||
- uses: codecov/codecov-action@v7
|
||||
with:
|
||||
file: ./coverage.txt
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
|
|
|||
4
.github/workflows/examples.yml
vendored
4
.github/workflows/examples.yml
vendored
|
|
@ -20,8 +20,8 @@ jobs:
|
|||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '^1'
|
||||
cache: true
|
||||
|
|
|
|||
|
|
@ -31,12 +31,10 @@ 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
|
||||
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]
|
||||
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
|
||||
noInput bool // whether input is disabled, in which case keyboard enhancement queries are pointless
|
||||
}
|
||||
|
||||
var _ renderer = &cursedRenderer{}
|
||||
|
|
@ -107,11 +105,6 @@ 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
|
||||
}
|
||||
|
|
@ -291,14 +284,6 @@ 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()
|
||||
|
|
@ -308,19 +293,10 @@ func (s *cursedRenderer) writeString(str string) (int, error) {
|
|||
}
|
||||
|
||||
// flush implements renderer.
|
||||
func (s *cursedRenderer) flush(closing bool) (bool, error) {
|
||||
func (s *cursedRenderer) flush(closing 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 {
|
||||
|
|
@ -342,22 +318,14 @@ func (s *cursedRenderer) flushLocked(closing bool) (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)
|
||||
}
|
||||
|
||||
// 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() {
|
||||
if !s.starting && !closing && !s.pendingErase && s.lastView != nil && viewEquals(s.lastView, &view) && frameArea == s.cellbuf.Bounds() {
|
||||
// No changes, nothing to do.
|
||||
return false, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// We're no longer starting.
|
||||
|
|
@ -476,7 +444,7 @@ func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
|
|||
}
|
||||
if !closing {
|
||||
// Request keyboard enhancements when they change
|
||||
s.query(ansi.RequestKittyKeyboard)
|
||||
_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -505,7 +473,7 @@ func (s *cursedRenderer) flushLocked(closing bool) (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 !colorEqual(c.newColor, c.oldColor) {
|
||||
if c.newColor != c.oldColor {
|
||||
if c.newColor == nil {
|
||||
// Reset the color if it was set to nil.
|
||||
_, _ = s.scr.WriteString(c.reset)
|
||||
|
|
@ -574,7 +542,7 @@ func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
|
|||
}
|
||||
|
||||
if err := s.scr.Flush(); err != nil {
|
||||
return true, fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
|
||||
return fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
|
||||
}
|
||||
|
||||
// Check if we have any render updates to flush.
|
||||
|
|
@ -661,13 +629,13 @@ func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
|
|||
s.logger.Printf("output: %q", buf.String())
|
||||
}
|
||||
if _, err := io.Copy(s.w, &buf); err != nil {
|
||||
return true, fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
|
||||
return fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
s.lastView = &view
|
||||
|
||||
return true, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// render implements renderer.
|
||||
|
|
@ -676,7 +644,6 @@ func (s *cursedRenderer) render(v View) {
|
|||
defer s.mu.Unlock()
|
||||
|
||||
s.view = v
|
||||
s.viewStale = false
|
||||
}
|
||||
|
||||
// reset implements renderer.
|
||||
|
|
@ -724,7 +691,6 @@ func (s *cursedRenderer) resize(w, h int) {
|
|||
s.width, s.height = w, h
|
||||
s.scr.Resize(s.width, s.height)
|
||||
s.pendingErase = true
|
||||
s.viewStale = true
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
|
|
@ -739,18 +705,6 @@ func (s *cursedRenderer) clearScreen() {
|
|||
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()
|
||||
}
|
||||
|
||||
// enableAltScreen sets the alt screen mode.
|
||||
// Note that this writes to the buffer directly if write is true.
|
||||
func enableAltScreen(s *cursedRenderer, enable bool, write bool) {
|
||||
|
|
@ -823,31 +777,9 @@ 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')
|
||||
|
|
@ -859,14 +791,9 @@ func (s *cursedRenderer) insertAbove(str string) error {
|
|||
lines := strings.Split(str, "\n")
|
||||
offset := len(lines)
|
||||
for _, line := range lines {
|
||||
// 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)
|
||||
lineWidth := ansi.StringWidth(line)
|
||||
if w > 0 && lineWidth > w {
|
||||
offset += (lineWidth - 1) / w
|
||||
offset += (lineWidth / w)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -881,8 +808,8 @@ func (s *cursedRenderer) insertAbove(str string) error {
|
|||
sb.WriteString(ansi.CursorUp(up))
|
||||
sb.WriteString(ansi.InsertLine(offset))
|
||||
for _, line := range lines {
|
||||
sb.WriteString(ansi.EraseLineRight)
|
||||
sb.WriteString(line)
|
||||
sb.WriteString(ansi.EraseLineRight)
|
||||
sb.WriteString("\r\n")
|
||||
}
|
||||
|
||||
|
|
@ -956,20 +883,6 @@ func setProgramStatus(s *cursedRenderer, prev, cur *ProgramStatus) {
|
|||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -985,8 +898,8 @@ func viewEquals(a, b *View) bool {
|
|||
a.ReportFocus != b.ReportFocus ||
|
||||
a.MouseMode != b.MouseMode ||
|
||||
a.WindowTitle != b.WindowTitle ||
|
||||
!colorEqual(a.ForegroundColor, b.ForegroundColor) ||
|
||||
!colorEqual(a.BackgroundColor, b.BackgroundColor) ||
|
||||
a.ForegroundColor != b.ForegroundColor ||
|
||||
a.BackgroundColor != b.BackgroundColor ||
|
||||
a.KeyboardEnhancements != b.KeyboardEnhancements {
|
||||
return false
|
||||
}
|
||||
|
|
@ -999,7 +912,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 ||
|
||||
!colorEqual(a.Cursor.Color, b.Cursor.Color) {
|
||||
a.Cursor.Color != b.Cursor.Color {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package tea
|
|||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image/color"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -12,150 +11,6 @@ import (
|
|||
"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
|
||||
}
|
||||
|
|
@ -228,103 +83,6 @@ func TestCursedRenderer_mouseVsFlush(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -352,7 +110,7 @@ func TestCursedRenderer_restoresKittyKeyboardStack(t *testing.T) {
|
|||
render := func(v View) {
|
||||
t.Helper()
|
||||
r.render(v)
|
||||
if _, err := r.flush(false); err != nil {
|
||||
if err := r.flush(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -413,7 +171,7 @@ func TestCursedRenderer_updatesKittyKeyboardFlagsInPlace(t *testing.T) {
|
|||
render := func(v View) {
|
||||
t.Helper()
|
||||
r.render(v)
|
||||
if _, err := r.flush(false); err != nil {
|
||||
if err := r.flush(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -443,251 +201,3 @@ func TestCursedRenderer_updatesKittyKeyboardFlagsInPlace(t *testing.T) {
|
|||
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")
|
||||
}
|
||||
|
|
|
|||
9
exec.go
9
exec.go
|
|
@ -100,15 +100,6 @@ 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 {
|
||||
|
|
|
|||
119
exec_test.go
119
exec_test.go
|
|
@ -4,9 +4,7 @@ import (
|
|||
"bytes"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type execFinishedMsg struct{ err error }
|
||||
|
|
@ -137,120 +135,3 @@ 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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
"log"
|
||||
"os"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// LogToFile sets up default logging to log to a file. This is helpful as we
|
||||
|
|
@ -43,8 +42,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 {
|
||||
finalRune, _ := utf8.DecodeLastRuneInString(prefix)
|
||||
if !unicode.IsSpace(finalRune) {
|
||||
finalChar := prefix[len(prefix)-1]
|
||||
if !unicode.IsSpace(rune(finalChar)) {
|
||||
prefix += " "
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -28,34 +27,3 @@ 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,9 +17,6 @@ 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 }
|
||||
|
||||
|
|
@ -30,7 +27,7 @@ func (n nilRenderer) resize(int, int) {}
|
|||
func (n nilRenderer) setColorProfile(colorprofile.Profile) {}
|
||||
|
||||
// flush implements the Renderer interface.
|
||||
func (nilRenderer) flush(bool) (bool, error) { return false, nil }
|
||||
func (nilRenderer) flush(bool) error { return nil }
|
||||
|
||||
// close implements the Renderer interface.
|
||||
func (nilRenderer) close() error { return nil }
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ func TestCursedRenderer_programStatus(t *testing.T) {
|
|||
v := NewView("hello")
|
||||
v.ProgramStatus = ps
|
||||
r.render(v)
|
||||
if _, err := r.flush(false); err != nil {
|
||||
if err := r.flush(false); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
return out.String()
|
||||
|
|
@ -72,7 +72,7 @@ func TestCursedRenderer_programStatus(t *testing.T) {
|
|||
// Resuming re-sends the last status.
|
||||
out.Reset()
|
||||
r.start()
|
||||
if _, err := r.flush(false); err != nil {
|
||||
if err := r.flush(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := out.String(); !strings.Contains(got, ansi.SetProgramStatus(*done)) {
|
||||
|
|
|
|||
|
|
@ -1,226 +0,0 @@
|
|||
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")
|
||||
}
|
||||
}
|
||||
13
renderer.go
13
renderer.go
|
|
@ -25,10 +25,8 @@ type renderer interface {
|
|||
// render renders a frame to the output.
|
||||
render(View)
|
||||
|
||||
// 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)
|
||||
// flush flushes the renderer's buffer to the output.
|
||||
flush(closing bool) error
|
||||
|
||||
// reset resets the renderer's state to its initial state.
|
||||
reset()
|
||||
|
|
@ -51,13 +49,6 @@ 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)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,269 +0,0 @@
|
|||
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")
|
||||
}
|
||||
}
|
||||
|
|
@ -138,9 +138,6 @@ 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.
|
||||
|
|
|
|||
|
|
@ -1,227 +0,0 @@
|
|||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
//go:build wasip1 || wasip2
|
||||
|
||||
package tea
|
||||
|
||||
// listenForResize on WASI: no SIGWINCH; report immediately done.
|
||||
func (p *Program) listenForResize(done chan struct{}) { close(done) }
|
||||
|
|
@ -55,69 +55,3 @@ func TestHandleSignalsReturnsAfterContextCancelDuringPendingSend(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
|
|
|
|||
329
tea.go
329
tea.go
|
|
@ -522,16 +522,8 @@ 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
|
||||
|
||||
|
|
@ -547,8 +539,7 @@ 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
|
||||
tracePath string
|
||||
logger uv.Logger
|
||||
|
||||
// where to read inputs from, this will usually be os.Stdin.
|
||||
input io.Reader
|
||||
|
|
@ -559,24 +550,18 @@ 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
|
||||
|
||||
|
|
@ -634,9 +619,7 @@ 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.
|
||||
|
|
@ -670,7 +653,10 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
|
|||
|
||||
tracePath, traceOk := os.LookupEnv("TEA_TRACE")
|
||||
if traceOk && len(tracePath) > 0 {
|
||||
p.tracePath = tracePath
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
return p
|
||||
|
|
@ -679,11 +665,6 @@ 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
|
||||
|
|
@ -695,34 +676,27 @@ func (p *Program) handleSignals() chan struct{} {
|
|||
go func() {
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer signal.Stop(sig)
|
||||
defer func() {
|
||||
signal.Stop(sig)
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
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 {
|
||||
continue
|
||||
}
|
||||
var msg Msg = QuitMsg{}
|
||||
if s == syscall.SIGINT {
|
||||
msg = InterruptMsg{}
|
||||
}
|
||||
select {
|
||||
case p.msgs <- msg:
|
||||
case <-p.ctx.Done():
|
||||
if atomic.LoadUint32(&p.ignoreSignals) == 0 {
|
||||
var msg Msg = QuitMsg{}
|
||||
if s == syscall.SIGINT {
|
||||
msg = InterruptMsg{}
|
||||
}
|
||||
select {
|
||||
case p.msgs <- msg:
|
||||
case <-p.ctx.Done():
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -916,7 +890,7 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
|
|||
p.execute(fmt.Sprint(msg.Msg))
|
||||
|
||||
case printLineMessage:
|
||||
p.keepWriteErr(p.renderer.insertAbove(msg.messageBody))
|
||||
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
|
||||
|
||||
case clearScreenMsg:
|
||||
p.renderer.clearScreen()
|
||||
|
|
@ -943,16 +917,6 @@ 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:
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1060,67 +1024,26 @@ 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, ttyOut, err := OpenTTY()
|
||||
ttyIn, _, 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
|
||||
}
|
||||
}
|
||||
|
|
@ -1143,10 +1066,6 @@ 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
|
||||
}
|
||||
|
||||
|
|
@ -1156,7 +1075,6 @@ 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)
|
||||
}
|
||||
|
||||
|
|
@ -1188,7 +1106,6 @@ 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
|
||||
}
|
||||
}
|
||||
|
|
@ -1214,7 +1131,6 @@ 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
|
||||
}
|
||||
}
|
||||
|
|
@ -1255,10 +1171,6 @@ 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)
|
||||
|
|
@ -1290,11 +1202,6 @@ 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
|
||||
}
|
||||
|
||||
|
|
@ -1320,25 +1227,13 @@ 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)
|
||||
}
|
||||
|
||||
|
|
@ -1352,7 +1247,6 @@ 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
|
||||
|
|
@ -1368,17 +1262,9 @@ 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.
|
||||
func (p *Program) flush() error {
|
||||
p.mu.Lock()
|
||||
|
|
@ -1398,27 +1284,6 @@ 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) {
|
||||
|
|
@ -1428,17 +1293,21 @@ func (p *Program) shutdown(kill bool) {
|
|||
// Wait for all handlers to finish.
|
||||
p.handlers.shutdown()
|
||||
|
||||
p.shutdownInput()
|
||||
// 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()
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
|
@ -1468,26 +1337,19 @@ func (p *Program) recoverFromPanic(r interface{}) {
|
|||
}
|
||||
}
|
||||
|
||||
// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace,
|
||||
// restores the terminal to a usable state, and signals the program to be killed.
|
||||
// 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.
|
||||
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.shutdown(true)
|
||||
p.cancel()
|
||||
// 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", trace), "\n", "\r\n")
|
||||
stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\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()))
|
||||
|
|
@ -1510,9 +1372,10 @@ 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 {
|
||||
|
|
@ -1520,18 +1383,6 @@ 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()
|
||||
}
|
||||
|
||||
|
|
@ -1566,11 +1417,10 @@ 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.Send(printLineMessage{
|
||||
p.msgs <- printLineMessage{
|
||||
messageBody: fmt.Sprint(args...),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Printf prints above the Program. It takes a format template followed by
|
||||
|
|
@ -1581,22 +1431,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.Send(printLineMessage{
|
||||
p.msgs <- printLineMessage{
|
||||
messageBody: fmt.Sprintf(template, args...),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// startRenderer starts the renderer.
|
||||
func (p *Program) startRenderer() {
|
||||
framerate := time.Second / time.Duration(p.fps)
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
|
||||
// Since the renderer can be restarted after a stop, we need to reset
|
||||
// the done channel and its corresponding sync.Once.
|
||||
|
|
@ -1605,74 +1455,20 @@ 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.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
|
||||
}
|
||||
case <-p.ticker.C:
|
||||
_ = p.flush()
|
||||
_ = p.renderer.flush(false)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
|
@ -1684,9 +1480,8 @@ func (p *Program) stopRenderer(kill bool) {
|
|||
|
||||
if !kill {
|
||||
// flush locks the mutex
|
||||
_, err := p.renderer.flush(true)
|
||||
p.keepWriteErr(err)
|
||||
_ = p.renderer.flush(true)
|
||||
}
|
||||
|
||||
p.keepWriteErr(p.renderer.close())
|
||||
_ = p.renderer.close()
|
||||
}
|
||||
|
|
|
|||
275
tea_test.go
275
tea_test.go
|
|
@ -6,9 +6,6 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
|
@ -94,28 +91,6 @@ 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
|
||||
|
|
@ -249,31 +224,6 @@ 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) {
|
||||
|
|
@ -585,49 +535,6 @@ 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
|
||||
|
|
@ -640,74 +547,6 @@ 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
|
||||
|
|
@ -775,44 +614,6 @@ 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
|
||||
}
|
||||
|
|
@ -1043,79 +844,3 @@ func TestProgressBarStateStringOutOfRange(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
141
tty.go
141
tty.go
|
|
@ -1,14 +1,12 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
uv "github.com/charmbracelet/ultraviolet"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/charmbracelet/x/term"
|
||||
)
|
||||
|
||||
|
|
@ -35,7 +33,7 @@ func (p *Program) initTerminal() error {
|
|||
// Bubble Tea program.
|
||||
func (p *Program) restoreTerminalState() error {
|
||||
// Flush queued commands.
|
||||
p.keepWriteErr(p.flush())
|
||||
_ = p.flush()
|
||||
|
||||
return p.restoreInput()
|
||||
}
|
||||
|
|
@ -62,18 +60,6 @@ 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.
|
||||
|
|
@ -91,145 +77,34 @@ func (p *Program) initInputReader(cancel bool) error {
|
|||
p.inputScanner = drv
|
||||
p.readLoopDone = make(chan struct{})
|
||||
|
||||
go p.readLoop(p.ctx, drv, p.readLoopDone, p.errs)
|
||||
go p.readLoop()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
func (p *Program) readLoop() {
|
||||
defer close(p.readLoopDone)
|
||||
|
||||
if err := scanner.StreamEvents(ctx, p.msgs); err != nil {
|
||||
if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-p.ctx.Done():
|
||||
return
|
||||
case errs <- err:
|
||||
case p.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(inputReadLoopTimeout):
|
||||
case <-time.After(500 * time.Millisecond): //nolint:mnd
|
||||
// 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
|
||||
|
|
|
|||
|
|
@ -1,197 +0,0 @@
|
|||
//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)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
//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
12
tty_other.go
|
|
@ -1,12 +0,0 @@
|
|||
//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() {}
|
||||
Loading…
Reference in a new issue