package ui import ( "context" "image" "strings" "sync" "testing" "time" "gioui.org/f32" "gioui.org/io/input" "gioui.org/io/pointer" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" "go.mitchellh.com/libghostty" "100gex/internal/rex" "100gex/internal/rex/rextest" "100gex/internal/rexsession" "100gex/internal/termview" "100gex/internal/theme" "100gex/internal/workspace" ) // testConfig is an init.lua that uses each kind of binding. const testConfig = ` rex.bind("ctrl+b>c", "client.tab.new") rex.bind("ctrl+b>shift+5", "pane.split", { direction = "right" }) rex.bind("ctrl+b>ctrl+b", "pane.send_key", { key = "ctrl+b" }) rex.bind("ctrl+r", "client.mode.enter", { name = "nav" }) rex.bind("nav/h", "pane.focus", { direction = "left" }) -- Replaces this client's default, a split. rex.bind("ctrl+shift+d", "pane.zoom") -- A Lua function: the client forwards the key to client.key. rex.bind("ctrl+g", function(ctx, ev) rex.call("com.superlogical.terminal.write", { session_id = ctx.session_id, block_id = ctx.block_id, args = { data = "lua!" } }) return true end) -- A Lua action: the client runs it with client.action. rex.action{ name = "shout", title = "Shout", run = function(ctx, args) rex.call("com.superlogical.terminal.write", { session_id = ctx.session_id, block_id = ctx.block_id, args = { data = "shout!" } }) end } rex.bind("ctrl+y", "shout") ` // uiHarness runs a UI as the app does, without a window. type uiHarness struct { t testing.TB u *UI router input.Router ops op.Ops size image.Point // the window's; testWidth by testHeight unless set // clock, if set, is the time frames are drawn at, instead of now. clock time.Time } func startUI(t testing.TB, srv *rextest.Server, c *rex.Conn, sessionID string) *uiHarness { t.Helper() ws, err := workspace.Start(context.Background(), c, srv.Endpoint, sessionID, nil, func() {}) if err != nil { t.Fatal(err) } t.Cleanup(ws.Close) h := &uiHarness{t: t, size: image.Pt(testWidth, testHeight)} h.u = New(ws, c, theme.NewShaper(), func() {}) // Tests draw frames with Gio, which can't draw cells. h.u.RowImages = true h.u.SetTarget(srv.Endpoint.String(), "") t.Cleanup(h.u.Close) return h } const testWidth, testHeight = 1200, 700 func (h *uiHarness) frame() rexsession.Frame { h.t.Helper() h.ops.Reset() gtx := layout.Context{ Ops: &h.ops, Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(h.size), Now: time.Now(), Source: h.router.Source(), } if !h.clock.IsZero() { gtx.Now = h.clock } f, _, err := h.u.Layout(gtx) if err != nil { h.t.Fatal(err) } h.router.Frame(&h.ops) return f } // held calls fn with the session's terminals held, as a frame holds them // while it takes what it draws. A frame lets them go before it draws, so // they are only had, by term, within fn. func (h *uiHarness) held(fn func(rexsession.Frame)) { h.t.Helper() s := h.u.session if s == nil { fn(rexsession.Frame{}) return } f, err := s.Sync() defer s.Release() if err != nil { h.t.Fatal(err) } fn(f) } // term returns a block's terminal, while held: see held. func (h *uiHarness) term(blockID string) *libghostty.Terminal { if h.u.session == nil { return nil } return h.u.session.Terminal(blockID) } // selection returns the text selected in the focused pane. func (h *uiHarness) selection() (text string, err error) { h.held(func(rexsession.Frame) { if term := h.u.focusedTerm(); term != nil { text, err = termview.SelectionText(term) } }) return text, err } // until draws frames until cond holds, then draws one more and returns // it. cond is called with the terminals held; the frame returned has let // them go. func (h *uiHarness) until(what string, cond func(rexsession.Frame) bool) rexsession.Frame { h.t.Helper() for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { h.frame() ok := false h.held(func(f rexsession.Frame) { ok = cond(f) }) if ok { // Draw what cond saw, so what the UI laid out is current. return h.frame() } if time.Now().After(deadline) { h.t.Fatalf("timed out waiting for %s", what) } } } // press types keys as termview reports them. func (h *uiHarness) press(keys ...rex.KeyEvent) { for _, k := range keys { h.held(func(rexsession.Frame) { h.u.key(k) }) // as during a frame h.frame() } } func screenText(term *libghostty.Terminal) string { if term == nil { return "" } f, err := libghostty.NewFormatter(term) if err != nil { return "" } defer f.Close() s, _ := f.FormatString() return s } func chord(mods, key string, char rune) rex.KeyEvent { k := rex.KeyEvent{Action: "press", Key: key, Mods: mods, UnshiftedCodepoint: char} if char != 0 { k.Text = string(char) } return k } var ( ctrlB = chord("ctrl", "key_b", 'b') ctrlG = chord("ctrl", "key_g", 'g') ctrlR = chord("ctrl", "key_r", 'r') ctrlY = chord("ctrl", "key_y", 'y') plainC = chord("", "key_c", 'c') plainH = chord("", "key_h", 'h') plainZ = chord("", "key_z", 'z') escape = chord("", "escape", 0) ctrlShiftD = chord("shift+ctrl", "key_d", 'd') ctrlShiftT = chord("shift+ctrl", "key_t", 't') percent = rex.KeyEvent{Action: "press", Key: "digit_5", Mods: "shift", ConsumedMods: "shift", Text: "%", UnshiftedCodepoint: '5'} ) func TestKeyBindings(t *testing.T) { srv := rextest.StartConfig(t, testConfig) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, rextest.RawCat...) c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the keymap and the block", func(f rexsession.Frame) bool { _, ok := h.u.serverActions["shout"] return ok && strings.Contains(screenText(h.term(b1)), "ready") }) shows := func(what, text string) { t.Helper() h.until(what, func(f rexsession.Frame) bool { return strings.Contains(screenText(h.term(b1)), text) }) } // A key bound to a Lua function goes to client.key, and the function // writes to the terminal. h.press(ctrlG) shows("the Lua function", "lua!") // A Lua action runs with client.action. h.press(ctrlY) shows("the Lua action", "lua!shout!") // ctrl+b twice sends one ctrl+b. h.press(ctrlB, ctrlB) shows("ctrl+b to arrive once", "lua!shout!^B") // A key that doesn't continue a sequence goes to the terminal, without // the ctrl+b before it. h.press(ctrlB, plainZ) shows("z after the abandoned sequence", "lua!shout!^Bz") // Escape cancels a sequence. h.press(ctrlB, escape, plainC) shows("c after the cancelled sequence", "lua!shout!^Bzc") // ctrl+b % splits. h.press(ctrlB) if got := h.u.keyState(); got != "Ctrl+B …" { t.Errorf("key state while a sequence is pending = %q", got) } h.press(percent) h.until("the split", func(f rexsession.Frame) bool { return len(f.Visible) == 2 && f.Window.FocusedBlockID != b1 }) // In the nav mode, h focuses left; Escape leaves the mode. h.press(ctrlR) if got := h.u.keyState(); got != "nav" { t.Errorf("key state in a mode = %q", got) } h.press(plainH) h.until("focus to move left", func(rexsession.Frame) bool { return h.u.session.FocusedBlock() == b1 }) h.press(escape) if got := h.u.keyState(); got != "" { t.Errorf("key state after Escape = %q", got) } // The configuration file's ctrl+shift+d replaces the default split. h.press(ctrlShiftD) h.until("the zoom", func(f rexsession.Frame) bool { return f.Window.ZoomedBlockID == b1 && len(f.Visible) == 1 }) h.press(ctrlShiftD) h.until("the zoom to end", func(f rexsession.Frame) bool { return f.Window.ZoomedBlockID == "" && len(f.Visible) == 2 }) // A default the file leaves alone still works. h.press(ctrlShiftT) f := h.until("the new tab", func(f rexsession.Frame) bool { return len(f.View.Windows) == 2 }) first := f.View.Windows[0].WindowID h.until("the new tab to be active", func(f rexsession.Frame) bool { return f.View.ActiveWindowID != first }) // ctrl+b c opens another. h.press(ctrlB, plainC) h.until("a third tab", func(f rexsession.Frame) bool { return len(f.View.Windows) == 3 }) // Another client can perform this client's actions. perform := func(action string, args any) error { done := make(chan error, 1) go func() { _, err := other.Call(context.Background(), "client.perform", map[string]any{ "client_id": c.Welcome().ClientID(), "action": action, "args": args, "session_id": sid, }, nil) done <- err }() for deadline := time.After(10 * time.Second); ; { select { case err := <-done: return err case <-deadline: t.Fatalf("client.perform %s didn't return", action) case <-time.After(20 * time.Millisecond): h.frame() } } } if err := perform("client.tab.goto", map[string]any{"index": 1}); err != nil { t.Fatal(err) } h.until("the first tab", func(f rexsession.Frame) bool { return f.View.ActiveWindowID == first }) if err := perform("client.sidebar.toggle", nil); err == nil { t.Error("performing an action this client lacks succeeded") } } // TestCopy selects a word in a real pane by double-clicking it, copies it // with the keymap's Ctrl+Shift+C, and checks what reached the clipboard. // Typing then clears the selection. func TestCopy(t *testing.T) { srv := rextest.Start(t) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, "/bin/sh", "-c", "printf 'alpha bravo charlie\\r\\n'; stty raw -echo; exec cat -vt") c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the pane", func(f rexsession.Frame) bool { return strings.Contains(screenText(h.term(b1)), "alpha bravo") }) // "bravo" is columns 6 to 10 of the first row. Find where the pane's // terminal sits from the view's own metrics. v := h.u.panes[b1].view cell := v.CellSize() pad := int(v.Padding) sidebar, titlebar, gap, border, header := int(theme.SidebarWide), int(theme.TitlebarHigh), int(theme.Gap), int(theme.Border), 28 x0, y0 := sidebar+gap+border+pad, titlebar+gap+border+header+border+pad p := f32.Pt(float32(x0+8*cell.X+cell.X/2), float32(y0+cell.Y/2)) for range 2 { for _, kind := range []pointer.Kind{pointer.Press, pointer.Release} { h.router.Queue(pointer.Event{Kind: kind, Source: pointer.Mouse, Position: p, Buttons: pointer.ButtonPrimary, Time: time.Duration(time.Now().UnixNano())}) } h.frame() } if got, _ := h.selection(); got != "bravo" { t.Fatalf("double-click selected %q, want %q", got, "bravo") } h.press(chord("shift+ctrl", "key_c", 'c')) h.frame() mime, data, ok := h.router.WriteClipboard() if !ok || mime != "application/text" || string(data) != "bravo" { t.Errorf("clipboard = %q, %q, %v; want application/text, bravo", mime, data, ok) } // Typing clears the selection. h.press(chord("", "key_x", 'x')) if got, _ := h.selection(); got != "" { t.Errorf("selection after typing = %q, want none", got) } } // fakePrimary is a primary selection for tests, so they leave the // desktop's alone. type fakePrimary struct { mu sync.Mutex text string } func (p *fakePrimary) Set(text string) error { p.mu.Lock() defer p.mu.Unlock() p.text = text return nil } func (p *fakePrimary) Get(context.Context) (string, error) { p.mu.Lock() defer p.mu.Unlock() return p.text, nil } func (p *fakePrimary) get() string { s, _ := p.Get(context.Background()); return s } // paneOrigin is where a pane's cells start in the window, for a pane that // fills the workspace. func paneOrigin(h *uiHarness, block string) (image.Point, image.Point) { v := h.u.panes[block].view pad := int(v.Padding) x := int(theme.SidebarWide) + int(theme.Gap) + int(theme.Border) + pad y := int(theme.TitlebarHigh) + int(theme.Gap) + int(theme.Border) + 28 + int(theme.Border) + pad return image.Pt(x, y), v.CellSize() } // TestPrimarySelection double-clicks a word, which becomes the primary // selection, then middle-clicks to paste it into the pane. func TestPrimarySelection(t *testing.T) { srv := rextest.Start(t) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, "/bin/sh", "-c", "printf 'alpha bravo charlie\\r\\n'; stty raw -echo; exec cat -vt") c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) sel := &fakePrimary{} h.u.Primary = sel h.until("the pane", func(f rexsession.Frame) bool { return strings.Contains(screenText(h.term(b1)), "alpha bravo") }) origin, cell := paneOrigin(h, b1) at := func(col, row int) f32.Point { return f32.Pt(float32(origin.X+col*cell.X+cell.X/2), float32(origin.Y+row*cell.Y+cell.Y/2)) } mouse := func(kind pointer.Kind, p f32.Point, b pointer.Buttons) { h.router.Queue(pointer.Event{Kind: kind, Source: pointer.Mouse, Position: p, Buttons: b, Time: time.Duration(time.Now().UnixNano())}) h.frame() } for range 2 { mouse(pointer.Press, at(14, 0), pointer.ButtonPrimary) mouse(pointer.Release, at(14, 0), pointer.ButtonPrimary) } h.until("the primary selection", func(rexsession.Frame) bool { return sel.get() == "charlie" }) mouse(pointer.Press, at(3, 3), pointer.ButtonTertiary) mouse(pointer.Release, at(3, 3), pointer.ButtonTertiary) h.until("the paste", func(f rexsession.Frame) bool { return strings.Contains(screenText(h.term(b1)), "\ncharlie") }) } // TestWheelToProgram scrolls over a program that reads the mouse, and // checks the program gets wheel reports, which the server encodes. The // block is another device's: the wheel takes it, as typing would. func TestWheelToProgram(t *testing.T) { srv := rextest.Start(t) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, "/bin/sh", "-c", `printf '\033[?1000h\033[?1006h'; stty raw -echo; printf 'ready\r\n'; exec cat -vt`) if _, err := other.OwnBlocks(context.Background(), sid, "take", b1); err != nil { t.Fatal(err) } c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the pane, owned elsewhere", func(f rexsession.Frame) bool { p := f.Panes[b1] return strings.Contains(screenText(h.term(b1)), "ready") && p.State.Owner != "" && !p.State.Owned }) origin, cell := paneOrigin(h, b1) h.router.Queue(pointer.Event{ Kind: pointer.Scroll, Source: pointer.Mouse, Position: f32.Pt(float32(origin.X+4*cell.X+cell.X/2), float32(origin.Y+2*cell.Y+cell.Y/2)), Scroll: f32.Pt(0, float32(2*cell.Y)), }) h.frame() // Two lines down at column 5, row 3 (1-based): SGR wheel-down is 65. h.until("two wheel reports, and the block", func(f rexsession.Frame) bool { return strings.Count(screenText(h.term(b1)), "^[[<65;5;3M") == 2 && f.Panes[b1].State.Owned }) } // TestClickToProgram clicks and drags over a program that reads the // mouse, and checks the program gets the reports, which the server // encodes. The block is another device's: the press takes it. func TestClickToProgram(t *testing.T) { srv := rextest.Start(t) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, "/bin/sh", "-c", `printf '\033[?1002h\033[?1006h'; stty raw -echo; printf 'ready\r\n'; exec cat -vt`) if _, err := other.OwnBlocks(context.Background(), sid, "take", b1); err != nil { t.Fatal(err) } c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the pane, owned elsewhere", func(f rexsession.Frame) bool { p := f.Panes[b1] return strings.Contains(screenText(h.term(b1)), "ready") && p.State.Owner != "" && !p.State.Owned }) origin, cell := paneOrigin(h, b1) at := func(col, row int) f32.Point { return f32.Pt(float32(origin.X+col*cell.X+cell.X/2), float32(origin.Y+row*cell.Y+cell.Y/2)) } mouse := func(kind pointer.Kind, p f32.Point, b pointer.Buttons) { h.router.Queue(pointer.Event{Kind: kind, Source: pointer.Mouse, Position: p, Buttons: b, Time: time.Duration(time.Now().UnixNano())}) h.frame() } mouse(pointer.Press, at(4, 2), pointer.ButtonPrimary) mouse(pointer.Move, at(6, 2), pointer.ButtonPrimary) mouse(pointer.Release, at(6, 2), 0) mouse(pointer.Press, at(1, 4), pointer.ButtonSecondary) mouse(pointer.Release, at(1, 4), 0) // SGR, 1-based: left press at 5,3; a drag with left held (32); the // release (lower-case m); then the right button (2). want := "^[[<0;5;3M^[[<32;7;3M^[[<0;7;3m^[[<2;2;5M^[[<2;2;5m" h.until("the mouse reports, and the block", func(f rexsession.Frame) bool { return strings.Contains(screenText(h.term(b1)), want) && f.Panes[b1].State.Owned }) if s, _ := h.selection(); s != "" { t.Errorf("clicking the program selected %q", s) } } // TestScrollbackDoesntClaim scrolls back through a shell's history, which // happens only here, and checks the other device keeps the block. func TestScrollbackDoesntClaim(t *testing.T) { srv := rextest.Start(t) other := srv.Dial(t, "other-device") sid, b1 := rextest.NewSession(t, other, "/bin/sh", "-c", `i=0; while [ $i -lt 100 ]; do echo "line $i"; i=$((i+1)); done; exec cat`) if _, err := other.OwnBlocks(context.Background(), sid, "take", b1); err != nil { t.Fatal(err) } c := srv.Dial(t, "100gex-test") h := startUI(t, srv, c, sid) h.until("the history", func(f rexsession.Frame) bool { p := f.Panes[b1] return strings.Contains(screenText(h.term(b1)), "line 99") && p.State.Owner != "" }) scrollbar := func() (s libghostty.Scrollbar) { h.held(func(f rexsession.Frame) { s, _ = h.term(b1).Scrollbar() }) return s } before := scrollbar() origin, cell := paneOrigin(h, b1) h.router.Queue(pointer.Event{ Kind: pointer.Scroll, Source: pointer.Mouse, Position: f32.Pt(float32(origin.X+cell.X), float32(origin.Y+cell.Y)), Scroll: f32.Pt(0, float32(-5*cell.Y)), }) h.frame() if after := scrollbar(); after.Offset+5 != before.Offset { t.Fatalf("scrollback offset %d after wheeling up 5, want %d", after.Offset, before.Offset-5) } time.Sleep(300 * time.Millisecond) // time for a wrong claim to land if f := h.frame(); f.Panes[b1].State.Owned { t.Error("scrolling the scrollback took the block") } }