// Package rexterm shows a Rex terminal block: it keeps a local copy of the // server's terminal, fed by the block's data connection, and sends input back // on the control connection. // // The server's terminal is the real one. It answers the program's queries // and decides the size, so the local copy never replies to anything and only // resizes when the stream says the server did. package rexterm import ( "context" "encoding/json" "errors" "fmt" "log" "runtime" "strings" "sync" "sync/atomic" "time" "go.mitchellh.com/libghostty" "100gex/internal/rex" "100gex/internal/termscreen" ) // State is what a pane knows about its block, apart from the terminal. type State struct { // Status describes the connection for people, such as "connecting". Status string // Exited is true once the block's program has exited, with ExitCode. Exited bool ExitCode int // Closed is true once the block has closed. Nothing more will come. Closed bool // Err is why the stream failed, if it did. Err error // Owner is the client that owns the block, or "" if none does. The // block takes its size from its owner. Owner string // Owned is true if this client owns the block. Owned bool } // Pane is one terminal block. Sync, Release and Close must be called from // one goroutine, the one that draws the terminal; the other methods may be // called from any goroutine. // // The stream's goroutine applies output to the terminal as it arrives, so // however fast a program prints, a frame never has to parse it: a frame // holds the terminal, from Sync to Release, only to draw it. type Pane struct { closeOnce sync.Once conn *rex.Conn ep rex.Endpoint sessionID string blockID string clientID string notify func() ctx context.Context cancel context.CancelFunc wg sync.WaitGroup inputs chan func(context.Context) error mu sync.Mutex state State applyErr error // a message the terminal couldn't take, for Sync wantSize termSize // the size to ask for sentSize termSize // the size last asked for // termMu guards term and its screen: the stream changes them, and a // frame takes what it draws from them. termMu sync.Mutex term *libghostty.Terminal scr *termscreen.Screen held bool // the drawing goroutine has termMu, from Sync to Release // wanted is set while Sync waits for termMu, so that the stream lets // it in after the slice it's parsing rather than taking the terminal // back: a mutex only hands itself over once a waiter has waited 1ms. wanted atomic.Bool } // parseSlice is the most output applied at a time while holding the // terminal: well under a millisecond's parsing, so a frame waits at most // that long for the terminal. const parseSlice = 8 << 10 type termSize struct { cols, rows uint16 cellWidth, cellHigh int } // Open starts showing a block. It connects in the background, so it returns // at once; notify is called from other goroutines whenever there is // something new for Sync, and must not block. conn must be attached to the // session. func Open(conn *rex.Conn, ep rex.Endpoint, sessionID, blockID string, notify func()) *Pane { ctx, cancel := context.WithCancel(context.Background()) p := &Pane{ conn: conn, ep: ep, sessionID: sessionID, blockID: blockID, clientID: conn.Welcome().ClientID(), notify: notify, ctx: ctx, cancel: cancel, inputs: make(chan func(context.Context) error, 4096), state: State{Status: "connecting"}, } // Take the block if no one has it, so it follows this client's size, // but don't take it from another client until the person types here. p.enqueue(func(ctx context.Context) error { return p.claim(ctx, "request") }) p.wg.Add(2) go p.runInputs() go p.runStream() return p } // SessionID and BlockID name the pane's block. func (p *Pane) SessionID() string { return p.sessionID } func (p *Pane) BlockID() string { return p.blockID } // Sync takes hold of the terminal and returns its screen, as the stream // has left it so far, with the pane's state. The screen is nil until the // snapshot has arrived. Output stops being applied until Release, which // must be called once the frame has taken what it draws; the terminal // mustn't be used after it, though the screen may be read. Calling Sync // again before Release keeps the hold. // // The error is a message from the server the terminal couldn't take. func (p *Pane) Sync() (*termscreen.Screen, State, error) { p.mu.Lock() state, err := p.state, p.applyErr p.applyErr = nil p.mu.Unlock() if !p.held { p.wanted.Store(true) p.termMu.Lock() p.wanted.Store(false) p.held = true } return p.scr, state, err } // Release lets output be applied to the terminal again, after Sync. It // does nothing if the terminal isn't held. func (p *Pane) Release() { if p.held { p.held = false p.termMu.Unlock() } } // Key sends a key to the block, giving Lua key bindings the first chance at // it. For the last key of a sequence, prefix holds the keys before it. A // press or repeat claims the block first, so that it follows this client's // size: the person is using it here. func (p *Pane) Key(k rex.KeyEvent, prefix ...string) { p.enqueue(func(ctx context.Context) error { if err := p.claimForInput(ctx, k.Action != "release"); err != nil { return err } _, err := p.conn.Key(ctx, p.sessionID, p.blockID, k, prefix...) return err }) } // Claim takes the block for this client, unless it's this client's // already, so that the block follows this client's size and colours. It is // for when the person acts on the pane here, such as by clicking it. func (p *Pane) Claim() { p.enqueue(func(ctx context.Context) error { return p.claimForInput(ctx, true) }) } // Wheel sends wheel turns to the program, at a cell: one line per message, // negative for up, as a mouse reports them. It claims the block first, as // typing does: the program acts on the wheel, so the person is using it // here. (Scrolling the local scrollback never reaches the server, and // claims nothing.) func (p *Pane) Wheel(col, row uint16, lines int) { step := 1 if lines < 0 { step, lines = -1, -lines } lines = min(lines, 8) p.enqueue(func(ctx context.Context) error { if err := p.claimForInput(ctx, true); err != nil { return err } for range lines { if err := p.conn.Wheel(ctx, p.sessionID, p.blockID, col, row, step); err != nil { return err } } return nil }) } // Mouse sends a mouse event to the program. A press claims the block // first, as typing does. func (p *Pane) Mouse(e rex.MouseEvent) { p.enqueue(func(ctx context.Context) error { if err := p.claimForInput(ctx, e.Action == "press"); err != nil { return err } return p.conn.Mouse(ctx, p.sessionID, p.blockID, e) }) } // SetTheme asks for the terminal's default colours. Like a size, the server // applies them while this client owns the block. func (p *Pane) SetTheme(t rex.TerminalTheme) { p.enqueue(func(ctx context.Context) error { return p.conn.SetTerminalTheme(ctx, p.sessionID, p.blockID, t) }) } // SendKey sends a key straight to the block, past any Lua key bindings. func (p *Pane) SendKey(k rex.KeyEvent) { p.enqueue(func(ctx context.Context) error { if err := p.claimForInput(ctx, true); err != nil { return err } return p.conn.SendKey(ctx, p.sessionID, p.blockID, k) }) } // claimForInput takes the block before active input, unless it's already // this client's. func (p *Pane) claimForInput(ctx context.Context, active bool) error { if active && !p.owned() { return p.claim(ctx, "take") } return nil } // Paste sends pasted text to the block, claiming it first. func (p *Pane) Paste(text string) { p.enqueue(func(ctx context.Context) error { if err := p.claimForInput(ctx, true); err != nil { return err } return p.conn.Paste(ctx, p.sessionID, p.blockID, text) }) } // RequestSize asks for the terminal to be resized to fit this client's view. // The server applies it only while this client owns the block, and // remembers it for when it does. Requests are coalesced, so only the latest // is sent. func (p *Pane) RequestSize(cols, rows uint16, cellWidth, cellHeight int) { p.mu.Lock() p.wantSize = termSize{cols, rows, cellWidth, cellHeight} p.mu.Unlock() p.enqueue(func(ctx context.Context) error { p.mu.Lock() want, sent := p.wantSize, p.sentSize p.mu.Unlock() if want == sent { return nil } if err := p.conn.ResizeTerminal(ctx, p.sessionID, p.blockID, want.cols, want.rows, want.cellWidth, want.cellHigh); err != nil { return err } p.mu.Lock() p.sentSize = want p.mu.Unlock() return nil }) } // HandleEvent updates the pane from a control connection event. Pass it // every event; it ignores the ones that aren't about its block. func (p *Pane) HandleEvent(ev rex.Event) { if ev.SessionID != p.sessionID { return } switch ev.Name { case "block_owner_changed": var e struct { BlockID string `json:"block_id"` Owner string `json:"owner"` } if json.Unmarshal(ev.Payload, &e) == nil && e.BlockID == p.blockID { p.setOwner(e.Owner) } case "block_closed": var e struct { BlockID string `json:"block_id"` } if json.Unmarshal(ev.Payload, &e) == nil && e.BlockID == p.blockID { p.update(func(s *State) { s.Closed, s.Status = true, "closed" }) } } } // closing counts panes whose streams are still ending. var closing sync.WaitGroup // Close stops showing the block. It returns at once: its stream ends, with // a close handshake that waits for the server, and its terminal is freed, // in the background, since Close is called while drawing, and a server // that has gone away answers only when the handshake times out. The pane // mustn't be used after, but Close may be called again, and does nothing. func (p *Pane) Close() { p.closeOnce.Do(p.close) } func (p *Pane) close() { p.Release() // the stream may be waiting to apply output p.cancel() closing.Add(1) go func() { defer closing.Done() p.wg.Wait() // The stream is over, so nothing else has the terminal. A frame // may still be reading its screen: Close waits for it. if p.term != nil { p.scr.Close() p.term.Close() p.term, p.scr = nil, nil } }() } // WaitClosed waits for the streams of closed panes to end, so that the // server sees them close rather than drop, or until timeout passes. It // reports whether they ended. func WaitClosed(timeout time.Duration) bool { done := make(chan struct{}) go func() { closing.Wait() close(done) }() select { case <-done: return true case <-time.After(timeout): return false } } func (p *Pane) enqueue(job func(context.Context) error) { select { case p.inputs <- job: default: log.Printf("rexterm: input queue full; dropping input for %s", p.blockID) } } // runInputs sends input in the order it was given, one call at a time, so // that keys reach the block in order. func (p *Pane) runInputs() { defer p.wg.Done() for { select { case job := <-p.inputs: ctx, cancel := context.WithTimeout(p.ctx, 10*time.Second) err := job(ctx) cancel() if err != nil && p.ctx.Err() == nil { log.Printf("rexterm: %v", err) } case <-p.ctx.Done(): return } } } func (p *Pane) claim(ctx context.Context, mode string) error { owners, err := p.conn.OwnBlocks(ctx, p.sessionID, mode, p.blockID) if err != nil { return fmt.Errorf("claim block: %w", err) } for _, o := range owners { if o.BlockID == p.blockID { p.setOwner(o.Owner) } } return nil } func (p *Pane) owned() bool { p.mu.Lock() defer p.mu.Unlock() return p.state.Owned } func (p *Pane) setOwner(owner string) { p.update(func(s *State) { s.Owner, s.Owned = owner, owner != "" && owner == p.clientID }) } // update changes the state and tells the drawing goroutine. func (p *Pane) update(change func(*State)) { p.mu.Lock() change(&p.state) p.mu.Unlock() p.notify() } // runStream connects to the block's stream and feeds it to the terminal // until the stream ends or the pane closes. func (p *Pane) runStream() { defer p.wg.Done() err := p.stream() if p.ctx.Err() != nil { return } p.update(func(s *State) { switch { case errors.Is(err, rex.ErrBlockClosed): s.Closed, s.Status = true, "closed" case errors.Is(err, rex.ErrStreamEnded): s.Closed, s.Status = true, "stream ended" default: s.Err, s.Status = err, "disconnected: "+err.Error() } }) } func (p *Pane) stream() error { ticket, err := p.conn.DataConnect(p.ctx, p.sessionID, p.blockID, "terminal", rex.TerminalSubprotocol) if err != nil { return err } data, err := rex.OpenData(p.ctx, p.ep, ticket) if err != nil { return err } // Closing the pane ends the stream with a normal close, which also ends // the Read below. Cancelling a Read would drop the connection instead, // and the server would keep the stream waiting for a resume. stop := context.AfterFunc(p.ctx, func() { data.Close() }) defer stop() p.update(func(s *State) { s.Status = "restoring" }) parser := rex.NewTerminalStream(data.Welcome().Nonce) h := &streamHandler{p: p} for { chunk, err := data.Read(context.Background()) if err != nil { return err } if err := parser.Feed(chunk, h); err != nil { data.Close() return err } if h.changed { h.changed = false p.notify() } } } // streamHandler applies the stream's parts to the terminal, on the // stream's goroutine. type streamHandler struct { p *Pane changed bool } func (h *streamHandler) Snapshot(data []byte) error { term, err := Restore(data) // without the terminal held: it's new if err != nil { return err } scr, err := termscreen.New(term) if err != nil { term.Close() return err } p := h.p p.lockForStream() old, oldScr := p.term, p.scr p.term, p.scr = term, scr p.termMu.Unlock() if old != nil { // No frame has the old terminal: frames get it under termMu. One // may still be reading its screen, which Close waits for. oldScr.Close() old.Close() } h.changed = true p.update(func(s *State) { s.Status = "live" }) return nil } // Output parses output into the terminal, a slice at a time, so that a // frame waiting to draw gets the terminal between slices. func (h *streamHandler) Output(data []byte) error { p := h.p for len(data) > 0 { n := min(len(data), parseSlice) p.lockForStream() if p.term != nil { // the stream always starts with a snapshot p.term.VTWrite(data[:n]) } p.termMu.Unlock() data = data[n:] } h.changed = true return nil } func (h *streamHandler) Message(m rex.Message) error { p := h.p switch m.Type { case "child_exited": p.update(func(s *State) { s.Exited, s.ExitCode = true, m.ExitCode }) case "resize", "theme": p.lockForStream() var err error if p.term != nil { err = apply(p.term, &m) } p.termMu.Unlock() if err != nil { p.mu.Lock() p.applyErr = err p.mu.Unlock() } h.changed = true } return nil } // lockForStream takes the terminal for the stream, after any frame waiting // for it. func (p *Pane) lockForStream() { for p.wanted.Load() { runtime.Gosched() } p.termMu.Lock() } // Restore decodes a snapshot into a new terminal. func Restore(snapshot []byte) (*libghostty.Terminal, error) { dec, err := libghostty.NewSnapshotDecoderBytesCopy(snapshot) if err != nil { return nil, fmt.Errorf("decode snapshot: %w", err) } defer dec.Close() term, err := dec.Decode() if err != nil { return nil, fmt.Errorf("decode snapshot: %w", err) } if end, err := dec.SourceOffset(); err != nil || end != uint(len(snapshot)) { term.Close() return nil, fmt.Errorf("decode snapshot: it ended at byte %d of %d (%v)", end, len(snapshot), err) } return term, nil } // apply applies one of Rex's messages to the terminal. func apply(term *libghostty.Terminal, m *rex.Message) error { switch m.Type { case "resize": if m.Cols == 0 || m.Rows == 0 { return fmt.Errorf("invalid resize to %dx%d", m.Cols, m.Rows) } if err := term.Resize(m.Cols, m.Rows, m.CellWidthPx, m.CellHeightPx); err != nil { return fmt.Errorf("resize to %dx%d: %w", m.Cols, m.Rows, err) } case "theme": // Each theme replaces the last; a colour left out is the built-in // one. for _, c := range []struct { value string set func(*libghostty.ColorRGB) error }{ {m.Foreground, term.SetColorForeground}, {m.Background, term.SetColorBackground}, {m.Cursor, term.SetColorCursor}, } { if err := c.set(parseColor(c.value)); err != nil { return fmt.Errorf("set theme: %w", err) } } var palette *libghostty.Palette if len(m.Palette) > 0 { pal := libghostty.DefaultPalette() for _, entry := range m.Palette { i, c, err := libghostty.ParsePaletteEntry(entry) if err != nil { continue // skip what we can't read, as for unknown fields } pal[i] = c } palette = &pal } if err := term.SetColorPalette(palette); err != nil { return fmt.Errorf("set palette: %w", err) } } return nil } // parseColor reads RRGGBB or #RRGGBB, returning nil for anything else. func parseColor(s string) *libghostty.ColorRGB { s = strings.TrimPrefix(s, "#") if len(s) != 6 { return nil } var r, g, b uint8 if _, err := fmt.Sscanf(s, "%02x%02x%02x", &r, &g, &b); err != nil { return nil } return &libghostty.ColorRGB{R: r, G: g, B: b} }