Compare commits
1 commit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8cf963fba8 |
3 changed files with 713 additions and 130 deletions
303
eventloop_test.go
Normal file
303
eventloop_test.go
Normal file
|
|
@ -0,0 +1,303 @@
|
||||||
|
package tea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// countModel counts the messages it handles and the views it renders.
|
||||||
|
type countModel struct {
|
||||||
|
count int // only touched by the event loop
|
||||||
|
views atomic.Int64 // calls to View
|
||||||
|
rendered atomic.Int64 // the count the last view showed
|
||||||
|
viewedAt atomic.Int64 // when View was last called, in Unix nanoseconds
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *countModel) Init() Cmd { return nil }
|
||||||
|
|
||||||
|
func (m *countModel) Update(msg Msg) (Model, Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case incrementMsg, MouseMotionMsg:
|
||||||
|
m.count++
|
||||||
|
case KeyPressMsg:
|
||||||
|
if msg.String() == "q" {
|
||||||
|
return m, Quit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *countModel) View() View {
|
||||||
|
m.views.Add(1)
|
||||||
|
m.rendered.Store(int64(m.count))
|
||||||
|
m.viewedAt.Store(time.Now().UnixNano())
|
||||||
|
return NewView(fmt.Sprintf("count: %d", m.count))
|
||||||
|
}
|
||||||
|
|
||||||
|
// recordingRenderer remembers the last view it was given and the last one
|
||||||
|
// it flushed.
|
||||||
|
type recordingRenderer struct {
|
||||||
|
nilRenderer
|
||||||
|
mu sync.Mutex
|
||||||
|
view View
|
||||||
|
flushed View
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recordingRenderer) render(v View) {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.view = v
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recordingRenderer) flush(bool) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.flushed = r.view
|
||||||
|
r.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recordingRenderer) lastFlushed() string {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
return r.flushed.Content
|
||||||
|
}
|
||||||
|
|
||||||
|
// runCountModel runs a countModel. The returned function quits the program
|
||||||
|
// and returns what Run returned.
|
||||||
|
func runCountModel(t *testing.T, input io.Reader, opts ...ProgramOption) (*Program, *countModel, func() (Model, error)) {
|
||||||
|
t.Helper()
|
||||||
|
if input == nil {
|
||||||
|
input = &bytes.Buffer{}
|
||||||
|
}
|
||||||
|
m := &countModel{}
|
||||||
|
p := NewProgram(m, append([]ProgramOption{
|
||||||
|
WithInput(input),
|
||||||
|
WithOutput(io.Discard),
|
||||||
|
WithoutSignalHandler(),
|
||||||
|
}, opts...)...)
|
||||||
|
type result struct {
|
||||||
|
model Model
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
done := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
model, err := p.Run()
|
||||||
|
done <- result{model, err}
|
||||||
|
}()
|
||||||
|
quit := func() (Model, error) {
|
||||||
|
p.Quit()
|
||||||
|
select {
|
||||||
|
case r := <-done:
|
||||||
|
return r.model, r.err
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("program didn't quit")
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { p.Kill() })
|
||||||
|
return p, m, quit
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitFor waits until cond is true.
|
||||||
|
func waitFor(t *testing.T, what string, cond func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for !cond() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("timed out waiting for %s", what)
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitIdle waits for the startup messages to be rendered and a frame to
|
||||||
|
// pass without a render, so the next message is an isolated one.
|
||||||
|
func waitIdle(t *testing.T, m *countModel, frame time.Duration) {
|
||||||
|
t.Helper()
|
||||||
|
waitFor(t, "the first views", func() bool { return m.views.Load() >= 2 })
|
||||||
|
waitFor(t, "a frame without views", func() bool {
|
||||||
|
return time.Since(time.Unix(0, m.viewedAt.Load())) > frame+frame/4
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderCoalescesBurst(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const n = 1000
|
||||||
|
p, m, quit := runCountModel(t, nil)
|
||||||
|
waitIdle(t, m, time.Second/defaultFPS)
|
||||||
|
|
||||||
|
before := m.views.Load()
|
||||||
|
for range n {
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
}
|
||||||
|
waitFor(t, "the last message to be rendered", func() bool { return m.rendered.Load() == n })
|
||||||
|
views := m.views.Load() - before
|
||||||
|
t.Logf("%d views for a burst of %d messages", views, n)
|
||||||
|
if views > n/10 {
|
||||||
|
t.Errorf("rendered %d views for a burst of %d messages", views, n)
|
||||||
|
}
|
||||||
|
if _, err := quit(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderCoalescesInputBurst(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const n = 1000
|
||||||
|
r, w := io.Pipe()
|
||||||
|
defer r.Close() //nolint:errcheck
|
||||||
|
_, m, quit := runCountModel(t, r)
|
||||||
|
waitIdle(t, m, time.Second/defaultFPS)
|
||||||
|
|
||||||
|
// Mouse drag motions, written at once like a terminal does when the
|
||||||
|
// program can't keep up.
|
||||||
|
var seqs strings.Builder
|
||||||
|
for i := range n {
|
||||||
|
fmt.Fprintf(&seqs, "\x1b[<32;%d;%dM", 1+i%80, 1+i%24)
|
||||||
|
}
|
||||||
|
before := m.views.Load()
|
||||||
|
if _, err := io.WriteString(w, seqs.String()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, "the last motion to be rendered", func() bool { return m.rendered.Load() == n })
|
||||||
|
views := m.views.Load() - before
|
||||||
|
t.Logf("%d views for a burst of %d motions", views, n)
|
||||||
|
if views > n/10 {
|
||||||
|
t.Errorf("rendered %d views for a burst of %d motions", views, n)
|
||||||
|
}
|
||||||
|
if _, err := quit(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderIsolatedMessagePromptly(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const fps = 5
|
||||||
|
frame := time.Second / fps
|
||||||
|
p, m, quit := runCountModel(t, nil, WithFPS(fps))
|
||||||
|
waitIdle(t, m, frame)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
waitFor(t, "the message to be rendered", func() bool { return m.rendered.Load() == 1 })
|
||||||
|
// A held back render would wait for the frame to pass.
|
||||||
|
if took := time.Since(start); took > frame/2 {
|
||||||
|
t.Errorf("an isolated message was rendered after %v, want right away", took)
|
||||||
|
}
|
||||||
|
if _, err := quit(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderContinuousStream(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const fps = 20
|
||||||
|
frame := time.Second / fps
|
||||||
|
p, m, quit := runCountModel(t, nil, WithFPS(fps))
|
||||||
|
waitIdle(t, m, frame)
|
||||||
|
|
||||||
|
// Send messages as fast as they are taken for a while: the view must
|
||||||
|
// still be rendered about once a frame, not after every message and not
|
||||||
|
// only at the end.
|
||||||
|
const streamFor = 500 * time.Millisecond
|
||||||
|
before := m.views.Load()
|
||||||
|
sent := 0
|
||||||
|
var shown []int64
|
||||||
|
for start := time.Now(); time.Since(start) < streamFor; {
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
sent++
|
||||||
|
if r := m.rendered.Load(); len(shown) == 0 || shown[len(shown)-1] != r {
|
||||||
|
shown = append(shown, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
views := m.views.Load() - before
|
||||||
|
frames := int64(streamFor / frame)
|
||||||
|
t.Logf("%d views and %d distinct states for %d messages in %d frames", views, len(shown), sent, frames)
|
||||||
|
if views < frames/2 || views > 2*frames+2 {
|
||||||
|
t.Errorf("rendered %d views for %d messages in %d frames", views, sent, frames)
|
||||||
|
}
|
||||||
|
if len(shown) < int(frames/2) {
|
||||||
|
t.Errorf("only %d distinct states were rendered while messages kept coming", len(shown))
|
||||||
|
}
|
||||||
|
waitFor(t, "the last message to be rendered", func() bool { return m.rendered.Load() == int64(sent) })
|
||||||
|
if _, err := quit(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderQuitAfterBurst(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const n = 500
|
||||||
|
rr := &recordingRenderer{}
|
||||||
|
m := &countModel{}
|
||||||
|
p := NewProgram(m,
|
||||||
|
WithInput(&bytes.Buffer{}),
|
||||||
|
WithOutput(io.Discard),
|
||||||
|
WithoutSignalHandler(),
|
||||||
|
)
|
||||||
|
p.renderer = rr
|
||||||
|
go func() {
|
||||||
|
for range n {
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
}
|
||||||
|
p.Quit()
|
||||||
|
}()
|
||||||
|
if _, err := p.Run(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := m.rendered.Load(); got != n {
|
||||||
|
t.Errorf("the last view showed %d, want %d", got, n)
|
||||||
|
}
|
||||||
|
if got, want := rr.lastFlushed(), fmt.Sprintf("count: %d", n); got != want {
|
||||||
|
t.Errorf("the last frame drawn was %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if views := m.views.Load(); views > n/10 {
|
||||||
|
t.Errorf("rendered %d views for a burst of %d messages", views, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRenderBeforeExec checks that the terminal is handed over with the
|
||||||
|
// latest view drawn, even when its render was held back.
|
||||||
|
func TestRenderBeforeExec(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
rr := &recordingRenderer{}
|
||||||
|
m := &countModel{}
|
||||||
|
p := NewProgram(m,
|
||||||
|
WithInput(&bytes.Buffer{}),
|
||||||
|
WithOutput(io.Discard),
|
||||||
|
WithoutSignalHandler(),
|
||||||
|
WithFPS(1), // so renders right after the first ones are held back
|
||||||
|
)
|
||||||
|
p.renderer = rr
|
||||||
|
var atExec string
|
||||||
|
go func() {
|
||||||
|
for m.views.Load() < 2 {
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
for range 10 {
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
}
|
||||||
|
p.Send(execMsg{cmd: &testExecCommand{run: func() { atExec = rr.lastFlushed() }}})
|
||||||
|
p.Quit()
|
||||||
|
}()
|
||||||
|
if _, err := p.Run(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := "count: 10"; atExec != want {
|
||||||
|
t.Errorf("the frame drawn when the terminal was handed over was %q, want %q", atExec, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testExecCommand is an ExecCommand that calls run.
|
||||||
|
type testExecCommand struct{ run func() }
|
||||||
|
|
||||||
|
func (c *testExecCommand) Run() error { c.run(); return nil }
|
||||||
|
func (c *testExecCommand) SetStdin(io.Reader) {}
|
||||||
|
func (c *testExecCommand) SetStdout(io.Writer) {}
|
||||||
|
func (c *testExecCommand) SetStderr(io.Writer) {}
|
||||||
210
render_order_test.go
Normal file
210
render_order_test.go
Normal file
|
|
@ -0,0 +1,210 @@
|
||||||
|
package tea
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sizeModel shows the width it was last given.
|
||||||
|
type sizeModel struct {
|
||||||
|
width int
|
||||||
|
views atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *sizeModel) Init() Cmd { return nil }
|
||||||
|
|
||||||
|
func (m *sizeModel) Update(msg Msg) (Model, Cmd) {
|
||||||
|
if msg, ok := msg.(WindowSizeMsg); ok {
|
||||||
|
m.width = msg.Width
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *sizeModel) View() View {
|
||||||
|
m.views.Add(1)
|
||||||
|
return NewView(fmt.Sprint(m.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
// sizeRenderer notes the first frame it flushes after a resize.
|
||||||
|
type sizeRenderer struct {
|
||||||
|
nilRenderer
|
||||||
|
mu sync.Mutex
|
||||||
|
view View
|
||||||
|
resized bool
|
||||||
|
flushed chan string // the first frame after a resize
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *sizeRenderer) render(v View) {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.view = v
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *sizeRenderer) resize(int, int) {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.resized = true
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *sizeRenderer) flush(bool) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if r.resized {
|
||||||
|
r.resized = false
|
||||||
|
select {
|
||||||
|
case r.flushed <- r.view.Content:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRenderAfterResize checks that the frame drawn after a resize is the
|
||||||
|
// view for the new size, even when a view was rendered just before.
|
||||||
|
func TestRenderAfterResize(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const fps = 10
|
||||||
|
sr := &sizeRenderer{flushed: make(chan string, 1)}
|
||||||
|
m := &sizeModel{}
|
||||||
|
p := NewProgram(m,
|
||||||
|
WithInput(&bytes.Buffer{}),
|
||||||
|
WithOutput(io.Discard),
|
||||||
|
WithoutSignalHandler(),
|
||||||
|
WithWindowSize(80, 24),
|
||||||
|
WithFPS(fps),
|
||||||
|
)
|
||||||
|
p.renderer = sr
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := p.Run()
|
||||||
|
done <- err
|
||||||
|
}()
|
||||||
|
defer func() {
|
||||||
|
p.Quit()
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Let the startup messages be rendered and drawn.
|
||||||
|
time.Sleep(3 * time.Second / fps)
|
||||||
|
select {
|
||||||
|
case <-sr.flushed:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
// A view rendered right before the resize.
|
||||||
|
views := m.views.Load()
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
for m.views.Load() == views {
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
p.Send(WindowSizeMsg{Width: 120, Height: 24})
|
||||||
|
select {
|
||||||
|
case got := <-sr.flushed:
|
||||||
|
if got != "120" {
|
||||||
|
t.Errorf("the first frame drawn after resizing to 120 columns was the view for %s", got)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("no frame was drawn after the resize")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// printModel prints the count it reaches with each increment.
|
||||||
|
type printModel struct {
|
||||||
|
count int
|
||||||
|
views atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *printModel) Init() Cmd { return nil }
|
||||||
|
|
||||||
|
func (m *printModel) Update(msg Msg) (Model, Cmd) {
|
||||||
|
if _, ok := msg.(incrementMsg); ok {
|
||||||
|
m.count++
|
||||||
|
return m, Println(m.count)
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *printModel) View() View {
|
||||||
|
m.views.Add(1)
|
||||||
|
return NewView(fmt.Sprint(m.count))
|
||||||
|
}
|
||||||
|
|
||||||
|
// printRenderer notes the view it has when lines are printed above it.
|
||||||
|
type printRenderer struct {
|
||||||
|
nilRenderer
|
||||||
|
mu sync.Mutex
|
||||||
|
view View
|
||||||
|
printed []string // each line printed, with the view below it
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *printRenderer) render(v View) {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.view = v
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *printRenderer) insertAbove(s string) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.printed = append(r.printed, s+" "+r.view.Content)
|
||||||
|
r.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRenderBeforePrint checks that a line printed by an update is printed
|
||||||
|
// above the view of that update or a later one, never an older one, even
|
||||||
|
// when the view's render was held back.
|
||||||
|
func TestRenderBeforePrint(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
const n = 3
|
||||||
|
pr := &printRenderer{}
|
||||||
|
m := &printModel{}
|
||||||
|
p := NewProgram(m,
|
||||||
|
WithInput(&bytes.Buffer{}),
|
||||||
|
WithOutput(io.Discard),
|
||||||
|
WithoutSignalHandler(),
|
||||||
|
WithFPS(10),
|
||||||
|
)
|
||||||
|
p.renderer = pr
|
||||||
|
go func() {
|
||||||
|
for m.views.Load() < 2 {
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
for range n {
|
||||||
|
p.Send(incrementMsg{})
|
||||||
|
}
|
||||||
|
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); {
|
||||||
|
pr.mu.Lock()
|
||||||
|
printed := len(pr.printed)
|
||||||
|
pr.mu.Unlock()
|
||||||
|
if printed == n {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
p.Quit()
|
||||||
|
}()
|
||||||
|
if _, err := p.Run(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pr.mu.Lock()
|
||||||
|
defer pr.mu.Unlock()
|
||||||
|
if len(pr.printed) != n {
|
||||||
|
t.Fatalf("printed %q, want %d lines", pr.printed, n)
|
||||||
|
}
|
||||||
|
for _, s := range pr.printed {
|
||||||
|
var line, shown int
|
||||||
|
if _, err := fmt.Sscan(s, &line, &shown); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if shown < line {
|
||||||
|
t.Errorf("line %d was printed above the view of %d, from before the update that printed it", line, shown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
330
tea.go
330
tea.go
|
|
@ -60,7 +60,8 @@ type Model interface {
|
||||||
Update(Msg) (Model, Cmd)
|
Update(Msg) (Model, Cmd)
|
||||||
|
|
||||||
// View renders the program's UI, which can be a string or a [Layer]. The
|
// View renders the program's UI, which can be a string or a [Layer]. The
|
||||||
// view is rendered after every Update.
|
// view is rendered after Update, at most about once a frame: messages that
|
||||||
|
// arrive together are rendered together.
|
||||||
View() View
|
View() View
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -764,147 +765,216 @@ func (p *Program) handleCommands(cmds chan Cmd) chan struct{} {
|
||||||
|
|
||||||
// eventLoop is the central message loop. It receives and handles the default
|
// eventLoop is the central message loop. It receives and handles the default
|
||||||
// Bubble Tea messages, update the model and triggers redraws.
|
// Bubble Tea messages, update the model and triggers redraws.
|
||||||
|
//
|
||||||
|
// Redraws are coalesced: messages that are already waiting are handled before
|
||||||
|
// the view is rendered, and while messages keep coming the view is rendered
|
||||||
|
// about once a frame, as the renderer doesn't draw more often than that. The
|
||||||
|
// latest model is always rendered once they stop.
|
||||||
func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
|
func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
|
||||||
|
frame := time.Second / time.Duration(p.fps)
|
||||||
|
var (
|
||||||
|
dirty bool // the model changed since it was last rendered
|
||||||
|
deadline time.Time // when to render even if messages are waiting
|
||||||
|
lastRender time.Time // when the view was last rendered
|
||||||
|
renderAt <-chan time.Time // fires when a held back render is due
|
||||||
|
)
|
||||||
|
render := func() {
|
||||||
|
dirty, renderAt = false, nil
|
||||||
|
lastRender = time.Now()
|
||||||
|
p.render(model)
|
||||||
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
var msg Msg
|
||||||
case <-p.ctx.Done():
|
waiting := false
|
||||||
return model, nil
|
if dirty && time.Now().Before(deadline) {
|
||||||
|
// Handle a message that is already waiting first.
|
||||||
case err := <-p.errs:
|
select {
|
||||||
return model, err
|
case msg = <-p.msgs:
|
||||||
|
waiting = true
|
||||||
case msg := <-p.msgs:
|
default:
|
||||||
msg = p.translateInputEvent(msg)
|
|
||||||
|
|
||||||
// Filter messages.
|
|
||||||
if p.filter != nil {
|
|
||||||
msg = p.filter(model, msg)
|
|
||||||
}
|
}
|
||||||
if msg == nil {
|
}
|
||||||
|
if dirty && !waiting {
|
||||||
|
wait := frame - time.Since(lastRender)
|
||||||
|
if wait <= 0 {
|
||||||
|
render()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if renderAt == nil {
|
||||||
// Handle special internal messages.
|
renderAt = time.After(wait)
|
||||||
switch msg := msg.(type) {
|
|
||||||
case QuitMsg:
|
|
||||||
return model, nil
|
|
||||||
|
|
||||||
case InterruptMsg:
|
|
||||||
return model, ErrInterrupted
|
|
||||||
|
|
||||||
case SuspendMsg:
|
|
||||||
if suspendSupported {
|
|
||||||
p.suspend()
|
|
||||||
}
|
|
||||||
|
|
||||||
case CapabilityMsg:
|
|
||||||
switch msg.Content {
|
|
||||||
case "RGB", "Tc":
|
|
||||||
if *p.profile != colorprofile.TrueColor {
|
|
||||||
tc := colorprofile.TrueColor
|
|
||||||
p.profile = &tc
|
|
||||||
go p.Send(ColorProfileMsg{*p.profile})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case ModeReportMsg:
|
|
||||||
switch msg.Mode {
|
|
||||||
case ansi.ModeSynchronizedOutput:
|
|
||||||
if msg.Value == ansi.ModeReset {
|
|
||||||
// The terminal supports synchronized output and it's
|
|
||||||
// currently disabled, so we can enable it on the renderer.
|
|
||||||
p.renderer.setSyncdUpdates(true)
|
|
||||||
}
|
|
||||||
case ansi.ModeUnicodeCore:
|
|
||||||
if msg.Value == ansi.ModeReset || msg.Value == ansi.ModeSet || msg.Value == ansi.ModePermanentlySet {
|
|
||||||
p.renderer.setWidthMethod(ansi.GraphemeWidth)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case MouseMsg:
|
|
||||||
switch msg.(type) {
|
|
||||||
case MouseClickMsg, MouseReleaseMsg, MouseWheelMsg, MouseMotionMsg:
|
|
||||||
// Only send mouse messages to the renderer if they are an
|
|
||||||
// actual mouse event.
|
|
||||||
if cmd := p.renderer.onMouse(msg); cmd != nil {
|
|
||||||
go p.Send(cmd())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case readClipboardMsg:
|
|
||||||
p.executeQuery(ansi.RequestSystemClipboard)
|
|
||||||
|
|
||||||
case setClipboardMsg:
|
|
||||||
p.execute(ansi.SetSystemClipboard(string(msg)))
|
|
||||||
|
|
||||||
case readPrimaryClipboardMsg:
|
|
||||||
p.executeQuery(ansi.RequestPrimaryClipboard)
|
|
||||||
|
|
||||||
case setPrimaryClipboardMsg:
|
|
||||||
p.execute(ansi.SetPrimaryClipboard(string(msg)))
|
|
||||||
|
|
||||||
case backgroundColorMsg:
|
|
||||||
p.executeQuery(ansi.RequestBackgroundColor)
|
|
||||||
|
|
||||||
case foregroundColorMsg:
|
|
||||||
p.executeQuery(ansi.RequestForegroundColor)
|
|
||||||
|
|
||||||
case cursorColorMsg:
|
|
||||||
p.executeQuery(ansi.RequestCursorColor)
|
|
||||||
|
|
||||||
case programStatusSupportMsg:
|
|
||||||
p.executeQuery(ansi.RequestProgramStatusSupport)
|
|
||||||
|
|
||||||
case execMsg:
|
|
||||||
// NB: this blocks.
|
|
||||||
p.exec(msg.cmd, msg.fn)
|
|
||||||
|
|
||||||
case terminalVersion:
|
|
||||||
p.executeQuery(ansi.RequestNameVersion)
|
|
||||||
|
|
||||||
case requestCapabilityMsg:
|
|
||||||
p.executeQuery(ansi.RequestTermcap(string(msg)))
|
|
||||||
|
|
||||||
case BatchMsg:
|
|
||||||
go p.execBatchMsg(msg)
|
|
||||||
continue
|
|
||||||
|
|
||||||
case sequenceMsg:
|
|
||||||
go p.execSequenceMsg(msg)
|
|
||||||
continue
|
|
||||||
|
|
||||||
case WindowSizeMsg:
|
|
||||||
p.renderer.resize(msg.Width, msg.Height)
|
|
||||||
|
|
||||||
case windowSizeMsg:
|
|
||||||
go p.checkResize()
|
|
||||||
|
|
||||||
case requestCursorPosMsg:
|
|
||||||
p.executeQuery(ansi.RequestCursorPositionReport)
|
|
||||||
|
|
||||||
case RawMsg:
|
|
||||||
p.execute(fmt.Sprint(msg.Msg))
|
|
||||||
|
|
||||||
case printLineMessage:
|
|
||||||
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
|
|
||||||
|
|
||||||
case clearScreenMsg:
|
|
||||||
p.renderer.clearScreen()
|
|
||||||
|
|
||||||
case ColorProfileMsg:
|
|
||||||
p.renderer.setColorProfile(msg.Profile)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var cmd Cmd
|
if !waiting {
|
||||||
model, cmd = model.Update(msg) // run update
|
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-p.ctx.Done():
|
case <-p.ctx.Done():
|
||||||
return model, nil
|
return model, nil
|
||||||
case cmds <- cmd: // process command (if any)
|
|
||||||
|
case err := <-p.errs:
|
||||||
|
return model, err
|
||||||
|
|
||||||
|
case <-renderAt:
|
||||||
|
render()
|
||||||
|
continue
|
||||||
|
|
||||||
|
case msg = <-p.msgs:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
msg = p.translateInputEvent(msg)
|
||||||
|
|
||||||
|
// Filter messages.
|
||||||
|
if p.filter != nil {
|
||||||
|
msg = p.filter(model, msg)
|
||||||
|
}
|
||||||
|
if msg == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle special internal messages.
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case QuitMsg:
|
||||||
|
return model, nil
|
||||||
|
|
||||||
|
case InterruptMsg:
|
||||||
|
return model, ErrInterrupted
|
||||||
|
|
||||||
|
case SuspendMsg:
|
||||||
|
if suspendSupported {
|
||||||
|
if dirty {
|
||||||
|
render() // the terminal shows the latest view while suspended
|
||||||
|
}
|
||||||
|
p.suspend()
|
||||||
}
|
}
|
||||||
|
|
||||||
p.render(model) // render view
|
case CapabilityMsg:
|
||||||
|
switch msg.Content {
|
||||||
|
case "RGB", "Tc":
|
||||||
|
if *p.profile != colorprofile.TrueColor {
|
||||||
|
tc := colorprofile.TrueColor
|
||||||
|
p.profile = &tc
|
||||||
|
go p.Send(ColorProfileMsg{*p.profile})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case ModeReportMsg:
|
||||||
|
switch msg.Mode {
|
||||||
|
case ansi.ModeSynchronizedOutput:
|
||||||
|
if msg.Value == ansi.ModeReset {
|
||||||
|
// The terminal supports synchronized output and it's
|
||||||
|
// currently disabled, so we can enable it on the renderer.
|
||||||
|
p.renderer.setSyncdUpdates(true)
|
||||||
|
}
|
||||||
|
case ansi.ModeUnicodeCore:
|
||||||
|
if msg.Value == ansi.ModeReset || msg.Value == ansi.ModeSet || msg.Value == ansi.ModePermanentlySet {
|
||||||
|
p.renderer.setWidthMethod(ansi.GraphemeWidth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case MouseMsg:
|
||||||
|
switch msg.(type) {
|
||||||
|
case MouseClickMsg, MouseReleaseMsg, MouseWheelMsg, MouseMotionMsg:
|
||||||
|
// Only send mouse messages to the renderer if they are an
|
||||||
|
// actual mouse event.
|
||||||
|
if cmd := p.renderer.onMouse(msg); cmd != nil {
|
||||||
|
go p.Send(cmd())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case readClipboardMsg:
|
||||||
|
p.executeQuery(ansi.RequestSystemClipboard)
|
||||||
|
|
||||||
|
case setClipboardMsg:
|
||||||
|
p.execute(ansi.SetSystemClipboard(string(msg)))
|
||||||
|
|
||||||
|
case readPrimaryClipboardMsg:
|
||||||
|
p.executeQuery(ansi.RequestPrimaryClipboard)
|
||||||
|
|
||||||
|
case setPrimaryClipboardMsg:
|
||||||
|
p.execute(ansi.SetPrimaryClipboard(string(msg)))
|
||||||
|
|
||||||
|
case backgroundColorMsg:
|
||||||
|
p.executeQuery(ansi.RequestBackgroundColor)
|
||||||
|
|
||||||
|
case foregroundColorMsg:
|
||||||
|
p.executeQuery(ansi.RequestForegroundColor)
|
||||||
|
|
||||||
|
case cursorColorMsg:
|
||||||
|
p.executeQuery(ansi.RequestCursorColor)
|
||||||
|
|
||||||
|
case programStatusSupportMsg:
|
||||||
|
p.executeQuery(ansi.RequestProgramStatusSupport)
|
||||||
|
|
||||||
|
case execMsg:
|
||||||
|
if dirty {
|
||||||
|
render() // the terminal shows the latest view while it's handed over
|
||||||
|
}
|
||||||
|
// NB: this blocks.
|
||||||
|
p.exec(msg.cmd, msg.fn)
|
||||||
|
|
||||||
|
case terminalVersion:
|
||||||
|
p.executeQuery(ansi.RequestNameVersion)
|
||||||
|
|
||||||
|
case requestCapabilityMsg:
|
||||||
|
p.executeQuery(ansi.RequestTermcap(string(msg)))
|
||||||
|
|
||||||
|
case BatchMsg:
|
||||||
|
go p.execBatchMsg(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
case sequenceMsg:
|
||||||
|
go p.execSequenceMsg(msg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
case WindowSizeMsg:
|
||||||
|
p.renderer.resize(msg.Width, msg.Height)
|
||||||
|
|
||||||
|
case windowSizeMsg:
|
||||||
|
go p.checkResize()
|
||||||
|
|
||||||
|
case requestCursorPosMsg:
|
||||||
|
p.executeQuery(ansi.RequestCursorPositionReport)
|
||||||
|
|
||||||
|
case RawMsg:
|
||||||
|
p.execute(fmt.Sprint(msg.Msg))
|
||||||
|
|
||||||
|
case printLineMessage:
|
||||||
|
if dirty {
|
||||||
|
render() // print above the view of the update that printed
|
||||||
|
}
|
||||||
|
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
|
||||||
|
|
||||||
|
case clearScreenMsg:
|
||||||
|
p.renderer.clearScreen()
|
||||||
|
|
||||||
|
case ColorProfileMsg:
|
||||||
|
p.renderer.setColorProfile(msg.Profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
var cmd Cmd
|
||||||
|
model, cmd = model.Update(msg) // run update
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-p.ctx.Done():
|
||||||
|
return model, nil
|
||||||
|
case cmds <- cmd: // process command (if any)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := msg.(WindowSizeMsg); ok {
|
||||||
|
// The renderer is at the new size already, so render the view
|
||||||
|
// for it now rather than have the old one drawn at it.
|
||||||
|
render()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !dirty {
|
||||||
|
// Render within a frame of the last render, or of now after a
|
||||||
|
// pause, even if messages keep coming.
|
||||||
|
dirty = true
|
||||||
|
deadline = lastRender.Add(frame)
|
||||||
|
if now := time.Now(); deadline.Before(now) {
|
||||||
|
deadline = now.Add(frame)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue