diff --git a/internal/rexsession/session.go b/internal/rexsession/session.go index b167eb1..187e991 100644 --- a/internal/rexsession/session.go +++ b/internal/rexsession/session.go @@ -39,9 +39,10 @@ type Session struct { seen uint64 // the highest revision an event has announced fetching bool destroyed bool - panes map[string]*rexterm.Pane // changed only by Sync - held []*rexterm.Pane // panes Sync holds, until Release - sizes map[string][4]int // cols, rows, cell width and height last asked for, by block + panes map[string]*rexterm.Pane // changed only by Sync + held []*rexterm.Pane // panes Sync holds, until Release + terms map[string]*libghostty.Terminal // their terminals, by block, until Release + sizes map[string][4]int // cols, rows, cell width and height last asked for, by block titles map[string]string // each block's terminal title, from the server titled map[string]bool // blocks whose title has been asked for @@ -52,7 +53,9 @@ type Session struct { pendingSince time.Time // when the switch to pending was seen } -// Frame is what Sync returns: the view to draw and each block's terminal. +// Frame is what Sync returns: the view to draw and each pane's state. It +// holds no terminal, so it may be kept and drawn from after Release; a +// terminal is had from [Session.Terminal], between Sync and Release. type Frame struct { View rex.View // Window is the window to draw, or nil if the session has none. It's @@ -71,9 +74,13 @@ type Frame struct { Destroyed bool } -// PaneFrame is one block's terminal, nil until it is restored, and state. +// PaneFrame is one open pane, as Sync found it. type PaneFrame struct { - Term *libghostty.Terminal + // Restored is true once the pane's terminal has arrived: until then, + // it has nothing to show. + Restored bool + // Title is the title the program set, from its terminal. + Title string State rexterm.State } @@ -96,6 +103,7 @@ func New(conn *rex.Conn, ep rex.Endpoint, view rex.View, notify func()) *Session sizes: make(map[string][4]int), titles: make(map[string]string), titled: make(map[string]bool), + terms: make(map[string]*libghostty.Terminal), } s.wg.Add(1) go s.runJobs() @@ -230,7 +238,7 @@ func visible(w *rex.Window) []string { // it can be drawn without empty panes. func (f Frame) Ready() bool { for _, id := range f.Visible { - if f.Panes[id].Term == nil { + if !f.Panes[id].Restored { return false } } @@ -339,7 +347,14 @@ func (s *Session) Sync() (Frame, error) { if err != nil { return f, err } - f.Panes[id] = PaneFrame{Term: term, State: st} + pf := PaneFrame{Restored: term != nil, State: st} + if term != nil { + s.terms[id] = term + if t, err := term.Title(); err == nil { + pf.Title = t + } + } + f.Panes[id] = pf } // Show the active window, unless a switch to it is still waiting for @@ -508,13 +523,22 @@ func cloneView(v rex.View) rex.View { return v } +// Terminal returns a block's terminal while the frame holds it, from Sync +// to Release: nil before its pane is restored, and after Release, when its +// output is being applied to it again. Only the goroutine that draws may +// call it, and use what it returns, until Release. +func (s *Session) Terminal(blockID string) *libghostty.Terminal { + return s.terms[blockID] +} + // Release lets output be applied to the terminals of the last Sync again. -// The frame mustn't use them after it. +// The frame mustn't use them after it: Terminal returns nil from then. func (s *Session) Release() { for _, p := range s.held { p.Release() } s.held = s.held[:0] + clear(s.terms) } // Close closes every pane, ending their streams. It doesn't close the diff --git a/internal/rexsession/session_test.go b/internal/rexsession/session_test.go index 4aafd31..d620284 100644 --- a/internal/rexsession/session_test.go +++ b/internal/rexsession/session_test.go @@ -73,7 +73,7 @@ func (h *harness) until(what string, cond func(rexsession.Frame) bool) rexsessio // shows reports whether f shows each block, and no others, and each has a // restored terminal whose screen contains text. -func shows(f rexsession.Frame, text string, blocks ...string) bool { +func shows(s *rexsession.Session, f rexsession.Frame, text string, blocks ...string) bool { if len(f.Visible) != len(blocks) { return false } @@ -84,7 +84,7 @@ func shows(f rexsession.Frame, text string, blocks ...string) bool { } for _, id := range blocks { p, ok := f.Panes[id] - if !ok || p.Term == nil || !strings.Contains(screen(p.Term), text) { + if !ok || !p.Restored || !strings.Contains(screen(s.Terminal(id)), text) { return false } } @@ -92,6 +92,9 @@ func shows(f rexsession.Frame, text string, blocks ...string) bool { } func screen(term *libghostty.Terminal) string { + if term == nil { + return "" + } f, err := libghostty.NewFormatter(term) if err != nil { return "" @@ -120,6 +123,27 @@ func eventually(t *testing.T, what string, cond func() bool) { } } +// TestFrameHoldsNoTerminal gives a frame its terminals from Sync to +// Release, and not after: what it draws comes with the frame. +func TestFrameHoldsNoTerminal(t *testing.T) { + srv := rextest.Start(t) + c := srv.Dial(t, "100gex-test") + sid, b := rextest.NewSession(t, c, "/bin/sh", "-c", `printf '\033]2;the title\007ready\r\n'; exec cat >/dev/null`) + h := follow(t, srv, c, sid) + f := h.until("the title", func(f rexsession.Frame) bool { + if h.s.Terminal(b) == nil && f.Panes[b].Restored { + t.Fatal("a restored pane's terminal isn't had while held") + } + return f.Panes[b].Title == "the title" + }) + if h.s.Terminal(b) != nil { + t.Error("a terminal is still had after Release") + } + if !f.Panes[b].Restored { + t.Error("the frame lost that its pane is restored") + } +} + func TestSession(t *testing.T) { srv := rextest.Start(t) // Another device changes the layout; this client follows. @@ -127,7 +151,7 @@ func TestSession(t *testing.T) { sid, b1 := rextest.NewSession(t, other, rextest.RawCat...) c := srv.Dial(t, "100gex-test") h := follow(t, srv, c, sid) - h.until("the first block", func(f rexsession.Frame) bool { return shows(f, "ready", b1) }) + h.until("the first block", func(f rexsession.Frame) bool { return shows(h.s, f, "ready", b1) }) // A split appears, with focus. var split struct { @@ -139,12 +163,12 @@ func TestSession(t *testing.T) { }, &split) b2 := split.BlockIDs[0] h.until("the split", func(f rexsession.Frame) bool { - return shows(f, "ready", b1, b2) && f.Window.FocusedBlockID == b2 + return shows(h.s, f, "ready", b1, b2) && f.Window.FocusedBlockID == b2 }) // Typing goes to the focused block. h.s.Key(rex.KeyEvent{Action: "press", Key: "key_x", Text: "x"}) - h.until("x in the split", func(f rexsession.Frame) bool { return strings.Contains(screen(f.Panes[b2].Term), "ready\nx") }) + h.until("x in the split", func(f rexsession.Frame) bool { return strings.Contains(screen(h.s.Terminal(b2)), "ready\nx") }) // Focusing a block takes effect here at once, and reaches the server. h.s.FocusBlock(b1) @@ -152,7 +176,7 @@ func TestSession(t *testing.T) { t.Fatalf("focused block after FocusBlock = %s, want %s", got, b1) } h.s.Key(rex.KeyEvent{Action: "press", Key: "key_y", Text: "y"}) - h.until("y in the first block", func(f rexsession.Frame) bool { return strings.Contains(screen(f.Panes[b1].Term), "ready\ny") }) + h.until("y in the first block", func(f rexsession.Frame) bool { return strings.Contains(screen(h.s.Terminal(b1)), "ready\ny") }) eventually(t, "the server to focus the first block", func() bool { v := serverView(t, other, sid) return v.ActiveWindow().FocusedBlockID == b1 @@ -168,7 +192,7 @@ func TestSession(t *testing.T) { }, &win) b3 := win.BlockIDs[0] f := h.until("the new window", func(f rexsession.Frame) bool { - return f.View.ActiveWindowID == win.WindowID && shows(f, "ready", b3) + return f.View.ActiveWindowID == win.WindowID && shows(h.s, f, "ready", b3) }) if len(f.View.Windows) != 2 || f.View.Windows[1].Label != "logs" { t.Errorf("windows = %+v", f.View.Windows) @@ -176,21 +200,21 @@ func TestSession(t *testing.T) { // The first window's blocks keep their terminals while hidden, so // switching back has nothing to wait for. - if p := f.Panes[b1]; p.Term == nil { + if p := f.Panes[b1]; !p.Restored { t.Error("a hidden window's block lost its terminal") } // Switching back shows the first window's blocks again. first := f.View.Windows[0].WindowID h.s.FocusWindow(first) - h.until("the first window", func(f rexsession.Frame) bool { return shows(f, "ready", b1, b2) }) + h.until("the first window", func(f rexsession.Frame) bool { return shows(h.s, f, "ready", b1, b2) }) eventually(t, "the server to switch windows", func() bool { return serverView(t, other, sid).ActiveWindowID == first }) // Zooming shows the zoomed block alone. rextest.Call(t, other, "session.zoom_block", map[string]any{"session_id": sid, "block_id": b2, "zoom": true}, nil) - h.until("the zoom", func(f rexsession.Frame) bool { return shows(f, "ready", b2) }) + h.until("the zoom", func(f rexsession.Frame) bool { return shows(h.s, f, "ready", b2) }) if got := h.s.FocusedBlock(); got != b2 { t.Errorf("focused block while zoomed = %s, want %s", got, b2) } @@ -198,7 +222,7 @@ func TestSession(t *testing.T) { // A closed block leaves the layout. rextest.Call(t, other, "block.close", map[string]any{"session_id": sid, "block_id": b2}, nil) - f = h.until("the close", func(f rexsession.Frame) bool { return shows(f, "", b1) }) + f = h.until("the close", func(f rexsession.Frame) bool { return shows(h.s, f, "", b1) }) if ids := f.Window.Layers[0].Blocks; !slices.ContainsFunc(ids, func(b rex.BlockInfo) bool { return b.BlockID == b1 }) || len(ids) != 1 { t.Errorf("blocks after close = %+v", ids) } diff --git a/internal/rexterm/output_test.go b/internal/rexterm/output_test.go index f3169c3..22351d8 100644 --- a/internal/rexterm/output_test.go +++ b/internal/rexterm/output_test.go @@ -17,7 +17,7 @@ import ( const maxSyncWait = time.Millisecond // TestSyncUnderOutput has a block print 8 MiB of random bytes, as -// cat /dev/urandom does, while frames hold the terminal to draw it. The +// cat /dev/urandom does, while frames take the terminal to draw it. The // stream parses the output, so a frame only waits for it to finish the // slice it is parsing, never for everything that arrived since the last // frame. @@ -49,11 +49,11 @@ func TestSyncUnderOutput(t *testing.T) { if err != nil { t.Fatal(err) } - // A frame drawing for 3ms, then 1ms before the next: 240 fps. + // A frame holds the terminal while it takes what it draws, then + // draws for 3ms without it, then waits 1ms for the next: 240 fps. done = strings.Contains(screen(t, term), "done-marker") - time.Sleep(3 * time.Millisecond) h.pane.Release() - time.Sleep(time.Millisecond) + time.Sleep(4 * time.Millisecond) } took := time.Since(start) slices.Sort(waits) diff --git a/internal/termview/bench_test.go b/internal/termview/bench_test.go index be0c05a..a2cd1e3 100644 --- a/internal/termview/bench_test.go +++ b/internal/termview/bench_test.go @@ -82,7 +82,10 @@ func newBenchPane(tb testing.TB, size image.Point, fill func(cols, rows int) []b func (p *benchPane) layout(tb testing.TB) { p.ops.Reset() - if _, err := p.view.Layout(p.gtx, p.term); err != nil { + if err := p.view.Update(p.gtx, p.term); err != nil { + tb.Fatal(err) + } + if _, err := p.view.Layout(p.gtx); err != nil { tb.Fatal(err) } } diff --git a/internal/termview/cursor_test.go b/internal/termview/cursor_test.go index da4e77f..fcd3e8b 100644 --- a/internal/termview/cursor_test.go +++ b/internal/termview/cursor_test.go @@ -47,7 +47,10 @@ func TestCursorShapes(t *testing.T) { v.Focused = focused ops.Reset() gtx := layout.Context{Ops: &ops, Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(image.Pt(w, h)), Now: now} - if _, err := v.Layout(gtx, term); err != nil { + if err := v.Update(gtx, term); err != nil { + t.Fatal(err) + } + if _, err := v.Layout(gtx); err != nil { t.Fatal(err) } if err := win.Frame(&ops); err != nil { @@ -134,7 +137,10 @@ func TestCursorBlinks(t *testing.T) { v.Focused = focused ops.Reset() gtx := layout.Context{Ops: &ops, Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(image.Pt(w, h)), Now: start.Add(at)} - if _, err := v.Layout(gtx, term); err != nil { + if err := v.Update(gtx, term); err != nil { + t.Fatal(err) + } + if _, err := v.Layout(gtx); err != nil { t.Fatal(err) } if err := win.Frame(&ops); err != nil { diff --git a/internal/termview/rows_test.go b/internal/termview/rows_test.go index 3e33db7..b6d9d9f 100644 --- a/internal/termview/rows_test.go +++ b/internal/termview/rows_test.go @@ -50,7 +50,10 @@ func TestRowsRedrawn(t *testing.T) { v.Focused = focused ops.Reset() gtx := layout.Context{Ops: &ops, Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(image.Pt(w, h)), Now: time.Now()} - if _, err := v.Layout(gtx, term); err != nil { + if err := v.Update(gtx, term); err != nil { + t.Fatal(err) + } + if _, err := v.Layout(gtx); err != nil { t.Fatal(err) } if err := win.Frame(&ops); err != nil { diff --git a/internal/termview/selection.go b/internal/termview/selection.go index ee6b535..e57dc69 100644 --- a/internal/termview/selection.go +++ b/internal/termview/selection.go @@ -106,8 +106,8 @@ func (s *selector) ready(term *libghostty.Terminal) error { // handlePointer applies the mouse events since the last frame: reports to // a program that reads the mouse, selection with the primary button, a -// middle click, and the wheel. It runs before -// drawing, so the frame shows the result. +// middle click, and the wheel. It runs in Update, before the terminal is +// read, so the frame shows the result. func (v *View) handlePointer(gtx layout.Context, term *libghostty.Terminal, m metrics, pad int) error { tracking, motion, err := mouseTracking(term) if err != nil { @@ -333,9 +333,14 @@ func (v *View) selectEvent(term *libghostty.Terminal, e pointer.Event, m metrics } case s.release: // A finished selection: a drag, or a double or triple click. + // Its text is read now, while the terminal is held. if v.OnSelected != nil { - if active, err := term.Selection(); err == nil && active != nil { - v.OnSelected() + text, err := SelectionText(term) + if err != nil { + return fmt.Errorf("selection text: %w", err) + } + if text != "" { + v.OnSelected(text) } } } diff --git a/internal/termview/selection_test.go b/internal/termview/selection_test.go index aa737e8..16d23e7 100644 --- a/internal/termview/selection_test.go +++ b/internal/termview/selection_test.go @@ -63,7 +63,10 @@ func (h *selectHarness) frame() { Source: h.router.Source(), Now: h.clock, } - if _, err := h.v.Layout(gtx, h.term); err != nil { + if err := h.v.Update(gtx, h.term); err != nil { + h.t.Fatal(err) + } + if _, err := h.v.Layout(gtx); err != nil { h.t.Fatal(err) } h.router.Frame(&h.ops) @@ -250,7 +253,7 @@ func TestAutoscroll(t *testing.T) { history(h, 50) bottom := h.offset() selected := 0 - h.v.OnSelected = func() { selected++ } + h.v.OnSelected = func(string) { selected++ } // Drag from the second row to above the top, and hold it there. h.mouse(pointer.Press, h.past(2, 1)) diff --git a/internal/termview/view.go b/internal/termview/view.go index c07963d..32db7f5 100644 --- a/internal/termview/view.go +++ b/internal/termview/view.go @@ -51,8 +51,13 @@ func NewGlyphs(faces []font.FontFace) *glyph.Rasterizer { } // View paints a terminal and reports the size that would fill it. It never -// changes the terminal: the terminal belongs to a Rex server, which decides +// resizes the terminal: the terminal belongs to a Rex server, which decides // its size. Keyboard input is handled separately, by [Keys]. +// +// A frame calls Update, while it holds the terminal, then Layout, once it +// has let the terminal go: Update applies the mouse to the terminal and +// takes what Layout draws, which is quick, so the terminal's output is +// parsed meanwhile, as Ghostty's renderer lets it be. type View struct { // FontSize is the size cells are drawn at. FontSize unit.Sp @@ -69,24 +74,24 @@ type View struct { // view changes, and on the first Layout. OnResize func(cols, rows uint16, cellWidth, cellHeight int) - // OnPress, if set, is called from Layout when a mouse button is pressed + // OnPress, if set, is called from Update when a mouse button is pressed // over the view. OnPress func() - // OnSelected, if set, is called from Layout when a selection is made: - // a drag ends, or a double or triple click. - OnSelected func() + // OnSelected, if set, is called from Update with the selected text + // when a selection is made: a drag ends, or a double or triple click. + OnSelected func(text string) - // OnMiddleClick, if set, is called from Layout on a middle click. + // OnMiddleClick, if set, is called from Update on a middle click. OnMiddleClick func() - // OnWheel, if set, is called from Layout with wheel turns for the + // OnWheel, if set, is called from Update with wheel turns for the // program: those over a program that reads the mouse, or on the // alternate screen. lines is negative for up. Other turns scroll the // scrollback. OnWheel func(col, row uint16, lines int) - // OnMouse, if set, is called from Layout with presses, releases and + // OnMouse, if set, is called from Update with presses, releases and // motion for a program that reads the mouse. Gestures that start with // Shift held select instead. OnMouse func(rex.MouseEvent) @@ -100,6 +105,12 @@ type View struct { rows *libghostty.RenderStateRowIterator cells *libghostty.RenderStateRowCells + // What Update took for Layout. term is the terminal rs was last + // updated from, or nil: only its identity is used after Update, to + // draw every row again when it is another. + term *libghostty.Terminal + scrollbar libghostty.Scrollbar + metrics metrics metricsPx int cols, lines uint16 @@ -227,11 +238,40 @@ func (v *View) CellSize() image.Point { return image.Pt(v.metrics.width, v.metri // Layout. func (v *View) Size() (cols, rows uint16) { return v.cols, v.lines } -// Layout paints term, which may be nil before it exists, filling +// Update applies the mouse events since the last frame to term, then takes +// from it what Layout draws. term may be nil before it exists. The caller +// must hold term, as a frame does, for the call, and not after: the view +// keeps no use of it beyond Update, so it can be parsed into while the +// frame draws. +// +// Updating again before Layout loses nothing: what changed in between is +// drawn too. +func (v *View) Update(gtx layout.Context, term *libghostty.Terminal) error { + // Mouse events act before the terminal is read, so this frame shows + // their result. + if err := v.handlePointer(gtx, term, v.measure(gtx), gtx.Dp(v.Padding)); err != nil { + return err + } + v.term = term + if term == nil { + return nil + } + if err := v.rs.Update(term); err != nil { + return fmt.Errorf("update render state: %w", err) + } + sb, err := term.Scrollbar() + if err != nil { + return fmt.Errorf("scrollbar: %w", err) + } + v.scrollbar = sb + return nil +} + +// Layout paints the terminal, as the last Update took it, filling // gtx.Constraints.Max. The terminal is drawn from the top left at its own // size; a terminal smaller than the view leaves a margin, and a larger one is -// cut off. -func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dimensions, error) { +// cut off. It reads no terminal: only what Update took. +func (v *View) Layout(gtx layout.Context) (layout.Dimensions, error) { full := gtx.Constraints.Max pad := gtx.Dp(v.Padding) size := image.Pt(max(full.X-2*pad, 1), max(full.Y-2*pad, 1)) @@ -239,18 +279,12 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim v.fit(size, m) defer clip.Rect{Max: full}.Push(gtx.Ops).Pop() - // Mouse events act before drawing, so this frame shows their result. - if err := v.handlePointer(gtx, term, m, pad); err != nil { - return layout.Dimensions{Size: full}, err - } v.registerPointer(gtx, full) + term := v.term if term == nil { return layout.Dimensions{Size: full}, nil // nothing to draw yet } - if err := v.rs.Update(term); err != nil { - return layout.Dimensions{Size: size}, fmt.Errorf("update render state: %w", err) - } colors, err := v.rs.Colors() if err != nil { return layout.Dimensions{Size: size}, fmt.Errorf("read colours: %w", err) @@ -370,9 +404,7 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim return layout.Dimensions{Size: size}, fmt.Errorf("clean render state: %w", err) } - if err := v.paintScrollbar(gtx, term, size, pad, defaultFg); err != nil { - return layout.Dimensions{Size: full}, err - } + v.paintScrollbar(gtx, size, pad, defaultFg) return layout.Dimensions{Size: full}, nil } @@ -570,13 +602,10 @@ func (v *View) forgetRows() { // paintScrollbar draws where the viewport is in the scrollback, along the // right edge, while it's scrolled back from the bottom. At the bottom, as a // terminal usually is, nothing is drawn. -func (v *View) paintScrollbar(gtx layout.Context, term *libghostty.Terminal, size image.Point, pad int, c color.NRGBA) error { - sb, err := term.Scrollbar() - if err != nil { - return fmt.Errorf("scrollbar: %w", err) - } +func (v *View) paintScrollbar(gtx layout.Context, size image.Point, pad int, c color.NRGBA) { + sb := v.scrollbar if sb.Total <= sb.Len || sb.Offset+sb.Len >= sb.Total { - return nil + return } height := float64(size.Y + pad) top := int(height * float64(sb.Offset) / float64(sb.Total)) @@ -585,7 +614,6 @@ func (v *View) paintScrollbar(gtx layout.Context, term *libghostty.Terminal, siz wide := gtx.Dp(4) right := size.X + pad - 1 // the cells' area is offset by pad; reach into the padding fillRect(gtx, c, image.Rect(right-wide, top-pad/2, right, bottom-pad/2)) - return nil } // measure returns the cell metrics for the current font size, measuring diff --git a/internal/termview/view_test.go b/internal/termview/view_test.go index c572fa8..2b5bfc7 100644 --- a/internal/termview/view_test.go +++ b/internal/termview/view_test.go @@ -56,8 +56,16 @@ func TestRenderSample(t *testing.T) { Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(image.Pt(width, height)), } - if _, err := view.Layout(gtx, term); err != nil { - t.Fatal(err) + // The first frame sizes the terminal; the second draws it at that + // size, as a frame after the server resizes it does. + for range 2 { + ops.Reset() + if err := view.Update(gtx, term); err != nil { + t.Fatal(err) + } + if _, err := view.Layout(gtx); err != nil { + t.Fatal(err) + } } if err := win.Frame(&ops); err != nil { t.Fatal(err) diff --git a/internal/ui/bench_test.go b/internal/ui/bench_test.go index d628087..6967055 100644 --- a/internal/ui/bench_test.go +++ b/internal/ui/bench_test.go @@ -74,12 +74,12 @@ func fourPanes(tb testing.TB, size image.Point, fill func(cols, rows int) []byte } for _, b := range blocks { p, pv := f.Panes[b], h.u.panes[b] - if pv == nil || !p.State.Owned || !strings.Contains(screenText(p.Term), "ready") { + if pv == nil || !p.State.Owned || !strings.Contains(screenText(h.term(b)), "ready") { return false } cols, rows := pv.view.Size() - tc, _ := p.Term.Cols() - tr, _ := p.Term.Rows() + tc, _ := h.term(b).Cols() + tr, _ := h.term(b).Rows() if cols == 0 || tc != cols || tr != rows { return false } @@ -102,7 +102,7 @@ func fourPanes(tb testing.TB, size image.Point, fill func(cols, rows int) []byte } h.until("four full panes", func(f rexsession.Frame) bool { for _, b := range blocks { - text := screenText(f.Panes[b].Term) + text := screenText(h.term(b)) cols, rows := h.u.panes[b].view.Size() if strings.Contains(text, "ready") || len(strings.Join(strings.Fields(text), "")) < int(cols)*int(rows)/2 { return false diff --git a/internal/ui/keys_test.go b/internal/ui/keys_test.go index 85fff53..349c29c 100644 --- a/internal/ui/keys_test.go +++ b/internal/ui/keys_test.go @@ -90,8 +90,8 @@ func (h *uiHarness) frame() rexsession.Frame { } // held calls fn with the session's terminals held, as a frame holds them -// while it draws. A frame lets them go once it's drawn, so the terminals -// of the frame it returns mustn't be read. +// while it takes what it draws. A frame lets them go before it draws, so +// they are only had, by term, within fn. func (h *uiHarness) held(fn func(rexsession.Frame)) { h.t.Helper() s := h.u.session @@ -104,11 +104,17 @@ func (h *uiHarness) held(fn func(rexsession.Frame)) { if err != nil { h.t.Fatal(err) } - h.u.frame = f // for focusedTerm, as during a frame - defer func() { h.u.frame = rexsession.Frame{} }() fn(f) } +// term returns a block's terminal, while held: see held. +func (h *uiHarness) term(blockID string) *libghostty.Terminal { + if h.u.session == nil { + return nil + } + return h.u.session.Terminal(blockID) +} + // selection returns the text selected in the focused pane. func (h *uiHarness) selection() (text string, err error) { h.held(func(rexsession.Frame) { @@ -190,12 +196,12 @@ func TestKeyBindings(t *testing.T) { h.until("the keymap and the block", func(f rexsession.Frame) bool { _, ok := h.u.serverActions["shout"] - return ok && strings.Contains(screenText(f.Panes[b1].Term), "ready") + return ok && strings.Contains(screenText(h.term(b1)), "ready") }) shows := func(what, text string) { t.Helper() h.until(what, func(f rexsession.Frame) bool { - return strings.Contains(screenText(f.Panes[b1].Term), text) + return strings.Contains(screenText(h.term(b1)), text) }) } @@ -291,7 +297,7 @@ func TestCopy(t *testing.T) { c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the pane", func(f rexsession.Frame) bool { - return strings.Contains(screenText(f.Panes[b1].Term), "alpha bravo") + return strings.Contains(screenText(h.term(b1)), "alpha bravo") }) // "bravo" is columns 6 to 10 of the first row. Find where the pane's @@ -369,7 +375,7 @@ func TestPrimarySelection(t *testing.T) { sel := &fakePrimary{} h.u.Primary = sel h.until("the pane", func(f rexsession.Frame) bool { - return strings.Contains(screenText(f.Panes[b1].Term), "alpha bravo") + return strings.Contains(screenText(h.term(b1)), "alpha bravo") }) origin, cell := paneOrigin(h, b1) at := func(col, row int) f32.Point { @@ -389,7 +395,7 @@ func TestPrimarySelection(t *testing.T) { mouse(pointer.Press, at(3, 3), pointer.ButtonTertiary) mouse(pointer.Release, at(3, 3), pointer.ButtonTertiary) h.until("the paste", func(f rexsession.Frame) bool { - return strings.Contains(screenText(f.Panes[b1].Term), "\ncharlie") + return strings.Contains(screenText(h.term(b1)), "\ncharlie") }) } @@ -407,7 +413,7 @@ func TestWheelToProgram(t *testing.T) { h := startUI(t, srv, c, sid) h.until("the pane, owned elsewhere", func(f rexsession.Frame) bool { p := f.Panes[b1] - return strings.Contains(screenText(p.Term), "ready") && p.State.Owner != "" && !p.State.Owned + return strings.Contains(screenText(h.term(b1)), "ready") && p.State.Owner != "" && !p.State.Owned }) origin, cell := paneOrigin(h, b1) h.router.Queue(pointer.Event{ @@ -418,7 +424,7 @@ func TestWheelToProgram(t *testing.T) { h.frame() // Two lines down at column 5, row 3 (1-based): SGR wheel-down is 65. h.until("two wheel reports, and the block", func(f rexsession.Frame) bool { - return strings.Count(screenText(f.Panes[b1].Term), "^[[<65;5;3M") == 2 && f.Panes[b1].State.Owned + return strings.Count(screenText(h.term(b1)), "^[[<65;5;3M") == 2 && f.Panes[b1].State.Owned }) } @@ -436,7 +442,7 @@ func TestClickToProgram(t *testing.T) { h := startUI(t, srv, c, sid) h.until("the pane, owned elsewhere", func(f rexsession.Frame) bool { p := f.Panes[b1] - return strings.Contains(screenText(p.Term), "ready") && p.State.Owner != "" && !p.State.Owned + return strings.Contains(screenText(h.term(b1)), "ready") && p.State.Owner != "" && !p.State.Owned }) origin, cell := paneOrigin(h, b1) at := func(col, row int) f32.Point { @@ -455,7 +461,7 @@ func TestClickToProgram(t *testing.T) { // release (lower-case m); then the right button (2). want := "^[[<0;5;3M^[[<32;7;3M^[[<0;7;3m^[[<2;2;5M^[[<2;2;5m" h.until("the mouse reports, and the block", func(f rexsession.Frame) bool { - return strings.Contains(screenText(f.Panes[b1].Term), want) && f.Panes[b1].State.Owned + return strings.Contains(screenText(h.term(b1)), want) && f.Panes[b1].State.Owned }) if s, _ := h.selection(); s != "" { t.Errorf("clicking the program selected %q", s) @@ -475,10 +481,10 @@ func TestScrollbackDoesntClaim(t *testing.T) { h := startUI(t, srv, c, sid) h.until("the history", func(f rexsession.Frame) bool { p := f.Panes[b1] - return strings.Contains(screenText(p.Term), "line 99") && p.State.Owner != "" + return strings.Contains(screenText(h.term(b1)), "line 99") && p.State.Owner != "" }) scrollbar := func() (s libghostty.Scrollbar) { - h.held(func(f rexsession.Frame) { s, _ = f.Panes[b1].Term.Scrollbar() }) + h.held(func(f rexsession.Frame) { s, _ = h.term(b1).Scrollbar() }) return s } before := scrollbar() diff --git a/internal/ui/output_test.go b/internal/ui/output_test.go new file mode 100644 index 0000000..cc1cb6d --- /dev/null +++ b/internal/ui/output_test.go @@ -0,0 +1,56 @@ +package ui + +import ( + "fmt" + "image" + "strings" + "testing" + "time" + + "100gex/internal/rex/rextest" + "100gex/internal/rexsession" +) + +// TestOutputWhileDrawing keeps drawing from slowing a pane's output: a +// frame holds the terminals only while it takes what it draws, and draws +// while their output is parsed, as Ghostty's renderer does. Holding them +// for the whole frame halved how fast output was parsed while frames were +// drawn at 240 fps, since a frame's layout is most of 4.17ms. +// +// It compares output parsed while drawing as fast as 240 fps allows with +// output parsed while barely drawing, on one full pane of random output, +// so the machine's speed cancels out. +func TestOutputWhileDrawing(t *testing.T) { + if testing.Short() { + t.Skip("streams 48 MiB") + } + srv := rextest.Start(t) + other := srv.Dial(t, "other-device") + const mib = 24 + rate := func(period time.Duration) float64 { + sid, b := rextest.NewSession(t, other, "/bin/sh", "-c", fmt.Sprintf( + `stty raw -echo; printf 'ready\r\n'; head -c 1 >/dev/null; head -c %d /dev/urandom; printf '\030\033cdone-marker'; exec cat >/dev/null`, mib<<20)) + h := startUI(t, srv, srv.Dial(t, "100gex-test"), sid) + h.size = image.Pt(1920, 1080) + h.until("the pane", func(rexsession.Frame) bool { return strings.Contains(screenText(h.term(b)), "ready") }) + h.u.session.Claim(b) + h.u.session.PasteTo(b, "x") // starts the output + start := time.Now() + for done := false; !done; { + if time.Since(start) > time.Minute { + t.Fatal("timed out waiting for the output to end") + } + frame := time.Now() + h.frame() + h.held(func(rexsession.Frame) { done = strings.Contains(screenText(h.term(b)), "done-marker") }) + time.Sleep(period - min(time.Since(frame), period)) + } + return mib / time.Since(start).Seconds() + } + idle := rate(50 * time.Millisecond) + busy := rate(time.Second / 240) + t.Logf("output parsed at %.1f MiB/s while drawing at 240 fps, %.1f MiB/s while barely drawing", busy, idle) + if busy < 0.7*idle { + t.Errorf("drawing slows output to %.0f%% of its speed; at most 30%% slower is allowed", 100*busy/idle) + } +} diff --git a/internal/ui/sidebar_test.go b/internal/ui/sidebar_test.go index 70e70f6..8b21a29 100644 --- a/internal/ui/sidebar_test.go +++ b/internal/ui/sidebar_test.go @@ -211,7 +211,7 @@ func TestWarmSessions(t *testing.T) { t.Fatalf("two frames after switching back, showing %s", f.View.SessionID) } h.held(func(f rexsession.Frame) { - if text := screenText(f.Panes[blocks[0]].Term); !strings.Contains(text, "while away") { + if text := screenText(h.term(blocks[0])); !strings.Contains(text, "while away") { t.Errorf("the session shown again says %q", text) } }) diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 248ee6b..0a4647b 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -107,7 +107,6 @@ type UI struct { wantPaste bool // read the clipboard and paste it wantCopy bool // copy the focused pane's selection wantSelectAll bool // select all of the focused pane - frame rexsession.Frame // the last frame drawn pasteTag tag windowActions system.Action // asked of the window this frame @@ -265,27 +264,16 @@ func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) u.last, u.shown = u.shown, k } } - var f rexsession.Frame - if u.session != nil { - // The frame holds the terminals while it draws them; their output - // waits until it's done. - defer u.session.Release() - defer func() { u.frame = rexsession.Frame{} }() - var err error - if f, err = u.session.Sync(); err != nil { - return f, 0, err - } + f, err := u.updateTerminals(gtx) + if err != nil { + return f, 0, err } - u.frame = f + // From here the frame draws what the panes took: the terminals are + // their streams' again. size := gtx.Constraints.Max theme.Fill(gtx, theme.Cream, image.Rectangle{Max: size}) - // Typing goes to the focused block, wherever the pointer is, unless a - // key binding or the palette takes it. - u.keys.Layout(gtx, u.key, !u.palette.open && !u.renaming()) - u.layoutPaste(gtx) - titlebar, sidebar := gtx.Dp(theme.TitlebarHigh), u.sidebarWide(gtx) if err := u.layoutWorkspace(gtx, f, image.Rect(sidebar, titlebar, size.X, size.Y)); err != nil { return f, 0, err @@ -304,6 +292,149 @@ func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) return f, actions, nil } +// updateTerminals is the part of a frame that has the terminals. It holds +// them, from Sync, while the keyboard, the clipboard and the mouse change +// them and each pane shown takes what it draws, then lets them go: the +// rest of the frame draws from what the panes took, and from the frame +// returned, which holds no terminal. +// +// That is Ghostty's renderer's way: a terminal is held only to copy what +// is drawn, and parsed into while it is drawn. Holding the terminals for +// the whole frame stopped every pane's output for as long as the frame +// took to draw, slow characters and all, rather than tens of microseconds. +func (u *UI) updateTerminals(gtx layout.Context) (rexsession.Frame, error) { + var f rexsession.Frame + if u.session != nil { + defer u.session.Release() + var err error + if f, err = u.session.Sync(); err != nil { + return f, err + } + } + + // Typing goes to the focused block, wherever the pointer is, unless a + // key binding or the palette takes it. + u.keys.Layout(gtx, u.key, !u.palette.open && !u.renaming()) + u.layoutPaste(gtx) + + for _, id := range f.Visible { + if _, ok := f.Panes[id]; !ok { + continue + } + p, err := u.paneView(id) + if err != nil { + return f, err + } + w := f.Window + p.view.OnPress = func() { u.pressPane(w, id) } + p.view.FontSize = u.FontSize + if err := p.view.Update(gtx, u.session.Terminal(id)); err != nil { + return f, err + } + } + return f, nil +} + +// paneView returns a block's drawing state, made the first time it's shown. +func (u *UI) paneView(blockID string) (*paneView, error) { + if p := u.panes[blockID]; p != nil { + return p, nil + } + if u.glyphs == nil { + u.glyphs = termview.NewGlyphs(append(gofont.Collection(), theme.Fonts()...)) + } + v, err := termview.New(u.glyphs) + if err != nil { + return nil, err + } + v.FontSize = u.FontSize + v.Padding = 6 + v.SelectionFg, v.SelectionBg = theme.Ink, theme.Lavender + v.OnResize = func(cols, rows uint16, cellWidth, cellHeight int) { + if u.session != nil { + u.session.RequestSize(blockID, cols, rows, cellWidth, cellHeight) + } + } + v.OnSelected = func(text string) { + if u.Primary == nil { + return + } + go func() { + if err := u.Primary.Set(text); err != nil { + u.report(err) + } + }() + } + v.OnMiddleClick = func() { + if u.Primary == nil || u.session == nil { + return + } + s := u.session + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + text, err := u.Primary.Get(ctx) + if err != nil { + u.report(err) + return + } + if text != "" { + s.PasteTo(blockID, text) + } + }() + } + v.OnMouse = func(e rex.MouseEvent) { + if u.session != nil { + u.session.Mouse(blockID, e) + } + } + v.OnWheel = func(col, row uint16, lines int) { + if u.session != nil { + u.session.Wheel(blockID, col, row, lines) + } + } + p := &paneView{view: v} + u.panes[blockID] = p + return p, nil +} + +// pressPane acts on a press anywhere on a block's card, in window w: it +// takes the block, as typing in it would, since the person is using it +// here. It also focuses the block if it isn't, and brings its layer to the +// front if it floats behind another. The window gaining focus does none of +// this. +func (u *UI) pressPane(w *rex.Window, blockID string) { + if u.session == nil { + return + } + u.session.Claim(blockID) + if w == nil { + return + } + if w.ZoomedBlockID != blockID && w.FocusedBlockID != blockID { + u.session.FocusBlock(blockID) + } + if layer, front := floatingLayer(w, blockID); layer != "" && !front { + u.session.RaiseLayer(layer) + } +} + +// floatingLayer returns the floating layer of w that holds blockID, or "" +// if it's tiled, and whether that layer is in front of the others. +func floatingLayer(w *rex.Window, blockID string) (layer string, front bool) { + last := "" + for _, l := range w.Layers { + if l.Kind == "tiled" { + continue + } + last = l.LayerID + if hasBlock(l, blockID) { + layer = l.LayerID + } + } + return layer, layer != "" && layer == last +} + // key acts on one key press: a binding takes it, or it goes to the focused // block. func (u *UI) key(k rex.KeyEvent) { @@ -327,12 +458,12 @@ func (u *UI) key(k rex.KeyEvent) { } // focusedTerm returns the focused block's terminal, or nil. It is only -// there during a frame, after Sync, while the frame holds the terminals. +// there while the frame holds the terminals: see updateTerminals. func (u *UI) focusedTerm() *libghostty.Terminal { if u.session == nil { return nil } - return u.frame.Panes[u.session.FocusedBlock()].Term + return u.session.Terminal(u.session.FocusedBlock()) } // selectAll selects everything in the focused block. @@ -525,10 +656,8 @@ func (u *UI) tabLabel(f rexsession.Frame, w *rex.Window, i int) string { // programTitle is the title the program in a block set, or "": from its // terminal, if it has a pane, else as the server reported it. func programTitle(f rexsession.Frame, blockID string) string { - if p, ok := f.Panes[blockID]; ok && p.Term != nil { - if t, err := p.Term.Title(); err == nil { - return strings.TrimSpace(t) - } + if p, ok := f.Panes[blockID]; ok && p.Restored { + return strings.TrimSpace(p.Title) } return strings.TrimSpace(f.Titles[blockID]) } @@ -658,44 +787,17 @@ func (u *UI) layoutPane(gtx layout.Context, f rexsession.Frame, blockID string, if r.Dx() < 4*border || r.Dy() < header+4*border { return nil } - p := u.panes[blockID] - if p == nil { - if u.glyphs == nil { - u.glyphs = termview.NewGlyphs(append(gofont.Collection(), theme.Fonts()...)) - } - v, err := termview.New(u.glyphs) - if err != nil { - return err - } - v.OnResize = func(cols, rows uint16, cellWidth, cellHeight int) { - if u.session != nil { - u.session.RequestSize(blockID, cols, rows, cellWidth, cellHeight) - } - } - p = &paneView{view: v} - u.panes[blockID] = p + p, err := u.paneView(blockID) + if err != nil { + return err } theme.Card(gtx, r, theme.White, shadow) u.paneSlots = append(u.paneSlots, paneSlot{block: blockID, rect: r}) - // A press anywhere on a card takes its block, as typing in it would: - // the person is using it here. It also focuses an unfocused card. The - // window gaining focus does neither. The terminal reports presses on - // it through OnPress; this handles the header. - // A press on a floating pane also brings its layer to the front. - press := func() { - if u.session != nil { - u.session.Claim(blockID) - if !focused { - u.session.FocusBlock(blockID) - } - if fl != nil && !fl.front { - u.session.RaiseLayer(fl.id) - } - } - } - // Dragging the header moves the pane: see paneHeaderEvent. + // A press on the header acts as one on the terminal does, which + // reports it through OnPress: see pressPane. Dragging the header + // moves the pane: see paneHeaderEvent. for { ev, ok := gtx.Event(pointer.Filter{Target: p, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel}) if !ok { @@ -706,7 +808,7 @@ func (u *UI) layoutPane(gtx layout.Context, f rexsession.Frame, blockID string, continue } if e.Kind == pointer.Press { - press() + u.pressPane(f.Window, blockID) } u.paneHeaderEvent(gtx, p, blockID, fl, e) } @@ -753,58 +855,12 @@ func (u *UI) layoutPane(gtx layout.Context, f rexsession.Frame, blockID string, if body.Empty() { return nil } - var err error at(gtx, body, func(gtx layout.Context) layout.Dimensions { defer clip.Rect{Max: body.Size()}.Push(gtx.Ops).Pop() p.view.FontSize = u.FontSize p.view.Focused = focused - p.view.Padding = 6 - p.view.OnPress = press - p.view.SelectionFg, p.view.SelectionBg = theme.Ink, theme.Lavender - p.view.OnSelected = func() { - if u.Primary == nil || pf.Term == nil { - return - } - text, err := termview.SelectionText(pf.Term) - if err != nil || text == "" { - return - } - go func() { - if err := u.Primary.Set(text); err != nil { - u.report(err) - } - }() - } - p.view.OnMiddleClick = func() { - if u.Primary == nil || u.session == nil { - return - } - s := u.session - go func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - text, err := u.Primary.Get(ctx) - if err != nil { - u.report(err) - return - } - if text != "" { - s.PasteTo(blockID, text) - } - }() - } - p.view.OnMouse = func(e rex.MouseEvent) { - if u.session != nil { - u.session.Mouse(blockID, e) - } - } - p.view.OnWheel = func(col, row uint16, lines int) { - if u.session != nil { - u.session.Wheel(blockID, col, row, lines) - } - } var dims layout.Dimensions - dims, err = p.view.Layout(gtx, pf.Term) + dims, err = p.view.Layout(gtx) return dims }) return err diff --git a/main.go b/main.go index 60cd0a0..e0e3cb4 100644 --- a/main.go +++ b/main.go @@ -156,7 +156,7 @@ func run(w *app.Window, server, sessionQuery string, opts options) error { w.Perform(system.ActionClose) } // Streams are parsed into the terminals in the background; - // a frame holds them only while Layout draws them. + // a frame holds them only while it takes what it draws. start := time.Now() gtx := app.NewContext(&ops, e) _, actions, err := u.Layout(gtx)