// 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" "slices" "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 { // Theme, if set, is the colours this client asks every terminal it // shows to use. Set it before the first Sync. Theme *rex.TerminalTheme 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 held []*rexterm.Pane // panes Sync holds, until Release sizes map[string][4]int // cols, rows, cell width and height last asked for, by block titles map[string]string // each block's terminal title, from the server titled map[string]bool // blocks whose title has been asked for // Used only by Sync. shown string // the window the last frame showed pending string // a window switched to that isn't shown yet pendingSince time.Time // when the switch to pending was seen } // Frame is what Sync returns: the view to draw and each block's terminal. type Frame struct { View rex.View // Window is the window to draw, or nil if the session has none. It's // the active window, unless a switch to that is waiting for its panes. Window *rex.Window // Visible lists the blocks Window shows, in drawing order. Visible []string // Panes holds the open panes: those of the active window, its // neighbours, and any window shown before. A tab whose blocks have no // pane yet can't show its program's title. Panes map[string]PaneFrame // Titles holds each block's terminal title, as the server reports it, // for blocks with no pane open. Titles map[string]string // 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), sizes: make(map[string][4]int), titles: make(map[string]string), titled: make(map[string]bool), } 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 "block_event": var e struct { BlockID string `json:"block_id"` Name string `json:"name"` Payload struct { Title string `json:"title"` } `json:"payload"` } if json.Unmarshal(ev.Payload, &e) == nil && e.Name == "title_changed" { s.mu.Lock() s.titles[e.BlockID] = e.Payload.Title s.mu.Unlock() s.notify() } 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 } // Ready reports whether every block the frame shows has its terminal, so // it can be drawn without empty panes. func (f Frame) Ready() bool { for _, id := range f.Visible { if f.Panes[id].Term == nil { return false } } return true } // warmTabs is how many windows either side of the active one get their // blocks' streams opened before they are shown, so switching to them has // nothing to wait for. Others open when they are first shown. As in rexia, // this bounds the streams opened up front in a session with many windows. const warmTabs = 2 // switchWait is how long a window switched to may take to restore its // panes before it's shown anyway, with whatever has arrived. const switchWait = 1500 * time.Millisecond // Sync opens panes for the blocks of the active window and its neighbours, // closes the panes of blocks that have left the session, and returns the // view and every open pane's terminal. A pane, once open, stays open while // its block is in a window. // // The frame holds the terminals: their output waits until Release, which // must be called once the frame is done with them, and they mustn't be // used after it. Calling Sync again before Release keeps the hold. // // When the active window changes to one whose panes aren't restored yet, // the frame goes on showing the window shown before, until they are or // switchWait passes, so that a switch never draws empty panes. func (s *Session) Sync() (Frame, error) { s.Release() s.mu.Lock() f := Frame{View: s.view, Destroyed: s.destroyed} s.mu.Unlock() exists := make(map[string]bool) for _, w := range f.View.Windows { for _, l := range w.Layers { for _, b := range l.Blocks { exists[b.BlockID] = true } } } warm := make(map[string]bool) active := -1 for i := range f.View.Windows { if f.View.Windows[i].WindowID == f.View.ActiveWindowID { active = i } } if active >= 0 { for _, id := range visible(&f.View.Windows[active]) { warm[id] = true } for i := max(active-warmTabs, 0); i <= min(active+warmTabs, len(f.View.Windows)-1); i++ { for _, id := range visible(&f.View.Windows[i]) { warm[id] = true } } } s.mu.Lock() var gone []*rexterm.Pane for id, p := range s.panes { if !exists[id] { gone = append(gone, p) delete(s.panes, id) } } // Titles: asked for once per block, then kept current by // title_changed events. for id := range exists { if !s.titled[id] { s.titled[id] = true s.wg.Add(1) go s.fetchTitle(id) } } f.Titles = make(map[string]string, len(s.titles)) for id, t := range s.titles { if exists[id] { f.Titles[id] = t } } for id := range warm { if _, ok := s.panes[id]; !ok { p := rexterm.Open(s.conn, s.ep, s.id, id, s.notify) if s.Theme != nil { p.SetTheme(*s.Theme) } s.panes[id] = p } } 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() s.held = append(s.held, p) if err != nil { return f, err } f.Panes[id] = PaneFrame{Term: term, State: st} } // Show the active window, unless a switch to it is still waiting for // its panes. f.Window = f.View.ActiveWindow() f.Visible = visible(f.Window) switch { case f.Window == nil || f.View.ActiveWindowID == s.shown: s.shown, s.pending = f.View.ActiveWindowID, "" case f.View.ActiveWindowID != s.pending: s.pending, s.pendingSince = f.View.ActiveWindowID, time.Now() fallthrough default: prev := f.View.Window(s.shown) if f.Ready() || prev == nil || time.Since(s.pendingSince) >= switchWait { s.shown, s.pending = f.View.ActiveWindowID, "" break } held := Frame{View: f.View, Panes: f.Panes, Window: prev, Visible: visible(prev)} if !held.Ready() { s.shown, s.pending = f.View.ActiveWindowID, "" break } f.Window, f.Visible = held.Window, held.Visible } return f, nil } // fetchTitle asks for a block's title. An event that arrived meanwhile is // newer, and wins. func (s *Session) fetchTitle(block string) { defer s.wg.Done() ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) defer cancel() var result struct { Title string `json:"title"` } if err := s.conn.BlockMethod(ctx, s.id, block, "com.superlogical.terminal.title", nil, &result); err != nil { return } s.mu.Lock() if _, ok := s.titles[block]; !ok { s.titles[block] = result.Title } s.mu.Unlock() s.notify() } // 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.sizes[blockID] = [4]int{int(cols), int(rows), cellWidth, cellHeight} 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 }) } // MoveWindow moves a window to just before another in the session's window // order, or to the end if beforeID is "". The view changes at once, before // the server confirms. func (s *Session) MoveWindow(windowID, beforeID string) { if windowID == beforeID { return } s.mu.Lock() from := s.view.WindowIndex(windowID) if from < 0 { s.mu.Unlock() return } v := cloneView(s.view) w := v.Windows[from] v.Windows = slices.Delete(v.Windows, from, from+1) to := len(v.Windows) if beforeID != "" { if to = v.WindowIndex(beforeID); to < 0 { s.mu.Unlock() return } } if to == from { s.mu.Unlock() return // already there } v.Windows = slices.Insert(v.Windows, to, w) s.view = v s.mu.Unlock() s.notify() args := map[string]any{"session_id": s.id, "window_id": windowID} if beforeID != "" { args["before_window_id"] = beforeID } s.call("session.move_window", args) } // 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 } // Release lets output be applied to the terminals of the last Sync again. // The frame mustn't use them after it. func (s *Session) Release() { for _, p := range s.held { p.Release() } s.held = s.held[:0] } // 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() } } // reportf tells people about a problem that doesn't stop the session. func (s *Session) reportf(format string, args ...any) { log.Printf("rexsession: "+format, args...) } 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 } } }