diff --git a/README.md b/README.md index 4671bd4..dea8543 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,10 @@ Other settings: standard input, for example `"claude -p --model sonnet"` - `diff_signs`: `true` marks changed lines with `+` and `-`, in place of a coloured bar - `cursor_line`: `false` turns off the tint of the line at the cursor +- `renderer`: `"kitty"` draws the screen as pictures with the kitty graphics + protocol, which Rex supports. A line changes at once, so the screen does not + flicker, and box lines join with no gap. The keys and the mouse work the + same. The default is `"text"` - `review_prefix` - `url_opener` - `focus_agent_after_send` diff --git a/cmd/rexdiff/install.go b/cmd/rexdiff/install.go index 317d64e..095f782 100644 --- a/cmd/rexdiff/install.go +++ b/cmd/rexdiff/install.go @@ -45,6 +45,7 @@ local settings = { -- placement = "split", -- split, zoomed, tab, or overlay -- layout = "unified", -- split (side by side when it fits) or unified -- guide_agent = "claude -p", -- the agent that writes the Guide tab + -- renderer = "kitty", -- draw with the kitty graphics protocol, with no flicker } ` diff --git a/go.mod b/go.mod index ebcdfe0..132428c 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,8 @@ require ( github.com/charmbracelet/x/ansi v0.11.9 github.com/rogpeppe/go-internal v1.16.0 github.com/sahilm/fuzzy v0.1.3 + golang.org/x/image v0.48.0 + golang.org/x/sys v0.50.0 ) require ( @@ -35,9 +37,8 @@ require ( github.com/xo/terminfo v1.0.0 // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect - golang.org/x/net v0.42.0 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.27.0 // indirect - golang.org/x/tools v0.35.0 // indirect + golang.org/x/net v0.61.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/text v0.44.0 // indirect + golang.org/x/tools v0.52.0 // indirect ) diff --git a/go.sum b/go.sum index b925765..b5d48f2 100644 --- a/go.sum +++ b/go.sum @@ -71,13 +71,15 @@ github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= -golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= -golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= -golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= -golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= -golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik= +golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= diff --git a/tui/config.go b/tui/config.go index f45499e..e5cc516 100644 --- a/tui/config.go +++ b/tui/config.go @@ -38,6 +38,14 @@ const ( markdownViewRendered markdownView = "rendered" ) +// renderer tells how rexdiff draws the screen. +type renderer string + +const ( + rendererText renderer = "text" // the cells of the terminal + rendererKitty renderer = "kitty" // pictures, with the kitty graphics protocol +) + // position is a side of the screen. type position string @@ -52,6 +60,7 @@ var ( configScopes = []Scope{ScopeUncommitted, ScopeBranch, ScopeLastTurn} markdownViews = []markdownView{markdownViewSource, markdownViewRendered} positions = []position{positionRight, positionLeft} + renderers = []renderer{rendererText, rendererKitty} ) // config holds the settings of rexdiff. The settings are at the top of @@ -81,6 +90,10 @@ type config struct { DiffSigns bool `json:"diff_signs"` // CursorLine tints the background of the line at the cursor. CursorLine bool `json:"cursor_line"` + // Renderer draws the screen as text, or as pictures with the kitty + // graphics protocol. The pictures change a whole line at once, so the + // screen does not flicker. + Renderer renderer `json:"renderer"` // FocusAgent tells if the focus moves to the agent after a send. Nil // means true. FocusAgent *bool `json:"focus_agent_after_send"` @@ -168,6 +181,7 @@ func defaultConfig() config { FileList: positionRight, FileListWidth: 32, CursorLine: true, + Renderer: rendererText, } } @@ -260,6 +274,7 @@ func (c config) checkChoices() error { {"default_scope", string(c.DefaultScope), names(configScopes...)}, {"markdown_view", string(c.MarkdownView), names(markdownViews...)}, {"file_list", string(c.FileList), names(positions...)}, + {"renderer", string(c.Renderer), names(renderers...)}, } for _, k := range choices { if !slices.Contains(k.allowed, k.value) { diff --git a/tui/kitty.go b/tui/kitty.go new file mode 100644 index 0000000..7e33b00 --- /dev/null +++ b/tui/kitty.go @@ -0,0 +1,393 @@ +package tui + +import ( + "bytes" + "compress/zlib" + "encoding/base64" + "fmt" + "image" + "image/color" + "os" + "strconv" + "sync" + "sync/atomic" + "time" + + tea "charm.land/bubbletea/v2" + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" + "golang.org/x/sys/unix" +) + +// The kitty renderer draws each line of the screen as a picture with the +// kitty graphics protocol, over the text that Bubble Tea draws. A line that +// changes gets a new picture, which replaces the old one at once, so the +// screen does not flicker. A line keeps its picture while it scrolls, so a +// scroll sends only the lines that come into view. +// +// The keys, the mouse, and the text of the pane work as in the text +// renderer: the text is still there, under the pictures. + +// ttyOut is the terminal of Bubble Tea in the kitty renderer. It writes the +// pictures of a frame after the text of that frame. A clear of the screen in +// the text, as after a resize, then cannot delete the new pictures. +// +// The pictures are only on the alternate screen. Before Bubble Tea leaves +// it, to quit or to run an editor, ttyOut deletes them, or they would cover +// the shell. Until Bubble Tea comes back, the pictures wait. +// +// A terminal that reads slowly blocks a write. The writes hold wmu, and +// queue takes only mu, so a frame that waits for the terminal does not stop +// the program: the keys still work, and q still quits. +type ttyOut struct { + *os.File + wmu sync.Mutex // orders the writes to the terminal + mu sync.Mutex // guards the fields below + pending []byte + timer *time.Timer + away bool // Bubble Tea left the alternate screen + leaves int // how many times Bubble Tea left it +} + +// pictureWait is how long the pictures of a frame wait for the text of the +// frame. A frame with no new text does not come, so the pictures then go +// by themselves. +const pictureWait = 50 * time.Millisecond + +// deleteAll deletes all the pictures on the screen and their data. +const deleteAll = "\x1b_Ga=d,d=A,q=2\x1b\\" + +// Write writes p, the output of Bubble Tea, and then the pictures that wait. +func (o *ttyOut) Write(p []byte) (int, error) { + o.wmu.Lock() + defer o.wmu.Unlock() + o.mu.Lock() + leaving := !o.away && bytes.Contains(p, []byte(ansi.ResetModeAltScreenSaveCursor)) + if leaving { + o.away, o.leaves, o.pending = true, o.leaves+1, nil + } + if bytes.Contains(p, []byte(ansi.SetModeAltScreenSaveCursor)) { + o.away = false + } + var pictures []byte + if !o.away { + pictures, o.pending = o.pending, nil + } + o.mu.Unlock() + + if leaving { + if _, err := o.WriteString(deleteAll); err != nil { + return 0, err + } + } + n, err := o.File.Write(p) + if err == nil && len(pictures) > 0 { + _, err = o.File.Write(pictures) + } + return n, err +} + +// left returns how many times Bubble Tea left the alternate screen. The +// pictures are gone after each time. +func (o *ttyOut) left() int { + o.mu.Lock() + defer o.mu.Unlock() + return o.leaves +} + +// queue keeps b until the next write of Bubble Tea, or for pictureWait. +func (o *ttyOut) queue(b []byte) { + o.mu.Lock() + defer o.mu.Unlock() + o.pending = append(o.pending, b...) + if o.timer == nil { + o.timer = time.AfterFunc(pictureWait, o.flush) + } else { + o.timer.Reset(pictureWait) + } +} + +func (o *ttyOut) flush() { + o.wmu.Lock() + defer o.wmu.Unlock() + o.mu.Lock() + var pictures []byte + if !o.away { + pictures, o.pending = o.pending, nil + } + o.mu.Unlock() + if len(pictures) > 0 { + _, _ = o.File.Write(pictures) + } +} + +// kittyScreen keeps the pictures in the terminal. Each picture is a line +// of the screen. Its kitty image ID comes from ids, and a placement shows it +// on row y with the placement ID y+1. +type kittyScreen struct { + out *ttyOut + pal palette + raster *raster + cols, rows int + cw, ch int // the cell in pixels, or 0 to ask the terminal + scr uv.ScreenBuffer // the cells of the last frame, kept for the next + last string // the content of the last frame + lastCursor image.Point // the cursor of the last frame, or -1, -1 + stale bool // draw all the lines again + settled atomic.Bool // no colour changed for colorSettle + settle *time.Timer // sets settled after a change of a colour + wake func() // makes the program draw, or nil + leaves int // ttyOut.left when the pictures were drawn + placed []uint32 // the image on each row, or 0 + ids map[string]uint32 // the image of each line, by its text and cursor + next uint32 // the last image ID +} + +// kittyWakeMsg makes the program draw the screen when its colours settle. +// Update has nothing to do for it. +type kittyWakeMsg struct{} + +// colorSettle is how long the pictures wait after a colour changes. The +// terminal answers the questions for its colours one by one, and each answer +// changes the pictures of all the lines: they wait for the last one. +const colorSettle = 150 * time.Millisecond + +// newKittyScreen makes a screen that draws on out. wake, if not nil, makes +// the program draw: it sends a message to the program. The screen draws +// after colorSettle, when the terminal had time to give its colours. +func newKittyScreen(out *ttyOut, wake func()) *kittyScreen { + k := &kittyScreen{out: out, wake: wake} + k.settle = time.AfterFunc(colorSettle, k.settleDone) + k.pal.fg = color.RGBA{0xdd, 0xdd, 0xdd, 0xff} + k.pal.bg = color.RGBA{0x1d, 0x1f, 0x21, 0xff} + for i := range k.pal.ansi { + r, g, b, _ := ansi.BasicColor(i).RGBA() + k.pal.ansi[i] = color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), 0xff} + } + return k +} + +// requestKittyPalette asks the terminal for its 16 ANSI colours, which the +// pictures use for the cells in those colours. +func requestKittyPalette() tea.Msg { + var b []byte + for i := range 16 { + b = fmt.Appendf(b, "\x1b]4;%d;?\x07", i) + } + return tea.RawMsg{Msg: string(b)} +} + +// setColor sets the colour of the text (fg), the background (bg), or ANSI +// colour i, from 0 to 15. A nil colour keeps the colour. +func (k *kittyScreen) setColor(c *color.RGBA, to color.Color) { + if to == nil { + return + } + r, g, b, _ := to.RGBA() + rgba := color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), 0xff} + if *c != rgba { + *c = rgba + k.stale = true + k.settled.Store(false) + k.settle.Reset(colorSettle) + } +} + +// resized tells the screen that the terminal changed its size. The cells +// can change their pixels and not their number, as on a move to a display +// of another scale. +func (k *kittyScreen) resized() { k.cw, k.ch = 0, 0 } + +// redraw draws all the lines again on the next frame. The terminal can lose +// the pictures of a pane that the user does not look at. +func (k *kittyScreen) redraw() { k.stale = true } + +// settleDone lets the screen draw in the colours that it has now. +func (k *kittyScreen) settleDone() { + k.settled.Store(true) + if k.wake != nil { + k.wake() + } +} + +// colors sets the default colours of the cells. +func (k *kittyScreen) colors(fg, bg color.Color) { + k.setColor(&k.pal.fg, fg) + k.setColor(&k.pal.bg, bg) +} + +// setANSI sets ANSI colour i from a reply of the terminal. +func (k *kittyScreen) setANSI(i int, c color.Color) { + if 0 <= i && i < len(k.pal.ansi) { + k.setColor(&k.pal.ansi[i], c) + } +} + +// cellPixels returns the size of a cell of the terminal in pixels. A +// terminal that does not tell gets the cells of a Retina Mac. The size +// only sets the sharpness: the terminal fits each picture to its cells. +func cellPixels(fd uintptr, cols, rows int) (cw, ch int) { + ws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ) + if err != nil || ws.Xpixel == 0 || ws.Ypixel == 0 || cols <= 0 || rows <= 0 { + return 16, 34 + } + return max(int(ws.Xpixel)/cols, 1), max(int(ws.Ypixel)/rows, 1) +} + +// draw shows content, a screen of cols by rows cells, with a cursor at +// cursor, if it is not nil. It sends only the lines that changed. +func (k *kittyScreen) draw(content string, cols, rows int, cursor *tea.Cursor) { + if cols <= 0 || rows <= 0 || !k.settled.Load() { + return + } + var b bytes.Buffer + // Synchronized output: the terminal shows all the changes at once. Save + // the cursor, for Bubble Tea moves it from where it left it. + b.WriteString("\x1b[?2026h\x1b7") + if k.cw == 0 || cols != k.cols || rows != k.rows { + // Only a resize changes the cells. Asking each frame costs a + // system call. + k.cw, k.ch = cellPixels(k.out.Fd(), cols, rows) + } + cw, ch := k.cw, k.ch + if k.raster == nil || k.raster.cw != cw || k.raster.ch != ch { + k.raster = newRaster(cw, ch) + k.stale = true + } + if leaves := k.out.left(); leaves != k.leaves { + k.leaves, k.stale = leaves, true + } + if k.stale || cols != k.cols || rows != k.rows { + b.WriteString(deleteAll) + k.cols, k.rows, k.stale = cols, rows, false + k.placed, k.ids = make([]uint32, rows), map[string]uint32{} + k.last = "" + } + // Most messages, such as the tick of each second, change nothing. + at := image.Pt(-1, -1) + if cursor != nil { + at = image.Pt(cursor.X, cursor.Y) + } + if content == k.last && at == k.lastCursor { + return + } + k.last, k.lastCursor = content, at + + if k.scr.RenderBuffer == nil || k.scr.Width() != cols || k.scr.Height() != rows { + k.scr = uv.NewScreenBuffer(cols, rows) + } else { + k.scr.Clear() + } + scr := k.scr + uv.NewStyledString(content).Draw(scr, scr.Bounds()) + type picture struct { + y, cursor int + id uint32 + data []byte // the pixels, compressed + } + var news []*picture + keys := make([]string, rows) + for y := range rows { + cx := -1 + if cursor != nil && cursor.Y == y { + cx = cursor.X + } + keys[y] = scr.Line(y).Render() + "\x00" + strconv.Itoa(cx) + if _, ok := k.ids[keys[y]]; !ok { + k.next++ + k.ids[keys[y]] = k.next + news = append(news, &picture{y: y, cursor: cx, id: k.next}) + } + } + var wg sync.WaitGroup + for _, p := range news { + wg.Go(func() { p.data = k.raster.linePixels(scr.Line(p.y), &k.pal, p.cursor) }) + } + wg.Wait() + for _, p := range news { + upload(&b, p.id, p.data, cols*cw, ch) + } + changed := len(news) > 0 + for y, key := range keys { + changed = changed || k.placed[y] != k.ids[key] + } + if !changed { + return + } + // Place every row again, not only the rows that changed. Bubble Tea + // scrolls the text with scroll regions, and a terminal moves the + // pictures with the text, so a row with the same picture as before can + // have it on another row now. A placement with the same image and + // placement ID moves to where it is placed again. + for y, key := range keys { + id := k.ids[key] + if old := k.placed[y]; old != 0 && old != id { + fmt.Fprintf(&b, "\x1b_Ga=d,d=i,i=%d,p=%d,q=2\x1b\\", old, y+1) + } + // C=1 keeps the cursor still, so the last row does not scroll. + fmt.Fprintf(&b, "\x1b[%d;1H\x1b_Ga=p,i=%d,p=%d,c=%d,r=1,C=1,q=2\x1b\\", y+1, id, y+1, cols) + k.placed[y] = id + } + k.prune(&b) + b.WriteString("\x1b8\x1b[?2026l") + k.out.queue(b.Bytes()) +} + +// prune deletes the pictures that are not on the screen when there are +// many. The others stay for a scroll back. +func (k *kittyScreen) prune(b *bytes.Buffer) { + if len(k.ids) <= 2*k.rows { + return + } + shown := make(map[uint32]bool, len(k.placed)) + for _, id := range k.placed { + shown[id] = true + } + for key, id := range k.ids { + if !shown[id] { + fmt.Fprintf(b, "\x1b_Ga=d,d=I,i=%d,q=2\x1b\\", id) + delete(k.ids, key) + } + } +} + +// zlibWriters keeps the compressors of the pictures, which are large, for +// the next lines. +var zlibWriters sync.Pool + +// compress returns the pixels compressed with zlib, as o=z of the protocol +// wants them. It is a few times faster than PNG, which picks a filter for +// each row of pixels, and the terminal does not have to undo the filters. +func compress(pix []byte) []byte { + var b bytes.Buffer + zw, _ := zlibWriters.Get().(*zlib.Writer) + if zw == nil { + zw, _ = zlib.NewWriterLevel(&b, zlib.BestSpeed) // the level is valid + } else { + zw.Reset(&b) + } + _, _ = zw.Write(pix) // a bytes.Buffer does not fail + _ = zw.Close() + zlibWriters.Put(zw) + return b.Bytes() +} + +// upload sends a picture of w by h RGBA pixels, compressed with zlib, as +// image id, in the chunks of the protocol. +func upload(b *bytes.Buffer, id uint32, data []byte, w, h int) { + s := base64.StdEncoding.EncodeToString(data) + const chunk = 4096 + for i := 0; i < len(s); i += chunk { + end := min(i+chunk, len(s)) + more := 0 + if end < len(s) { + more = 1 + } + if i == 0 { + fmt.Fprintf(b, "\x1b_Ga=t,f=32,o=z,s=%d,v=%d,i=%d,q=2,m=%d;%s\x1b\\", + w, h, id, more, s[i:end]) + } else { + fmt.Fprintf(b, "\x1b_Gm=%d;%s\x1b\\", more, s[i:end]) + } + } +} diff --git a/tui/kitty_test.go b/tui/kitty_test.go new file mode 100644 index 0000000..4b986fd --- /dev/null +++ b/tui/kitty_test.go @@ -0,0 +1,230 @@ +package tui + +import ( + "fmt" + "image/color" + "os" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +// testOut returns a ttyOut on a file, and a function that sends what the +// timer would send and returns all that went to the file since the last +// call. +func testOut(t *testing.T) (*ttyOut, func() string) { + t.Helper() + f, err := os.CreateTemp(t.TempDir(), "tty") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.Close() }) + out := &ttyOut{File: f} + seen := 0 + return out, func() string { + out.flush() + b, err := os.ReadFile(f.Name()) + if err != nil { + t.Fatal(err) + } + s := string(b[seen:]) + seen = len(b) + return s + } +} + +// TestKittyDrawSendsOnlyNewLines checks that a scroll by one line uploads +// one picture and moves the others, and that the same screen sends nothing. +func TestKittyDrawSendsOnlyNewLines(t *testing.T) { + out, sent := testOut(t) + k := newKittyScreen(out, nil) + k.settled.Store(true) + k.draw("a\nb\nc", 3, 3, nil) + if got := strings.Count(sent(), "a=t,"); got != 3 { + t.Fatalf("first frame: %d uploads, want 3", got) + } + k.draw("a\nb\nc", 3, 3, nil) + if got := sent(); got != "" { + t.Fatalf("same frame sent %q", got) + } + k.draw("b\nc\nd", 3, 3, nil) + s := sent() + if got := strings.Count(s, "a=t,"); got != 1 { + t.Fatalf("scroll: %d uploads, want 1", got) + } + if got := strings.Count(s, "a=p,"); got != 3 { + t.Fatalf("scroll: %d placements, want 3", got) + } + k.draw("b\nc\nd", 4, 3, nil) // a resize draws all again + if s := sent(); !strings.Contains(s, "d=A") || strings.Count(s, "a=t,") != 3 { + t.Fatalf("resize did not draw again: %q", s) + } +} + +// TestKittyLeaveAltScreen checks that the pictures go before Bubble Tea +// leaves the alternate screen, to quit or to run an editor, that no picture +// goes to the shell, and that the pictures come back with the program. +func TestKittyLeaveAltScreen(t *testing.T) { + out, sent := testOut(t) + k := newKittyScreen(out, nil) + k.settled.Store(true) + + k.draw("a", 1, 1, nil) + _, _ = out.Write([]byte("frame")) + k.draw("b", 1, 1, nil) // the last frame + _, _ = out.Write([]byte("bye" + ansi.ResetModeAltScreenSaveCursor)) + got := sent() + leave := strings.Index(got, "bye") + if del := strings.LastIndex(got, deleteAll); del < 0 || del > leave { + t.Fatalf("no delete before leaving: %q", got) + } + if strings.Contains(got[leave:], "a=p,") { + t.Fatalf("a picture after leaving: %q", got[leave:]) + } + k.draw("c", 1, 1, nil) // a frame after leaving + if strings.Contains(sent(), "a=p,") { + t.Fatal("a picture went to the shell") + } + + k.draw("c", 1, 1, nil) // after the editor: draw all again + _, _ = out.Write([]byte(ansi.SetModeAltScreenSaveCursor + "back")) + got = sent() + if back := strings.Index(got, "back"); back < 0 || !strings.Contains(got[back:], "a=p,") { + t.Fatalf("no picture after coming back: %q", got) + } +} + +// TestKittyColorsSettle checks that the answers of the terminal for its +// colours, which come one by one, make one new drawing and not one each. +func TestKittyColorsSettle(t *testing.T) { + out, sent := testOut(t) + woke := make(chan struct{}, 1) + k := newKittyScreen(out, func() { woke <- struct{}{} }) + <-woke + k.draw("a", 1, 1, nil) + sent() + for i := range 16 { + k.setANSI(i, color.RGBA{uint8(i), 0, 0, 0xff}) + k.draw("a", 1, 1, nil) + } + if s := sent(); s != "" { + t.Fatalf("drew before the colours settled: %q", s) + } + <-woke + k.draw("a", 1, 1, nil) + if n := strings.Count(sent(), "a=t,"); n != 1 { + t.Fatalf("%d uploads after the colours settled, want 1", n) + } +} + +// TestKittyPlacesAllRowsAgain checks that a frame with a change places the +// rows that did not change too. A scroll region of Bubble Tea moves their +// pictures in the terminal, so they must go back to their rows. Only the +// row that changed deletes its old picture. +func TestKittyPlacesAllRowsAgain(t *testing.T) { + out, sent := testOut(t) + k := newKittyScreen(out, nil) + k.settled.Store(true) + k.draw("x\nx\na", 1, 3, nil) + sent() + k.draw("x\nx\nb", 1, 3, nil) + s := sent() + for y := 1; y <= 3; y++ { + if !strings.Contains(s, fmt.Sprintf("\x1b[%d;1H\x1b_Ga=p,", y)) { + t.Errorf("row %d not placed again: %q", y, s) + } + } + if n := strings.Count(s, "a=d,d=i,"); n != 1 { + t.Errorf("%d placements deleted, want 1: %q", n, s) + } +} + +// BenchmarkKittyMove moves the cursor down a large file on a large screen +// in the kitty renderer, as a user does with j. Each frame changes a few +// lines. Profile it with: +// +// go test ./tui -run '^$' -bench KittyMove -cpuprofile cpu.out +func BenchmarkKittyMove(b *testing.B) { + benchKitty(b, tea.KeyPressMsg{Code: 'j', Text: "j"}) +} + +// BenchmarkKittyRedraw draws a screen of 200 by 60 cells whose lines all +// change in each frame, as after a jump to another file. +func BenchmarkKittyRedraw(b *testing.B) { + null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + b.Fatal(err) + } + defer null.Close() + k := newKittyScreen(&ttyOut{File: null}, nil) + k.settled.Store(true) + line := lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Background(lipgloss.Color("#1d2b1f")) + n := 0 + for b.Loop() { + var s strings.Builder + for y := range 60 { + n++ + s.WriteString(line.Width(200).Render(fmt.Sprintf("%6d x := compute(%d) // 日本語", n, y)) + "\n") + } + k.draw(s.String(), 200, 60, nil) + k.out.flush() + } +} + +func benchKitty(b *testing.B, key tea.KeyPressMsg) { + m, dir := newTestModel(b) + var src strings.Builder + for i := range 5000 { + src.WriteString("\tx := compute(" + strings.Repeat("a", i%40) + ") // 日本語\n") + } + write(b, dir, "big.go", "package a\nfunc f() {\n"+src.String()+"}\n") + m.reload() + m.pickFile(1) + m = step(b, m, tea.WindowSizeMsg{Width: 200, Height: 60}) + null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + b.Fatal(err) + } + defer null.Close() + m.kitty = newKittyScreen(&ttyOut{File: null}, nil) + m.kitty.settled.Store(true) + _ = m.View() + for b.Loop() { + next, _ := m.Update(key) + m = *next.(*model) + _ = m.View() + m.kitty.out.flush() + } +} + +// TestKittyRedrawAndResize checks that a focus draws all the lines again, +// for the terminal can lose the pictures of a pane that is not seen, and +// that a resize asks the terminal for the pixels of a cell again, though +// the columns and the rows stay. +func TestKittyRedrawAndResize(t *testing.T) { + out, sent := testOut(t) + k := newKittyScreen(out, nil) + k.settled.Store(true) + k.draw("a\nb", 1, 2, nil) + sent() + + k.redraw() + k.draw("a\nb", 1, 2, nil) + if s := sent(); !strings.Contains(s, deleteAll) || strings.Count(s, "a=t,") != 2 { + t.Fatalf("a focus did not draw all again: %q", s) + } + + k.cw, k.ch = 8, 17 // as on a display of another scale + k.raster = newRaster(8, 17) + k.resized() + k.draw("a\nb", 1, 2, nil) + if k.cw == 8 { + t.Fatal("a resize did not ask the terminal for the cell again") + } + if s := sent(); strings.Count(s, "a=t,") != 2 { + t.Fatalf("new cells did not draw all again: %q", s) + } +} diff --git a/tui/model.go b/tui/model.go index 634acd1..cd3b361 100644 --- a/tui/model.go +++ b/tui/model.go @@ -234,6 +234,7 @@ type model struct { restartState string // the file of the state for the restart, or "" w, h int + kitty *kittyScreen // draws the screen as pictures, or nil for text bg, fg color.Color red color.Color // the ANSI red of the terminal, or nil green color.Color // the ANSI green of the terminal, or nil @@ -403,6 +404,9 @@ func tick(d time.Duration) tea.Cmd { func (m *model) Init() tea.Cmd { cmds := []tea.Cmd{tick(time.Second), m.loadPR()} cmds = append(cmds, requestColors...) + if m.kitty != nil { + cmds = append(cmds, requestKittyPalette) + } if m.rex != nil { cmds = append(cmds, m.listAgents(agentsMsg{})) } @@ -592,10 +596,16 @@ func (m *model) handle(msg tea.Msg) tea.Cmd { switch msg := msg.(type) { case tea.WindowSizeMsg: m.w, m.h = msg.Width, msg.Height + if m.kitty != nil { + m.kitty.resized() + } m.editor.SetWidth(max(m.mainWidth()-8, 20)) m.rerender() case tea.FocusMsg: m.focused = true + if m.kitty != nil { + m.kitty.redraw() + } m.reloadIfChanged() case tea.BlurMsg: m.focused = false @@ -777,6 +787,9 @@ func (m *model) onPalette(reply string) { if !ok { return } + if m.kitty != nil { + m.kitty.setANSI(i, c) + } switch { case i == 1 && !sameColor(m.red, c): m.red = c diff --git a/tui/raster.go b/tui/raster.go new file mode 100644 index 0000000..db9017d --- /dev/null +++ b/tui/raster.go @@ -0,0 +1,402 @@ +package tui + +import ( + "image" + "image/color" + "image/draw" + "math" + "os" + "sync" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" + "golang.org/x/image/font" + "golang.org/x/image/font/gofont/gomono" + "golang.org/x/image/font/gofont/gomonobold" + "golang.org/x/image/font/gofont/gomonobolditalic" + "golang.org/x/image/font/gofont/gomonoitalic" + "golang.org/x/image/font/opentype" + "golang.org/x/image/font/sfnt" + "golang.org/x/image/math/fixed" +) + +// The styles of a font, the index of fontFiles and of a chain. +const ( + styleRegular = iota + styleBold + styleItalic + styleBoldItalic +) + +// fontFiles are the monospace fonts for each style, the first that exists +// wins. SF Mono comes with Terminal on macOS. +var fontFiles = [4][]string{ + {"/System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts/SF-Mono-Regular.otf", + "/System/Library/Fonts/Menlo.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/TTF/DejaVuSansMono.ttf"}, + {"/System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts/SF-Mono-Bold.otf", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", + "/usr/share/fonts/TTF/DejaVuSansMono-Bold.ttf"}, + {"/System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts/SF-Mono-RegularItalic.otf", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Oblique.ttf", + "/usr/share/fonts/TTF/DejaVuSansMono-Oblique.ttf"}, + {"/System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts/SF-Mono-BoldItalic.otf", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-BoldOblique.ttf", + "/usr/share/fonts/TTF/DejaVuSansMono-BoldOblique.ttf"}, +} + +// fallbackFiles have the glyphs that the monospace fonts lack: symbols, and +// Japanese and Chinese text. +var fallbackFiles = []string{ + "/System/Library/Fonts/Menlo.ttc", + "/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc", + "/System/Library/Fonts/Apple Symbols.ttf", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", +} + +// goFonts are the last fonts of each chain. They are in the binary. +var goFonts = [4][]byte{gomono.TTF, gomonobold.TTF, gomonoitalic.TTF, gomonobolditalic.TTF} + +// fontChains are the fonts of each style, in the order of the search for a +// glyph. They load once, on the first frame. +var fontChains = sync.OnceValue(func() [4][]*sfnt.Font { + var fallbacks []*sfnt.Font + for _, p := range fallbackFiles { + if f := loadFontFile(p); f != nil { + fallbacks = append(fallbacks, f) + } + } + var chains [4][]*sfnt.Font + for s := range chains { + for _, p := range fontFiles[s] { + if f := loadFontFile(p); f != nil { + chains[s] = append(chains[s], f) + break + } + } + chains[s] = append(chains[s], fallbacks...) + f, _ := opentype.Parse(goFonts[s]) // the Go fonts parse + chains[s] = append(chains[s], f) + } + return chains +}) + +// loadFontFile returns the font in the file at p, the first font of a +// collection, or nil. +func loadFontFile(p string) *sfnt.Font { + data, err := os.ReadFile(p) + if err != nil { + return nil + } + if f, err := opentype.Parse(data); err == nil { + return f + } + c, err := opentype.ParseCollection(data) + if err != nil { + return nil + } + f, err := c.Font(0) + if err != nil { + return nil + } + return f +} + +// glyphKey names the picture of a cell's text. +type glyphKey struct { + text string + style int + width int // in cells +} + +// raster draws lines of cells in pixels. The cells are cw by ch pixels. +type raster struct { + cw, ch int + baseline int // from the top of a cell + thin int // the width of a line of a box + chains [4][]*sfnt.Font + faces [4][]font.Face + buf sfnt.Buffer + + mu sync.Mutex // guards the faces and glyphs, which rows share + glyphs map[glyphKey]*image.Alpha + lines sync.Pool // *image.RGBA of a line, for the next line +} + +// newRaster makes a raster for cells of cw by ch pixels. The font size +// makes the advance of the monospace font one cell, as in a terminal. +func newRaster(cw, ch int) *raster { + r := &raster{cw: cw, ch: ch, chains: fontChains(), glyphs: map[glyphKey]*image.Alpha{}} + r.thin = max(1, int(math.Round(float64(ch)/17))) + mono := r.chains[styleRegular][0] + upem := fixed.I(int(mono.UnitsPerEm())) + adv := 0.6 // of an em, if the font has no zero + if i, err := mono.GlyphIndex(&r.buf, '0'); err == nil && i != 0 { + if a, err := mono.GlyphAdvance(&r.buf, i, upem, font.HintingNone); err == nil { + adv = float64(a) / float64(upem) + } + } + m, _ := mono.Metrics(&r.buf, upem, font.HintingNone) + asc, desc := float64(m.Ascent)/float64(upem), float64(m.Descent)/float64(upem) + size := min(float64(cw)/adv, float64(ch)/max(asc+desc, 1)) + r.baseline = int(math.Round((float64(ch)-(asc+desc)*size)/2 + asc*size)) + for s, chain := range r.chains { + for _, f := range chain { + face, _ := opentype.NewFace(f, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingNone}) + r.faces[s] = append(r.faces[s], face) + } + } + return r +} + +// palette resolves the colours of cells. +type palette struct { + fg, bg color.RGBA + ansi [16]color.RGBA +} + +// rgba returns c in the colours of the terminal, or def if c is nil. +func (p *palette) rgba(c color.Color, def color.RGBA) color.RGBA { + switch c := c.(type) { + case nil: + return def + case ansi.BasicColor: + return p.ansi[c&15] + case ansi.IndexedColor: + if c < 16 { + return p.ansi[c] + } + } + r, g, b, _ := c.RGBA() + return color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), 0xff} +} + +// colors returns the text and the background colours of a cell. +func (p *palette) colors(s uv.Style) (fg, bg color.RGBA) { + fg, bg = p.rgba(s.Fg, p.fg), p.rgba(s.Bg, p.bg) + if s.Attrs&uv.AttrReverse != 0 { + fg, bg = bg, fg + } + if s.Attrs&uv.AttrFaint != 0 { + fg = mix(fg, bg, 0.5) + } + return fg, bg +} + +// mix returns a moved toward b by t, from 0 to 1. +func mix(a, b color.RGBA, t float64) color.RGBA { + m := func(x, y uint8) uint8 { return uint8(float64(x) + (float64(y)-float64(x))*t + 0.5) } + return color.RGBA{m(a.R, b.R), m(a.G, b.G), m(a.B, b.B), 0xff} +} + +// linePixels draws a line of cells, and returns its RGBA pixels compressed +// for the terminal. +func (r *raster) linePixels(cells uv.Line, p *palette, cursor int) []byte { + img, _ := r.lines.Get().(*image.RGBA) + if size := image.Rect(0, 0, len(cells)*r.cw, r.ch); img == nil || img.Rect != size { + img = image.NewRGBA(size) + } + r.draw(img, cells, p, cursor) + data := compress(img.Pix) + r.lines.Put(img) + return data +} + +// draw draws a line of cells on img, a picture of the size of the line, +// over all of its pixels. cursor is the column of a cursor to draw, or -1. +func (r *raster) draw(img *image.RGBA, cells uv.Line, p *palette, cursor int) { + for x := 0; x < len(cells); { + c := cells[x] + w := max(c.Width, 1) + fg, bg := p.colors(c.Style) + rect := image.Rect(x*r.cw, 0, min(x+w, len(cells))*r.cw, r.ch) + draw.Draw(img, rect, image.NewUniform(bg), image.Point{}, draw.Src) + if c.Style.Attrs&uv.AttrConceal == 0 { + r.cell(img, rect, c, fg) + } + x += w + } + if cursor >= 0 && cursor < len(cells) { + bar := image.Rect(cursor*r.cw, 0, cursor*r.cw+2*r.thin, r.ch) + draw.Draw(img, bar, image.NewUniform(p.fg), image.Point{}, draw.Src) + } +} + +// cell draws the text and the lines of one cell in rect. +func (r *raster) cell(img *image.RGBA, rect image.Rectangle, c uv.Cell, fg color.RGBA) { + ink := image.NewUniform(fg) + if rs := []rune(c.Content); len(rs) == 1 && r.shape(img, rect, rs[0], ink) { + // drawn as a shape + } else if c.Content != "" && c.Content != " " { + style := styleRegular + if c.Style.Attrs&uv.AttrBold != 0 { + style |= styleBold + } + if c.Style.Attrs&uv.AttrItalic != 0 { + style |= styleItalic + } + if mask := r.glyph(glyphKey{c.Content, style, max(c.Width, 1)}); mask != nil { + draw.DrawMask(img, rect, ink, image.Point{}, mask, image.Point{}, draw.Over) + } + } + if c.Style.Underline != uv.UnderlineNone { + y := min(r.baseline+r.thin, r.ch-r.thin) + uc := image.NewUniform(fg) + if c.Style.UnderlineColor != nil { + cr, cg, cb, _ := c.Style.UnderlineColor.RGBA() + uc = image.NewUniform(color.RGBA{uint8(cr >> 8), uint8(cg >> 8), uint8(cb >> 8), 0xff}) + } + draw.Draw(img, image.Rect(rect.Min.X, y, rect.Max.X, y+r.thin), uc, image.Point{}, draw.Src) + } + if c.Style.Attrs&uv.AttrStrikethrough != 0 { + y := r.baseline - r.ch*3/10 + draw.Draw(img, image.Rect(rect.Min.X, y, rect.Max.X, y+r.thin), ink, image.Point{}, draw.Src) + } +} + +// glyph returns the coverage of the text of a cell, or nil for none. The +// text is in the middle of its cells. A font that lacks the first rune +// gives the next font of the chain the text. +func (r *raster) glyph(k glyphKey) *image.Alpha { + r.mu.Lock() + defer r.mu.Unlock() + if m, ok := r.glyphs[k]; ok { + return m + } + first := []rune(k.text)[0] + chain := r.chains[k.style] + face := r.faces[k.style][len(chain)-1] + for i, f := range chain { + if g, err := f.GlyphIndex(&r.buf, first); err == nil && g != 0 { + face = r.faces[k.style][i] + break + } + } + m := image.NewAlpha(image.Rect(0, 0, k.width*r.cw, r.ch)) + d := font.Drawer{Dst: m, Src: image.Opaque, Face: face} + adv := d.MeasureString(k.text) + d.Dot = fixed.Point26_6{X: max(fixed.I(k.width*r.cw)-adv, 0) / 2, Y: fixed.I(r.baseline)} + d.DrawString(k.text) + r.glyphs[k] = m + return m +} + +// The arms of a box line, from the middle of the cell to an edge. +const ( + armUp = 1 << iota + armDown + armLeft + armRight + heavy // the arms are thick +) + +// boxArms are the box lines that rexdiff draws. They join the next cells +// with no gap, which a font does not do. +var boxArms = map[rune]int{ + '─': armLeft | armRight, '━': armLeft | armRight | heavy, + '│': armUp | armDown, '┃': armUp | armDown | heavy, + '┌': armRight | armDown, '┐': armLeft | armDown, + '└': armUp | armRight, '┘': armUp | armLeft, + '├': armUp | armDown | armRight, '┤': armUp | armDown | armLeft, + '┬': armLeft | armRight | armDown, '┴': armLeft | armRight | armUp, + '┼': armUp | armDown | armLeft | armRight, +} + +// roundCorners are the arms of the round corners of a box. +var roundCorners = map[rune]int{ + '╭': armRight | armDown, '╮': armLeft | armDown, + '╰': armUp | armRight, '╯': armUp | armLeft, +} + +// shape draws a box line or a block in rect, and reports whether ch is one. +func (r *raster) shape(img *image.RGBA, rect image.Rectangle, ch rune, ink image.Image) bool { + x0, y0, w, h := rect.Min.X, rect.Min.Y, r.cw, r.ch + fill := func(x1, y1, x2, y2 int) { + draw.Draw(img, image.Rect(x1, y1, x2, y2).Intersect(rect), ink, image.Point{}, draw.Src) + } + switch { + case 0x2581 <= ch && ch <= 0x2588: // lower eighths, to the full block + fill(x0, y0+h-h*int(ch-0x2580)/8, x0+w, y0+h) + case 0x2589 <= ch && ch <= 0x258f: // left eighths + fill(x0, y0, x0+w*int(0x2590-ch)/8, y0+h) + case ch == '▀': + fill(x0, y0, x0+w, y0+h/2) + case ch == '▐': + fill(x0+w/2, y0, x0+w, y0+h) + case ch == '▔': + fill(x0, y0, x0+w, y0+h/8) + case ch == '▕': + fill(x0+w-w/8, y0, x0+w, y0+h) + default: + arms, ok := boxArms[ch] + round, isRound := roundCorners[ch] + if !ok && !isRound { + return false + } + t := r.thin + if arms&heavy != 0 { + t *= 2 + } + mx, my := x0+(w-t)/2, y0+(h-t)/2 // the top left of the middle + if isRound { + r.corner(img, rect, round, ink) + return true + } + if arms&armUp != 0 { + fill(mx, y0, mx+t, my+t) + } + if arms&armDown != 0 { + fill(mx, my, mx+t, y0+h) + } + if arms&armLeft != 0 { + fill(x0, my, mx+t, my+t) + } + if arms&armRight != 0 { + fill(mx, my, x0+w, my+t) + } + } + return true +} + +// corner draws a round corner: a quarter circle from the middle of the +// cell, and straight lines from it to the two edges of its arms. +func (r *raster) corner(img *image.RGBA, rect image.Rectangle, arms int, ink image.Image) { + t := float64(r.thin) + w, h := float64(r.cw), float64(r.ch) + cx, cy := w/2, h/2 // the middle of the line + rad := w / 2 + sx, sy := -1.0, -1.0 // where the centre of the circle is, from the middle + if arms&armRight != 0 { + sx = 1 + } + if arms&armDown != 0 { + sy = 1 + } + ox, oy := cx+sx*rad, cy+sy*rad // the centre of the circle + col := ink.At(0, 0) + cr, cg, cb, _ := col.RGBA() + for py := 0; py < r.ch; py++ { + for px := 0; px < r.cw; px++ { + x, y := float64(px)+0.5, float64(py)+0.5 + var cover float64 + switch { + case (x-ox)*sx > 0: // the straight arm left or right + cover = t/2 + 0.5 - math.Abs(y-cy) + case (y-oy)*sy > 0: // the straight arm up or down + cover = t/2 + 0.5 - math.Abs(x-cx) + default: + cover = t/2 + 0.5 - math.Abs(math.Hypot(x-ox, y-oy)-rad) + } + if cover <= 0 { + continue + } + a := min(cover, 1) + dst := img.RGBAAt(rect.Min.X+px, rect.Min.Y+py) + blend := func(d uint8, s uint32) uint8 { return uint8(float64(d)*(1-a) + float64(s>>8)*a + 0.5) } + img.SetRGBA(rect.Min.X+px, rect.Min.Y+py, color.RGBA{blend(dst.R, cr), blend(dst.G, cg), blend(dst.B, cb), 0xff}) + } + } +} diff --git a/tui/tui.go b/tui/tui.go index 6f66974..17dd2cd 100644 --- a/tui/tui.go +++ b/tui/tui.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log/slog" + "os" "slices" "strings" @@ -110,13 +111,24 @@ func Run(ctx context.Context, o Options) (resume string, err error) { m.log.Debug("set label", "err", err) } } - program := tea.NewProgram(&m, tea.WithContext(ctx)) + opts := []tea.ProgramOption{tea.WithContext(ctx)} + var out *ttyOut + if cfg.Renderer == rendererKitty { + out = &ttyOut{File: os.Stdout} + opts = append(opts, tea.WithOutput(out)) + } + program := tea.NewProgram(&m, opts...) + if out != nil { + // After NewProgram: the timer of the screen sends to program. + m.kitty = newKittyScreen(out, func() { program.Send(kittyWakeMsg{}) }) + } if o.Rex != nil { go o.Rex.Watch(ctx, func(e rex.Event) { program.Send(eventMsg(e)) }) } final, err := program.Run() if fm, ok := final.(*model); ok && err == nil { if fm.restartState != "" { + fm.kitty = nil // the pictures went when the program left the screen // Keep the last screen until the new rexdiff draws, so that // the restart does not show the shell of the pane. fmt.Print("\x1b[?1049h\x1b[?25l\x1b[H" + fm.View().Content) diff --git a/tui/view.go b/tui/view.go index 19e313c..cc12382 100644 --- a/tui/view.go +++ b/tui/view.go @@ -718,6 +718,10 @@ func (m *model) View() tea.View { v.ReportFocus = true v.ProgramStatus = m.programStatus() v.Cursor = caret + if m.kitty != nil { + m.kitty.colors(m.fg, m.bg) + m.kitty.draw(screen, m.w, m.h, caret) + } return v }