From 2a99db5d640efed2dfd6d3a44ea03c2b9d71c20d Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Fri, 20 Nov 2026 14:48:45 +0000 Subject: [PATCH] Show a session's layout: tabs, splits, floating layers, and focus The app now shows a whole session instead of one block. - internal/rexsession: follows a session. It fetches session.view when a session_view_changed event announces a newer revision (several changes can share one fetch), and keeps a pane for each block the active window shows: the zoomed block alone, or every block in each layer that isn't minimized. Focusing a block or switching windows takes effect locally at once and is sent to the server in order. - internal/ui: draws a tab per window and the active window's layers back to front, with each block at its rect (fractions of the window, for floating layers too). Neighbouring panes share a 1px separator, and floating layers get a frame. Clicking a pane focuses it, and clicking a tab switches to it. Unfocused panes are dimmed and draw an outline cursor. Keys go to the focused block. - internal/termview: View only draws now. Keyboard input moved to Keys, which serves the whole window. - rextest: shared helpers for dialing, creating sessions and blocks, and a raw cat -vt command that shows the bytes a block receives. Tests drive a second client that splits, opens windows, zooms, closes blocks and destroys the session, and check this client follows. Clicks go through Gio's input router. --- internal/rex/rextest/server.go | 61 +++++ internal/rex/session.go | 7 +- internal/rexsession/session.go | 354 ++++++++++++++++++++++++++++ internal/rexsession/session_test.go | 193 +++++++++++++++ internal/rexterm/pane_test.go | 51 +--- internal/termview/input.go | 45 +++- internal/termview/view.go | 51 ++-- internal/termview/view_test.go | 1 + internal/ui/ui.go | 286 ++++++++++++++++++++++ internal/ui/ui_test.go | 151 ++++++++++++ main.go | 61 ++--- 11 files changed, 1131 insertions(+), 130 deletions(-) create mode 100644 internal/rexsession/session.go create mode 100644 internal/rexsession/session_test.go create mode 100644 internal/ui/ui.go create mode 100644 internal/ui/ui_test.go diff --git a/internal/rex/rextest/server.go b/internal/rex/rextest/server.go index 49b4436..e30f41a 100644 --- a/internal/rex/rextest/server.go +++ b/internal/rex/rextest/server.go @@ -4,6 +4,7 @@ package rextest import ( "bytes" + "context" "net" "os" "os/exec" @@ -100,3 +101,63 @@ func shortTempDir(t testing.TB) string { t.Cleanup(func() { os.RemoveAll(dir) }) return dir } + +// Dial opens a control connection to s, closed when the test ends. +func (s *Server) Dial(t testing.TB, name string) *rex.Conn { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + c, err := rex.Dial(ctx, s.Endpoint, rex.ClientInfo{Kind: "app", Name: name}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +// Block returns a layout block that runs command directly, with no shell. +func Block(command ...string) map[string]any { + return map[string]any{"block": map[string]any{ + "flavor": "com.superlogical.terminal.shell", + "options": map[string]any{"shell": "none", "command": command}, + }} +} + +// RawCat is a command that shows every byte it receives, as cat -vt does +// with the terminal in raw mode, after printing "ready" once it is. +var RawCat = []string{"/bin/sh", "-c", "stty raw -echo; printf 'ready\\r\\n'; exec cat -vt"} + +// NewSession creates a session whose one window holds one block running +// command, attaches c to it, and returns the session and block IDs. +func NewSession(t testing.TB, c *rex.Conn, command ...string) (sessionID, blockID string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + var created struct { + SessionID string `json:"session_id"` + InitialWindows []struct { + BlockIDs []string `json:"block_ids"` + } `json:"initial_windows"` + } + _, err := c.Call(ctx, "session.create", map[string]any{ + "initial_windows": []any{map[string]any{"layout": Block(command...)}}, + }, &created) + if err != nil { + t.Fatal(err) + } + if _, _, err := c.Attach(ctx, created.SessionID); err != nil { + t.Fatal(err) + } + return created.SessionID, created.InitialWindows[0].BlockIDs[0] +} + +// Call makes a call that must succeed, and decodes its result into result, +// which may be nil. +func Call(t testing.TB, c *rex.Conn, method string, args, result any) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := c.Call(ctx, method, args, result); err != nil { + t.Fatalf("%s: %v", method, err) + } +} diff --git a/internal/rex/session.go b/internal/rex/session.go index ed49572..e84d363 100644 --- a/internal/rex/session.go +++ b/internal/rex/session.go @@ -25,9 +25,12 @@ type View struct { } // ActiveWindow returns the window the session shows, or nil if it has none. -func (v *View) ActiveWindow() *Window { +func (v *View) ActiveWindow() *Window { return v.Window(v.ActiveWindowID) } + +// Window returns the window with the given ID, or nil. +func (v *View) Window(id string) *Window { for i := range v.Windows { - if v.Windows[i].WindowID == v.ActiveWindowID { + if v.Windows[i].WindowID == id { return &v.Windows[i] } } diff --git a/internal/rexsession/session.go b/internal/rexsession/session.go new file mode 100644 index 0000000..2064811 --- /dev/null +++ b/internal/rexsession/session.go @@ -0,0 +1,354 @@ +// Package rexsession follows one Rex session: it keeps the session's view +// current from the server's events, and a pane for each block the active +// window shows. +package rexsession + +import ( + "context" + "encoding/json" + "log" + "sync" + "time" + + "go.mitchellh.com/libghostty" + + "100gex/internal/rex" + "100gex/internal/rexterm" +) + +// Session is one attached session. Sync, Key, and Close must be called from +// the goroutine that draws; the other methods may be called from any. +type Session struct { + conn *rex.Conn + ep rex.Endpoint + id string + notify func() + + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + jobs chan func(context.Context) error + + mu sync.Mutex + view rex.View + seen uint64 // the highest revision an event has announced + fetching bool + destroyed bool + panes map[string]*rexterm.Pane // changed only by Sync +} + +// Frame is what Sync returns: the view to draw and each visible block's +// terminal. +type Frame struct { + View rex.View + // Window is the active window, or nil if the session has none. + Window *rex.Window + // Panes holds a pane for each block the active window shows. + Panes map[string]PaneFrame + // Destroyed is true once the session is gone. + Destroyed bool +} + +// PaneFrame is one block's terminal, nil until it is restored, and state. +type PaneFrame struct { + Term *libghostty.Terminal + State rexterm.State +} + +// New follows the session whose view is given, which conn must be attached +// to. notify is called from other goroutines when there is something new for +// Sync, and must not block. +func New(conn *rex.Conn, ep rex.Endpoint, view rex.View, notify func()) *Session { + ctx, cancel := context.WithCancel(context.Background()) + s := &Session{ + conn: conn, + ep: ep, + id: view.SessionID, + notify: notify, + ctx: ctx, + cancel: cancel, + jobs: make(chan func(context.Context) error, 256), + view: view, + seen: view.Revision, + panes: make(map[string]*rexterm.Pane), + } + s.wg.Add(1) + go s.runJobs() + return s +} + +// ID returns the session's ID. +func (s *Session) ID() string { return s.id } + +// HandleEvent updates the session from a control connection event. Pass it +// every event newer than the view the session started with. +func (s *Session) HandleEvent(ev rex.Event) { + if ev.SessionID != s.id && !(ev.Name == "session_destroyed" && ev.SessionID == "") { + return + } + s.mu.Lock() + panes := make([]*rexterm.Pane, 0, len(s.panes)) + for _, p := range s.panes { + panes = append(panes, p) + } + s.mu.Unlock() + for _, p := range panes { + p.HandleEvent(ev) + } + + switch ev.Name { + case "session_view_changed": + var e struct { + Revision uint64 `json:"revision"` + } + if json.Unmarshal(ev.Payload, &e) == nil { + s.viewChanged(e.Revision) + } + case "session_destroyed": + var e struct { + SessionID string `json:"session_id"` + } + if json.Unmarshal(ev.Payload, &e) == nil && (e.SessionID == s.id || ev.SessionID == s.id) { + s.mu.Lock() + s.destroyed = true + s.mu.Unlock() + s.notify() + } + } +} + +// viewChanged fetches the view if revision is newer than any seen. Events +// can arrive out of revision order, and several changes can share a fetch. +func (s *Session) viewChanged(revision uint64) { + s.mu.Lock() + defer s.mu.Unlock() + if revision <= s.seen { + return + } + s.seen = revision + if s.fetching { + return // the running fetch goes again when it sees seen moved + } + s.fetching = true + s.wg.Add(1) + go s.fetchViews() +} + +func (s *Session) fetchViews() { + defer s.wg.Done() + for { + ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) + view, _, err := s.conn.SessionView(ctx, s.id) + cancel() + + s.mu.Lock() + if err == nil && view.Revision > s.view.Revision { + s.view = view + } + again := err == nil && s.seen > s.view.Revision && s.ctx.Err() == nil + if !again { + s.fetching = false + } + s.mu.Unlock() + if err != nil && s.ctx.Err() == nil { + if rex.IsCode(err, "session_not_found") { + s.mu.Lock() + s.destroyed = true + s.mu.Unlock() + } else { + log.Printf("rexsession: fetch view: %v", err) + } + } + s.notify() + if !again { + return + } + } +} + +// visible returns the blocks the window shows, in drawing order: the zoomed +// block alone, or every block in each layer that isn't minimized. +func visible(w *rex.Window) []string { + if w == nil { + return nil + } + if w.ZoomedBlockID != "" { + return []string{w.ZoomedBlockID} + } + var ids []string + for _, l := range w.Layers { + if l.State == "minimized" { + continue + } + for _, b := range l.Blocks { + ids = append(ids, b.BlockID) + } + } + return ids +} + +// Sync opens panes for blocks that have come into view and closes the ones +// that have gone, then returns the view and every visible block's terminal. +// The terminals are only valid until the next Sync or Close. +func (s *Session) Sync() (Frame, error) { + s.mu.Lock() + f := Frame{View: s.view, Destroyed: s.destroyed} + s.mu.Unlock() + f.Window = f.View.ActiveWindow() + + want := make(map[string]bool) + for _, id := range visible(f.Window) { + want[id] = true + } + s.mu.Lock() + var gone []*rexterm.Pane + for id, p := range s.panes { + if !want[id] { + gone = append(gone, p) + delete(s.panes, id) + } + } + for id := range want { + if _, ok := s.panes[id]; !ok { + s.panes[id] = rexterm.Open(s.conn, s.ep, s.id, id, s.notify) + } + } + panes := make(map[string]*rexterm.Pane, len(s.panes)) + for id, p := range s.panes { + panes[id] = p + } + s.mu.Unlock() + for _, p := range gone { + p.Close() + } + + f.Panes = make(map[string]PaneFrame, len(panes)) + for id, p := range panes { + term, st, err := p.Sync() + if err != nil { + return f, err + } + f.Panes[id] = PaneFrame{Term: term, State: st} + } + return f, nil +} + +// FocusedBlock returns the block that typing goes to: the active window's +// focused block, or "" if there is none. +func (s *Session) FocusedBlock() string { + s.mu.Lock() + defer s.mu.Unlock() + if w := s.view.ActiveWindow(); w != nil { + if w.ZoomedBlockID != "" { + return w.ZoomedBlockID + } + return w.FocusedBlockID + } + return "" +} + +// Key sends a key to the focused block. +func (s *Session) Key(k rex.KeyEvent) { + id := s.FocusedBlock() + s.mu.Lock() + p := s.panes[id] + s.mu.Unlock() + if p != nil { + p.Key(k) + } +} + +// RequestSize asks for a block's terminal to be resized to fit this client's +// view of it. +func (s *Session) RequestSize(blockID string, cols, rows uint16, cellWidth, cellHeight int) { + s.mu.Lock() + p := s.panes[blockID] + s.mu.Unlock() + if p != nil { + p.RequestSize(cols, rows, cellWidth, cellHeight) + } +} + +// FocusBlock focuses a block. Typing goes to it at once, before the server +// confirms. +func (s *Session) FocusBlock(blockID string) { + s.mu.Lock() + if w := s.view.ActiveWindow(); w != nil { + if w.FocusedBlockID == blockID { + s.mu.Unlock() + return + } + s.view = cloneView(s.view) + s.view.ActiveWindow().FocusedBlockID = blockID + } + s.mu.Unlock() + s.notify() + s.enqueue(func(ctx context.Context) error { + _, err := s.conn.Call(ctx, "session.focus_block", map[string]string{"session_id": s.id, "block_id": blockID}, nil) + return err + }) +} + +// FocusWindow makes a window the active one. The view changes at once, +// before the server confirms. +func (s *Session) FocusWindow(windowID string) { + s.mu.Lock() + if s.view.ActiveWindowID == windowID { + s.mu.Unlock() + return + } + s.view = cloneView(s.view) + s.view.ActiveWindowID = windowID + s.mu.Unlock() + s.notify() + s.enqueue(func(ctx context.Context) error { + _, err := s.conn.Call(ctx, "session.focus_window", map[string]string{"session_id": s.id, "window_id": windowID}, nil) + return err + }) +} + +// cloneView copies the parts of v that a local change touches, so that a +// Frame already handed out never changes under its reader. +func cloneView(v rex.View) rex.View { + v.Windows = append([]rex.Window(nil), v.Windows...) + return v +} + +// Close closes every pane, ending their streams. It doesn't close the +// connection. +func (s *Session) Close() { + s.cancel() + s.wg.Wait() + s.mu.Lock() + panes := s.panes + s.panes = nil + s.mu.Unlock() + for _, p := range panes { + p.Close() + } +} + +func (s *Session) enqueue(job func(context.Context) error) { + select { + case s.jobs <- job: + default: + log.Printf("rexsession: request queue full; dropping a request") + } +} + +// runJobs makes requests one at a time, in order. +func (s *Session) runJobs() { + defer s.wg.Done() + for { + select { + case job := <-s.jobs: + ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) + if err := job(ctx); err != nil && s.ctx.Err() == nil { + log.Printf("rexsession: %v", err) + } + cancel() + case <-s.ctx.Done(): + return + } + } +} diff --git a/internal/rexsession/session_test.go b/internal/rexsession/session_test.go new file mode 100644 index 0000000..fc87ef9 --- /dev/null +++ b/internal/rexsession/session_test.go @@ -0,0 +1,193 @@ +package rexsession_test + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + "go.mitchellh.com/libghostty" + + "100gex/internal/rex" + "100gex/internal/rex/rextest" + "100gex/internal/rexsession" +) + +// harness runs a session as the app does. +type harness struct { + t *testing.T + s *rexsession.Session + wake chan struct{} +} + +func follow(t *testing.T, srv *rextest.Server, c *rex.Conn, sessionID string) *harness { + t.Helper() + view, seq, err := c.Attach(context.Background(), sessionID) + if err != nil { + t.Fatal(err) + } + h := &harness{t: t, wake: make(chan struct{}, 1)} + h.s = rexsession.New(c, srv.Endpoint, view, func() { + select { + case h.wake <- struct{}{}: + default: + } + }) + t.Cleanup(h.s.Close) + go func() { + for ev := range c.Events() { + if ev.Seq > seq { + h.s.HandleEvent(ev) + } + } + }() + return h +} + +// until syncs the session until cond holds, and returns that frame. +func (h *harness) until(what string, cond func(rexsession.Frame) bool) rexsession.Frame { + h.t.Helper() + deadline := time.After(10 * time.Second) + for { + f, err := h.s.Sync() + if err != nil { + h.t.Fatal(err) + } + if cond(f) { + return f + } + select { + case <-h.wake: + case <-time.After(50 * time.Millisecond): + case <-deadline: + h.t.Fatalf("timed out waiting for %s; view %+v", what, f.View) + } + } +} + +// shows reports whether f has a restored terminal for each block, and no +// others, and each screen contains text. +func shows(f rexsession.Frame, text string, blocks ...string) bool { + if len(f.Panes) != len(blocks) { + return false + } + for _, id := range blocks { + p, ok := f.Panes[id] + if !ok || p.Term == nil || !strings.Contains(screen(p.Term), text) { + return false + } + } + return true +} + +func screen(term *libghostty.Terminal) string { + f, err := libghostty.NewFormatter(term) + if err != nil { + return "" + } + defer f.Close() + s, _ := f.FormatString() + return s +} + +// serverView returns the session's view as another client sees it. +func serverView(t *testing.T, c *rex.Conn, sessionID string) rex.View { + t.Helper() + v, _, err := c.SessionView(context.Background(), sessionID) + if err != nil { + t.Fatal(err) + } + return v +} + +func eventually(t *testing.T, what string, cond func() bool) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(20 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + } +} + +func TestSession(t *testing.T) { + srv := rextest.Start(t) + // Another device changes the layout; this client follows. + other := srv.Dial(t, "other-device") + sid, b1 := rextest.NewSession(t, other, rextest.RawCat...) + c := srv.Dial(t, "100gex-test") + h := follow(t, srv, c, sid) + h.until("the first block", func(f rexsession.Frame) bool { return shows(f, "ready", b1) }) + + // A split appears, with focus. + var split struct { + BlockIDs []string `json:"block_ids"` + } + rextest.Call(t, other, "session.new_split", map[string]any{ + "session_id": sid, "anchor_id": b1, "direction": "horizontal", "side": "after", + "layout": rextest.Block(rextest.RawCat...), "focus": true, + }, &split) + b2 := split.BlockIDs[0] + h.until("the split", func(f rexsession.Frame) bool { + return shows(f, "ready", b1, b2) && f.Window.FocusedBlockID == b2 + }) + + // Typing goes to the focused block. + h.s.Key(rex.KeyEvent{Action: "press", Key: "key_x", Text: "x"}) + h.until("x in the split", func(f rexsession.Frame) bool { return strings.Contains(screen(f.Panes[b2].Term), "ready\nx") }) + + // Focusing a block takes effect here at once, and reaches the server. + h.s.FocusBlock(b1) + if got := h.s.FocusedBlock(); got != b1 { + t.Fatalf("focused block after FocusBlock = %s, want %s", got, b1) + } + h.s.Key(rex.KeyEvent{Action: "press", Key: "key_y", Text: "y"}) + h.until("y in the first block", func(f rexsession.Frame) bool { return strings.Contains(screen(f.Panes[b1].Term), "ready\ny") }) + eventually(t, "the server to focus the first block", func() bool { + v := serverView(t, other, sid) + return v.ActiveWindow().FocusedBlockID == b1 + }) + + // A new window becomes active: only its block is shown. + var win struct { + WindowID string `json:"window_id"` + BlockIDs []string `json:"block_ids"` + } + rextest.Call(t, other, "session.new_window", map[string]any{ + "session_id": sid, "window_label": "logs", "layout": rextest.Block(rextest.RawCat...), + }, &win) + b3 := win.BlockIDs[0] + f := h.until("the new window", func(f rexsession.Frame) bool { + return f.View.ActiveWindowID == win.WindowID && shows(f, "ready", b3) + }) + if len(f.View.Windows) != 2 || f.View.Windows[1].Label != "logs" { + t.Errorf("windows = %+v", f.View.Windows) + } + + // Switching back shows the first window's blocks again. + first := f.View.Windows[0].WindowID + h.s.FocusWindow(first) + h.until("the first window", func(f rexsession.Frame) bool { return shows(f, "ready", b1, b2) }) + eventually(t, "the server to switch windows", func() bool { + return serverView(t, other, sid).ActiveWindowID == first + }) + + // Zooming shows the zoomed block alone. + rextest.Call(t, other, "session.zoom_block", map[string]any{"session_id": sid, "block_id": b2, "zoom": true}, nil) + h.until("the zoom", func(f rexsession.Frame) bool { return shows(f, "ready", b2) }) + if got := h.s.FocusedBlock(); got != b2 { + t.Errorf("focused block while zoomed = %s, want %s", got, b2) + } + rextest.Call(t, other, "session.zoom_block", map[string]any{"session_id": sid, "block_id": b2, "zoom": false}, nil) + + // A closed block leaves the layout. + rextest.Call(t, other, "block.close", map[string]any{"session_id": sid, "block_id": b2}, nil) + f = h.until("the close", func(f rexsession.Frame) bool { return shows(f, "", b1) }) + if ids := f.Window.Layers[0].Blocks; !slices.ContainsFunc(ids, func(b rex.BlockInfo) bool { return b.BlockID == b1 }) || len(ids) != 1 { + t.Errorf("blocks after close = %+v", ids) + } + + // The session going away ends it. + rextest.Call(t, other, "session.destroy", map[string]any{"session_id": sid}, nil) + h.until("the session to end", func(f rexsession.Frame) bool { return f.Destroyed }) +} diff --git a/internal/rexterm/pane_test.go b/internal/rexterm/pane_test.go index 19b2b04..8149ba2 100644 --- a/internal/rexterm/pane_test.go +++ b/internal/rexterm/pane_test.go @@ -13,35 +13,6 @@ import ( "100gex/internal/rexterm" ) -// session creates a session whose one block runs command directly, attaches -// c to it, and returns the session and block IDs. -func session(t *testing.T, c *rex.Conn, command ...string) (sessionID, blockID string) { - t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - var created struct { - SessionID string `json:"session_id"` - InitialWindows []struct { - BlockIDs []string `json:"block_ids"` - } `json:"initial_windows"` - } - _, err := c.Call(ctx, "session.create", map[string]any{ - "initial_windows": []any{map[string]any{ - "layout": map[string]any{"block": map[string]any{ - "flavor": "com.superlogical.terminal.shell", - "options": map[string]any{"shell": "none", "command": command}, - }}, - }}, - }, &created) - if err != nil { - t.Fatal(err) - } - if _, _, err := c.Attach(ctx, created.SessionID); err != nil { - t.Fatal(err) - } - return created.SessionID, created.InitialWindows[0].BlockIDs[0] -} - // harness runs a pane as the app does: events go to HandleEvent, and Sync // is called from the test goroutine. type harness struct { @@ -113,24 +84,12 @@ func size(term *libghostty.Terminal) (cols, rows uint16) { return cols, rows } -func dial(t *testing.T, srv *rextest.Server, name string) *rex.Conn { - t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - c, err := rex.Dial(ctx, srv.Endpoint, rex.ClientInfo{Kind: "app", Name: name}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { c.Close() }) - return c -} - func TestPane(t *testing.T) { srv := rextest.Start(t) - c := dial(t, srv, "100gex-test") + c := srv.Dial(t, "100gex-test") // cat -v in raw mode shows every byte it receives, so the screen shows // how the server encoded each key. - sid, bid := session(t, c, "/bin/sh", "-c", "stty raw -echo; printf 'ready\\r\\n'; exec cat -vt") + sid, bid := rextest.NewSession(t, c, rextest.RawCat...) h := open(t, srv, c, sid, bid) h.until("the snapshot", func(term *libghostty.Terminal, st rexterm.State) bool { @@ -177,8 +136,8 @@ func TestPane(t *testing.T) { // it, but typing does. func TestOwnership(t *testing.T) { srv := rextest.Start(t) - other := dial(t, srv, "other-device") - sid, bid := session(t, other, "/bin/sh", "-c", "stty raw -echo; printf 'ready\\r\\n'; exec cat -vt") + other := srv.Dial(t, "other-device") + sid, bid := rextest.NewSession(t, other, rextest.RawCat...) ctx := context.Background() if _, err := other.OwnBlocks(ctx, sid, "take", bid); err != nil { t.Fatal(err) @@ -187,7 +146,7 @@ func TestOwnership(t *testing.T) { t.Fatal(err) } - c := dial(t, srv, "100gex-test") + c := srv.Dial(t, "100gex-test") if _, _, err := c.Attach(ctx, sid); err != nil { t.Fatal(err) } diff --git a/internal/termview/input.go b/internal/termview/input.go index f4007b1..c5d0673 100644 --- a/internal/termview/input.go +++ b/internal/termview/input.go @@ -4,8 +4,10 @@ import ( "unicode" "unicode/utf8" + "gioui.org/io/event" "gioui.org/io/key" "gioui.org/layout" + "gioui.org/op/clip" "100gex/internal/rex" ) @@ -138,31 +140,48 @@ var usUnshifted = map[rune]rune{ ':': ';', '"': '\'', '<': ',', '>': '.', '?': '/', } -// handleInput reports the keyboard input received since the last frame. -func (v *View) handleInput(gtx layout.Context) { +// Keys turns keyboard input into Rex key events. One Keys serves a whole +// window: the events go to whichever block has focus. +type Keys struct { + filters []event.Filter + focused bool +} + +// NewKeys returns a keyboard input handler. +func NewKeys() *Keys { + k := &Keys{} + k.filters = []event.Filter{key.FocusFilter{Target: k}} + for _, f := range keyFilters(k) { + k.filters = append(k.filters, f) + } + return k +} + +// Layout takes keyboard focus for the area of gtx.Constraints.Max, and calls +// send with each key typed since the last frame. +func (k *Keys) Layout(gtx layout.Context, send func(rex.KeyEvent)) { for { - ev, ok := gtx.Event(v.filters...) + ev, ok := gtx.Event(k.filters...) if !ok { - return + break } switch e := ev.(type) { case key.FocusEvent: - v.focused = e.Focus + k.focused = e.Focus case key.EditEvent: - v.sendKey(textKey(e.Text)) + send(textKey(e.Text)) case key.Event: if e.State != key.Press { continue } - if k, ok := translateKey(e); ok { - v.sendKey(k) + if ke, ok := translateKey(e); ok { + send(ke) } } } -} - -func (v *View) sendKey(k rex.KeyEvent) { - if v.OnKey != nil { - v.OnKey(k) + defer clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops).Pop() + event.Op(gtx.Ops, k) + if !k.focused { + gtx.Execute(key.FocusCmd{Tag: k}) } } diff --git a/internal/termview/view.go b/internal/termview/view.go index 59e1680..b761319 100644 --- a/internal/termview/view.go +++ b/internal/termview/view.go @@ -14,8 +14,6 @@ import ( "gioui.org/f32" "gioui.org/font" - "gioui.org/io/event" - "gioui.org/io/key" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" @@ -25,8 +23,6 @@ import ( "golang.org/x/image/math/fixed" "go.mitchellh.com/libghostty" - - "100gex/internal/rex" ) // Typeface is the font family list cells are drawn with. Go Mono must be in @@ -35,15 +31,16 @@ import ( // Go Mono lacks (CJK, emoji) resolve to an arbitrary face and draw as tofu. const Typeface font.Typeface = "Go Mono, monospace, emoji" -// View paints a terminal and reports the keys typed into it and the size -// that would fill it. It never changes the terminal: the terminal belongs to -// a Rex server, which decides its size. +// View paints a terminal and reports the size that would fill it. It never +// changes the terminal: the terminal belongs to a Rex server, which decides +// its size. Keyboard input is handled separately, by [Keys]. type View struct { // FontSize is the size cells are drawn at. FontSize unit.Sp - // OnKey receives keyboard input. It is called from Layout. - OnKey func(rex.KeyEvent) + // Focused draws the cursor solid; otherwise it is drawn as an outline, + // to show that typing goes elsewhere. + Focused bool // OnResize is called from Layout when the number of cells that fit the // view changes, and on the first Layout. @@ -55,9 +52,6 @@ type View struct { rows *libghostty.RenderStateRowIterator cells *libghostty.RenderStateRowCells - filters []event.Filter - focused bool - metrics metrics metricsPx int cols, lines uint16 @@ -97,10 +91,6 @@ func New(shaper *text.Shaper) (*View, error) { v.Close() return nil, err } - v.filters = []event.Filter{key.FocusFilter{Target: v}} - for _, f := range keyFilters(v) { - v.filters = append(v.filters, f) - } return v, nil } @@ -121,20 +111,16 @@ func (v *View) Close() { // Layout. func (v *View) Size() (cols, rows uint16) { return v.cols, v.lines } -// Layout handles input and paints term, which may be nil before it exists. -// The terminal is drawn from the top left at its own size; a terminal -// smaller than the view leaves a margin, and a larger one is cut off. +// Layout paints term, which may be nil before it exists, filling +// gtx.Constraints.Max. The terminal is drawn from the top left at its own +// size; a terminal smaller than the view leaves a margin, and a larger one is +// cut off. func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dimensions, error) { size := gtx.Constraints.Max - v.handleInput(gtx) m := v.measure(gtx) v.fit(size, m) defer clip.Rect{Max: size}.Push(gtx.Ops).Pop() - event.Op(gtx.Ops, v) - if !v.focused { - gtx.Execute(key.FocusCmd{Tag: v}) - } if term == nil { paint.FillShape(gtx.Ops, color.NRGBA{A: 0xff}, clip.Rect{Max: size}.Op()) return layout.Dimensions{Size: size}, nil @@ -203,8 +189,13 @@ func (v *View) Layout(gtx layout.Context, term *libghostty.Terminal) (layout.Dim if onCursor { v.fillCells(gtx, bgColor, defaultBg, bgStart, x, top, m) bgStart = x + 1 - fillRect(gtx, cursorColor, image.Rect(x*m.width, top, (x+1)*m.width, top+m.height)) - fg = bg + cell := image.Rect(x*m.width, top, (x+1)*m.width, top+m.height) + if v.Focused { + fillRect(gtx, cursorColor, cell) + fg = bg + } else { + strokeRect(gtx, cursorColor, cell, max(1, m.width/8)) + } } v.graphemes, err = v.cells.GraphemesInto(v.graphemes[:0]) @@ -367,6 +358,14 @@ func fillRect(gtx layout.Context, c color.NRGBA, r image.Rectangle) { paint.FillShape(gtx.Ops, c, clip.Rect(r).Op()) } +// strokeRect outlines r with lines w pixels wide, inside r. +func strokeRect(gtx layout.Context, c color.NRGBA, r image.Rectangle, w int) { + fillRect(gtx, c, image.Rect(r.Min.X, r.Min.Y, r.Max.X, r.Min.Y+w)) + fillRect(gtx, c, image.Rect(r.Min.X, r.Max.Y-w, r.Max.X, r.Max.Y)) + fillRect(gtx, c, image.Rect(r.Min.X, r.Min.Y, r.Min.X+w, r.Max.Y)) + fillRect(gtx, c, image.Rect(r.Max.X-w, r.Min.Y, r.Max.X, r.Max.Y)) +} + func rgb(c libghostty.ColorRGB) color.NRGBA { return color.NRGBA{R: c.R, G: c.G, B: c.B, A: 0xff} } diff --git a/internal/termview/view_test.go b/internal/termview/view_test.go index d2c9969..11ef7d3 100644 --- a/internal/termview/view_test.go +++ b/internal/termview/view_test.go @@ -44,6 +44,7 @@ func TestRenderSample(t *testing.T) { t.Fatal(err) } defer view.Close() + view.Focused = true // The view only asks for a size; a Rex server would apply it. view.OnResize = func(cols, rows uint16, cellW, cellH int) { if err := term.Resize(cols, rows, uint32(cellW), uint32(cellH)); err != nil { diff --git a/internal/ui/ui.go b/internal/ui/ui.go new file mode 100644 index 0000000..0a14d6b --- /dev/null +++ b/internal/ui/ui.go @@ -0,0 +1,286 @@ +// Package ui draws a Rex session in a Gio window: a tab for each of its +// windows, and the active window's blocks in its layout. +package ui + +import ( + "image" + "image/color" + "math" + + "gioui.org/font" + "gioui.org/io/event" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/op/paint" + "gioui.org/text" + "gioui.org/unit" + "gioui.org/widget" + "gioui.org/widget/material" + + "100gex/internal/rex" + "100gex/internal/rexsession" + "100gex/internal/termview" +) + +// Colours of the window's chrome. The terminals keep their own. +var ( + chromeBg = color.NRGBA{R: 0x1e, G: 0x1e, B: 0x22, A: 0xff} + separator = color.NRGBA{R: 0x3a, G: 0x3a, B: 0x42, A: 0xff} + activeTab = color.NRGBA{R: 0x2e, G: 0x2e, B: 0x36, A: 0xff} + tabText = color.NRGBA{R: 0x9a, G: 0x9a, B: 0xa6, A: 0xff} + activeText = color.NRGBA{R: 0xe8, G: 0xe8, B: 0xee, A: 0xff} + floatBorder = color.NRGBA{R: 0x6a, G: 0x6a, B: 0x78, A: 0xff} + unfocusedDim = color.NRGBA{A: 0x40} // laid over panes that typing doesn't go to +) + +// UI draws one session. +type UI struct { + session *rexsession.Session + shaper *text.Shaper + theme *material.Theme + keys *termview.Keys + + // FontSize is the size of the terminals' text. + FontSize unit.Sp + + panes map[string]*paneView + tabs map[string]*widget.Clickable +} + +// paneView is the drawing state of one block. +type paneView struct { + view *termview.View +} + +// New returns a UI for session, drawing text with shaper, which must include +// termview's typeface. +func New(session *rexsession.Session, shaper *text.Shaper) *UI { + th := material.NewTheme() + th.Shaper = shaper + th.Face = font.Typeface("Go, sans-serif") + return &UI{ + session: session, + shaper: shaper, + theme: th, + keys: termview.NewKeys(), + FontSize: 14, + panes: make(map[string]*paneView), + tabs: make(map[string]*widget.Clickable), + } +} + +// Close frees the drawing state of every pane. +func (u *UI) Close() { + for id, p := range u.panes { + p.view.Close() + delete(u.panes, id) + } +} + +// Layout draws the session, filling gtx.Constraints.Max. It returns the +// frame it drew, so the caller can tell when the session has gone. +func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, error) { + f, err := u.session.Sync() + if err != nil { + return f, err + } + size := gtx.Constraints.Max + paint.FillShape(gtx.Ops, chromeBg, clip.Rect{Max: size}.Op()) + + // Typing goes to the focused block, wherever the pointer is. + u.keys.Layout(gtx, u.session.Key) + + tabsHeight := 0 + if f.View.SessionID != "" { + tabsHeight = u.layoutTabs(gtx, &f.View) + } + content := image.Rect(0, tabsHeight, size.X, size.Y) + if err := u.layoutWindow(gtx, f, content); err != nil { + return f, err + } + u.forgetPanes(f) + return f, nil +} + +// layoutTabs draws a tab for each window and returns the bar's height. +func (u *UI) layoutTabs(gtx layout.Context, v *rex.View) int { + height := gtx.Dp(28) + gtx.Constraints = layout.Exact(image.Pt(gtx.Constraints.Max.X, height)) + + children := make([]layout.FlexChild, 0, len(v.Windows)) + for i := range v.Windows { + w := &v.Windows[i] + click := u.tabs[w.WindowID] + if click == nil { + click = new(widget.Clickable) + u.tabs[w.WindowID] = click + } + if click.Clicked(gtx) { + u.session.FocusWindow(w.WindowID) + } + active := w.WindowID == v.ActiveWindowID + label := w.Label + if label == "" { + label = "Window" + } + children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { + return click.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + return tab(gtx, u.theme, label, active) + }) + })) + } + layout.Flex{}.Layout(gtx, children...) + paint.FillShape(gtx.Ops, separator, clip.Rect{Min: image.Pt(0, height-1), Max: image.Pt(gtx.Constraints.Max.X, height)}.Op()) + + // Forget tabs for windows that have closed. + for id := range u.tabs { + if v.Window(id) == nil { + delete(u.tabs, id) + } + } + return height +} + +func tab(gtx layout.Context, th *material.Theme, label string, active bool) layout.Dimensions { + l := material.Label(th, unit.Sp(13), label) + l.Color = tabText + l.MaxLines = 1 + if active { + l.Color = activeText + } + m := op.Record(gtx.Ops) + dims := layout.Inset{Left: 14, Right: 14}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + return layout.Center.Layout(gtx, l.Layout) + }) + call := m.Stop() + if active { + paint.FillShape(gtx.Ops, activeTab, clip.Rect{Max: dims.Size}.Op()) + } + call.Add(gtx.Ops) + paint.FillShape(gtx.Ops, separator, clip.Rect{Min: image.Pt(dims.Size.X-1, 0), Max: dims.Size}.Op()) + return dims +} + +// layoutWindow draws the active window's blocks in area: the zoomed block +// alone, or each layer's layout, back to front. +func (u *UI) layoutWindow(gtx layout.Context, f rexsession.Frame, area image.Rectangle) error { + w := f.Window + if w == nil { + return nil + } + focused := w.FocusedBlockID + if w.ZoomedBlockID != "" { + return u.layoutPane(gtx, f, w.ZoomedBlockID, area, true) + } + for _, l := range w.Layers { + if l.State == "minimized" || l.Layout == nil { + continue + } + bounds := place(l.Bounds, area, area) + if l.Kind != "tiled" { + // A frame around a floating layer sets it apart from what's + // beneath. + paint.FillShape(gtx.Ops, floatBorder, clip.Rect(bounds.Inset(-1)).Op()) + } + for _, leaf := range leaves(l.Layout, nil) { + r := place(leaf.Rect, area, bounds).Intersect(bounds) + if err := u.layoutPane(gtx, f, leaf.BlockID, r, leaf.BlockID == focused); err != nil { + return err + } + } + } + return nil +} + +// leaves appends the blocks under n, in layout order. +func leaves(n *rex.LayoutNode, out []*rex.LayoutNode) []*rex.LayoutNode { + if n == nil { + return out + } + if n.Split != nil { + return leaves(n.Split.After, leaves(n.Split.Before, out)) + } + if n.BlockID != "" { + out = append(out, n) + } + return out +} + +// place turns a rect given as fractions of the window into pixels within +// area. Edges are rounded on their own, so neighbours share them exactly. +// A pane gives up its right and bottom pixel to a separator wherever it +// doesn't reach the edge of bounds, the layer it is in. +func place(frac [4]float64, area, bounds image.Rectangle) image.Rectangle { + w, h := float64(area.Dx()), float64(area.Dy()) + r := image.Rect( + area.Min.X+int(math.Round(frac[0]*w)), + area.Min.Y+int(math.Round(frac[1]*h)), + area.Min.X+int(math.Round((frac[0]+frac[2])*w)), + area.Min.Y+int(math.Round((frac[1]+frac[3])*h)), + ) + if r.Max.X < bounds.Max.X { + r.Max.X-- + } + if r.Max.Y < bounds.Max.Y { + r.Max.Y-- + } + return r.Intersect(area) +} + +// layoutPane draws one block in r. +func (u *UI) layoutPane(gtx layout.Context, f rexsession.Frame, blockID string, r image.Rectangle, focused bool) error { + if r.Empty() { + return nil + } + p := u.panes[blockID] + if p == nil { + v, err := termview.New(u.shaper) + if err != nil { + return err + } + v.OnResize = func(cols, rows uint16, cellWidth, cellHeight int) { + u.session.RequestSize(blockID, cols, rows, cellWidth, cellHeight) + } + p = &paneView{view: v} + u.panes[blockID] = p + } + + defer op.Offset(r.Min).Push(gtx.Ops).Pop() + gtx.Constraints = layout.Exact(r.Size()) + area := clip.Rect{Max: r.Size()}.Push(gtx.Ops) + defer area.Pop() + + // A press on an unfocused pane focuses it. + for { + ev, ok := gtx.Event(pointer.Filter{Target: p, Kinds: pointer.Press}) + if !ok { + break + } + if e, ok := ev.(pointer.Event); ok && e.Kind == pointer.Press && !focused { + u.session.FocusBlock(blockID) + } + } + event.Op(gtx.Ops, p) + + p.view.FontSize = u.FontSize + p.view.Focused = focused + if _, err := p.view.Layout(gtx, f.Panes[blockID].Term); err != nil { + return err + } + if !focused && len(f.Panes) > 1 { + paint.FillShape(gtx.Ops, unfocusedDim, clip.Rect{Max: r.Size()}.Op()) + } + return nil +} + +// forgetPanes frees the drawing state of blocks that are no longer shown. +func (u *UI) forgetPanes(f rexsession.Frame) { + for id, p := range u.panes { + if _, ok := f.Panes[id]; !ok { + p.view.Close() + delete(u.panes, id) + } + } +} diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go new file mode 100644 index 0000000..867642a --- /dev/null +++ b/internal/ui/ui_test.go @@ -0,0 +1,151 @@ +package ui + +import ( + "context" + "image" + "testing" + "time" + + "gioui.org/f32" + "gioui.org/font/gofont" + "gioui.org/io/input" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/text" + "gioui.org/unit" + + "100gex/internal/rex" + "100gex/internal/rex/rextest" + "100gex/internal/rexsession" +) + +func TestPlace(t *testing.T) { + area := image.Rect(0, 30, 1001, 631) // odd sizes, so fractions don't divide evenly + // Three panes: left half, and the right half split in two. + left := place([4]float64{0, 0, 0.5, 1}, area, area) + topRight := place([4]float64{0.5, 0, 0.5, 0.5}, area, area) + bottomRight := place([4]float64{0.5, 0.5, 0.5, 0.5}, area, area) + + // Neighbours leave exactly one pixel between them for the separator, + // and the panes reach the area's edges. + if left.Max.X+1 != topRight.Min.X || topRight.Max.Y+1 != bottomRight.Min.Y { + t.Errorf("separators: left %v, top right %v, bottom right %v", left, topRight, bottomRight) + } + if left.Min != area.Min || bottomRight.Max != area.Max || topRight.Max.X != area.Max.X { + t.Errorf("panes don't fill the area %v: %v %v %v", area, left, topRight, bottomRight) + } + + // In a floating layer, panes stop at the layer's edges. + bounds := place([4]float64{0.2, 0.25, 0.6, 0.5}, area, area) + if got := place([4]float64{0.2, 0.25, 0.6, 0.5}, area, bounds).Intersect(bounds); got != bounds { + t.Errorf("floating pane %v, want the layer's %v", got, bounds) + } +} + +func TestLeaves(t *testing.T) { + tree := &rex.LayoutNode{Split: &rex.Split{ + Before: &rex.LayoutNode{BlockID: "a"}, + After: &rex.LayoutNode{Split: &rex.Split{ + Before: &rex.LayoutNode{BlockID: "b"}, + After: &rex.LayoutNode{BlockID: "c"}, + }}, + }} + var got []string + for _, n := range leaves(tree, nil) { + got = append(got, n.BlockID) + } + if len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "c" { + t.Errorf("leaves = %v, want a b c", got) + } +} + +// TestClicks drives the UI with pointer events: clicking a pane focuses it, +// and clicking a tab switches windows. +func TestClicks(t *testing.T) { + srv := rextest.Start(t) + other := srv.Dial(t, "other-device") + sid, b1 := rextest.NewSession(t, other, rextest.RawCat...) + var split struct { + BlockIDs []string `json:"block_ids"` + } + rextest.Call(t, other, "session.new_split", map[string]any{ + "session_id": sid, "anchor_id": b1, "direction": "horizontal", "side": "after", + "layout": rextest.Block(rextest.RawCat...), "focus": true, + }, &split) + b2 := split.BlockIDs[0] + var win struct { + WindowID string `json:"window_id"` + } + rextest.Call(t, other, "session.new_window", map[string]any{ + "session_id": sid, "window_label": "logs", "layout": rextest.Block(rextest.RawCat...), "focus": false, + }, &win) + + c := srv.Dial(t, "100gex-test") + view, seq, err := c.Attach(context.Background(), sid) + if err != nil { + t.Fatal(err) + } + s := rexsession.New(c, srv.Endpoint, view, func() {}) + defer s.Close() + go func() { + for ev := range c.Events() { + if ev.Seq > seq { + s.HandleEvent(ev) + } + } + }() + u := New(s, text.NewShaper(text.WithCollection(gofont.Collection()))) + defer u.Close() + + const width, height = 1000, 600 + var router input.Router + var ops op.Ops + frame := func() rexsession.Frame { + ops.Reset() + gtx := layout.Context{ + Ops: &ops, + Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, + Constraints: layout.Exact(image.Pt(width, height)), + Now: time.Now(), + Source: router.Source(), + } + f, err := u.Layout(gtx) + if err != nil { + t.Fatal(err) + } + router.Frame(&ops) + return f + } + click := func(x, y float32) { + for _, kind := range []pointer.Kind{pointer.Press, pointer.Release} { + router.Queue(pointer.Event{ + Kind: kind, Source: pointer.Mouse, Position: f32.Pt(x, y), + Buttons: pointer.ButtonPrimary, + }) + } + } + until := func(what string, cond func(rexsession.Frame) bool) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { + if cond(frame()) { + return + } + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + } + } + + until("both panes", func(f rexsession.Frame) bool { return len(f.Panes) == 2 && f.Window.FocusedBlockID == b2 }) + + // The left half of the window, below the tabs, is the first block. + click(width/4, height/2) + until("the click to focus the first block", func(f rexsession.Frame) bool { return s.FocusedBlock() == b1 }) + + // The second tab is the new window. + click(150, 14) + until("the click to switch windows", func(f rexsession.Frame) bool { + return f.View.ActiveWindowID == win.WindowID && len(f.Panes) == 1 + }) +} diff --git a/main.go b/main.go index 53ba0ac..6fb650b 100644 --- a/main.go +++ b/main.go @@ -1,13 +1,13 @@ // Command 100gex is a Linux client for Superlogical's Rex. // -// For now it shows one block: the focused block of a session's active window. +// It shows one session: a tab for each of its windows, and the active +// window's blocks in their layout. package main import ( "context" "errors" "flag" - "fmt" "log" "os" "os/signal" @@ -22,8 +22,8 @@ import ( "gioui.org/unit" "100gex/internal/rex" - "100gex/internal/rexterm" - "100gex/internal/termview" + "100gex/internal/rexsession" + "100gex/internal/ui" ) func main() { @@ -75,25 +75,14 @@ func run(w *app.Window, server, sessionQuery string) error { if err != nil { return err } - win := view.ActiveWindow() - if win == nil { - return fmt.Errorf("session %q has no windows", view.Label) - } - blockID := win.FocusedBlockID - if win.ZoomedBlockID != "" { - blockID = win.ZoomedBlockID - } - if blockID == "" { - return fmt.Errorf("session %q has no focused block", view.Label) - } w.Option(app.Title(view.Label + " — 100gex")) - pane := rexterm.Open(conn, ep, view.SessionID, blockID, w.Invalidate) - defer pane.Close() + sess := rexsession.New(conn, ep, view, w.Invalidate) + defer sess.Close() go func() { for ev := range conn.Events() { if ev.Seq > seq { // older events are already in the view - pane.HandleEvent(ev) + sess.HandleEvent(ev) } } w.Invalidate() // the connection ended @@ -102,13 +91,8 @@ func run(w *app.Window, server, sessionQuery string) error { // Go Mono is bundled; system fonts stay loaded as fallbacks for // characters it lacks, such as CJK and emoji. shaper := text.NewShaper(text.WithCollection(gofont.Collection())) - tv, err := termview.New(shaper) - if err != nil { - return err - } - defer tv.Close() - tv.OnKey = pane.Key - tv.OnResize = pane.RequestSize + u := ui.New(sess, shaper) + defer u.Close() var ops op.Ops for { @@ -116,30 +100,21 @@ func run(w *app.Window, server, sessionQuery string) error { case app.DestroyEvent: return e.Err case app.FrameEvent: - // The terminal is only touched from this goroutine: the stream - // is collected in the background and applied here. - term, st, err := pane.Sync() + // Terminals are only touched from this goroutine: streams are + // collected in the background and applied here. + gtx := app.NewContext(&ops, e) + f, err := u.Layout(gtx) if err != nil { return err } - switch { - case st.Closed: - w.Perform(system.ActionClose) - case st.Err != nil: - return st.Err - case conn.Err() != nil: - if errors.Is(conn.Err(), rex.ErrClosed) { - w.Perform(system.ActionClose) - } else { - return conn.Err() - } - } + e.Frame(gtx.Ops) - gtx := app.NewContext(&ops, e) - if _, err := tv.Layout(gtx, term); err != nil { + switch err := conn.Err(); { + case f.Destroyed, errors.Is(err, rex.ErrClosed): + w.Perform(system.ActionClose) + case err != nil: return err } - e.Frame(gtx.Ops) } } } -- knotmirror 0.0.1