diff --git a/base/terminal/images.go b/base/terminal/images.go new file mode 100644 index 0000000000..51025a50b8 --- /dev/null +++ b/base/terminal/images.go @@ -0,0 +1,270 @@ +package terminal + +import ( + "image" + "image/draw" + "math" + "slices" + + "github.com/nsgo-dev/nsgo/base/terminal/internal/vt" + "github.com/nsgo-dev/nsgo/core" +) + +// graphic is a placement snapshot in canvas points, with source coordinates in image pixels. Pixels and placements advance together with the render state. +type graphic struct { + source core.ImageSource + imageID, placementID uint32 + z int32 + sx, sy, sw, sh, x, y, w, h float32 +} + +type graphicImage struct { + generation uint64 + source core.ImageSource +} + +// crop clips the destination and moves the source by the same fraction. +func (g graphic) crop(x, y, w, h float32) (graphic, bool) { + if g.w <= 0 || g.h <= 0 { + return g, false + } + x0, y0 := max(g.x, x), max(g.y, y) + x1, y1 := min(g.x+g.w, x+w), min(g.y+g.h, y+h) + if x1 <= x0 || y1 <= y0 { + return g, false + } + g.sx += (x0 - g.x) * g.sw / g.w + g.sy += (y0 - g.y) * g.sh / g.h + g.sw *= (x1 - x0) / g.w + g.sh *= (y1 - y0) / g.h + g.x, g.y, g.w, g.h = x0, y0, x1-x0, y1-y0 + return g, true +} + +// snapshotGraphics runs with Terminal.mu held, only when render state advances. +func (v *view) snapshotGraphics() { + t := v.t + if v.imageCache == nil { + v.imageCache = map[uint32]graphicImage{} + } + seen := map[uint32]bool{} + source := func(id uint32) (core.ImageSource, bool) { + gen := t.term.ImageGeneration(id) + if gen == 0 { + return core.ImageSource{}, false + } + seen[id] = true + cached, ok := v.imageCache[id] + if ok && cached.generation == gen { + return cached.source, true + } + img, ok := t.term.Image(id) + if !ok { + return core.ImageSource{}, false + } + var raw *image.NRGBA + if img.Format == vt.ImageRGBA { + raw = &image.NRGBA{Pix: img.Pixels, Stride: 4 * img.Width, Rect: image.Rect(0, 0, img.Width, img.Height)} + } else { + raw = decoded(img) + } + pixels := image.NewRGBA(raw.Rect) + draw.Draw(pixels, pixels.Rect, raw, image.Point{}, draw.Src) + src := core.ImageSource{Pixels: pixels, Version: gen, Size: core.Size{Width: core.Points(img.Width), Height: core.Points(img.Height)}} + v.imageCache[id] = graphicImage{gen, src} + return src, true + } + // Drop pixel references from placements that disappeared, including the unused tail of the reused backing array. + clear(v.graphics) + v.graphics = v.graphics[:0] + var virtual []vt.Placement + t.term.Placements(func(p vt.Placement) { + if p.Virtual { + virtual = append(virtual, p) + return + } + if !p.Visible { + return + } + src, ok := source(p.ImageID) + if !ok { + return + } + xoff, yoff, w, h := placementGeometry(p, v.cellW, v.cellH, v.ratio, t.size.cellW, t.size.cellH) + v.graphics = append(v.graphics, graphic{source: src, imageID: p.ImageID, placementID: p.ID, z: p.Z, + sx: float32(p.SrcX), sy: float32(p.SrcY), sw: float32(p.SrcW), sh: float32(p.SrcH), + x: v.padX + float32(p.Col)*v.cellW + xoff, + y: v.padY + float32(p.Row)*v.cellH + yoff, + w: w, h: h}) + }) + // Sort before choosing a virtual target without an explicit placement ID. + slices.SortFunc(virtual, func(a, b vt.Placement) int { return cmpID(a.ID, b.ID) }) + if len(virtual) > 0 { + rs := t.rs + rs.Rows() + for y := 0; rs.NextRow(); y++ { + var prev placeholder + previous := false + for x, c := range rs.RowCells() { + if c.Codepoint != kittyPlaceholder { + previous = false + continue + } + p := placeholderOf(rs.CellStyle(x), rs.CellGraphemes(x, nil)) + if previous && p.follows(prev) { + if p.row < 0 { + p.row = prev.row + } + if p.col < 0 { + p.col = prev.col + 1 + } + if p.high < 0 { + p.high = prev.high + } + } + p.row, p.col, p.high = max(p.row, 0), max(p.col, 0), max(p.high, 0) + prev, previous = p, true + id := p.low | uint32(p.high)<<24 + for _, pl := range virtual { + if pl.ImageID != id || p.placement != 0 && p.placement != pl.ID { + continue + } + src, ok := source(id) + if !ok { + break + } + iw, ih := float32(src.Size.Width), float32(src.Size.Height) + cols, rows := pl.ParamCols, pl.ParamRows + if cols == 0 { + cols = int(math.Ceil(float64(iw / (v.cellW * v.ratio)))) + } + if rows == 0 { + rows = int(math.Ceil(float64(ih / (v.cellH * v.ratio)))) + } + if cols <= 0 || rows <= 0 || p.col >= cols || p.row >= rows { + break + } + gw, gh := float32(cols)*v.cellW, float32(rows)*v.cellH + scale := min(gw/iw, gh/ih) + w, h := iw*scale, ih*scale + cx, cy := v.padX+float32(x)*v.cellW, v.padY+float32(y)*v.cellH + g := graphic{source: src, imageID: id, placementID: pl.ID, z: pl.Z, sw: iw, sh: ih, + x: cx - float32(p.col)*v.cellW + (gw-w)/2, y: cy - float32(p.row)*v.cellH + (gh-h)/2, w: w, h: h} + if g, ok = g.crop(cx, cy, v.cellW, v.cellH); ok { + v.graphics = append(v.graphics, g) + } + break + } + } + } + } + for id := range v.imageCache { + if !seen[id] { + delete(v.imageCache, id) + } + } + slices.SortStableFunc(v.graphics, func(a, b graphic) int { + if a.z < b.z { + return -1 + } + if a.z > b.z { + return 1 + } + if n := cmpID(a.imageID, b.imageID); n != 0 { + return n + } + return cmpID(a.placementID, b.placementID) + }) +} + +// placementGeometry keeps natural image pixels and offsets physical, but maps explicit cell counts to the actual fractional canvas grid. The VT API reports integral cell pixels; scaling its whole rectangle would stretch natural images. +func placementGeometry(p vt.Placement, cw, ch, ratio float32, cellW, cellH int) (xoff, yoff, w, h float32) { + xoff = float32(min(p.XOffset, max(cellW-1, 0))) / ratio + yoff = float32(min(p.YOffset, max(cellH-1, 0))) / ratio + w, h = float32(p.Width)/ratio, float32(p.Height)/ratio + if p.ParamCols > 0 { + w = max(float32(p.ParamCols)*cw-xoff, 0) + } + if p.ParamRows > 0 { + h = max(float32(p.ParamRows)*ch-yoff, 0) + } + if p.ParamCols > 0 && p.ParamRows == 0 && p.SrcW > 0 { + h = w * float32(p.SrcH) / float32(p.SrcW) + } + if p.ParamRows > 0 && p.ParamCols == 0 && p.SrcH > 0 { + w = h * float32(p.SrcW) / float32(p.SrcH) + } + return +} + +func cmpID(a, b uint32) int { + if a < b { + return -1 + } + if a > b { + return 1 + } + return 0 +} + +const kittyPlaceholder = '\U0010eeee' + +type placeholder struct { + low, placement uint32 + row, col, high int +} + +func placeholderOf(s vt.Style, graphemes []rune) placeholder { + p := placeholder{low: graphicID(s.FG), placement: graphicID(s.UnderlineColor), row: -1, col: -1, high: -1} + indices := []*int{&p.row, &p.col, &p.high} + if len(graphemes) > 0 && graphemes[0] == kittyPlaceholder { + graphemes = graphemes[1:] + } + for i, r := range graphemes { + if i >= len(indices) { + break + } + if at, ok := slices.BinarySearch(kittyDiacritics[:], r); ok && (i != 2 || at < 256) { + *indices[i] = at + } + } + return p +} + +func graphicID(c vt.Color) uint32 { + switch c.Kind { + case 1: + return uint32(c.Index) + case 2: + return uint32(c.RGB.R)<<16 | uint32(c.RGB.G)<<8 | uint32(c.RGB.B) + } + return 0 +} + +func (p placeholder) follows(prev placeholder) bool { + return p.low == prev.low && p.placement == prev.placement && (p.row < 0 || p.row == prev.row) && (p.col < 0 || p.col == prev.col+1) && (p.high < 0 || p.high == prev.high) +} + +// paintGraphics draws one of the protocol's three stacking layers. Negative images above backgrounds are clipped to each row so later row backgrounds cannot cover a preceding row's image. +func (f *frame) paintGraphics(layer, row int) { + v := f.v + x, y, w, h := v.padX, v.padY, float32(v.cols)*v.cellW, float32(v.rows)*v.cellH + if layer == 1 { + y += float32(row) * v.cellH + h = v.cellH + } + for _, g := range v.graphics { + l := 2 + if g.z < -1<<30 { + l = 0 + } else if g.z < 0 { + l = 1 + } + if l != layer { + continue + } + if g, ok := g.crop(x, y, w, h); ok { + f.d.DrawImageFrom(g.source, g.sx, g.sy, g.sw, g.sh, g.x, g.y, g.w, g.h) + } + } +} diff --git a/base/terminal/images_diacritics.go b/base/terminal/images_diacritics.go new file mode 100644 index 0000000000..e706d3e05e --- /dev/null +++ b/base/terminal/images_diacritics.go @@ -0,0 +1,30 @@ +package terminal + +// kittyDiacritics is the coordinate alphabet specified by the Kitty graphics protocol. Its order is stable protocol data, not Unicode sort order guessed at runtime. Source: https://sw.kovidgoyal.net/kitty/_downloads/f0a0de9ec8d9ff4456206db8e0814937/rowcolumn-diacritics.txt +var kittyDiacritics = [...]rune{ + 0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346, 0x034a, 0x034b, 0x034c, + 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369, + 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592, + 0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059c, 0x059d, 0x059e, 0x059f, 0x05a0, 0x05a1, + 0x05a8, 0x05a9, 0x05ab, 0x05ac, 0x05af, 0x05c4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615, + 0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065a, 0x065b, 0x065d, 0x065e, 0x06d6, 0x06d7, 0x06d8, + 0x06d9, 0x06da, 0x06db, 0x06dc, 0x06df, 0x06e0, 0x06e1, 0x06e2, 0x06e4, 0x06e7, 0x06e8, 0x06eb, + 0x06ec, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736, 0x073a, 0x073d, 0x073f, 0x0740, 0x0741, 0x0743, + 0x0745, 0x0747, 0x0749, 0x074a, 0x07eb, 0x07ec, 0x07ed, 0x07ee, 0x07ef, 0x07f0, 0x07f1, 0x07f3, + 0x0816, 0x0817, 0x0818, 0x0819, 0x081b, 0x081c, 0x081d, 0x081e, 0x081f, 0x0820, 0x0821, 0x0822, + 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082a, 0x082b, 0x082c, 0x082d, 0x0951, 0x0953, 0x0954, + 0x0f82, 0x0f83, 0x0f86, 0x0f87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76, + 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e, 0x1b6f, 0x1b70, 0x1b71, + 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda, 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4, + 0x1dc5, 0x1dc6, 0x1dc7, 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5, + 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde, 0x1ddf, 0x1de0, 0x1de1, + 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe, 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7, + 0x20db, 0x20dc, 0x20e1, 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2, + 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb, 0x2dec, 0x2ded, 0x2dee, + 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4, 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa, + 0x2dfb, 0x2dfc, 0x2dfd, 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1, + 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea, 0xa8eb, 0xa8ec, 0xa8ed, + 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2, 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1, + 0xfe20, 0xfe21, 0xfe22, 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186, 0x1d187, + 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242, 0x1d243, 0x1d244, +} diff --git a/base/terminal/images_test.go b/base/terminal/images_test.go new file mode 100644 index 0000000000..04992b332e --- /dev/null +++ b/base/terminal/images_test.go @@ -0,0 +1,354 @@ +package terminal + +import ( + "bytes" + "encoding/base64" + "fmt" + "github.com/nsgo-dev/nsgo/base/terminal/internal/vt" + "image" + stdcolor "image/color" + "image/png" + "math" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func kittyImage(id uint32, placement string, pixels ...byte) string { + return fmt.Sprintf("\x1b_Ga=T,f=32,s=2,v=2,i=%d,C=1,q=2%s;%s\x1b\\", id, placement, base64.StdEncoding.EncodeToString(pixels)) +} + +var redImage = []byte{255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255} +var greenImage = []byte{0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255} + +func graphicsView(t *testing.T, opts Options, theme *Theme) (*Terminal, *Ref, *nsgotest.App) { + t.Helper() + term := protocolTerminal(t, opts) + ref := &Ref{} + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return View{Terminal: term, Ref: ref, Theme: theme, DarkTheme: theme, TestID: "term", NoKeyBar: true, Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}} + }, nsgotest.Size(480, 240)) + term.Feed([]byte("\x1b[?25l")) + app.Settle() + return term, ref, app +} + +func canvasOps(t *testing.T, app *nsgotest.App) []driver.DrawOp { + t.Helper() + var find func(*nsgotest.View) []driver.DrawOp + find = func(v *nsgotest.View) []driver.DrawOp { + if v.Drawing != nil { + return v.Ops + } + for _, c := range v.Children { + if ops := find(c); ops != nil { + return ops + } + } + return nil + } + ops := find(app.Find("id:term")) + if ops == nil { + t.Fatal("terminal canvas missing") + } + return ops +} + +func imageOps(t *testing.T, app *nsgotest.App) []driver.DrawOp { + var out []driver.DrawOp + for _, op := range canvasOps(t, app) { + if op.Kind == driver.DrawImage { + out = append(out, op) + } + } + return out +} + +func TestTerminalGraphicsLifecycle(t *testing.T) { + term, ref, app := graphicsView(t, Options{}, nil) + term.Feed([]byte(kittyImage(7, ",c=4,r=2", redImage...))) + app.Settle() + ops := imageOps(t, app) + if len(ops) != 1 { + t.Fatalf("image ops %d, want 1", len(ops)) + } + first := ops[0].Image.Pixels + if got := first.RGBAAt(0, 0); got != (stdcolor.RGBA{255, 0, 0, 255}) { + t.Fatalf("pixels %v", got) + } + if ops[0].W != 4*ref.v.cellW || ops[0].H != 2*ref.v.cellH { + t.Fatalf("image size %v×%v", ops[0].W, ops[0].H) + } + // A synchronized update holds the exact image snapshot, then releases new pixels. + term.Feed([]byte("\x1b[?2026h" + kittyImage(7, ",c=4,r=2", greenImage...))) + app.Settle() + if got := imageOps(t, app)[0].Image.Pixels; got != first { + t.Fatal("image changed during synchronized update") + } + term.Feed([]byte("\x1b[?2026l")) + app.Settle() + second := imageOps(t, app)[0].Image.Pixels + if second == first || second.RGBAAt(0, 0) != (stdcolor.RGBA{0, 255, 0, 255}) { + t.Fatal("replacement did not show") + } + // Unchanged generations reuse the same decoded source. + term.Feed([]byte("text")) + app.Settle() + if imageOps(t, app)[0].Image.Pixels != second { + t.Fatal("recopied unchanged image") + } + term.Feed([]byte("\x1b[?1049h")) + app.Settle() + if len(imageOps(t, app)) != 0 { + t.Fatal("main-screen image leaked onto alternate screen") + } + term.Feed([]byte("\x1b[?1049l")) + app.Settle() + if len(imageOps(t, app)) != 1 { + t.Fatal("main-screen image missing after alternate screen") + } + term.Feed([]byte("\x1b_Ga=d,d=I,i=7,q=2\x1b\\")) + app.Settle() + if len(imageOps(t, app)) != 0 || len(ref.v.imageCache) != 0 { + t.Fatal("deleted image retained") + } +} + +func TestTerminalGraphicsPNGAndLimit(t *testing.T) { + for _, limit := range []int64{0, -1, 8} { + t.Run(fmt.Sprint(limit), func(t *testing.T) { + term, _, app := graphicsView(t, Options{ImageLimit: limit}, nil) + img := image.NewNRGBA(image.Rect(0, 0, 2, 2)) + img.SetNRGBA(0, 0, stdcolor.NRGBA{200, 100, 50, 128}) + var b bytes.Buffer + png.Encode(&b, img) + term.Feed([]byte("\x1b_Ga=T,f=100,i=8,c=2,r=2,q=2;" + base64.StdEncoding.EncodeToString(b.Bytes()) + "\x1b\\")) + app.Settle() + ops := imageOps(t, app) + if limit != 0 { + if len(ops) != 0 { + t.Fatal("image bypassed limit") + } + return + } + if len(ops) != 1 { + t.Fatalf("PNG image ops %d", len(ops)) + } + if got := ops[0].Image.Pixels.RGBAAt(0, 0); got.R != 100 || got.G != 50 || got.B != 25 || got.A != 128 { + t.Fatalf("premultiplied PNG %v", got) + } + }) + } +} + +func TestTerminalGraphicsPlaceholders(t *testing.T) { + term, ref, app := graphicsView(t, Options{}, nil) + // 0x01000009 exercises the high-byte diacritic; the second cell inherits its row, next column and high byte. Underline color names placement 3. + id := uint32(0x01000009) + text := kittyImage(id, ",U=1,p=3,c=2,r=1", redImage...) + "\x1b[38;2;0;0;9;58;2;0;0;3m" + string([]rune{kittyPlaceholder, kittyDiacritics[0], kittyDiacritics[0], kittyDiacritics[1], kittyPlaceholder}) + "\x1b[0m" + term.Feed([]byte(text)) + app.Settle() + ops := imageOps(t, app) + if len(ops) != 2 { + t.Fatalf("virtual image ops %d, want 2", len(ops)) + } + for _, op := range ops { + if op.W > ref.v.cellW || op.H > ref.v.cellH { + t.Fatalf("placeholder escaped its cell %+v", op) + } + } + if ops[1].X <= ops[0].X { + t.Fatal("inherited placeholder did not advance") + } + for _, op := range canvasOps(t, app) { + if op.Kind == driver.DrawFillText && strings.ContainsRune(op.Text, kittyPlaceholder) { + t.Fatal("placeholder was drawn as text") + } + } + app.Screenshot("terminal-graphics-placeholder") +} + +func TestTerminalSearchColorsAndUpdates(t *testing.T) { + th := DarkTheme() + th.Search = core.RGB(0x123456) + th.SearchText = core.RGB(0xabcdef) + th.SearchSelected = core.RGB(0x654321) + th.SearchSelectedText = core.RGB(0xfedcba) + var statuses []SearchStatus + term, ref, app := graphicsView(t, Options{OnSearch: func(s SearchStatus) { statuses = append(statuses, s) }}, th) + term.Feed([]byte("foo BAR foo\r\nfoo")) + term.Search("FOO") + app.WaitUntil(time.Second, func() bool { return term.SearchStatus().Total == 3 && !term.SearchStatus().Searching }) + app.Settle() + if st := term.SearchStatus(); st.Selected != 1 { + t.Fatalf("search status %+v", st) + } + // Configured foregrounds must be set for glyphs, and each opaque highlight must appear before its glyph run in the draw stream. + fill := core.Color(0) + highlights := 0 + texts := 0 + for _, op := range canvasOps(t, app) { + if op.Kind == driver.DrawFillColor { + fill = op.Color + } + if op.Kind == driver.DrawRect && (fill == th.Search || fill == th.SearchSelected) { + highlights++ + } + if op.Kind == driver.DrawFillText && strings.Contains(strings.ToLower(op.Text), "foo") { + texts++ + if highlights == 0 || fill != th.SearchText && fill != th.SearchSelectedText { + t.Fatalf("search glyph %q color %x before %d highlights", op.Text, fill, highlights) + } + } + } + if highlights != 3 || texts != 3 { + t.Fatalf("highlights %d, glyph runs %d", highlights, texts) + } + term.SearchNext() + app.Settle() + if term.SearchStatus().Selected != 2 { + t.Fatal("next match did not select older result") + } + term.SearchPrevious() + app.Settle() + if term.SearchStatus().Selected != 1 { + t.Fatal("previous match did not return") + } + term.Feed([]byte(" foo")) + app.WaitUntil(time.Second, func() bool { return term.SearchStatus().Total == 4 }) + term.EndSearch() + app.Settle() + if len(ref.v.matches) != 0 || term.SearchStatus() != (SearchStatus{}) { + t.Fatal("ended search left matches") + } + if len(statuses) < 4 || statuses[len(statuses)-1] != (SearchStatus{}) { + t.Fatalf("OnSearch statuses %+v", statuses) + } + app.Screenshot("terminal-search-ended") +} + +func TestTerminalGraphicsCropStackAndScroll(t *testing.T) { + term, ref, app := graphicsView(t, Options{}, DarkTheme()) + // The same source is placed in all three layers over a nondefault cell background. Cropping and physical offsets must survive the canvas snapshot. + term.Feed([]byte("\x1b[44mXX\x1b[0m\x1b[H" + + kittyImage(11, ",c=2,r=2,z=-1073741825", redImage...) + + kittyImage(12, ",c=2,r=2,z=-1,X=1,Y=2,x=1,w=1", greenImage...) + + kittyImage(13, ",c=2,r=2,z=1", redImage...))) + app.Settle() + ops := imageOps(t, app) + // z=-1 is split between rows, so later row backgrounds cannot erase it. + if len(ops) != 4 { + t.Fatalf("image draws %d, want 4", len(ops)) + } + if ops[0].Image.Pixels.RGBAAt(0, 0) != (stdcolor.RGBA{255, 0, 0, 255}) || ops[1].X1 != 1 || ops[1].X2 != 1 { + t.Fatal("source crop changed") + } + if ops[1].X != ref.v.padX+1/ref.v.ratio || ops[1].Y != ref.v.padY+2/ref.v.ratio { + t.Fatalf("physical offset %+v", ops[1]) + } + bg, text, front, back := -1, -1, -1, -1 + fill := core.Color(0) + for i, op := range canvasOps(t, app) { + if op.Kind == driver.DrawFillColor { + fill = op.Color + } + if op.Kind == driver.DrawImage && op.Image.Pixels == ops[0].Image.Pixels { + back = i + } + if op.Kind == driver.DrawImage && op.Image.Pixels == ops[len(ops)-1].Image.Pixels { + front = i + } + if op.Kind == driver.DrawRect && fill == core.RGB(0x2472c8) { + bg = i + } + if op.Kind == driver.DrawFillText && strings.Contains(op.Text, "XX") { + text = i + } + } + if !(back >= 0 && back < bg && bg < text && text < front) { + t.Fatalf("stack back=%d bg=%d text=%d front=%d", back, bg, text, front) + } + term.Feed([]byte(fmt.Sprintf("\x1b[%d;1H\n", ref.v.rows))) + app.Settle() + for _, g := range ref.v.graphics { + if g.y >= ref.v.padY { + t.Fatal("scroll did not move image origin above viewport") + } + } + for _, op := range imageOps(t, app) { + if op.Y < ref.v.padY || op.H > ref.v.cellH+0.01 { + t.Fatalf("scrolled image not clipped %+v", op) + } + } +} + +func TestGraphicsFractionalGridAndPixels(t *testing.T) { + p := vt.Placement{XOffset: 2, YOffset: 3, Width: 40, Height: 20, SrcW: 40, SrcH: 20} + x, y, w, h := placementGeometry(p, 7.8, 16.5, 1.25, 9, 20) + if x != 1.6 || y != 2.4 || w != 32 || h != 16 { + t.Fatalf("natural geometry %v %v %v %v", x, y, w, h) + } + p.ParamCols = 4 + _, _, w, h = placementGeometry(p, 7.8, 16.5, 1.25, 9, 20) + if math.Abs(float64(w-29.6)) > 0.001 || math.Abs(float64(h-14.8)) > 0.001 { + t.Fatalf("one-axis grid %v %v", w, h) + } + p.ParamRows = 2 + _, _, w, h = placementGeometry(p, 7.8, 16.5, 1.25, 9, 20) + if math.Abs(float64(w-29.6)) > 0.001 || math.Abs(float64(h-30.6)) > 0.001 { + t.Fatalf("two-axis grid %v %v", w, h) + } +} + +// TestTerminalGraphicsPixels checks real platform output in addition to draw records. Capture skips on headless runs, where there are no native pixels. +func TestTerminalGraphicsPixels(t *testing.T) { + th := DarkTheme() + th.Search = core.RGB(0xffe082) + th.SearchSelected = core.RGB(0xf2a57e) + term, ref, app := graphicsView(t, Options{}, th) + term.Feed([]byte("foo and foo\x1b[3;3H" + kittyImage(1, ",c=6,r=3", redImage...))) + term.Search("foo") + app.WaitUntil(time.Second, func() bool { return term.SearchStatus().Total == 2 }) + app.Settle() + app.Screenshot("terminal-search-and-images") + pixels := app.Capture() + sx, sy := float32(pixels.Bounds().Dx())/480, float32(pixels.Bounds().Dy())/240 + at := func(x, y float32) stdcolor.RGBA { + return stdcolor.RGBAModel.Convert(pixels.At(int(x*sx), int(y*sy))).(stdcolor.RGBA) + } + v := ref.v + if got := at(v.padX+4*v.cellW, v.padY+3*v.cellH); got.R < 240 || got.G > 20 || got.B > 20 { + t.Fatalf("native image pixel %v", got) + } + // Sample low in each match cell, outside the text glyphs. + for _, x := range []float32{0.25, 8.25} { + got := at(v.padX+x*v.cellW, v.padY+0.9*v.cellH) + if got.R < 200 || got.G < 100 || got.B > 160 { + t.Fatalf("native search pixel at %.2f: %v", x, got) + } + } +} + +func TestSearchRevealsScrollbackInSameFrame(t *testing.T) { + term, ref, app := graphicsView(t, Options{}, nil) + term.Feed([]byte("anchor\r\n" + strings.Repeat("later\r\n", 50))) + term.Search("anchor") + app.WaitUntil(time.Second, func() bool { return term.SearchStatus().Total == 1 && !term.SearchStatus().Searching }) + app.Settle() + if len(ref.v.matches) != 1 { + t.Fatal("search did not bring its result into view") + } + found := false + for _, op := range canvasOps(t, app) { + if op.Kind == driver.DrawFillText && strings.Contains(op.Text, "anchor") { + found = true + } + } + if !found { + t.Fatal("search highlight used a newer viewport than its text snapshot") + } +} diff --git a/base/terminal/internal/vt/lib.go b/base/terminal/internal/vt/lib.go index 028f819fb7..bb5570906f 100644 --- a/base/terminal/internal/vt/lib.go +++ b/base/terminal/internal/vt/lib.go @@ -286,7 +286,7 @@ func cStringAt(p uintptr) string { // cell is the layout of the packed GhosttyCell, from the manifest. var cell struct { - tag, codepoint, styleID, wide, hyperlink bitField + tag, codepoint, styleID, wide, hyperlink, semantic bitField // paletteIndex, r, g and b are the content of cells holding only a // background color. paletteIndex, r, g, b bitField @@ -328,6 +328,10 @@ var enums = []struct { {"GhosttyRenderStateCursorVisualStyle", "BLOCK_HOLLOW", int64(CursorBlockHollow)}, {"GhosttyRenderStateDirty", "FULL", int64(Full)}, {"GhosttyTerminalData", "KITTY_GRAPHICS", dataKittyGraphics}, + {"GhosttyTerminalData", "CURSOR_AT_PROMPT", dataCursorAtPrompt}, + {"GhosttyTerminalOption", "SEMANTIC_PROMPT", optSemanticPrompt}, + {"GhosttySemanticPromptKind", "INPUT_START", 2}, + {"GhosttyCellSemanticContent", "INPUT", 1}, {"GhosttyTerminalData", "COLOR_FOREGROUND", dataColorFg}, {"GhosttyTerminalData", "COLOR_FOREGROUND_DEFAULT", dataColorFgDefault}, {"GhosttyTerminalData", "KITTY_KEYBOARD_FLAGS", dataKittyKeyboardFlags}, @@ -447,6 +451,7 @@ func (m *manifest) check() error { field(&cell.styleID, "style_id") field(&cell.wide, "wide") field(&cell.hyperlink, "hyperlink") + field(&cell.semantic, "semantic_content") arm(&cell.codepoint, "CODEPOINT", "codepoint") arm(&cell.paletteIndex, "BG_COLOR_PALETTE", "index") arm(&cell.r, "BG_COLOR_RGB", "r") diff --git a/base/terminal/internal/vt/terminal.go b/base/terminal/internal/vt/terminal.go index 97153d6e3e..d355bb02ba 100644 --- a/base/terminal/internal/vt/terminal.go +++ b/base/terminal/internal/vt/terminal.go @@ -23,6 +23,8 @@ type Terminal struct { // library writes for it, a Kitty protocol EPERM, is dropped, as the // read of a terminal that is not the one to answer. silent bool + // promptInput is true between OSC 133 input-start and output/prompt markers. + promptInput bool // deferred is the clipboard read the embedder answers later: the // library's refusal, which follows the read's effect, is held back // and captured in it. @@ -141,6 +143,7 @@ const ( optTerminfoName = 37 optResizePullBack = 40 optRenderHold = 41 + optSemanticPrompt = 42 dataCols = 1 dataRows = 2 @@ -155,6 +158,7 @@ const ( dataColorFgDefault = 22 // the same, defaults alone dataViewportActive = 32 dataMode = 37 + dataCursorAtPrompt = 39 dataMouseShape = 41 ) @@ -188,6 +192,7 @@ func NewTerminal(cols, rows int, effects Effects) (*Terminal, error) { t.setValue(optDeviceAttributes, cbDeviceAttributes) t.setValue(optDesktopNotification, cbDesktopNotification) t.setValue(optProgressReport, cbProgressReport) + t.setValue(optSemanticPrompt, cbSemanticPrompt) // Images of the Kitty graphics protocol are refused until SetImageLimit // takes them, so that programs fall back to something else. t.SetImageLimit(0) @@ -260,7 +265,10 @@ func (t *Terminal) Cursor() (x, y int) { } // Reset resets the terminal fully (RIS). -func (t *Terminal) Reset() { call(fnTerminalReset, t.h) } +func (t *Terminal) Reset() { + t.promptInput = false + call(fnTerminalReset, t.h) +} // SetColors sets the default colors, which programs may change: the // foreground, the background, the cursor's (nil for the text's) and the @@ -543,6 +551,18 @@ func (t *Terminal) CellWide(ref GridRef) Wide { return Wide(cell.wide.of(raw)) } +// CellIsInput reports whether OSC 133 marks a cell as shell input. +func (t *Terminal) CellIsInput(ref GridRef) bool { + var raw uint64 + return ok(call(fnGridRefCell, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&raw)))) && cell.semantic.of(raw) == 1 +} + +// CursorAtPrompt reports whether OSC 133 places the cursor in the current shell prompt or input. Alternate-screen programs never qualify. +func (t *Terminal) CursorAtPrompt() bool { + var at bool + return t.get(dataCursorAtPrompt, unsafe.Pointer(&at)) == nil && at +} + // Hyperlink returns the URI of the hyperlink (OSC 8) of a cell, or "". func (t *Terminal) Hyperlink(ref GridRef) string { var buf [512]byte @@ -703,10 +723,17 @@ func clamp16(v int) int { return max(1, min(v, 0xFFFF)) } // The callbacks of every terminal, made once: purego's are never freed. var ( cbWritePTY, cbBell, cbTitleChanged, cbPwdChanged, cbRenderHold, cbClipboardWrite, cbClipboardRead, cbSize, - cbColorScheme, cbDeviceAttributes, cbDesktopNotification, cbProgressReport, cbNoRead uintptr + cbColorScheme, cbDeviceAttributes, cbDesktopNotification, cbProgressReport, cbSemanticPrompt, cbNoRead uintptr ) func makeCallbacks() { + cbSemanticPrompt = newCallback(func(_, id, req uintptr) uintptr { + if t := terminalOf(id); t != nil && req != 0 { + p := (*semanticPrompt)(mem(req)) + t.promptInput = p.kind == 2 + } + return 0 + }) // A GhosttyMimeReader for PasteEvent, which the library never calls // (it reads nothing for an event); it gives no data if it did. cbNoRead = newCallback(func(_, _, _, _, _ uintptr) uintptr { return 0 }) @@ -906,3 +933,6 @@ func cBytes(b []byte) cString { } return cString{ptr: uintptr(unsafe.Pointer(&b[0])), len: uintptr(len(b))} } + +// CursorInInput reports an active OSC 133 command-input phase at the cursor. +func (t *Terminal) CursorInInput() bool { return t.promptInput && t.CursorAtPrompt() && !t.AltScreen() } diff --git a/base/terminal/internal/vt/types.go b/base/terminal/internal/vt/types.go index 1c2a526747..ae2ee2c424 100644 --- a/base/terminal/internal/vt/types.go +++ b/base/terminal/internal/vt/types.go @@ -233,6 +233,15 @@ type progressReport struct { progress int8 } +// semanticPrompt is a GhosttyTerminalSemanticPrompt. +type semanticPrompt struct { + size uintptr + kind, promptKind int32 + hasExitCode bool + exitCode int32 + command, error cString +} + // deviceAttributes is a GhosttyDeviceAttributes. type deviceAttributes struct { conformance uint16 @@ -273,6 +282,7 @@ func layouts() map[string]layout { pa paste dn desktopNotification pr progressReport + sp semanticPrompt da deviceAttributes fo formatterOptions ) @@ -345,6 +355,7 @@ func layouts() map[string]layout { "GhosttyMimeReader": {unsafe.Sizeof(mimeReader{}), map[string]uintptr{"read": 0, "userdata": unsafe.Offsetof(mimeReader{}.userdata)}}, "GhosttyTerminalDesktopNotification": {unsafe.Sizeof(dn), map[string]uintptr{"title": unsafe.Offsetof(dn.title), "body": unsafe.Offsetof(dn.body)}}, "GhosttyTerminalProgressReport": {unsafe.Sizeof(pr), map[string]uintptr{"state": unsafe.Offsetof(pr.state), "progress": unsafe.Offsetof(pr.progress)}}, + "GhosttyTerminalSemanticPrompt": {unsafe.Sizeof(sp), map[string]uintptr{"kind": unsafe.Offsetof(sp.kind), "prompt_kind": unsafe.Offsetof(sp.promptKind), "has_exit_code": unsafe.Offsetof(sp.hasExitCode), "exit_code": unsafe.Offsetof(sp.exitCode), "command": unsafe.Offsetof(sp.command), "error": unsafe.Offsetof(sp.error)}}, "GhosttyDeviceAttributes": {unsafe.Sizeof(da), map[string]uintptr{"primary": 0, "secondary": unsafe.Offsetof(da.deviceType), "tertiary": unsafe.Offsetof(da.unitID)}}, "GhosttyRenderStateRowId": {unsafe.Sizeof(RowID{}), map[string]uintptr{"bits": 0}}, "GhosttyFormatterTerminalOptions": {unsafe.Sizeof(fo), map[string]uintptr{ diff --git a/base/terminal/prompt.go b/base/terminal/prompt.go new file mode 100644 index 0000000000..fe2699fbb7 --- /dev/null +++ b/base/terminal/prompt.go @@ -0,0 +1,107 @@ +package terminal + +import ( + "bytes" + + "github.com/nsgo-dev/nsgo/base/terminal/internal/vt" + "github.com/nsgo-dev/nsgo/core" +) + +// promptDistance counts editable graphemes in the current logical input line, ignoring prompt prefixes and the spacer cells of wide characters. The cursor may sit just after its last printed input cell. Terminal.mu is held. +func (t *Terminal) promptDistance(col, row int) (int, bool) { + if t.term == nil || !t.term.AtBottom() || !t.term.CursorInInput() { + return 0, false + } + if ref, ok := t.term.CellAt(col, row); ok && col > 0 && t.term.CellWide(ref) == vt.SpacerTail { + col-- + } + x, y := t.term.Cursor() + _, rows := t.term.Size() + first, last := y, y + for first > 0 { + kind, _ := t.term.Row(first) + _, wrap := t.term.Row(first - 1) + if kind != vt.PromptContinuation || !wrap { + break + } + first-- + } + for last+1 < rows { + _, wrap := t.term.Row(last) + kind, _ := t.term.Row(last + 1) + if !wrap || kind != vt.PromptContinuation { + break + } + last++ + } + if row < first || row > last { + return 0, false + } + var input []gridCell + for line := first; line <= last; line++ { + _, cols := t.term.RowText(line) + previous := -1 + for _, cell := range cols { + if cell == previous { + continue + } + previous = cell + ref, ok := t.term.CellAt(cell, line) + if ok && t.term.CellIsInput(ref) { + input = append(input, gridCell{cell, line}) + } + } + } + before := func(a, b gridCell) bool { return a.y < b.y || a.y == b.y && a.x < b.x } + index := func(at gridCell) int { + i := 0 + for i < len(input) && before(input[i], at) { + i++ + } + return i + } + return index(gridCell{col, row}) - index(gridCell{x, y}), true +} + +// movePrompt sends ordinary cursor keys, encoded in the program's active key modes, as one contiguous input. The release rechecks the prompt because output may have ended input or replaced the prompt since the press. +func (v *view) movePrompt(col, row int) { + t := v.t + if t == nil { + return + } + t.mu.Lock() + defer t.redraw() + defer t.mu.Unlock() + distance, ok := t.promptDistance(col, row) + if !ok || distance == 0 { + return + } + if v.keys == nil { + var err error + v.keys, err = vt.NewKeyEncoder() + if err != nil { + return + } + } + key := vt.KeyArrowRight + if distance < 0 { + key = vt.KeyArrowLeft + distance = -distance + } + v.keys.Sync(t.term, false) + data := v.keys.Encode(vt.KeyEvent{Action: vt.KeyPress, Key: key}) + if len(data) > 0 { + t.in.push(bytes.Repeat(data, distance)) + t.term.SetSelection(nil) + } +} + +// promptCell excludes padding and points beyond the viewport instead of clamping an outside release onto an edge cell. +func (v *view) promptCell(p core.Point) (col, row int, inside bool) { + x, y := float32(p.X), float32(float64(p.Y)-v.scrollY) + if x < v.padX || y < v.padY || x >= v.padX+float32(v.cols)*v.cellW || y >= v.padY+float32(v.rows)*v.cellH { + return 0, 0, false + } + col, row, _, _ = v.cellAt(p) + return col, row, true +} diff --git a/base/terminal/prompt_test.go b/base/terminal/prompt_test.go new file mode 100644 index 0000000000..9feec983a9 --- /dev/null +++ b/base/terminal/prompt_test.go @@ -0,0 +1,129 @@ +package terminal + +import ( + "strings" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func protocolTerminal(t *testing.T, opts Options) *Terminal { + t.Helper() + if opts.Conn == nil { + opts.Conn = newPipe() + } + term, err := New(opts) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { term.Close() }) + return term +} + +func TestPromptDistance(t *testing.T) { + for _, tc := range []struct { + name, input string + cols, col, row, want int + }{ + {"ascii", "abc", 20, 2, 0, -3}, + {"prompt prefix", "abc", 20, 0, 0, -3}, + {"past end", "abc", 20, 18, 0, 0}, + {"wide tail", "a界b", 20, 4, 0, -2}, + {"graphemes", "e\u0301👍🏽z", 20, 3, 0, -2}, + {"wrapped", "abcdefghijkl", 10, 3, 0, -11}, + {"wrapped second row", "abcdefghijkl", 10, 2, 1, -2}, + {"space", "a b ", 20, 3, 0, -3}, + } { + t.Run(tc.name, func(t *testing.T) { + term := protocolTerminal(t, Options{}) + term.Resize(tc.cols, 6) + term.Feed([]byte("\x1b]133;A\a$ \x1b]133;B\a" + tc.input)) + term.mu.Lock() + got, ok := term.promptDistance(tc.col, tc.row) + term.mu.Unlock() + if !ok || got != tc.want { + t.Fatalf("distance %d,%v, want %d,true", got, ok, tc.want) + } + }) + } +} + +func TestPromptRejectsOutputAndOtherScreens(t *testing.T) { + for _, tc := range []struct { + name, prefix, suffix string + scroll bool + }{ + {name: "unmarked", prefix: "$ abc"}, + {name: "output starts", prefix: "\x1b]133;A\a$ \x1b]133;B\aabc", suffix: "\x1b]133;C\a"}, + {name: "command ends", prefix: "\x1b]133;A\a$ \x1b]133;B\aabc", suffix: "\x1b]133;D;0\a"}, + {name: "new prompt before input", prefix: "\x1b]133;A\a$ \x1b]133;B\aabc", suffix: "\x1b]133;A\a$ "}, + {name: "alternate screen", prefix: "\x1b]133;A\a$ \x1b]133;B\aabc", suffix: "\x1b[?1049h"}, + {name: "scrollback", prefix: strings.Repeat("out\r\n", 20) + "\x1b]133;A\a$ \x1b]133;B\aabc", scroll: true}, + } { + t.Run(tc.name, func(t *testing.T) { + term := protocolTerminal(t, Options{}) + term.Resize(20, 5) + term.Feed([]byte(tc.prefix + tc.suffix)) + term.mu.Lock() + if tc.scroll { + term.term.ScrollToRow(0) + } + _, ok := term.promptDistance(2, 0) + term.mu.Unlock() + if ok { + t.Fatal("accepted a click outside active command input") + } + }) + } +} + +func TestOptionClickPrompt(t *testing.T) { + conn := newRecordingConn() + term := protocolTerminal(t, Options{Conn: conn}) + ref := &Ref{} + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return View{Terminal: term, Ref: ref, TestID: "term", AutoFocus: true, NoKeyBar: true, Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}} + }, nsgotest.Size(480, 240)) + term.Feed([]byte("\x1b]133;A\a$ \x1b]133;B\aa界b")) + app.Settle() + v := ref.v + at := func(x, y int) core.Point { + return core.Point{X: core.Points(v.padX + (float32(x)+0.5)*v.cellW), Y: core.Points(v.padY + (float32(y)+0.5)*v.cellH)} + } + sent := func(want string) { + t.Helper() + var got string + app.WaitUntil(2*time.Second, func() bool { got += conn.take(); return got == want }) + } + app.PressAtWith("id:term-screen", at(4, 0), core.Modifiers{Alt: true}) + sent(strings.Repeat("\x1b[D", 2)) + // Application cursor mode is respected, and a cursor moved back by the shell can move right again without counting wide spacers as editable characters. + term.Feed([]byte("\x1b[?1h\x1b[1;3H")) + app.Settle() + app.PressAtWith("id:term-screen", at(5, 0), core.Modifiers{Alt: true}) + sent(strings.Repeat("\x1bOC", 2)) + // A drag, an outside release, and output between press and release send none. + for _, mode := range []string{"drag", "outside", "output"} { + app.Post(func() { + e := core.PressEvent{Position: at(3, 0), Modifiers: core.Modifiers{Alt: true}, Clicks: 1} + v.pressDown(e) + switch mode { + case "drag": + v.mouseMove(core.MouseEvent{Position: at(5, 0)}) + v.mouseMove(core.MouseEvent{Position: at(3, 0)}) + case "outside": + e.Position.X = -10 + case "output": + term.Feed([]byte("\x1b]133;C\a")) + } + v.pressUp(e) + }) + app.Settle() + if got := conn.take(); got != "" { + t.Errorf("%s sent %q", mode, got) + } + } + app.Screenshot("terminal-option-click") +} diff --git a/base/terminal/terminal.go b/base/terminal/terminal.go index 3f797f29bd..ddd890d580 100644 --- a/base/terminal/terminal.go +++ b/base/terminal/terminal.go @@ -56,6 +56,8 @@ type Options struct { // Scrollback is about how many bytes of output to keep above the // screen: 10 MB when zero, none when negative. Scrollback int + // ImageLimit bounds Kitty graphics storage in bytes: 64 MiB when zero, disabled when negative. + ImageLimit int64 // Cursor is the cursor programs reset to: a block when zero. Cursor CursorStyle // CursorBlink sets the default blinking state. Programs @@ -185,6 +187,11 @@ func New(opts Options) (*Terminal, error) { return nil, err } t.term.SetTerminfoName("xterm-256color") + limit := opts.ImageLimit + if limit == 0 { + limit = 64 << 20 + } + t.term.SetImageLimit(uint64(max(limit, 0))) // Grapheme clusters take the cells of their width, as in Ghostty. t.term.SetModeDefault(vt.ModeGraphemes, true) switch { diff --git a/base/terminal/theme.go b/base/terminal/theme.go index 3c448fc24c..c44bf90e9a 100644 --- a/base/terminal/theme.go +++ b/base/terminal/theme.go @@ -17,9 +17,7 @@ type Theme struct { // opaque, when unset. SelectionText colors the selected text: its own // colors when unset. Selection, SelectionText core.Color - // Search, SearchText, SearchSelected and SearchSelectedText are - // Ghostty's search colors, which theme files set; the view does not - // search yet. + // Search, SearchText, SearchSelected and SearchSelectedText are the backgrounds and foregrounds of search matches and the current match. Unset colors use gold backgrounds and black text. Search, SearchText, SearchSelected, SearchSelectedText core.Color // Palette holds the 16 colors of programs: black, red, green, yellow, // blue, magenta, cyan and white, then their bright kinds. diff --git a/base/terminal/view.go b/base/terminal/view.go index e6387bd15a..fddb85ca46 100644 --- a/base/terminal/view.go +++ b/base/terminal/view.go @@ -206,6 +206,8 @@ func (p View) Render(cx *core.Scope) core.Node { // view is a View's state, on the engine's goroutine. type view struct { + graphics []graphic + imageCache map[uint32]graphicImage // searched is the status OnSearch was last told; matches are the // search's spans the viewport shows, in matchBuf's memory. searched SearchStatus @@ -241,12 +243,14 @@ type view struct { // mouse is over while hovered, armed that the key opening links is // held, linkOn that the mouse shows a hand as a press would open link, // and pressedLink the URL a press on a link opens as it ends there. - link link - hover [2]int - hovered bool - armed bool - linkOn *core.Signal[bool] - pressedLink string + link link + hover [2]int + hovered bool + armed bool + linkOn *core.Signal[bool] + pressedLink string + promptPress gridCell + promptPressed, promptDragged bool // The grid as the last drawing laid it out, in points. cellW, cellH, padX, padY float32 @@ -342,8 +346,11 @@ func (v *view) draw(d *core.Drawing, size core.Size) { t.term.SetMode(vt.ModeSyncOutput, false) t.held = false } + searching := t.find.drive(t.term) + searched := t.find.status if !t.held { t.rs.Update(t.term) + v.snapshotGraphics() // Output and scrolling move what is under the mouse. v.findLink() } @@ -351,13 +358,12 @@ func (v *view) draw(d *core.Drawing, size core.Size) { v.reported = [2]int{cols, rows} cx.Post(func() { v.p.OnSizeChange(cols, rows) }) } - searching := t.find.drive(t.term) - searched := t.find.status - cols, rows := t.term.Size() - v.matches, v.matchBuf = t.viewportMatches(v.matches, v.matchBuf, cols, rows) + if !t.held { + cols, rows := t.term.Size() + v.matches, v.matchBuf = t.viewportMatches(v.matches, v.matchBuf, cols, rows) + } fr := frame{v: v, d: d, rs: t.rs, th: th, focused: focused, composing: composing} fr.paint(size) - fr.paintMatches() t.mu.Unlock() if searched != v.searched { v.searched = searched @@ -374,23 +380,35 @@ func (v *view) draw(d *core.Drawing, size core.Size) { v.follow(size) } -// paintMatches marks the matches of the search the viewport shows. -func (f *frame) paintMatches() { - v, th := f.v, f.th - or := func(c, fallback core.Color) core.Color { - if c != 0 { - return c +// searchColors returns the match colors under a cell, including the configured foreground. Search backgrounds are painted before glyphs and the cursor. +func (f *frame) searchColors(x, y int) (bg, fg core.Color, matched bool) { + for _, m := range f.matchRows[y] { + if x < m.x0 || x > m.x1 { + continue } - return fallback - } - match := or(th.Search, core.RGB(0xffe082)).Faded(0.45) - selected := or(th.SearchSelected, core.RGB(0xf2a57e)).Faded(0.6) - for _, m := range v.matches { - c := match + bg, fg = f.th.Search, f.th.SearchText if m.selected { - c = selected + bg, fg = f.th.SearchSelected, f.th.SearchSelectedText } - f.d.SetFillColor(c).FillRect(v.padX+float32(m.x0)*v.cellW, v.padY+float32(m.y)*v.cellH, float32(m.x1-m.x0+1)*v.cellW, v.cellH) + if bg == 0 { + bg = core.RGB(0xffe082) + if m.selected { + bg = core.RGB(0xf2a57e) + } + } + if fg == 0 { + fg = core.RGB(0x000000) + } + return bg, fg, true + } + return 0, 0, false +} + +func (f *frame) paintMatches(y int) { + v := f.v + for _, m := range f.matchRows[y] { + bg, _, _ := f.searchColors(m.x0, y) + f.d.SetFillColor(bg).FillRect(v.padX+float32(m.x0)*v.cellW, v.padY+float32(y)*v.cellH, float32(m.x1-m.x0+1)*v.cellW, v.cellH) } } @@ -460,13 +478,14 @@ func (v *view) scrolled(e core.ScrollEvent) { // frame draws one frame. type frame struct { - v *view - d *core.Drawing - rs *vt.RenderState - th *Theme - colors vt.Colors - focused bool - anySel bool + v *view + d *core.Drawing + rs *vt.RenderState + th *Theme + colors vt.Colors + matchRows map[int][]matchSpan + focused bool + anySel bool // composing is what an input method composes. composing string contrast map[[2]core.Color]core.Color @@ -519,6 +538,10 @@ type run struct { func (f *frame) paint(size core.Size) { v, d, rs := f.v, f.d, f.rs f.colors = rs.Colors() + f.matchRows = make(map[int][]matchSpan) + for _, m := range v.matches { + f.matchRows[m.y] = append(f.matchRows[m.y], m) + } cw, ch := v.cellW, v.cellH ox, oy := v.padX, v.padY m := d.TextMetrics("M", v.font(false, false)) @@ -527,6 +550,7 @@ func (f *frame) paint(size core.Size) { if !v.p.Transparent { d.SetFillColor(bg).FillRect(0, 0, float32(size.Width), float32(size.Height)) } + f.paintGraphics(0, 0) selection := f.th.Selection if selection == 0 { selection = color(f.colors.Foreground).Faded(0.3) @@ -632,6 +656,12 @@ func (f *frame) paint(size core.Size) { } st.fg = adjusted } + if _, fg, matched := f.searchColors(x, y); matched { + st.fg = fg + } + if c.Codepoint == kittyPlaceholder { + continue + } if st.underline != 0 { ul := st.fg if st.hasUl { @@ -681,10 +711,12 @@ func (f *frame) paint(size core.Size) { } } flushSpan() + f.paintGraphics(1, y) if sel { f.anySel = true d.SetFillColor(selection).FillRect(ox+float32(selA)*cw, ry, float32(selB-selA+1)*cw, ch) } + f.paintMatches(y) for _, r := range runs { x := ox + float32(r.x)*cw if len(r.text) == 1 && drawGraphics(d, r.text[0], x, ry, cw, ch, v.ratio, r.fg) { @@ -707,6 +739,7 @@ func (f *frame) paint(size core.Size) { } } } + f.paintGraphics(2, 0) if cur.Visible && cur.InView { x, y := ox+float32(cur.X)*cw, oy+float32(cur.Y)*ch d.Save() @@ -1049,12 +1082,21 @@ func (v *view) pressDown(e core.PressEvent) { return } col, row, px, py := v.cellAt(e.Position) + v.promptPressed, v.promptDragged = false, false if v.opensLinks(e.Modifiers) { if l := t.linkAt(col, row); l.url != "" { v.pressedLink = l.url return } } + if e.Modifiers.Alt && !e.Modifiers.Control && !e.Modifiers.Platform && !e.Modifiers.Shift { + if _, _, inside := v.promptCell(e.Position); inside { + if _, ok := t.promptDistance(col, row); ok { + v.promptPress, v.promptPressed = gridCell{col, row}, true + return + } + } + } v.hovered = false v.findLink() if !v.ensureGesture() { @@ -1082,6 +1124,11 @@ func (v *view) mouseMove(e core.MouseEvent) { if t == nil { return } + if v.promptPressed { + col, row, inside := v.promptCell(e.Position) + v.promptDragged = !inside || v.promptDragged || v.promptPress != (gridCell{col, row}) + return + } if v.selecting { v.lastMouse = e.Position t.mu.Lock() @@ -1108,6 +1155,9 @@ func (v *view) mouseMove(e core.MouseEvent) { } func (v *view) mouseLeave(core.MouseEvent) { + if v.promptPressed { + v.promptDragged = true + } t := v.t if t == nil { return @@ -1169,6 +1219,14 @@ func (v *view) dragTo(p core.Point) { func (v *view) pressUp(e core.PressEvent) { t := v.t + if v.promptPressed { + v.promptPressed = false + col, row, inside := v.promptCell(e.Position) + if inside && !v.promptDragged && v.promptPress == (gridCell{col, row}) { + v.movePrompt(col, row) + } + return + } if url := v.pressedLink; url != "" && t != nil { v.pressedLink = "" col, row, _, _ := v.cellAt(e.Position) diff --git a/changelog.d/terminal-search-images-1461.md b/changelog.d/terminal-search-images-1461.md new file mode 100644 index 0000000000..da6512a79d --- /dev/null +++ b/changelog.d/terminal-search-images-1461.md @@ -0,0 +1,3 @@ +### Added + +- Render terminal search colors and Kitty images and move the cursor with Option-click in OSC 133 command input (#1461 by @houko). diff --git a/docs/architecture/terminal.md b/docs/architecture/terminal.md index 0acfad375d..b81ae81ab7 100644 --- a/docs/architecture/terminal.md +++ b/docs/architecture/terminal.md @@ -29,7 +29,7 @@ A terminal no view shows, as a server's for a session, sizes with `Resize` and ` `Close` closes `Conn` or ends the local program. On macOS and Linux it hangs up the terminal and every process group of its session, the program's and those of the jobs an interactive shell started, then sends them SIGTERM after 250 ms and SIGKILL after another 250 ms, so programs inheriting an ignored SIGHUP still exit; a program that wants to outlive the terminal starts a session of its own (`setsid`). Shutdown runs off the caller's goroutine; `Done` waits for it. The PTY keeps the leader's PID, which is also the session's ID, reserved until its last signal, even if the leader exits before its children, so escalation cannot signal a reused PID. Windows closes ConPTY, which ends its attached processes. The app owns the terminal's lifetime and calls `Close` in its view's cleanup when they should end together. -`Search` finds text in the screen and the scrollback, a slice of the search each frame, reports through `OnSearch` and marks the matches the viewport shows. +`Search` finds text in the screen and the scrollback, a slice of the search each frame, reports through `OnSearch` and marks the matches the viewport shows. `SearchNext` selects older matches and `SearchPrevious` newer ones; `EndSearch` removes the highlights. The configured search background and foreground colors paint before glyphs and the cursor. Search-driven viewport changes precede the render snapshot, and synchronized output holds its highlights with its text. ## View @@ -43,6 +43,14 @@ A terminal no view shows, as a server's for a session, sizes with `Resize` and ` - The font, the themes and the padding are the view's props, so changing them builds the view again while the terminal and its program go on. - `Keybinds` register after the focused, noncomposing input's defaults, so later actions override them. `actions.go` owns the session-independent subset of Ghostty actions: clipboard, selection, clear, font size and ignore; window and tab actions remain the app's. A view's tracked point size drives its grid and input font in place, with Ghostty's 1–255 point bounds and reset to the configured size. A secondary click opens an unstyled `base.ContextMenu` with the package's localized Copy, Paste, Select All and Clear items; `RightClickAction` can copy, paste, choose by selection or leave the event to the app. [Terminal actions](../public/en/terminal.md) documents the API. +## Images and shell integration + +`Options.ImageLimit` enables Kitty graphics storage, 64 MiB by default and disabled when negative, on every target that runs the terminal. The smaller default than Ghostty's 320 MiB accounts for the view and core's copies of visible pixels. Programs send RGB, RGBA or PNG images; the pinned library handles transmission, replacement, deletion, scrolling, source cropping and normal relative placements. The view caches premultiplied canvas images by image ID and generation, drops offscreen sources, and snapshots them with text so synchronized updates freeze both. + +The view clips image placements to the grid. Z below `-1<<30` paints before nondefault cell backgrounds, other negative Z between backgrounds and text, and nonnegative Z above text but below the cursor and IME. Ties paint in image ID and then placement ID order. Natural sizes and offsets are physical pixels; explicit cell sizes use the view's fractional grid, preserving aspect ratio when only one dimension is requested. Unicode placeholders (`U+10EEEE`) resolve image/placement IDs from raw colors and coordinates from Kitty's diacritics, inherit omitted adjacent coordinates, and fit their virtual grid with centered aspect preservation. Relative placements rooted in virtual placements remain a goal because the pinned placement API does not resolve their viewport positions. + +An Alt/Option-only click in the active OSC 133 command input sends ordinary left/right cursor keys, encoded in the program's modes. The semantic-prompt callback enables it only between input-start (`B`) and output, command-end or prompt-start markers; the row-based cursor-at-prompt flag alone also covers output on a prompt row. Clicks count editable graphemes across soft wraps, normalize wide spacers and clamp to the input's ends. Scrollback, the alternate screen, unmarked output, drags, releases outside the viewport and output that ends input between press and release send no movement. Shells supply their own OSC 133 integration; NSGo injects no shell scripts. + ## Touch screens Where `Env.Desktop` is false: diff --git a/docs/public/en/components.md b/docs/public/en/components.md index 0d5e4ce738..0b7dad4bb6 100644 --- a/docs/public/en/components.md +++ b/docs/public/en/components.md @@ -128,3 +128,9 @@ Themes give `ui`'s components their look in light and dark. `desktop.SetWindowLevel` keeps a window above the others, as a timer or a desktop pet does, or below them, and `desktop.SetWindowFrame` moves and sizes it. `desktop.CanSetWindowLevel` and `desktop.CanPlaceWindows` say whether they take effect in a window's scope: both do on macOS, Windows and Linux under X11, and neither for an ordinary Wayland toplevel, whose compositor stacks and places it. A window opened with `desktop.WindowOptions{Transparent: true}`, or the main window with `nsgo.WindowTransparent()`, has no background or frame, so the desktop shows wherever the app draws nothing, as for a desktop pet or a widget; a view with `Desktop.WindowDrag` moves it. `NoShadow` drops the system's shadow and `SkipTaskbar` keeps the window off the Windows taskbar and Alt+Tab and the X11 task list, and `desktop.SetWindowTransparent`, `SetWindowShadow` and `SetSkipTaskbar` change them later. Windows changes transparency only in a window opened transparent, which has no shadow, and Wayland has no hint to keep a window off its task list. `desktop.CanMakeWindowsTransparent` and `desktop.CanSkipTaskbar` say in a window's scope whether these take effect: transparency needs DirectComposition on Windows and a compositor on Linux, as X11 without one has none, and on macOS `desktop.SetDockVisible` takes the app off the Dock. + +## Terminal + +Import `base/terminal` and create a session with `terminal.New(terminal.Options{Conn: conn})` for a remote stream, or set `Command` for a local program on macOS, Linux or Windows. Render `terminal.View{Terminal: session}` and call `Close` when the session ends. `Options.ImageLimit` bounds Kitty graphics storage in bytes: zero uses 64 MiB, a negative value disables images. Programs can send RGB, RGBA or PNG images and Unicode placeholder placements. + +Call `Search(text)` to highlight matches in the screen and scrollback, `SearchNext` and `SearchPrevious` to select them, and `EndSearch` to clear them. `Options.OnSearch` reports `SearchStatus`; `Theme.Search`, `SearchText`, `SearchSelected` and `SearchSelectedText` set match colors. Shells that emit OSC 133 markers support Alt/Option-click within their active command input to move the cursor. NSGo does not install shell integration scripts. diff --git a/docs/public/zh/components.md b/docs/public/zh/components.md index 697cf57c66..ed5d71571f 100644 --- a/docs/public/zh/components.md +++ b/docs/public/zh/components.md @@ -119,3 +119,9 @@ core.Text{Content: "Done", Class: "self-start rounded-full bg-zinc-100 px-3 py-1 `desktop.SetWindowLevel` 让窗口保持在其他窗口之上(比如计时器或桌面宠物),或置于其下;`desktop.SetWindowFrame` 移动窗口并调整大小。`desktop.CanSetWindowLevel` 和 `desktop.CanPlaceWindows` 说明它们在窗口的 scope 中是否生效:macOS、Windows 和 Linux 的 X11 下二者都生效;普通 Wayland 顶层窗口的层叠和位置由合成器决定,二者均不支持。 用 `desktop.WindowOptions{Transparent: true}` 打开的窗口,或用 `nsgo.WindowTransparent()` 打开的主窗口,没有背景和边框,应用不绘制的地方都会露出桌面,适合桌面宠物或小组件;带 `Desktop.WindowDrag` 的视图可以拖动它。`NoShadow` 去掉系统阴影,`SkipTaskbar` 让窗口不出现在 Windows 任务栏和 Alt+Tab 以及 X11 的任务列表中;之后可以用 `desktop.SetWindowTransparent`、`SetWindowShadow` 和 `SetSkipTaskbar` 修改它们。Windows 只能在以透明方式打开的窗口中切换透明,这种窗口没有阴影;Wayland 没有让窗口不出现在任务列表中的提示。`desktop.CanMakeWindowsTransparent` 和 `desktop.CanSkipTaskbar` 说明它们在窗口的 scope 中是否生效:Windows 上透明需要 DirectComposition,Linux 上需要合成器(没有合成器的 X11 不支持);在 macOS 上用 `desktop.SetDockVisible` 让应用不出现在程序坞中。 + +## 终端 + +导入 `base/terminal`,使用 `terminal.New(terminal.Options{Conn: conn})` 连接远程字节流,或设置 `Command` 在 macOS、Linux、Windows 上运行本地程序。通过 `terminal.View{Terminal: session}` 显示终端,会话结束时调用 `Close`。`Options.ImageLimit` 限制 Kitty 图像存储的字节数:零使用 64 MiB,负值禁用图像。程序可以发送 RGB、RGBA、PNG 图像和 Unicode 占位符布局。 + +调用 `Search(text)` 高亮屏幕和滚动历史中的匹配项,通过 `SearchNext` 和 `SearchPrevious` 切换,使用 `EndSearch` 清除。`Options.OnSearch` 报告 `SearchStatus`;`Theme.Search`、`SearchText`、`SearchSelected` 和 `SearchSelectedText` 设置匹配颜色。发送 OSC 133 标记的 shell 支持在当前命令输入区内通过 Alt/Option 单击移动光标。NSGo 不会安装 shell 集成脚本。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 621572c2a6..f0e4463b25 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -245,7 +245,7 @@ What `base/terminal` still lacks of a terminal app's features, Ghostty's the ref | Mouse reports and the wheel on full-screen programs | `mouse-reporting`, `mouse-scroll-multiplier`, [#1456](https://github.com/nsgo-dev/nsgo/issues/1456) | A program that takes the mouse gets presses, moves and the wheel as it asks, and the alternate screen gets the wheel as arrows | | Clipboard protocols | `clipboard-read`, `clipboard-write`, [#1458](https://github.com/nsgo-dev/nsgo/issues/1458) | Programs copy with OSC 52 and read the clipboard as the app allows, and the Kitty clipboard protocol offers pasted images | | Keybinds, zoom, the context menu and secondary clicks | `keybind`, `right-click-action`, [#1459](https://github.com/nsgo-dev/nsgo/issues/1459) | Shared view actions override defaults while focused and not composing, zoom resizes the grid in place, and secondary clicks offer Copy, Paste, Select All and Clear or a clipboard policy; headless and native macOS regressions cover them, with native Windows/Linux menu acceptance still to run | -| Search, images and shell integration | Find, the Kitty graphics protocol, `shell-integration`, [#1461](https://github.com/nsgo-dev/nsgo/issues/1461) | A search highlights matches, programs show images, and OSC 133 prompts take Option+click to move the cursor | +| Images relative to Unicode placements | Kitty graphics, [#1461](https://github.com/nsgo-dev/nsgo/issues/1461) | Resolve the viewport positions of relative placements rooted in virtual Unicode placements; search highlights, ordinary and Unicode image placements, and OSC 133 Option+click are implemented | ## Widgets diff --git a/skills/nsgo/references/components.md b/skills/nsgo/references/components.md index 1b51f1644d..b1e7e2c235 100644 --- a/skills/nsgo/references/components.md +++ b/skills/nsgo/references/components.md @@ -29,6 +29,7 @@ Use `ui`'s component whenever one exists: it is `base`'s control with NSGo's loo - Let `diagram.View` follow its container's width; `RenderDiagram: diagram.RenderDiagram` fits a TextView's Mermaid blocks to their viewport. Wide flowcharts can turn down while labels keep their size ([text](https://nsgo.dev/docs/text.md)). - For terminal rendering, `Options.CursorBlink` enables the default blink; programs may override it. `View.MinimumContrast` adjusts ordinary text and `PaddingColor` takes `PaddingBackground`, `PaddingExtend` or `PaddingExtendAlways`; TSX uses `cursorBlink`, `minimumContrast` and `paddingColor` ([Terminal](https://nsgo.dev/docs/terminal.md)). - `widget.Update` publishes the same timeline to Apple widgets and Android App Widgets. Android standalone APKs/AABs generate providers from `widgets` in YAML; use registered URL schemes for `Entry.URL` and `Style.Link`, `Image` for portable artwork, and allow background transitions to follow Android's inexact alarm schedule. [Widgets](https://nsgo.dev/docs/widgets.md). +- `base/terminal` renders Kitty RGB/RGBA/PNG images with `Options.ImageLimit` (zero: 64 MiB; negative: disabled), search colors through `Theme.Search`, `SearchText`, `SearchSelected`, `SearchSelectedText`, and Alt/Option-click cursor movement in an active OSC 133 command input. Apps provide shell integration markers; NSGo installs no scripts. [Terminal](https://nsgo.dev/docs/components.md#terminal) - Use `ui.ShellTab.TextFunc` and `ui.TabShell.LabelFunc` for a changing tab title and bar name, and set `Edge` (`mobile.TabBarLeading`, `mobile.TabBarTrailing` or `mobile.TabBarAutomatic`, reading `core.Env.VerticalBarEdge`) on `mobile.TabBar` or `ui.TabShell` to place the bar vertically along an edge. - Set `tabBarBackground`, `tabBarIdle`, `tabBarSelected` and `tabBarIndicator` as Android `mobile.TabBar` palette roles. A custom palette uses `Accent` for selected content by default. diff --git a/tsx/terminal/terminal.go b/tsx/terminal/terminal.go index 4087f671cf..f280357729 100644 --- a/tsx/terminal/terminal.go +++ b/tsx/terminal/terminal.go @@ -21,6 +21,7 @@ type Terminal struct { Env []string Conn io.ReadWriteCloser Scrollback int + ImageLimit int64 Cursor terminal.CursorStyle CursorBlink bool // OnTitle, OnExit and OnBell run as the program sets the title, ends @@ -121,7 +122,7 @@ func (p Terminal) Render(cx *core.Scope) core.Node { cx.Post(fn) } } - opts := terminal.Options{Command: p.Command, Dir: p.Dir, Env: p.Env, Conn: p.Conn, Scrollback: p.Scrollback, Cursor: p.Cursor, CursorBlink: p.CursorBlink} + opts := terminal.Options{Command: p.Command, Dir: p.Dir, Env: p.Env, Conn: p.Conn, Scrollback: p.Scrollback, ImageLimit: p.ImageLimit, Cursor: p.Cursor, CursorBlink: p.CursorBlink} if p.OnTitle != nil { opts.OnTitle = func(s string) { post(func() { p.OnTitle(s) }) } }