perf(renderer): stop the frame ticker while nothing changes (#1832)
Co-authored-by: Drew Smirnoff <drew@charm.land> Signed-off-by: Drew Smirnoff <drew@charm.land>
This commit is contained in:
parent
67b4c7a8a2
commit
e4d617e7e0
7 changed files with 337 additions and 26 deletions
|
|
@ -293,7 +293,7 @@ func (s *cursedRenderer) writeString(str string) (int, error) {
|
|||
}
|
||||
|
||||
// flush implements renderer.
|
||||
func (s *cursedRenderer) flush(closing bool) error {
|
||||
func (s *cursedRenderer) flush(closing bool) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
|
|
@ -325,7 +325,7 @@ func (s *cursedRenderer) flush(closing bool) error {
|
|||
|
||||
if !s.starting && !closing && !s.pendingErase && s.lastView != nil && viewEquals(s.lastView, &view) && frameArea == s.cellbuf.Bounds() {
|
||||
// No changes, nothing to do.
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// We're no longer starting.
|
||||
|
|
@ -542,7 +542,7 @@ func (s *cursedRenderer) flush(closing bool) error {
|
|||
}
|
||||
|
||||
if err := s.scr.Flush(); err != nil {
|
||||
return fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
|
||||
return true, fmt.Errorf("bubbletea: error flushing screen writer: %w", err)
|
||||
}
|
||||
|
||||
// Check if we have any render updates to flush.
|
||||
|
|
@ -629,13 +629,13 @@ func (s *cursedRenderer) flush(closing bool) error {
|
|||
s.logger.Printf("output: %q", buf.String())
|
||||
}
|
||||
if _, err := io.Copy(s.w, &buf); err != nil {
|
||||
return fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
|
||||
return true, fmt.Errorf("bubbletea: error flushing update to the writer: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
s.lastView = &view
|
||||
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// render implements renderer.
|
||||
|
|
|
|||
|
|
@ -110,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)
|
||||
}
|
||||
}
|
||||
|
|
@ -171,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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ func (n nilRenderer) resize(int, int) {}
|
|||
func (n nilRenderer) setColorProfile(colorprofile.Profile) {}
|
||||
|
||||
// flush implements the Renderer interface.
|
||||
func (nilRenderer) flush(bool) error { return nil }
|
||||
func (nilRenderer) flush(bool) (bool, error) { return false, nil }
|
||||
|
||||
// close implements the Renderer interface.
|
||||
func (nilRenderer) close() error { return nil }
|
||||
|
|
|
|||
|
|
@ -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)) {
|
||||
|
|
|
|||
|
|
@ -25,8 +25,10 @@ type renderer interface {
|
|||
// render renders a frame to the output.
|
||||
render(View)
|
||||
|
||||
// flush flushes the renderer's buffer to the output.
|
||||
flush(closing bool) error
|
||||
// flush flushes the renderer's buffer to the output. It reports whether
|
||||
// there was anything to draw, so the caller can tell an idle screen from
|
||||
// an active one.
|
||||
flush(closing bool) (bool, error)
|
||||
|
||||
// reset resets the renderer's state to its initial state.
|
||||
reset()
|
||||
|
|
|
|||
269
renderer_park_test.go
Normal file
269
renderer_park_test.go
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
)
|
||||
|
||||
// These tests cover the renderer stopping its ticker while nothing changes.
|
||||
// Once the ticker is stopped, a change only reaches the output if whatever
|
||||
// made it woke the renderer, so each test parks the renderer first and then
|
||||
// checks that the change is drawn.
|
||||
|
||||
// safeBuffer is an output that can be read while the program writes to it.
|
||||
type safeBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *safeBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p) //nolint:wrapcheck
|
||||
}
|
||||
|
||||
func (b *safeBuffer) Len() int {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Len()
|
||||
}
|
||||
|
||||
// since returns everything written after the first n bytes.
|
||||
func (b *safeBuffer) since(n int) string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()[n:]
|
||||
}
|
||||
|
||||
// tickRenderer records when the renderer goroutine flushes, which happens
|
||||
// once per tick of the frame ticker.
|
||||
type tickRenderer struct {
|
||||
renderer
|
||||
|
||||
mu sync.Mutex
|
||||
ticks int
|
||||
}
|
||||
|
||||
func (r *tickRenderer) flush(closing bool) (bool, error) {
|
||||
if !closing {
|
||||
r.mu.Lock()
|
||||
r.ticks++
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return r.renderer.flush(closing)
|
||||
}
|
||||
|
||||
// count returns the number of ticks so far.
|
||||
func (r *tickRenderer) count() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.ticks
|
||||
}
|
||||
|
||||
type setViewMsg func(*View)
|
||||
|
||||
type runCmdMsg struct{ cmd Cmd }
|
||||
|
||||
type parkModel struct{ view View }
|
||||
|
||||
func (m *parkModel) Init() Cmd { return nil }
|
||||
|
||||
func (m *parkModel) Update(msg Msg) (Model, Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case setViewMsg:
|
||||
msg(&m.view)
|
||||
case runCmdMsg:
|
||||
return m, msg.cmd
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m *parkModel) View() View { return m.view }
|
||||
|
||||
type parkHarness struct {
|
||||
t *testing.T
|
||||
p *Program
|
||||
out *safeBuffer
|
||||
r *tickRenderer
|
||||
frame time.Duration
|
||||
done chan struct{}
|
||||
err error // valid once done is closed
|
||||
}
|
||||
|
||||
func newParkHarness(t *testing.T, fps int, opts ...ProgramOption) *parkHarness {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
h := &parkHarness{
|
||||
t: t,
|
||||
out: &safeBuffer{},
|
||||
frame: time.Second / time.Duration(fps),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
h.r = &tickRenderer{renderer: newCursedRenderer(h.out, nil, 80, 24)}
|
||||
opts = append([]ProgramOption{
|
||||
WithContext(ctx),
|
||||
WithInput(&bytes.Buffer{}),
|
||||
WithOutput(h.out),
|
||||
WithFPS(fps),
|
||||
WithWindowSize(80, 24),
|
||||
}, opts...)
|
||||
h.p = NewProgram(&parkModel{view: NewView("first")}, opts...)
|
||||
h.p.renderer = h.r
|
||||
|
||||
go func() {
|
||||
defer close(h.done)
|
||||
_, h.err = h.p.Run()
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
h.p.Kill()
|
||||
<-h.done
|
||||
})
|
||||
return h
|
||||
}
|
||||
|
||||
// waitParked waits until the renderer has stopped ticking.
|
||||
func (h *parkHarness) waitParked() {
|
||||
h.t.Helper()
|
||||
|
||||
// Parked means no tick for well over a frame. The ticker runs for about
|
||||
// half a second of unchanged frames before it stops.
|
||||
quiet := 6 * h.frame
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
n := h.r.count()
|
||||
for time.Now().Before(deadline) {
|
||||
time.Sleep(quiet)
|
||||
m := h.r.count()
|
||||
if m == n && n > 0 {
|
||||
return
|
||||
}
|
||||
n = m
|
||||
}
|
||||
h.t.Fatal("the renderer never stopped ticking")
|
||||
}
|
||||
|
||||
// waitOutput waits until everything in want is written after mark and
|
||||
// returns how long that took.
|
||||
func (h *parkHarness) waitOutput(mark int, within time.Duration, want ...string) time.Duration {
|
||||
h.t.Helper()
|
||||
|
||||
start := time.Now()
|
||||
for {
|
||||
got := h.out.since(mark)
|
||||
missing := ""
|
||||
for _, w := range want {
|
||||
if !strings.Contains(got, w) {
|
||||
missing = w
|
||||
break
|
||||
}
|
||||
}
|
||||
if missing == "" {
|
||||
return time.Since(start)
|
||||
}
|
||||
if time.Since(start) > within {
|
||||
h.t.Fatalf("%q not written within %v after waking a parked renderer; got %q", missing, within, got)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *parkHarness) setView(fn func(*View)) {
|
||||
h.p.Send(setViewMsg(fn))
|
||||
}
|
||||
|
||||
// waitDone waits for Run to return.
|
||||
func (h *parkHarness) waitDone() error {
|
||||
h.t.Helper()
|
||||
|
||||
const within = 2 * time.Second
|
||||
select {
|
||||
case <-h.done:
|
||||
return h.err
|
||||
case <-time.After(within):
|
||||
h.t.Fatalf("Run did not return within %v", within)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// nopExecCommand is an ExecCommand that does nothing.
|
||||
type nopExecCommand struct{}
|
||||
|
||||
func (nopExecCommand) Run() error { return nil }
|
||||
func (nopExecCommand) SetStdin(io.Reader) {}
|
||||
func (nopExecCommand) SetStdout(io.Writer) {}
|
||||
func (nopExecCommand) SetStderr(io.Writer) {}
|
||||
|
||||
func TestRendererStopsTickingWhenIdle(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
h := newParkHarness(t, 60)
|
||||
h.waitOutput(0, 5*time.Second, "first")
|
||||
h.waitParked()
|
||||
|
||||
n := h.r.count()
|
||||
time.Sleep(time.Second)
|
||||
if ticks := h.r.count() - n; ticks != 0 {
|
||||
t.Errorf("an idle program ticked %d times in a second, want 0", ticks)
|
||||
}
|
||||
}
|
||||
|
||||
// Every way of giving the renderer work must wake it.
|
||||
func TestRendererWakes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func(c Cmd) func(h *parkHarness) {
|
||||
return func(h *parkHarness) { h.p.Send(runCmdMsg{c}) }
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
do func(h *parkHarness)
|
||||
want []string
|
||||
}{
|
||||
{"content", func(h *parkHarness) { h.setView(func(v *View) { v.Content = "second" }) }, []string{"second"}},
|
||||
{"Println", cmd(Println("printed")), []string{"printed"}},
|
||||
{"raw", cmd(Raw("\x1b]2;raw\x07")), []string{"\x1b]2;raw\x07"}},
|
||||
{"exec", cmd(Exec(nopExecCommand{}, nil)), []string{ansi.SetModeBracketedPaste, "first"}},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
h := newParkHarness(t, 60)
|
||||
h.waitOutput(0, 5*time.Second, "first")
|
||||
h.waitParked()
|
||||
|
||||
mark := h.out.Len()
|
||||
tc.do(h)
|
||||
took := h.waitOutput(mark, 2*time.Second, tc.want...)
|
||||
t.Logf("drawn %v after waking", took)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRendererQuitWhileParked(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
h := newParkHarness(t, 60)
|
||||
h.waitParked()
|
||||
|
||||
mark := h.out.Len()
|
||||
h.setView(func(v *View) { v.Content = "last" })
|
||||
h.p.Quit()
|
||||
if err := h.waitDone(); err != nil {
|
||||
t.Errorf("Run returned %v, want nil", err)
|
||||
}
|
||||
if !strings.Contains(h.out.since(mark), "last") {
|
||||
t.Error("final frame not drawn")
|
||||
}
|
||||
}
|
||||
68
tea.go
68
tea.go
|
|
@ -553,15 +553,16 @@ type Program struct {
|
|||
// 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
|
||||
|
||||
|
|
@ -620,6 +621,7 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
|
|||
msgs: make(chan Msg),
|
||||
errs: make(chan error, 1),
|
||||
rendererDone: make(chan struct{}),
|
||||
rendererWake: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
// Apply all options to the program.
|
||||
|
|
@ -917,6 +919,16 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
|
|||
func (p *Program) render(model Model) {
|
||||
if p.renderer != nil {
|
||||
p.renderer.render(model.View()) // send view to renderer
|
||||
p.wakeRenderer()
|
||||
}
|
||||
}
|
||||
|
||||
// wakeRenderer restarts the renderer's ticker if it was stopped because
|
||||
// nothing was changing. It never blocks.
|
||||
func (p *Program) wakeRenderer() {
|
||||
select {
|
||||
case p.rendererWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1247,6 +1259,7 @@ 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
|
||||
|
|
@ -1440,13 +1453,12 @@ func (p *Program) Printf(template string, args ...any) {
|
|||
// startRenderer starts the renderer.
|
||||
func (p *Program) startRenderer() {
|
||||
framerate := time.Second / time.Duration(p.fps)
|
||||
if p.ticker == nil {
|
||||
p.ticker = time.NewTicker(framerate)
|
||||
} else {
|
||||
// If the ticker already exists, it has been stopped and we need to
|
||||
// reset it.
|
||||
p.ticker.Reset(framerate)
|
||||
}
|
||||
// Stop ticking after about half a second of frames with nothing to draw.
|
||||
idleFrames := max(p.fps/2, 1)
|
||||
|
||||
// Each run of the renderer gets its own ticker, so a goroutine that is
|
||||
// still exiting can't stop the ticker of the next one.
|
||||
ticker := time.NewTicker(framerate)
|
||||
|
||||
// Since the renderer can be restarted after a stop, we need to reset
|
||||
// the done channel and its corresponding sync.Once.
|
||||
|
|
@ -1455,15 +1467,43 @@ func (p *Program) startRenderer() {
|
|||
// Start the renderer.
|
||||
p.renderer.start()
|
||||
go func() {
|
||||
defer ticker.Stop()
|
||||
|
||||
var (
|
||||
idle int // consecutive frames with nothing to draw
|
||||
parked bool // whether the ticker is stopped
|
||||
realign bool // whether the ticker runs a shortened interval
|
||||
last time.Time // when the ticker last fired
|
||||
)
|
||||
for {
|
||||
select {
|
||||
case <-p.rendererDone:
|
||||
p.ticker.Stop()
|
||||
return
|
||||
|
||||
case <-p.ticker.C:
|
||||
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)
|
||||
}
|
||||
_ = p.flush()
|
||||
_ = p.renderer.flush(false)
|
||||
if drew, _ := p.renderer.flush(false); 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
|
@ -1480,7 +1520,7 @@ func (p *Program) stopRenderer(kill bool) {
|
|||
|
||||
if !kill {
|
||||
// flush locks the mutex
|
||||
_ = p.renderer.flush(true)
|
||||
_, _ = p.renderer.flush(true)
|
||||
}
|
||||
|
||||
_ = p.renderer.close()
|
||||
|
|
|
|||
Loading…
Reference in a new issue