package rexsession import ( "context" "encoding/json" "fmt" "net/url" "strings" "100gex/internal/rex" ) // shellFlavor makes the terminal blocks that new panes and tabs start with. const shellFlavor = "com.superlogical.terminal.shell" // floatBounds is where a newly floated pane goes, as fractions of the window. var floatBounds = [4]float64{0.15, 0.15, 0.7, 0.7} // Split splits the focused block, putting a new shell on the given side: // left, right, up, down, or auto for the longer side. The shell starts in // the focused block's working directory. func (s *Session) Split(side string) { s.SplitBlock(s.FocusedBlock(), side) } // SplitBlock splits anchor as Split does the focused block, and focuses the // new shell. func (s *Session) SplitBlock(anchor, side string) { if anchor == "" { return } if side == "auto" || side == "best_fit" { side = "down" if w, h := s.blockSize(anchor); w > h { side = "right" } } var direction, place string switch side { case "left": direction, place = "horizontal", "before" case "right": direction, place = "horizontal", "after" case "up": direction, place = "vertical", "before" case "down": direction, place = "vertical", "after" default: s.reportf("split: unknown direction %q", side) return } s.enqueue(func(ctx context.Context) error { _, err := s.conn.Call(ctx, "session.new_split", map[string]any{ "session_id": s.id, "anchor_id": anchor, "direction": direction, "side": place, "layout": s.shellLayout(ctx, anchor), "focus": true, }, nil) return err }) } // shellLayout is a layout of one shell, in the working directory of block. func (s *Session) shellLayout(ctx context.Context, block string) map[string]any { options := map[string]any{} if dir := s.workingDirectory(ctx, block); dir != "" { options["cwd"] = dir } return map[string]any{"block": map[string]any{"flavor": shellFlavor, "options": options}} } // workingDirectory returns the directory a program in block last reported, // or "" if none did. func (s *Session) workingDirectory(ctx context.Context, block string) string { if block == "" { return "" } var result struct { PWD string `json:"pwd"` } if err := s.conn.BlockMethod(ctx, s.id, block, "com.superlogical.terminal.pwd", nil, &result); err != nil { return "" } if u, err := url.Parse(result.PWD); err == nil && u.Scheme == "file" { return u.Path } return result.PWD } // ClosePane closes the focused block and ends its program. func (s *Session) ClosePane() { s.onFocused("block.close", nil) } // ToggleZoom zooms the focused block to fill its window, or undoes the zoom. func (s *Session) ToggleZoom() { s.mu.Lock() w := s.view.ActiveWindow() var block string zoom := true if w != nil { block = w.FocusedBlockID if w.ZoomedBlockID != "" { block, zoom = w.ZoomedBlockID, false } } s.mu.Unlock() if block == "" { return } s.call("session.zoom_block", map[string]any{"session_id": s.id, "block_id": block, "zoom": zoom}) } // FocusDirection focuses the nearest block to the left, right, above, or // below the focused one. func (s *Session) FocusDirection(direction string) { s.call("session.focus_direction", map[string]any{"session_id": s.id, "direction": direction}) } // FocusNextPane focuses the next block in the window, or the previous one. func (s *Session) FocusNextPane(next bool) { method := "session.focus_previous_pane" if next { method = "session.focus_next_pane" } s.call(method, map[string]any{"session_id": s.id, "wrap": true}) } // Float moves the focused block out of the layout into a floating layer. func (s *Session) Float() { s.FloatBlock(s.FocusedBlock()) } // FloatBlock moves a block out of its window's layout into a floating layer. func (s *Session) FloatBlock(block string) { if block == "" { return } s.call("session.float_block", map[string]any{"session_id": s.id, "block_id": block, "bounds": floatBounds}) } // DockBlock moves a floating block back into its window's layout, beside // the layout's largest block, across that block's longer side. It does // nothing if the block isn't floating in the active window or the layout is // empty. func (s *Session) DockBlock(block string) { anchor := s.dockAnchor(block) if anchor == "" { return } direction := "vertical" if w, h := s.blockSize(anchor); w > h { direction = "horizontal" } s.call("session.move_block", map[string]any{ "session_id": s.id, "block_id": block, "anchor_block_id": anchor, "direction": direction, "side": "after", }) } // dockAnchor picks the block in the active window's layout that a floating // block docks beside: the largest. It returns "" if block isn't floating // there or the layout is empty. func (s *Session) dockAnchor(block string) string { s.mu.Lock() defer s.mu.Unlock() w := s.view.ActiveWindow() if w == nil { return "" } floating := false var tiled *rex.LayoutNode for _, l := range w.Layers { if l.Kind == "tiled" { tiled = l.Layout } else if hasBlock(l, block) { floating = true } } if !floating { return "" } anchor, best := "", 0.0 var walk func(n *rex.LayoutNode) walk = func(n *rex.LayoutNode) { switch { case n == nil: case n.Split != nil: walk(n.Split.Before) walk(n.Split.After) case n.BlockID != "" && n.Rect[2]*n.Rect[3] > best: anchor, best = n.BlockID, n.Rect[2]*n.Rect[3] } } walk(tiled) return anchor } // NewFloating opens a shell in a new floating layer, in the focused block's // working directory. func (s *Session) NewFloating() { focused := s.FocusedBlock() s.enqueue(func(ctx context.Context) error { _, err := s.conn.Call(ctx, "session.new_layer", map[string]any{ "session_id": s.id, "bounds": floatBounds, "layout": s.shellLayout(ctx, focused), "focus": true, }, nil) return err }) } // MinimizeFloating minimizes the floating layer that holds the focused // block. It does nothing if the focused block isn't floating. func (s *Session) MinimizeFloating() { s.mu.Lock() var layer string if w := s.view.ActiveWindow(); w != nil { for _, l := range w.Layers { if l.Kind != "tiled" && hasBlock(l, w.FocusedBlockID) { layer = l.LayerID } } } s.mu.Unlock() if layer == "" { return } s.call("session.set_layer_state", map[string]any{"session_id": s.id, "layer_id": layer, "state": "minimized"}) } // RestoreFloating brings every minimized floating layer in the active window // back. func (s *Session) RestoreFloating() { s.mu.Lock() var layers []string if w := s.view.ActiveWindow(); w != nil { for _, l := range w.Layers { if l.State == "minimized" { layers = append(layers, l.LayerID) } } } s.mu.Unlock() for _, id := range layers { s.call("session.set_layer_state", map[string]any{"session_id": s.id, "layer_id": id, "state": "normal", "focus": true}) } } func hasBlock(l rex.Layer, block string) bool { for _, b := range l.Blocks { if b.BlockID == block { return true } } return false } // NewTab opens a window with one shell, in the focused block's working // directory, and makes it active. func (s *Session) NewTab() { focused := s.FocusedBlock() s.enqueue(func(ctx context.Context) error { _, err := s.conn.Call(ctx, "session.new_window", map[string]any{ "session_id": s.id, "layout": s.shellLayout(ctx, focused), }, nil) return err }) } // CloseTab closes the active window and every block in it. func (s *Session) CloseTab() { s.mu.Lock() id := s.view.ActiveWindowID s.mu.Unlock() if id != "" { s.call("session.close_window", map[string]any{"session_id": s.id, "window_id": id}) } } // NextTab makes the next window active, or the previous one, wrapping round. func (s *Session) NextTab(next bool) { method := "session.focus_previous_window" if next { method = "session.focus_next_window" } s.call(method, map[string]any{"session_id": s.id, "wrap": true}) } // GotoTab makes the window at a 1-based position active. 0 or less, or past // the end, does nothing; the last window can be reached with -1. func (s *Session) GotoTab(position int) { s.mu.Lock() windows := s.view.Windows var id string switch { case position > 0 && position <= len(windows): id = windows[position-1].WindowID case position == -1 && len(windows) > 0: id = windows[len(windows)-1].WindowID } s.mu.Unlock() if id != "" { s.FocusWindow(id) } } // Claim takes a block for this client, so that it follows this client's // size and colours: the person is using it here. func (s *Session) Claim(blockID string) { s.mu.Lock() p := s.panes[blockID] s.mu.Unlock() if p != nil { p.Claim() } } // PasteTo pastes text into a block. func (s *Session) PasteTo(blockID, text string) { s.mu.Lock() p := s.panes[blockID] s.mu.Unlock() if p != nil { s.typed(blockID) p.Paste(text) } } // Wheel sends wheel turns to a block's program, at a cell. func (s *Session) Wheel(blockID string, col, row uint16, lines int) { s.mu.Lock() p := s.panes[blockID] s.mu.Unlock() if p != nil { p.Wheel(col, row, lines) } } // Mouse sends a mouse event to a block's program. func (s *Session) Mouse(blockID string, e rex.MouseEvent) { s.mu.Lock() p := s.panes[blockID] s.mu.Unlock() if p != nil { p.Mouse(e) } } // SendKey sends a key straight to the focused block, past Lua key bindings. func (s *Session) SendKey(k rex.KeyEvent) { if p := s.focusedPane(); p != nil { s.typed(s.FocusedBlock()) p.SendKey(k) } } // ForwardKey sends a key to the focused block through client.key, with the // keys of a sequence before it, so a Lua function bound to it can answer. func (s *Session) ForwardKey(k rex.KeyEvent, prefix []string) { if p := s.focusedPane(); p != nil { s.typed(s.FocusedBlock()) p.Key(k, prefix...) } } // Paste pastes text into the focused block. func (s *Session) Paste(text string) { if p := s.focusedPane(); p != nil { s.typed(s.FocusedBlock()) p.Paste(text) } } // ServerAction runs an action the server provides: one from the // configuration file, or a block's, on the focused block. The configuration // file's actions can ask this client to perform client actions; perform is // called with those, in order, on a background goroutine. func (s *Session) ServerAction(action string, args json.RawMessage, perform func([]rex.ClientAction)) { block := s.FocusedBlock() s.enqueue(func(ctx context.Context) error { result, err := s.conn.Action(ctx, s.id, block, action, args) if err != nil { return fmt.Errorf("%s: %w", action, err) } if len(result.ClientActions) > 0 && perform != nil { perform(result.ClientActions) } return nil }) } func (s *Session) focusedPane() interface { Key(rex.KeyEvent, ...string) SendKey(rex.KeyEvent) Paste(string) } { id := s.FocusedBlock() s.mu.Lock() defer s.mu.Unlock() if p, ok := s.panes[id]; ok { return p } return nil } // onFocused calls a method on the focused block, with extra arguments. func (s *Session) onFocused(method string, args map[string]any) { block := s.FocusedBlock() if block == "" { return } payload := map[string]any{"session_id": s.id, "block_id": block} for k, v := range args { payload[k] = v } s.call(method, payload) } // call queues a request that must run in order with the others. func (s *Session) call(method string, args any) { s.enqueue(func(ctx context.Context) error { if _, err := s.conn.Call(ctx, method, args, nil); err != nil { return fmt.Errorf("%s: %w", strings.TrimPrefix(method, "session."), err) } return nil }) } // blockSize returns the size in pixels this client last asked for a block's // terminal to be. func (s *Session) blockSize(block string) (width, height int) { s.mu.Lock() defer s.mu.Unlock() sz := s.sizes[block] return int(sz[0]) * int(sz[2]), int(sz[1]) * int(sz[3]) } // MoveBlock moves a block into a new split beside anchor, which may be in // another window or layer. direction is "horizontal" for side by side or // "vertical" for one above the other; side is "before" for the left or top // part, or "after". func (s *Session) MoveBlock(blockID, anchorID, direction, side string) { if blockID == anchorID { return } s.call("session.move_block", map[string]any{ "session_id": s.id, "block_id": blockID, "anchor_block_id": anchorID, "direction": direction, "side": side, }) } // SwapBlocks swaps the places of two blocks. func (s *Session) SwapBlocks(a, b string) { if a == b { return } s.call("session.swap_blocks", map[string]any{"session_id": s.id, "block_id": a, "other_block_id": b}) } // MoveLayer moves or resizes a floating layer to bounds, as x, y, width and // height fractions of the window. func (s *Session) MoveLayer(layerID string, bounds [4]float64) { s.call("session.resize_layer", map[string]any{"session_id": s.id, "layer_id": layerID, "bounds": bounds}) } // ResizePane moves the border of the split between blocks before and after // so that the before part gets ratio of its space. direction is the // split's: "horizontal" for side by side, "vertical" for one above the // other. func (s *Session) ResizePane(direction, before, after string, ratio float64) { s.call("session.resize_pane", map[string]any{ "session_id": s.id, "direction": direction, "before_block_id": before, "after_block_id": after, "ratio": ratio, }) } // RaiseLayer brings a floating layer in front of the others. func (s *Session) RaiseLayer(layerID string) { s.call("session.raise_layer", map[string]any{"session_id": s.id, "layer_id": layerID}) }