package termview_test import ( "bytes" "fmt" "image" "slices" "testing" "time" "gioui.org/font/gofont" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" "go.mitchellh.com/libghostty" "100gex/internal/present" "100gex/internal/sample" "100gex/internal/scene" "100gex/internal/termscreen" "100gex/internal/termview" "100gex/internal/theme" ) // benchPane is one pane filling a window, its terminal full of content // that is written once: the frames drawn afterwards cost only drawing. type benchPane struct { view *termview.View term *libghostty.Terminal scr *termscreen.Screen ops op.Ops gtx layout.Context line int // the line selected last, by the selecting change } // benchGlyphs draws the benchmarks' characters, as 100gex does: with the // system's fonts. var benchGlyphs = termview.NewGlyphs(append(gofont.Collection(), theme.Fonts()...)) // screens are what the benchmarks fill a pane with. var screens = []struct { name string fill func(cols, rows int) []byte }{ {"plain", sample.Plain}, {"code", sample.Code}, {"styled", sample.Styled}, // the worst case: every cell its own colours } // newBenchPane makes a pane of size pixels, as 100gex draws them, sizes its // terminal to fit, as a Rex server would, and fills it. func newBenchPane(tb testing.TB, size image.Point, fill func(cols, rows int) []byte) *benchPane { tb.Helper() term, err := libghostty.NewTerminal(libghostty.WithSize(80, 24)) if err != nil { tb.Fatal(err) } tb.Cleanup(term.Close) scr := termview.NewScreen(tb, term) tb.Cleanup(scr.Close) view, err := termview.New(benchGlyphs) if err != nil { tb.Fatal(err) } tb.Cleanup(view.Close) view.FontSize = 15 view.Focused = true view.Padding = 6 view.OnResize = func(cols, rows uint16, cellW, cellH int) { if err := term.Resize(cols, rows, uint32(cellW), uint32(cellH)); err != nil { tb.Fatal(err) } } p := &benchPane{view: view, term: term, scr: scr} p.gtx = layout.Context{ Ops: &p.ops, Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(size), Now: time.Now(), } p.layout(tb) // sizes the terminal cols, rows := view.Size() term.VTWrite(fill(int(cols), int(rows))) p.layout(tb) // shapes every glyph once, as the first frame after output does return p } func (p *benchPane) layout(tb testing.TB) { p.ops.Reset() if err := p.view.Update(p.gtx, p.scr); err != nil { tb.Fatal(err) } if _, err := p.view.Layout(p.gtx); err != nil { tb.Fatal(err) } } // paneSizes are the panes measured: a quarter of a 1080p screen, as a // window split four ways has, and the whole of one. var paneSizes = []image.Point{{960, 540}, {1920, 1080}} // changes are what happens to a pane's screen between frames: a row is // drawn again only when it changes. var changes = []struct { name string change func(p *benchPane) }{ // The screen stays as it is, as in a pane beside the one in use. {"unchanged", func(*benchPane) {}}, // One row changes, away from the cursor, as a clock or a status line // does. {"one-row", func(p *benchPane) { p.term.VTWrite([]byte("\x1b7\x1b[3;5Hx\x1b8")) }}, // The selection moves, as dragging it does: the terminal marks every // row changed, but two are. {"selecting", func(p *benchPane) { _, rows := p.view.Size() p.line = (p.line + 1) % int(rows) ref, err := p.term.GridRef(libghostty.Point{Tag: libghostty.PointTagViewport, Y: uint32(p.line)}) if err != nil { panic(err) } sel, err := p.term.SelectLine(libghostty.SelectLineOptions{Ref: ref}) if err != nil { panic(err) } if err := p.term.SetSelection(sel); err != nil { 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) }}, } // BenchmarkLayout measures the work 100gex does on the CPU for each frame // of a full pane: reading the cells of rows that changed, turning them into // drawing operations, and replaying the rest. func BenchmarkLayout(b *testing.B) { for _, size := range paneSizes { for _, s := range screens { for _, c := range changes { b.Run(fmt.Sprintf("%dx%d/%s/%s", size.X, size.Y, s.name, c.name), func(b *testing.B) { p := newBenchPane(b, size, s.fill) b.ReportAllocs() for b.Loop() { c.change(p) p.layout(b) } }) } } } } // frameSizes are the panes whose whole frames are measured: paneSizes, // and the whole of a large laptop's screen. var frameSizes = append(paneSizes, image.Pt(3356, 2060)) // frameChanges are the changes whose frames are measured, by name. var frameChanges = []string{"unchanged", "one-row", "region-scroll", "every-row"} // BenchmarkFrame measures a pane's whole frames as the window draws them, // after each of frameChanges, with its rows painted, or drawn as cells by // the GPU: the pane is a layer, drawn again only when it changed, then // composited, until the GPU is done. It reports the // frame's parts: layout-µs on the CPU, reading cells and painting rows; // submit-µs handing the layer to Gio and the compositor, uploads included; // and gpu-µs waiting for the GPU to finish. Its fps is the frame rate one // such pane alone allows. func BenchmarkFrame(b *testing.B) { for _, size := range frameSizes { for _, sc := range screens[1:] { // code, and the worst case, styled for _, name := range frameChanges { i := slices.IndexFunc(changes, func(c struct { name string change func(p *benchPane) }) bool { return c.name == name }) change := changes[i].change for _, grid := range []bool{false, true} { mode := map[bool]string{false: "rows", true: "cells"}[grid] b.Run(fmt.Sprintf("%dx%d/%s/%s/%s", size.X, size.Y, sc.name, name, mode), func(b *testing.B) { win, err := present.NewHeadless(size) if err != nil { b.Skipf("no headless GPU context: %v", err) } defer win.Release() p := newBenchPane(b, size, sc.fill) p.view.Grid = grid var s scene.Scene var root op.Ops var lay, submit, gpu time.Duration frame := func() { change(p) t0 := time.Now() root.Reset() s.Begin(size) gtx := s.Layer(p.gtx, "pane", scene.Spec{Bounds: image.Rectangle{Max: size}, Opaque: true, Cells: p.view.Cells()}) if err := p.view.Update(gtx, p.scr); err != nil { b.Fatal(err) } if _, err := p.view.Layout(gtx); err != nil { b.Fatal(err) } s.End(&root) t1 := time.Now() if _, err := win.Frame(&s); err != nil { b.Fatal(err) } t2 := time.Now() // Wait for the GPU to draw it. if err := win.Screenshot(onePixel); err != nil { b.Fatal(err) } lay, submit, gpu = lay+t1.Sub(t0), submit+t2.Sub(t1), gpu+time.Since(t2) } for range 5 { frame() } lay, submit, gpu = 0, 0, 0 b.ReportAllocs() start := time.Now() for b.Loop() { frame() } n := float64(b.N) b.ReportMetric(float64(b.N)/time.Since(start).Seconds(), "fps") b.ReportMetric(float64(lay.Microseconds())/n, "layout-µs") b.ReportMetric(float64(submit.Microseconds())/n, "submit-µs") b.ReportMetric(float64(gpu.Microseconds())/n, "gpu-µs") }) } } } } } // TestLayoutAllocs keeps a full pane's frame from allocating per cell, even // with every row drawn again: its buffers, rows and shaped glyphs are // reused from frame to frame, so a busy screen makes no more garbage than // an empty one. func TestLayoutAllocs(t *testing.T) { for _, s := range screens { p := newBenchPane(t, image.Pt(1920, 1080), s.fill) allocs := testing.AllocsPerRun(20, func() { termview.ForgetRows(p.view) p.layout(t) }) _, rows := p.view.Size() limit := maxAllocsPerRow * float64(rows) t.Logf("%s: %.0f allocations a frame, %.1f a row", s.name, allocs, allocs/float64(rows)) if allocs > limit { t.Errorf("%s: a frame of a full pane makes %.0f allocations; at most %.0f, %v a row, are allowed", s.name, allocs, limit, maxAllocsPerRow) } } } 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 // again: a few, from reading the terminal, and for a row of many colours // the image they're painted with, but none a cell. A 1080p pane has about // 200 cells a row. const maxAllocsPerRow = 8