Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705// Package termview draws a libghostty terminal in a Gio window.//// The terminal's state lives in libghostty; this package only reads it through// a render state and paints it on a fixed monospace cell grid. Each row is// painted into an image on the CPU, from characters the glyph package draws// once each, and repainted only when it changes: the GPU only draws a few// images, however much text there is. Each cell's text is shaped on its own// and placed at the cell's column, so characters stay on the grid even when// a fallback font with different advances is used.package termview
import ( "fmt" "image" "image/color" "math" "runtime" "slices" "sync" "sync/atomic" "time" "unsafe"
"gioui.org/font" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" "gioui.org/op/paint" "gioui.org/unit"
"go.mitchellh.com/libghostty"
"100gex/internal/glyph" "100gex/internal/rex" "100gex/internal/rowpaint")
// Typeface is the font family list cells are drawn with: Iosevka if it is// installed, else Go Mono, which must be among the faces given to// [NewGlyphs]. The generic families after them matter: fonts are only// fallbacks if they match a listed family, so without them characters// these fonts lack (CJK, emoji) resolve to an arbitrary face and draw as// tofu.const Typeface font.Typeface = "Iosevka Nerd Font, Iosevka, Go Mono, monospace, emoji"
// NewGlyphs returns what views draw characters with: [Typeface], from faces// and the system's fonts. Views drawn from one goroutine can share one, and// each character is then drawn once for all of them.func NewGlyphs(faces []font.FontFace) *glyph.Rasterizer { return glyph.New(glyph.Options{Families: string(Typeface), Faces: faces})}
// 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// its size. Keyboard input is handled separately, by [Keys].type View struct { // FontSize is the size cells are drawn at. FontSize unit.Sp
// Focused draws the cursor solid; otherwise it is drawn as an outline, // to show that typing goes elsewhere. Focused bool
// Padding is space around the cells, painted in the terminal's // background colour. Padding unit.Dp
// OnResize is called from Layout when the number of cells that fit the // 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 // 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()
// OnMiddleClick, if set, is called from Layout on a middle click. OnMiddleClick func()
// OnWheel, if set, is called from Layout 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 // motion for a program that reads the mouse. Gestures that start with // Shift held select instead. OnMouse func(rex.MouseEvent)
// SelectionFg and SelectionBg colour selected text. SelectionFg, SelectionBg color.NRGBA
glyphs *glyph.Rasterizer
rs *libghostty.RenderState rows *libghostty.RenderStateRowIterator cells *libghostty.RenderStateRowCells
metrics metrics metricsPx int cols, lines uint16
sel selector report reporter scroll float32 // wheel travel not yet a whole line, in lines
// blinkSince is when the cursor last showed after a change; it // blinks from then. blinkFor is the cursor that change was to. blinkSince time.Time blinkFor cursorState
// Reused between frames. style libghostty.RenderCellStyle graphemes []uint32 runes []rune 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 // were drawn with, and shown the rows of the frame, from the top. drawn map[rowID]*drawnRow spare []*drawnRow look look shown []*drawnRow frame uint64 // counts Layouts, to find rows no longer shown
// rowID and rowDirty are the current row's, read by rowValues. rowID rowID rowDirty bool rowValues []unsafe.Pointer
// cursorOp is the block cursor's cell, painted for cursorFor, kept // while the cursor stays the same. cursorOp paint.ImageOp cursorFor cursorCell}
// cursorCell is what a block cursor's cell is painted from.type cursorCell struct { glyph *glyph.Glyph fg, bg color.NRGBA m metrics painted bool}
// rowID is a row's identity, a GhosttyRenderStateRowId: it stays the same// as the row moves, so a row that only scrolled is replayed.type rowID [2]uint64
// rowKeys are what Layout reads of each row, into View.rowValues.var rowKeys = []libghostty.RenderStateRowData{libghostty.RenderStateRowDataID, libghostty.RenderStateRowDataDirty}
// drawnRow is one row, as read from the terminal and painted, to show// again in later frames until it changes.type drawnRow struct { cells []rowpaint.Cell 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// drawn again.type look struct { term *libghostty.Terminal m metrics px int fg, bg, selFg, selBg color.NRGBA}
// metrics describe one cell in pixels at the current font size.type metrics struct { width, height int baseline int // distance from the cell's top to the text baseline}
// New returns a View that draws characters with glyphs, made by// [NewGlyphs].func New(glyphs *glyph.Rasterizer) (*View, error) { v := &View{ FontSize: 14, glyphs: glyphs, SelectionFg: color.NRGBA{R: 0x21, G: 0x15, B: 0x2D, A: 0xff}, SelectionBg: color.NRGBA{R: 0xDA, G: 0xB6, B: 0xFF, A: 0xff}, } var err error if v.rs, err = libghostty.NewRenderState(); err != nil { return nil, err } if v.rows, err = libghostty.NewRenderStateRowIterator(); err != nil { v.Close() return nil, err } if v.cells, err = libghostty.NewRenderStateRowCells(); err != nil { v.Close() return nil, err } v.rowValues = []unsafe.Pointer{unsafe.Pointer(&v.rowID), unsafe.Pointer(&v.rowDirty)} return v, nil}
// Close releases the render state.func (v *View) Close() { v.sel.close() if v.cells != nil { v.cells.Close() } if v.rows != nil { v.rows.Close() } if v.rs != nil { v.rs.Close() }}
// CellSize reports a cell's size in pixels, as of the most recent Layout.func (v *View) CellSize() image.Point { return image.Pt(v.metrics.width, v.metrics.height) }
// Size reports the number of cells that fit the view, as of the most recent// Layout.func (v *View) Size() (cols, rows uint16) { return v.cols, v.lines }
// Layout paints term, which may be nil before it exists, 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) { full := gtx.Constraints.Max pad := gtx.Dp(v.Padding) size := image.Pt(max(full.X-2*pad, 1), max(full.Y-2*pad, 1)) m := v.measure(gtx) 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) 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) } defaultFg, defaultBg := rgb(colors.Foreground), rgb(colors.Background) paint.FillShape(gtx.Ops, defaultBg, clip.Rect{Max: full}.Op()) defer op.Offset(image.Pt(pad, pad)).Push(gtx.Ops).Pop() defer clip.Rect{Max: size}.Push(gtx.Ops).Pop()
cur, err := v.cursor() if err != nil { return layout.Dimensions{Size: size}, err } cur.color = defaultFg if colors.CursorHasValue { cur.color = rgb(colors.Cursor) } // A cursor that moves or changes shows at once, and blinks from then. blinks := cur.visible && cur.blinking && v.Focused if !blinks || cur != v.blinkFor { v.blinkSince, v.blinkFor = gtx.Now, cur }
// Rows are drawn once and replayed until they change. A change to // anything every row is drawn with starts them all again. want := look{term: term, m: m, px: gtx.Sp(v.FontSize), fg: defaultFg, bg: defaultBg, selFg: v.SelectionFg, selBg: v.SelectionBg} dirty, err := v.rs.Dirty() if err != nil { return layout.Dimensions{Size: size}, fmt.Errorf("dirty state: %w", err) } if want != v.look { v.forgetRows() v.look = want } // A full change, as selecting or scrolling makes, marks every row // changed, though few are: each is read, and painted only if it // differs. all := dirty == libghostty.RenderStateDirtyFull if err := v.rs.RowIterator(v.rows); err != nil { return layout.Dimensions{Size: size}, fmt.Errorf("iterate rows: %w", err) } v.frame++ v.shown, v.painting = v.shown[:0], v.painting[:0] var cursorRow *drawnRow for y := 0; v.rows.Next(); y++ { // One call for both, into the view's own memory: the typed // getters cost a call and an allocation each, every row, every // frame. if err := v.rows.GetMulti(rowKeys, v.rowValues); err != nil { return layout.Dimensions{Size: size}, fmt.Errorf("row %d: %w", y, err) } id, changed := v.rowID, v.rowDirty || all r := v.drawn[id] 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. 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) } 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 { cursorRow = r if changed { // output on the cursor's row, often typing v.blinkSince = gtx.Now } } 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() { continue } off := op.Offset(image.Pt(0, y*m.height)).Push(gtx.Ops) area := clip.Rect{Max: r.img.Rect.Size()}.Push(gtx.Ops) r.op.Add(gtx.Ops) paint.PaintOp{}.Add(gtx.Ops) area.Pop() off.Pop() } // The cursor is drawn over the rows, so a row needn't be painted // again as it moves or blinks. if cursorRow != nil && (!blinks || blinkOn(gtx.Now.Sub(v.blinkSince))) { v.drawCursor(gtx, m, cur, cursorRow, want.bg) } for id, r := range v.drawn { 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)}) } if err := v.rs.Clean(); err != nil { 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 } return layout.Dimensions{Size: full}, nil}
// readRow appends the iterator's current row to r.cells: each cell's colours,// with the selection's, and its character's drawing.func (v *View) readRow(r *drawnRow, l look) error { if err := v.rows.Cells(v.cells); err != nil { return fmt.Errorf("cells: %w", err) } sel := [2]int{-1, -2} // the selected columns if rs, err := v.rows.Selection(); err != nil { return fmt.Errorf("selection: %w", err) } else if rs != nil { sel = [2]int{int(rs.StartX), int(rs.EndX)} } for x := 0; v.cells.Next(); x++ { if err := v.cells.StyleInto(&v.style); err != nil { return fmt.Errorf("cell %d style: %w", x, err) } fg, bg := l.fg, l.bg if v.style.HasForeground { fg = rgb(v.style.Foreground) } if v.style.HasBackground { bg = rgb(v.style.Background) } if v.style.Inverse { fg, bg = bg, fg } if v.style.Faint { fg.A /= 2 } if x >= sel[0] && x <= sel[1] { fg, bg = l.selFg, l.selBg } var err error v.graphemes, err = v.cells.GraphemesInto(v.graphemes[:0]) if err != nil { return fmt.Errorf("cell %d text: %w", x, err) } var g *glyph.Glyph if len(v.graphemes) > 0 { v.runes = v.runes[:0] for _, cp := range v.graphemes { v.runes = append(v.runes, rune(cp)) } g = v.glyphs.GlyphRunes(v.runes, glyph.Style{Bold: v.style.Bold, Italic: v.style.Italic}, l.px) } r.cells = append(r.cells, rowpaint.Cell{Bg: bg, Fg: fg, Glyph: g}) } return nil}
// parallelRows is how many rows each goroutine paints, at least, when// rows are painted at once. Fewer aren't worth a goroutine.const parallelRows = 4
// paintRows paints the rows read this frame into their images, on as many// cores as there are rows to keep busy: a screen that scrolled is painted// all at once.func (v *View) paintRows(m metrics) { rows := v.painting paintRow := func(r *drawnRow) { size := image.Pt(len(r.cells)*m.width, m.height) if r.img == nil || r.img.Rect.Size() != size { r.img = image.NewRGBA(image.Rectangle{Max: size}) } rowpaint.Paint(r.img, r.cells, m.width, m.baseline) } if workers := min(runtime.GOMAXPROCS(0), len(rows)/parallelRows); workers > 1 { var next atomic.Int64 var wg sync.WaitGroup for range workers { wg.Go(func() { for i := int(next.Add(1)) - 1; i < len(rows); i = int(next.Add(1)) - 1 { paintRow(rows[i]) } }) } wg.Wait() } else { for _, r := range rows { paintRow(r) } } // The image changed, so Gio needs a new op to upload it again. for _, r := range rows { r.op = paint.NewImageOp(r.img) r.op.Filter = paint.FilterNearest }}
// 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 { r := v.spare[n-1] v.spare = v.spare[:n-1] return r } return new(drawnRow)}
// forgetRows drops every drawn row, so that each is drawn again.func (v *View) forgetRows() { if v.drawn == nil { v.drawn = make(map[rowID]*drawnRow) } for id, r := range v.drawn { delete(v.drawn, id) v.spare = append(v.spare, r) }}
// 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) } if sb.Total <= sb.Len || sb.Offset+sb.Len >= sb.Total { return nil } height := float64(size.Y + pad) top := int(height * float64(sb.Offset) / float64(sb.Total)) bottom := int(height * float64(sb.Offset+sb.Len) / float64(sb.Total)) bottom = max(bottom, top+gtx.Dp(12)) 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// only when the pixel size changes.func (v *View) measure(gtx layout.Context) metrics { px := gtx.Sp(v.FontSize) if px == v.metricsPx && v.metrics.width > 0 { return v.metrics } gm := v.glyphs.Metrics(px) v.metrics, v.metricsPx = metrics{width: gm.Width, height: gm.Height, baseline: gm.Baseline}, px return v.metrics}
// fit works out how many whole cells fit in size, and reports a change.func (v *View) fit(size image.Point, m metrics) { cols := uint16(min(max(size.X/m.width, 1), math.MaxUint16)) rows := uint16(min(max(size.Y/m.height, 1), math.MaxUint16)) if cols == v.cols && rows == v.lines { return } v.cols, v.lines = cols, rows if v.OnResize != nil { v.OnResize(cols, rows, m.width, m.height) }}
type cursorState struct { visible, blinking bool x, y uint16 style libghostty.CursorStyle // the shape a program asked for, by DECSCUSR color color.NRGBA}
// blinkEvery is how long a blinking cursor is shown, and then hidden.const blinkEvery = 600 * time.Millisecond
// blinkOn reports whether a cursor blinking for d is showing.func blinkOn(d time.Duration) bool { return d%(2*blinkEvery) < blinkEvery }
// nextBlink is when a cursor blinking since since next shows or hides,// after now.func nextBlink(since, now time.Time) time.Time { return since.Add((now.Sub(since)/blinkEvery + 1) * blinkEvery)}
// cursor reads the cursor in one call, rather than a call for each of its// parts.func (v *View) cursor() (cursorState, error) { c, err := v.rs.Cursor() if err != nil { return cursorState{}, fmt.Errorf("cursor: %w", err) } if !c.Visible || !c.ViewportHasValue { return cursorState{}, nil } return cursorState{visible: true, blinking: c.Blinking, x: c.ViewportX, y: c.ViewportY, style: c.VisualStyle}, nil}
// drawCursor draws the cursor over its row, in the shape the program asked// for. An unfocused view draws every shape as an outline, so it's plain// which pane has the keyboard. A block shows the cell's character in the// cell's background colour; bg is the background of a cell past the row's// end.func (v *View) drawCursor(gtx layout.Context, m metrics, cur cursorState, row *drawnRow, bg color.NRGBA) { x, y := int(cur.x), int(cur.y) cell := image.Rect(x*m.width, y*m.height, (x+1)*m.width, (y+1)*m.height) line := max(1, m.width/8) style := cur.style if !v.Focused { style = libghostty.CursorStyleBlockHollow } switch style { case libghostty.CursorStyleBar: fillRect(gtx, cur.color, image.Rect(cell.Min.X, cell.Min.Y, cell.Min.X+max(2, line), cell.Max.Y)) return case libghostty.CursorStyleUnderline: fillRect(gtx, cur.color, image.Rect(cell.Min.X, cell.Max.Y-max(2, line), cell.Max.X, cell.Max.Y)) return case libghostty.CursorStyleBlockHollow: strokeRect(gtx, cur.color, cell, line) return } want := cursorCell{bg: cur.color, fg: bg, m: m, painted: true} if x < len(row.cells) { want.glyph, want.fg = row.cells[x].Glyph, row.cells[x].Bg } if want != v.cursorFor { img := image.NewRGBA(image.Rect(0, 0, m.width, m.height)) rowpaint.Paint(img, []rowpaint.Cell{{Bg: want.bg, Fg: want.fg, Glyph: want.glyph}}, m.width, m.baseline) v.cursorOp, v.cursorFor = paint.NewImageOp(img), want v.cursorOp.Filter = paint.FilterNearest } off := op.Offset(cell.Min).Push(gtx.Ops) area := clip.Rect{Max: cell.Size()}.Push(gtx.Ops) v.cursorOp.Add(gtx.Ops) paint.PaintOp{}.Add(gtx.Ops) area.Pop() off.Pop()}
func fillRect(gtx layout.Context, c color.NRGBA, r image.Rectangle) { paint.FillShape(gtx.Ops, c, clip.Rect(r).Op())}
// strokeRect outlines r with lines w pixels wide, inside r.func strokeRect(gtx layout.Context, c color.NRGBA, r image.Rectangle, w int) { fillRect(gtx, c, image.Rect(r.Min.X, r.Min.Y, r.Max.X, r.Min.Y+w)) fillRect(gtx, c, image.Rect(r.Min.X, r.Max.Y-w, r.Max.X, r.Max.Y)) fillRect(gtx, c, image.Rect(r.Min.X, r.Min.Y, r.Min.X+w, r.Max.Y)) fillRect(gtx, c, image.Rect(r.Max.X-w, r.Min.Y, r.Max.X, r.Max.Y))}
func rgb(c libghostty.ColorRGB) color.NRGBA { return color.NRGBA{R: c.R, G: c.G, B: c.B, A: 0xff}}