From aba5a8a7930e1814cd2d1e20f9df7ad6c2e268e2 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Sun, 22 Nov 2026 20:54:10 +0000 Subject: [PATCH] Reuse the paintings of rows that moved, though the terminal counts them as new A full-screen program scrolls by moving lines within the screen: a newline in a scroll region, or inserting or deleting lines. libghostty gives the moved rows new IDs, so every row on screen was painted and uploaded to the GPU again, a slow frame each time a chat like Claude Code's scrolled. A row that changed is now read into a row of its own, and before painting, each row to paint takes the painting of a row no longer shown with the same cells, if there is one, found by a hash of the cells. For a full 1080p pane, a frame of a scroll region moving a line, until the GPU is done, goes from 4.0ms to 2.0ms; what's left is reading the cells. TestRowsRedrawn gains steps that scroll regions and insert and delete lines, and fails if rows are matched by their hash alone. --- internal/termview/bench_test.go | 12 ++++ internal/termview/rows_test.go | 35 +++++++++ internal/termview/view.go | 124 +++++++++++++++++++++++++++----- 3 files changed, 153 insertions(+), 18 deletions(-) diff --git a/internal/termview/bench_test.go b/internal/termview/bench_test.go index 5aa9089..be0c05a 100644 --- a/internal/termview/bench_test.go +++ b/internal/termview/bench_test.go @@ -1,6 +1,7 @@ package termview_test import ( + "bytes" "fmt" "image" "testing" @@ -118,6 +119,15 @@ var changes = []struct { panic(err) } }}, + // A scroll region moves up a line, as a chat or an editor scrolls: the + // terminal counts the moved rows as new. + {"region-scroll", func(p *benchPane) { + _, rows := p.view.Size() + p.line++ + fmt.Fprintf(regionScroll, "\x1b[2;%dr\x1b[%d;1H\r\nline %d\x1b[r", rows-1, rows-1, p.line) + p.term.VTWrite(regionScroll.Bytes()) + regionScroll.Reset() + }}, // Every row is drawn again, as when the screen scrolls or is redrawn. {"every-row", func(p *benchPane) { termview.ForgetRows(p.view) }}, } @@ -197,6 +207,8 @@ func TestLayoutAllocs(t *testing.T) { } } +var regionScroll = new(bytes.Buffer) + var onePixel = image.NewRGBA(image.Rect(0, 0, 1, 1)) // maxAllocsPerRow is the allocations a frame may make for each row drawn diff --git a/internal/termview/rows_test.go b/internal/termview/rows_test.go index 2355ea1..3e33db7 100644 --- a/internal/termview/rows_test.go +++ b/internal/termview/rows_test.go @@ -127,6 +127,16 @@ func TestRowsRedrawn(t *testing.T) { t.Fatal(err) } check("scrolling to the bottom") + // Full-screen programs scroll part of the screen in place: the rows' + // cells move to rows the terminal counts as new. + write("\x1b[2;4Hsame\x1b[3;4Hsame\x1b[2;6r\x1b[6;1H\r\nin the region\x1b[r") + check("scrolling within a region") + write("\x1b[3;1H\x1b[2L") + check("inserting lines") + write("\x1b[2;1H\x1b[M") + check("deleting a line") + write("\x1b[1;7r\x1b[1;1H\x1bM\x1bM\x1b[r") + check("scrolling a region down") if err := term.SetColorBackground(&libghostty.ColorRGB{R: 0x20, G: 0x30, B: 0x40}); err != nil { t.Fatal(err) } @@ -142,3 +152,28 @@ func TestRowsRedrawn(t *testing.T) { write("\x1b[2J\x1b[Hcleared") check("clearing the screen") } + +// TestMovedRowsReused scrolls the screen each way programs do, and checks +// that only the row with new cells is painted: the rest moved, and keep +// their paintings, though the terminal counts some as new rows. +func TestMovedRowsReused(t *testing.T) { + for _, c := range []struct{ name, seq string }{ + {"output scrolling the screen", "\r\nnew line"}, + {"scrolling within a region", "\x1b[1;4r\x1b[4;1H\r\nnew line\x1b[r"}, + {"scrolling up", "\x1b[S"}, + {"deleting a line", "\x1b[1;1H\x1b[M"}, + {"inserting a line", "\x1b[1;1H\x1b[L"}, + } { + h := newSelectHarness(t) + h.term.VTWrite([]byte("\x1b[2J")) + for i := range 5 { + h.term.VTWrite([]byte(fmt.Sprintf("\x1b[%d;1Hrow %d", i+1, i))) + } + h.frame() + h.term.VTWrite([]byte(c.seq)) + h.frame() + if got := Painted(h.v); got != 1 { + t.Errorf("%s: %d rows painted, want 1", c.name, got) + } + } +} diff --git a/internal/termview/view.go b/internal/termview/view.go index 022a80a..c07963d 100644 --- a/internal/termview/view.go +++ b/internal/termview/view.go @@ -117,8 +117,9 @@ type View struct { style libghostty.RenderCellStyle graphemes []uint32 runes []rune - painting []*drawnRow // rows read this frame, to paint - unused []rowpaint.Cell // a row's cells as they were, to read into next + painting []*drawnRow // rows read this frame, to paint + replaced []*drawnRow // rows whose cells changed this frame, as they were + byCells map[uint64]*drawnRow // reuseRows' rows no longer shown, by hashCells // drawn holds each row on screen as last drawn, to replay until it // changes; spare holds rows to draw into again. look is what they @@ -162,6 +163,7 @@ type drawnRow struct { img *image.RGBA // the row painted; reused when it's painted again op paint.ImageOp // img, as last painted frame uint64 // the last Layout that showed it + same *drawnRow // the next row in byCells with the same hash } // look is what every row is drawn with. When it changes, every row is @@ -302,26 +304,27 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim } id, changed := v.rowID, v.rowDirty || all r := v.drawn[id] - fresh := r == nil - if fresh { - r = v.spareRow() - v.drawn[id] = r - changed = true - } - if changed { + if r == nil || changed { // Painting a row costs uploading it to the GPU again, which // is most of a frame's cost when every row is: a row whose - // cells are as they were keeps its painting. - old := r.cells - r.cells = v.unused[:0] - if err := v.readRow(r, want); err != nil { + // cells are as they were keeps its painting. A row that + // changed is read into a row of its own, so its old painting + // is there for reuse if another row now has those cells. + n := v.spareRow() + n.cells = n.cells[:0] + if err := v.readRow(n, want); err != nil { return layout.Dimensions{Size: size}, fmt.Errorf("row %d: %w", y, err) } - v.unused = old - if fresh || !slices.Equal(r.cells, old) { - v.painting = append(v.painting, r) - } else { + if r != nil && slices.Equal(n.cells, r.cells) { + v.spare = append(v.spare, n) changed = false + } else { + if r != nil { + v.replaced = append(v.replaced, r) + } + v.drawn[id] = n + r, changed = n, true + v.painting = append(v.painting, r) } } if cur.visible && int(cur.y) == y { @@ -333,6 +336,7 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim r.frame = v.frame v.shown = append(v.shown, r) } + v.reuseRows() v.paintRows(m) for y, r := range v.shown { if r.img == nil || r.img.Rect.Empty() { @@ -351,11 +355,14 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim v.drawCursor(gtx, m, cur, cursorRow, want.bg) } for id, r := range v.drawn { - if r.frame != v.frame { // scrolled away, or replaced + if r.frame != v.frame { // scrolled away delete(v.drawn, id) v.spare = append(v.spare, r) } } + v.spare = append(v.spare, v.replaced...) + clear(v.replaced) + v.replaced = v.replaced[:0] if blinks { gtx.Execute(op.InvalidateCmd{At: nextBlink(v.blinkSince, gtx.Now)}) } @@ -458,6 +465,87 @@ func (v *View) paintRows(m metrics) { } } +// reuseRows gives each row to paint whose cells are those of a row +// painted before and no longer shown that row's painting instead. A +// program that scrolls part of the screen, as a full-screen program such +// as an editor or a chat does, moves rows' cells to rows the terminal +// counts as new: they needn't be painted, nor uploaded, again. +func (v *View) reuseRows() { + if len(v.painting) == 0 { + return + } + if v.byCells == nil { + v.byCells = make(map[uint64]*drawnRow) + } + clear(v.byCells) + add := func(r *drawnRow) { + if r.img == nil { + return + } + h := hashCells(r.cells) + r.same = v.byCells[h] + v.byCells[h] = r + } + for _, r := range v.drawn { + if r.frame != v.frame { + add(r) + } + } + for _, r := range v.replaced { + add(r) + } + if len(v.byCells) == 0 { + return + } + painting := v.painting[:0] + for _, r := range v.painting { + h := hashCells(r.cells) + var prev *drawnRow + c := v.byCells[h] + for c != nil && !slices.Equal(c.cells, r.cells) { + prev, c = c, c.same + } + if c == nil { + painting = append(painting, r) + continue + } + if prev == nil { + if c.same == nil { + delete(v.byCells, h) + } else { + v.byCells[h] = c.same + } + } else { + prev.same = c.same + } + c.same = nil + r.img, c.img = c.img, r.img + r.op, c.op = c.op, r.op + } + for _, r := range v.byCells { // unlink what's left + for r != nil { + next := r.same + r.same = nil + r = next + } + } + v.painting = painting +} + +// hashCells hashes a row's cells, for reuseRows to find rows with the +// same. +func hashCells(cells []rowpaint.Cell) uint64 { + const prime = 1099511628211 + h := uint64(14695981039346656037) + for _, c := range cells { + h ^= uint64(c.Bg.R) | uint64(c.Bg.G)<<8 | uint64(c.Bg.B)<<16 | uint64(c.Fg.R)<<24 | uint64(c.Fg.G)<<32 | uint64(c.Fg.B)<<40 | uint64(c.Fg.A)<<48 + h *= prime + h ^= uint64(uintptr(unsafe.Pointer(c.Glyph))) + h *= prime + } + return h +} + // spareRow returns a row to draw into, reusing one that left the view. func (v *View) spareRow() *drawnRow { if n := len(v.spare); n > 0 { -- knotmirror 0.0.1