From d7e9be973c281fc835b87f8b4c812d77e0fab148 Mon Sep 17 00:00:00 2001 From: James Magahern Date: Tue, 17 Nov 2026 01:08:35 -0800 Subject: [PATCH] Build server-backed psyTerm with multiplexing and themed UI Move terminal sessions, tabs, panes, and state into a persistent headless server with local socket and SSH clients. Launch GUIs through a managed single-threaded zygote while keeping rendering responsive. Add animated cursors, themed chrome, teal pane focus outlines, uniform tabs, and middle-truncated names. Support program/CWD titles, manual renaming, home-directory abbreviation, and automatic pane/tab removal when shells exit. Document the process architecture, controls, and third-party cursor sources. Validated with 57 tests, strict Clippy, and live Wayland checks. --- Cargo.lock | 40 +- Cargo.toml | 5 +- README.md | 262 +++++--- THIRD_PARTY_NOTICES.md | 29 + licenses/neovide-MIT.txt | 21 + src/chrome.rs | 198 ++++++ src/client.rs | 289 ++++++++ src/colors.rs | 4 +- src/cursor.rs | 446 ++++++++++++ src/label.rs | 155 +++++ src/launcher.rs | 754 +++++++++++++++++++++ src/main.rs | 128 +++- src/pane_name.rs | 656 ++++++++++++++++++ src/protocol.rs | 319 +++++++++ src/render.rs | 9 +- src/server.rs | 1384 ++++++++++++++++++++++++++++++++++++++ src/session.rs | 45 +- src/terminal.rs | 923 +++++++++++++++++-------- 18 files changed, 5257 insertions(+), 410 deletions(-) create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 licenses/neovide-MIT.txt create mode 100644 src/chrome.rs create mode 100644 src/client.rs create mode 100644 src/cursor.rs create mode 100644 src/label.rs create mode 100644 src/launcher.rs create mode 100644 src/pane_name.rs create mode 100644 src/protocol.rs create mode 100644 src/server.rs diff --git a/Cargo.lock b/Cargo.lock index 7b4dfc0..9dd1cc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -538,6 +538,15 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bindgen" version = "0.71.1" @@ -4007,6 +4016,23 @@ dependencies = [ "cc", ] +[[package]] +name = "psyterm" +version = "0.1.0" +dependencies = [ + "alacritty_terminal", + "anyhow", + "async-channel 2.5.0", + "bincode", + "env_logger", + "futures-lite 2.6.1", + "gpui", + "libc", + "log", + "serde", + "unicode-segmentation", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -5366,20 +5392,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "terminal" -version = "0.1.0" -dependencies = [ - "alacritty_terminal", - "anyhow", - "async-channel 2.5.0", - "env_logger", - "futures-lite 2.6.1", - "gpui", - "libc", - "log", -] - [[package]] name = "thiserror" version = "1.0.69" diff --git a/Cargo.toml b/Cargo.toml index 7b47fed..3d1f979 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "terminal" +name = "psyterm" version = "0.1.0" edition = "2024" publish = false @@ -7,11 +7,14 @@ publish = false [dependencies] alacritty_terminal = "=0.26.0" anyhow = "1" +serde = { version = "1", features = ["derive"] } +bincode = "1.3" async-channel = "2" gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] } log = "0.4" env_logger = "0.11" futures-lite = "2" +unicode-segmentation = "1" [target.'cfg(target_os = "linux")'.dependencies] libc = "0.2" diff --git a/README.md b/README.md index b0034ac..54cfe29 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,17 @@ -# Terminal +# psyTerm -A small GPU-rendered terminal built with [GPUI 0.2.2](https://gpui.rs/) and -[alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/). -The initial target is Linux desktop on Wayland. Alacritty provides the terminal -state machine, VTE parser, scrollback, PTY, and shell I/O; GPUI provides the window, -text rendering, and desktop input. +A Wayland terminal and multiplexer built with [GPUI 0.2.2](https://gpui.rs/) +and [alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/). +A separate server owns terminal emulation, shells, tabs, panes, and scrollback. +GUI processes display its snapshots and send input commands. Closing a window +detaches it; the shells keep running for the next local or remote connection. ## Build and run -Use a recent stable Rust toolchain; development currently uses Rust 1.96. Launch -from Linux 5.3 or newer (pidfd-based shell cleanup), in a running Wayland desktop with `WAYLAND_DISPLAY` set and a working Vulkan -driver. This build enables GPUI's Wayland backend only. +Use recent stable Rust (development uses 1.96) and Linux 5.3 or newer. GUI +processes require a running Wayland desktop and a working Vulkan driver. +The server and SSH bridge do not initialize GPUI, Wayland, or Vulkan, although +the shared executable still needs its dynamically linked libraries installed. Representative Fedora dependencies: @@ -30,120 +31,205 @@ sudo apt install build-essential cmake pkg-config \ fonts-dejavu-core ``` -The package names follow the relevant portions of -[Zed's Linux dependency script](https://github.com/zed-industries/zed/blob/main/script/linux). -Your GPU may need its vendor's Vulkan driver instead of Mesa. GPUI 0.2.2 also -links the XKB X11 library even when only its Wayland window backend is enabled. +These are the relevant portions of [Zed's Linux dependency script](https://github.com/zed-industries/zed/blob/main/script/linux). +GPUI 0.2.2 links the XKB X11 library even with only its Wayland backend enabled. +Use your GPU vendor's Vulkan driver where appropriate. ```sh cargo run --locked -# Optimized build: -cargo run --locked --release + +cargo build --locked --release +./target/release/psyterm ``` -The window starts `$SHELL`, falling back to `/bin/sh`, and inherits the launch -directory. The child receives `TERM=xterm-256color` and `COLORTERM=truecolor`. -Run `exit` or close the window to end the session. To select another shell: +The default command starts or reuses a local server, asks its zygote to fork a +GUI, and returns. Running it again opens another view of the same workspace. +The first attachment to an empty server creates a shell. Shells use the +server's `$SHELL` (falling back to `/bin/sh`), environment, and startup directory; +they receive `TERM=xterm-256color` and `COLORTERM=truecolor`. + +The server retains its startup environment. Set shell or GUI environment +preferences before starting that server, or use `--gui` to launch a diagnostic +GUI directly from the current environment. After rebuilding, the server refreshes +its zygote for new GUI windows, preserving existing windows and shells. Changes +to server logic or the protocol still require restarting the server; +`--shutdown` also ends its shell sessions. + +This build uses protocol version 2. An older server must be restarted before +attaching; the new `psyterm --shutdown` command can stop a version-1 server. +Finish any running work first, since shutdown ends its sessions, then launch +`psyterm` again to start the updated server. + +## Commands and connections + +| Command | Behavior | +| --- | --- | +| `psyterm` | Open a local window through the server's zygote | +| `psyterm --remote user@host` | Open a local GUI connected to the remote server over SSH | +| `psyterm --gui` | Launch a GUI directly, bypassing the zygote | +| `psyterm --list` | Inspect tabs and panes in the running local server | +| `psyterm --shutdown` | Stop the local server and end its sessions | +| `psyterm --server` | Run the terminal server in the foreground | +| `psyterm --socket PATH` | Select a separate local server socket; combine with other options | +| `psyterm --bridge` | Proxy the binary protocol between stdin/stdout and a local server | + +By default the socket is `$XDG_RUNTIME_DIR/psyterm/server.sock`, with a private +per-user temporary directory as fallback. A custom socket must have a real, +user-owned parent directory with mode `0700`: ```sh -SHELL=/bin/bash cargo run --locked +mkdir -m 700 "$XDG_RUNTIME_DIR/psyterm-dev" +cargo run --locked -- --socket "$XDG_RUNTIME_DIR/psyterm-dev/server.sock" ``` -For diagnostics, use `RUST_LOG=debug cargo run --locked`. If no window appears, -check that the process has access to your Wayland session and that Vulkan works -on that desktop. To inspect the renderer's CPU work without enabling logs from -all dependencies: +Sockets and log files are private to the current UID; peers are checked with +Linux credentials. Server and zygote logs are beside the socket as +`server.sock.log` and `server.sock.zygote.log`. + +SSH uses `BatchMode=yes`: configure key/agent authentication and known-host trust +before connecting. The remote host needs a compatible `psyterm` executable in +its noninteractive SSH `PATH`. Override that executable with +`PSYTERM_REMOTE_BIN`; this direct-launch example uses the current environment: ```sh -RUST_LOG=terminal::timing=debug cargo run --locked +PSYTERM_REMOTE_BIN=/home/me/bin/psyterm \ + cargo run --locked -- --gui --remote me@workstation ``` -Each frame logs `prepare_us` and `paint_us`, the time in microseconds spent in -our preparation and painting callbacks. These exclude GPU execution, compositor -scheduling, and presentation; they are not measurements of total input latency. +SSH starts `psyterm --bridge` on the remote host, which starts or reuses that +host's server. stdout carries only framed protocol bytes. No TCP listener or +separate network authentication service is exposed. To end remote sessions, +run `psyterm --shutdown` on the remote host, for example through SSH. -## Controls and behavior +## Controls | Input | Action | | --- | --- | -| Drag with the left mouse button | Select text | -| Double-click / triple-click | Select a word / line | -| Ctrl+Shift+C | Copy the selection | -| Ctrl+Shift+V | Paste, respecting bracketed-paste mode | +| Click a tab | Switch the server's active tab | +| `+` or Ctrl+Shift+T | Create a tab | +| Ctrl+Shift+D | Add a pane beside the focused pane | +| Ctrl+Shift+Left / Right | Focus the previous / next pane | +| Ctrl+Shift+W | Close the focused pane and its shell | +| Ctrl+Shift+R | Edit the pane name | +| Enter / Esc while renaming | Save / cancel the edit | +| Save a blank name | Restore automatic pane naming | +| Window `×` | Detach this GUI; keep server sessions running | +| Drag / double-click / triple-click | Select text / word / line | +| Ctrl+Shift+C / V | Copy selection / paste with negotiated bracketed-paste mode | | Mouse wheel / touchpad | Scroll terminal history | -| Shift+PageUp / Shift+PageDown | Scroll one page | -| Shift+Home / Shift+End | Jump to the oldest history / live screen | +| Shift+PageUp / PageDown | Scroll one page | +| Shift+Home / End | Jump to oldest history / live screen | Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows, -navigation keys, and function keys are sent to the terminal application. -In alternate-screen applications, Shift+navigation is passed through and the -wheel sends arrow keys when the application enables alternate scrolling. +navigation keys, and function keys reach the terminal application. +Alternate-screen applications receive shifted navigation; the wheel sends +arrow keys when the application enables alternate scrolling. -The renderer supports ANSI and 256-color palettes, truecolor, bold/italic/dim, -underlining, reverse video, selection, wide characters and combining marks. -Window resizing updates both the terminal grid and PTY size. Alternate-screen -applications use Alacritty's terminal modes. Scrollback retains up to 10,000 -lines by default. The view selects an installed font in this order: Hermit -(including its Hurmit Nerd Font variants), SF Mono, Noto Sans Mono, Iosevka, -then another fixed-pitch family. Font advances are checked to avoid choosing a -proportional fallback. Text is 15 logical pixels, with a 20-pixel line height and -8-pixel padding. +Each pane has a name above its terminal content. The server chooses a manual +name first, then the running program's OSC title, then the shell's current +directory. Automatic directory names abbreviate the server’s home directory +with `~`; pane headers and equal-width tabs truncate long names in the middle. +It checks shell directories every 500 ms, including while the shell is idle. Manual names survive program title changes and client disconnects; +returning to automatic naming uses the latest program title or directory. -## Structure +When a shell exits, its pane closes automatically. An empty tab closes too, +and focus moves to an adjacent remaining pane or tab when needed. After the +last shell exits, the window stays open with `+` available to start another tab. -| Module | Responsibility | +Clients share the server's active tab, focused pane, selection, and scrollback +position. The most recent GUI resize sets each pane's grid size. These are +shared views of one workspace, not independent per-client layouts. Tabs and +panes survive GUI disconnects but are stored in daemon memory, not persisted +across server shutdown or machine restart. + +## Appearance + +The inset terminal surface and titlebar use the dark Sybil palette shared by +Huayra, Attractor, and Sybil. Tabs retain violet accents; pane headers use teal, +with a matching border around the active pane. The titlebar contains equal-width +tabs and connection/window controls. `src/chrome.rs` records the theme sources. + +Cursor motion adapts Neovide's four independently sprung corners: leading +corners move first and trailing corners stretch behind. The blink follows +buzzlocker: 500 ms solid after input, 500 ms cubic fade-out, then an immediate +return to solid. An inactive window or pane shows a stationary hollow cursor. +Neovide's MIT license and both sources are recorded in +[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). + +Font preference is Hermit (including Hurmit Nerd Font variants), SF Mono, +Noto Sans Mono, Iosevka, then another verified fixed-pitch family. Text uses +15 logical pixels and a 20-pixel line height. Rendering supports ANSI/256 +colors, truecolor, bold/italic/dim, underline, reverse video, wide characters, +and combining marks. Alacritty supplies terminal modes and 10,000 lines of +scrollback by default. + +## Processes and source + +| Component | Responsibility | | --- | --- | -| `src/main.rs` | Application startup and window lifecycle | -| `src/session.rs` | One shell, PTY event loop, terminal grid, resize, and shutdown | -| `src/terminal.rs` | One terminal view: focus, selection, scrollback, clipboard, text input, and render coordination | -| `src/render.rs` | Cached terminal text layout and batched drawing | -| `src/input.rs` | Xterm-style key encoding and paste framing | -| `src/colors.rs` | Default palette, runtime color overrides, and cell color attributes | -| `src/fonts.rs` | Preferred installed fonts and verified fixed-pitch fallback | +| `server.rs`, `session.rs` | Authoritative workspace, PTYs, child processes, parser, terminal grids, selection, scrolling, and resize | +| `protocol.rs`, `client.rs` | Versioned bounded messages, local socket / SSH transport, snapshot delivery | +| `launcher.rs` | Server startup, private paths, lifecycle locks, and the server-owned GUI zygote | +| `terminal.rs` | Snapshot-only GUI workspace and panes, input, focus, and animation scheduling | +| `pane_name.rs`, `label.rs` | Pane name editor, Unicode composition, and middle-truncated labels | +| `render.rs`, `cursor.rs` | Cached text and batched drawing; cursor motion and blink | +| `chrome.rs`, `colors.rs`, `fonts.rs` | Window chrome, terminal colors, font selection | +| `input.rs`, `main.rs` | Key/paste encoding and CLI/process-role dispatch | -The session does not depend on GPUI or window layout. Future tabs or split panes -can compose multiple views and sessions while reusing the parser and PTY code. -Persistent multiplexing would add a session owner outside the window lifecycle. +The server starts the zygote on demand and manages its lifetime. The zygote +checks that it is single-threaded and forks GUI children **before** GPUI, +Wayland, Vulkan, font discovery, or executors initialize. Children inherit the +loaded executable mappings and avoid another `exec`; graphics and font setup +still happen in each child. This is a safe prefork foundation, not a guarantee +of the fastest possible launch time. Headless terminal/bridge use does not +start the zygote. -PTY events wake the UI through an asynchronous channel. Output notifications -are coalesced, and the UI yields between event batches so a busy child cannot -monopolize the UI task. There is no periodic redraw polling. Typing requests a -new frame when shell output arrives, or immediately if it changes selection, -scrollback position, or input-method composition. +Snapshot queues retain the newest frame for a slow client rather than an +unbounded backlog. GUI rows keep their shaped text until the snapshot changes. +ASCII runs, Unicode glyphs, backgrounds, and decorations are batched; cursor +animation reuses prepared terminal rows. Blink holds use timed wakeups, and +inactive cursors schedule no animation frames. -The renderer retains shaped text for unchanged rows. It groups adjacent ASCII -cells into text runs, while keeping wide and combining-character cells aligned -to terminal columns. Blank margins are skipped, and matching backgrounds and -text decorations are merged into spans to reduce drawing work. +The project uses published crates, with no local Alacritty checkout required. +The small [vendored xattr patch](vendor/xattr/PATCH.md) fixes GPUI's transitive +Linux `ENOATTR` compatibility issue. `Cargo.lock` records dependency versions. -The build uses published crates and does not require a local Alacritty checkout. -`vendor/xattr` carries a small compatibility patch for GPUI's transitive -`zed-async-tar` dependency: Linux now uses `libc::ENODATA` in place of a removed -`ENOATTR` alias. See [the patch notes](vendor/xattr/PATCH.md). The dependency -versions are recorded in `Cargo.lock`. +## Development -## Development and scope - -The development profile retains debug information and assertions, with level-1 -optimization and level-2 optimization for GPUI and the font-shaping crates. -This keeps `cargo run` responsive during window resizing; the first build takes -longer than a fully unoptimized build. Unicode clusters use cached glyphs in one -shared paint layer, preserving cell positions without per-character layers. +The development profile retains debug information and assertions with level-1 +optimization, plus level-2 optimization for GPUI and shaping crates. Preserve +these settings when evaluating responsiveness; full-grid shaping and scene +construction are expensive in a completely unoptimized build. ```sh cargo fmt --check cargo check --locked cargo test --locked cargo clippy --locked --all-targets -- -D warnings + +RUST_LOG=psyterm::timing=debug cargo run --locked -- --gui ``` -Tests cover key and paste encoding, palette behavior, terminal parsing and -resizing, and PTY lifecycle. They do not replace testing rendering and input -under a real compositor. +`prepare_us` and `paint_us` measure CPU callback time in microseconds. They +exclude GPU execution, compositor scheduling, and presentation, so they are +not end-to-end input-latency measurements. -This first version has a single shell and window. It does not yet provide panes, -tabs, session persistence, configuration files, application mouse reporting, -the Kitty keyboard protocol, OSC 52 clipboard access, or clickable hyperlinks. -macOS is an intended next target and has not been validated. Font shaping, -input methods, and terminal application compatibility still need broader -desktop testing. +Tests cover protocol framing, socket ownership, binary bridge flushing, +key/paste encoding, palettes, fonts, cursor curves, rendering assembly, PTY +lifecycle, and server reattachment/layout behavior. Pane tests cover natural +shell exit, empty-tab removal, focus preservation, idle directory changes, +program/manual name precedence, title resets, and rename persistence. Editor +tests cover Unicode selection and composition; protocol tests pin the previous +version's shutdown handshake. + +Live Hyprland checks verified GUI→zygote→server ancestry, a single-threaded +zygote, no server GPU descriptors, two simultaneous GUIs, tabs/splits, and shell +survival after detaching. An actual SSH connection to a separate headless +server on localhost verified input and reattachment. Replacing a running +executable refreshed its zygote while the original GUI and shell stayed alive. +These are Linux checks; remote-network latency and macOS remain unverified. + +Linux Wayland is the implemented platform; macOS is a future target. Current +limits include side-by-side panes only, shared per-server viewport state, no +disk-restored sessions, no configuration files, no application mouse reporting, +no Kitty keyboard protocol, no OSC 52 clipboard access, and no clickable links. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..2b4c14f --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,29 @@ +# Third-party notices + +## Neovide cursor motion + +`src/cursor.rs` adapts the four-corner cursor animation and analytically integrated +critically damped spring from Neovide: + +- `src/renderer/cursor_renderer/mod.rs` +- `src/renderer/animation_utils.rs` +- Source revision: `468b71f7e6fd4f995720b2f43da20608b37eb9b0` +- Copyright (c) 2023 Neovide Contributors +- License: MIT; the complete notice is in [licenses/neovide-MIT.txt](licenses/neovide-MIT.txt). + +The spring formula, front/back corner timing, 150 ms long-move duration, and +40 ms short-move duration are retained. Coordinates and painting are adapted to +GPUI instead of Skia. Particle effects are not included. + +## buzzlocker cursor blink + +The blink behavior in `src/cursor.rs` follows the author's buzzlocker code, +reused at the author's explicit request: + +- `src/render.c`: `update_single_animation`, cursor branch +- `src/animation.c`: `anim_qubic_ease_out` +- `src/main.c`: `reset_cursor_flash_anim` +- Source revision: `53157cb4d60585078cf4c89048fa807530f1d088` + +It holds at full opacity for 500 ms after input, fades out with a 500 ms cubic +ease-out curve, then returns to full opacity for 500 ms. It does not fade in. diff --git a/licenses/neovide-MIT.txt b/licenses/neovide-MIT.txt new file mode 100644 index 0000000..c2c2a1e --- /dev/null +++ b/licenses/neovide-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Neovide Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/chrome.rs b/src/chrome.rs new file mode 100644 index 0000000..ad4954d --- /dev/null +++ b/src/chrome.rs @@ -0,0 +1,198 @@ +//! psyTerm chrome using the shared Sybil palette from the user's applications. +//! +//! Color sources: +//! - Huayra `src/styles.css`, active `data-theme="sybil"` theme. +//! - Sybil `web/src/index.css`, root color tokens. +//! - Attractor `chrome/browser/resources/attractor/theme.css`, surface tokens. +use std::rc::Rc; + +use gpui::{ + App, Div, ElementId, MouseButton, SharedString, Stateful, Window, div, prelude::*, px, rgb, +}; + +use crate::label::middle_label; + +pub const APP_BACKGROUND: u32 = 0x06060f; +pub const PANEL_BACKGROUND: u32 = 0x080817; +pub const TERMINAL_BACKGROUND: u32 = 0x080917; +pub const CONTROL_BACKGROUND: u32 = 0x131122; +pub const HOVER_BACKGROUND: u32 = 0x1c1830; +pub const ACTIVE_BACKGROUND: u32 = 0x231c3b; +pub const BORDER: u32 = 0x282145; +pub const TEXT: u32 = 0xf3f1f8; +pub const MUTED: u32 = 0xa29fbc; +pub const ACCENT: u32 = 0x9858f9; +pub const CYAN: u32 = 0x4bdbf1; +// Huayra's Sybil green: hsl(163 72% 45%). +pub const PANE_FOCUS: u32 = 0x20c597; +pub const PANE_MUTED: u32 = 0x527f73; +pub const DANGER: u32 = 0xf26977; +pub const CONTENT_INSET: f32 = 8.; +pub const HEADER_HEIGHT: f32 = 44.; + +pub struct ChromeTab { + pub id: u64, + pub label: SharedString, + pub active: bool, +} + +/// An app-owned titlebar. Callbacks issue server commands; no tab state lives here. +/// The close callback should detach this GUI, leaving server sessions alive. +pub fn header( + connection: SharedString, + tabs: Vec, + on_tab: impl Fn(u64, &mut Window, &mut App) + 'static, + on_new: impl Fn(&mut Window, &mut App) + 'static, + on_close: impl Fn(&mut Window, &mut App) + 'static, +) -> Div { + let on_tab = Rc::new(on_tab); + let mut tab_strip = div() + .flex() + .items_center() + .gap(px(4.)) + .flex_1() + .min_w_0() + .h_full() + .overflow_hidden(); + for tab in tabs { + let on_tab = on_tab.clone(); + let active = tab.active; + let id = tab.id; + tab_strip = tab_strip.child( + div() + .id(ElementId::Name(format!("tab-{id}").into())) + .flex() + .items_center() + .gap(px(7.)) + .h(px(29.)) + .flex_basis(px(200.)) + .flex_shrink() + .min_w_0() + .max_w(px(200.)) + .px(px(10.)) + .border_1() + .border_color(rgb(if active { BORDER } else { PANEL_BACKGROUND })) + .bg(rgb(if active { + ACTIVE_BACKGROUND + } else { + PANEL_BACKGROUND + })) + .text_color(rgb(if active { TEXT } else { MUTED })) + .text_size(px(11.)) + .cursor_pointer() + .hover(|style| style.bg(rgb(HOVER_BACKGROUND)).text_color(rgb(TEXT))) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(move |_, window, cx| { + cx.stop_propagation(); + on_tab(id, window, cx); + }) + .child( + div() + .w(px(3.)) + .flex_shrink_0() + .h(px(12.)) + .bg(rgb(if active { ACCENT } else { BORDER })), + ) + .child( + div() + .flex_1() + .min_w_0() + .h_full() + .overflow_hidden() + .child(middle_label(tab.label)), + ), + ); + } + + div() + .flex() + .flex_col() + .flex_shrink_0() + .h(px(HEADER_HEIGHT)) + .w_full() + .bg(rgb(PANEL_BACKGROUND)) + .border_b_1() + .border_color(rgb(BORDER)) + .font_family(".SystemUIFont") + .text_color(rgb(TEXT)) + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(12.)) + .flex_1() + .min_h_0() + .on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move()) + .child(tab_strip) + .child( + div() + .flex() + .items_center() + .flex_shrink_0() + .gap(px(5.)) + .max_w(px(170.)) + .text_size(px(10.)) + .text_color(rgb(MUTED)) + .child(div().size(px(4.)).rounded_full().bg(rgb(CYAN))) + .child(div().text_ellipsis().child(connection)), + ) + .child(control("new-tab", "+", false, on_new)) + .child(control("detach-window", "×", true, on_close)), + ) +} + +fn control( + id: &'static str, + label: &'static str, + danger: bool, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + div() + .id(id) + .flex() + .items_center() + .justify_center() + .flex_shrink_0() + .size(px(27.)) + .text_size(px(18.)) + .text_color(rgb(MUTED)) + .cursor_pointer() + .hover(move |style| { + style + .bg(rgb(if danger { + CONTROL_BACKGROUND + } else { + HOVER_BACKGROUND + })) + .text_color(rgb(if danger { DANGER } else { TEXT })) + }) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(move |_, window, cx| { + cx.stop_propagation(); + on_click(window, cx); + }) + .child(label) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_constructs_each_control_without_duplicate_hover_styles() { + // GPUI rejects installing a hover style twice before the first window + // frame. Exercise the complete header, including its danger control. + let _ = header( + "Local".into(), + vec![ChromeTab { + id: 1, + label: "Shell".into(), + active: true, + }], + |_, _, _| {}, + |_, _| {}, + |_, _| {}, + ); + } +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..74ee6dc --- /dev/null +++ b/src/client.rs @@ -0,0 +1,289 @@ +//! Display-only client transport. No terminal parser, PTY, or shell lives here. +use crate::protocol::{self, ClientMessage, ServerMessage, Snapshot}; +use anyhow::{Context, Result, bail}; +use std::{ + collections::VecDeque, + io::{Read, Write}, + net::Shutdown, + os::unix::net::UnixStream, + path::Path, + process::{Child, Command, Stdio}, + sync::{Arc, Mutex, mpsc}, + thread, +}; + +#[derive(Default)] +pub struct Update { + pub snapshot: Option>, + pub clipboard: VecDeque, + pub error: Option, +} + +pub struct Updates { + signal: async_channel::Receiver<()>, + pending: Arc>, +} +impl Updates { + pub async fn recv(&self) -> Option { + self.signal.recv().await.ok()?; + Some(std::mem::take(&mut *self.pending.lock().unwrap())) + } +} + +#[derive(Clone)] +pub struct Client(Arc); +struct Connection { + commands: mpsc::Sender, + socket: Option, + ssh: Mutex>, +} +impl Drop for Connection { + fn drop(&mut self) { + // Detach closes this transport, never a server-owned PTY. + if let Some(socket) = &self.socket { + let _ = socket.shutdown(Shutdown::Both); + } + if let Some(mut child) = self.ssh.lock().unwrap().take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Client { + pub fn connect(socket: &Path, remote: Option<&str>) -> Result<(Self, Updates)> { + let (reader, writer, socket, ssh): (Box, Box, _, _) = + if let Some(remote) = remote { + if remote.is_empty() || remote.starts_with('-') || remote.contains(['\n', '\r']) { + bail!("invalid SSH destination"); + } + let executable = + std::env::var("PSYTERM_REMOTE_BIN").unwrap_or_else(|_| "psyterm".into()); + let remote_command = format!("exec {} --bridge", shell_quote(&executable)); + let mut child = Command::new("ssh") + .args([ + "-T", + "-o", + "BatchMode=yes", + "-o", + "ConnectTimeout=10", + "--", + remote, + &remote_command, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .context("start SSH terminal transport")?; + let reader = Box::new(child.stdout.take().unwrap()) as Box; + let writer = Box::new(child.stdin.take().unwrap()) as Box; + (reader, writer, None, Some(child)) + } else { + let stream = UnixStream::connect(socket).context("connect to psyTerm server")?; + crate::launcher::verify_peer(&stream)?; + ( + Box::new(stream.try_clone()?) as Box, + Box::new(stream.try_clone()?) as Box, + Some(stream), + None, + ) + }; + let (commands, receive) = mpsc::channel(); + let (signal, notifications) = async_channel::bounded(1); + let pending = Arc::new(Mutex::new(Update::default())); + let connection = Self(Arc::new(Connection { + commands, + socket, + ssh: Mutex::new(ssh), + })); + let errors = pending.clone(); + let notify = signal.clone(); + thread::Builder::new() + .name("psyterm-client-writer".into()) + .spawn(move || { + let mut writer = writer; + while let Ok(message) = receive.recv() { + if let Err(error) = protocol::write_message(&mut writer, &message) { + errors.lock().unwrap().error = Some(format!("Connection lost: {error:#}")); + let _ = notify.try_send(()); + break; + } + } + })?; + let incoming = pending.clone(); + thread::Builder::new() + .name("psyterm-client-reader".into()) + .spawn(move || { + let mut reader = reader; + let mut greeted = false; + loop { + let message = protocol::read_message::(&mut reader); + let mut update = incoming.lock().unwrap(); + match message { + Ok(ServerMessage::Hello { version, .. }) + if version == protocol::VERSION => + { + greeted = true + } + Ok(ServerMessage::Hello { .. }) => { + update.error = + Some("Server protocol version differs from this GUI".into()); + let _ = signal.try_send(()); + break; + } + Ok(ServerMessage::Snapshot(snapshot)) if greeted => { + if let Err(error) = validate_snapshot(&snapshot) { + update.error = Some(error.to_string()); + let _ = signal.try_send(()); + break; + } + // A slow window never accumulates a queue of obsolete frames. + update.snapshot = Some(Arc::new(snapshot)); + } + Ok(ServerMessage::Clipboard(text)) if greeted => { + if update.clipboard.len() < 16 { + update.clipboard.push_back(text); + } + } + Ok(ServerMessage::Error(error)) => update.error = Some(error), + Ok(ServerMessage::Closing) => { + update.error = + Some("Server stopped. Shell sessions have ended.".into()); + let _ = signal.try_send(()); + break; + } + Ok(ServerMessage::Pong) => {} + Ok(_) => { + update.error = Some("Server sent data before its handshake".into()); + } + Err(error) => { + update.error = Some(format!( + "Disconnected — sessions remain on the server. {error:#}" + )); + let _ = signal.try_send(()); + break; + } + } + drop(update); + let _ = signal.try_send(()); + } + })?; + connection.send(ClientMessage::Hello { + version: protocol::VERSION, + })?; + connection.send(ClientMessage::Attach)?; + Ok(( + connection, + Updates { + signal: notifications, + pending, + }, + )) + } + + pub fn send(&self, message: ClientMessage) -> Result<()> { + self.0 + .commands + .send(message) + .context("server transport is closed") + } + pub fn input(&self, pane: u64, bytes: Vec) -> Result<()> { + for chunk in bytes.chunks(64 * 1024) { + self.send(ClientMessage::Input { + pane, + bytes: chunk.to_vec(), + })?; + } + Ok(()) + } +} + +fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +fn validate_snapshot(snapshot: &Snapshot) -> Result<()> { + if snapshot.tabs.len() > 256 || snapshot.panes.len() > 64 { + bail!("Server layout exceeds client limits"); + } + for pane in &snapshot.panes { + let count = usize::from(pane.columns) * usize::from(pane.lines); + if pane.columns < 2 + || pane.lines == 0 + || count > 1_000_000 + || pane.cells.len() != count + || pane.selected.len() != count + || pane.colors.len() > alacritty_terminal::term::color::COUNT + { + bail!("Server sent an invalid terminal grid"); + } + } + Ok(()) +} + +/// SSH starts this command on the remote host. Only framed protocol bytes use stdout. +pub fn bridge(socket: &Path) -> Result<()> { + crate::launcher::ensure_server(socket)?; + let stream = UnixStream::connect(socket)?; + let mut output = stream.try_clone()?; + let copy_input = thread::spawn(move || { + let result = copy_and_flush(&mut std::io::stdin().lock(), &mut output); + let _ = output.shutdown(Shutdown::Write); + result + }); + let mut input = stream; + copy_and_flush(&mut input, &mut std::io::stdout().lock())?; + // Don't wait indefinitely for stdin after a remote server disconnects. + drop(copy_input); + Ok(()) +} + +// stdout is line-buffered even over SSH. Flush each binary chunk; waiting for a +// newline or EOF can withhold a frame tail and deadlock an otherwise idle GUI. +fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::Result<()> { + let mut buffer = [0u8; 64 * 1024]; + loop { + let count = match reader.read(&mut buffer) { + Ok(0) => return Ok(()), + Ok(count) => count, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + }; + writer.write_all(&buffer[..count])?; + writer.flush()?; + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn binary_bridge_flushes_without_newlines() { + struct Output { + bytes: Vec, + flushes: usize, + } + impl Write for Output { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + self.flushes += 1; + Ok(()) + } + } + let mut output = Output { + bytes: Vec::new(), + flushes: 0, + }; + copy_and_flush(&mut b"binary-without-newlines".as_slice(), &mut output).unwrap(); + assert_eq!(output.bytes, b"binary-without-newlines"); + assert!(output.flushes > 0); + } + #[test] + fn remote_binary_paths_are_shell_quoted() { + assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'"); + } +} diff --git a/src/colors.rs b/src/colors.rs index cb58da3..772287f 100644 --- a/src/colors.rs +++ b/src/colors.rs @@ -9,8 +9,8 @@ use alacritty_terminal::{ }; use gpui::Hsla; -pub const BACKGROUND: u32 = 0x181a1f; -pub const FOREGROUND: u32 = 0xd8dee9; +pub const BACKGROUND: u32 = 0x080917; +pub const FOREGROUND: u32 = 0xf3f1f8; const ANSI: [u32; 16] = [ 0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, 0x5c6370, diff --git a/src/cursor.rs b/src/cursor.rs new file mode 100644 index 0000000..bfeb4e5 --- /dev/null +++ b/src/cursor.rs @@ -0,0 +1,446 @@ +//! Neovide's four-corner spring motion with buzzlocker's cubic fade blink. +//! +//! Motion derives from Neovide (MIT, copyright 2023 Neovide Contributors). +//! See THIRD_PARTY_NOTICES.md and licenses/neovide-MIT.txt for source attribution. +//! The blink is adapted from buzzlocker's render.c / animation.c at its author's +//! request. Keep its asymmetric fade-out / immediate-on behavior. + +use std::time::{Duration, Instant}; + +use alacritty_terminal::vte::ansi::CursorShape; +use gpui::{Bounds, Hsla, PathBuilder, Pixels, Point, Window, point, px}; + +const LONG_MOVE: f32 = 0.150; +const SHORT_MOVE: f32 = 0.040; +const BLINK_HOLD: f32 = 0.5; +const BLINK_FADE: f32 = 0.5; +const STANDARD_CORNERS: [[f32; 2]; 4] = [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]]; + +/// The spring equations are retained from Neovide's animation_utils.rs. +#[derive(Clone, Copy, Default)] +struct CriticallyDampedSpringAnimation { + position: f32, + velocity: f32, +} + +impl CriticallyDampedSpringAnimation { + fn update(&mut self, dt: f32, animation_length: f32) -> bool { + if animation_length <= dt { + self.reset(); + return false; + } + if self.position == 0.0 { + return false; + } + + // Analytical solution for a critically damped harmonic oscillator. + // Omega reaches the destination with 2% tolerance in animation_length. + let zeta = 1.0; + let omega = 4.0 / (zeta * animation_length); + let a = self.position; + let b = self.position * omega + self.velocity; + let c = (-omega * dt).exp(); + self.position = (a + b * dt) * c; + self.velocity = c * (-a * omega - b * dt * omega + b); + + if self.position.abs() < 0.01 { + self.reset(); + false + } else { + true + } + } + + fn reset(&mut self) { + self.position = 0.0; + self.velocity = 0.0; + } +} + +#[derive(Clone, Copy, Default)] +struct Corner { + position: [f32; 2], + destination: [f32; 2], + x: CriticallyDampedSpringAnimation, + y: CriticallyDampedSpringAnimation, + animation_length: f32, +} + +impl Corner { + fn snap(&mut self, destination: [f32; 2]) { + self.destination = destination; + self.position = destination; + self.x.reset(); + self.y.reset(); + } + + fn update(&mut self, dt: f32) -> bool { + let mut moving = self.x.update(dt, self.animation_length); + moving |= self.y.update(dt, self.animation_length); + self.position = [ + self.destination[0] - self.x.position, + self.destination[1] - self.y.position, + ]; + moving + } +} + +#[derive(Clone, Copy)] +struct Target { + bounds: Bounds, + shape: CursorShape, + color: Hsla, +} + +#[derive(Default)] +pub struct CursorAnimator { + corners: [Corner; 4], + target: Option, + last_frame: Option, + last_activity: Option, + was_focused: bool, +} + +struct Frame { + points: [Point; 4], + opacity: f32, + outline: bool, + next: Option, +} + +impl CursorAnimator { + pub fn new() -> Self { + Self::default() + } + + /// Cursor bounds are in window coordinates and cover a full terminal cell + /// (two cells for a wide block cursor). Pass the desired fill alpha in color; + /// an overlay renderer can use a translucent color to leave text readable. + pub fn set_target( + &mut self, + bounds: Bounds, + shape: CursorShape, + color: Hsla, + now: Instant, + ) { + let next = Target { + bounds, + shape, + color, + }; + let changed = self + .target + .is_none_or(|old| old.bounds != bounds || old.shape != shape); + if !changed { + self.target = Some(next); + return; + } + + // Advance the old destination before redirecting, preserving its spring + // velocity. Reset the clock here so a move after an idle blink hold does + // not get interpreted as a huge animation time step and snap instantly. + if self.was_focused { + self.advance_motion(now); + } + let destinations = destinations(next); + if self.target.is_none() || !self.was_focused || shape == CursorShape::Hidden { + for (corner, destination) in self.corners.iter_mut().zip(destinations) { + corner.snap(destination); + } + } else { + self.jump(next, destinations); + } + self.target = Some(next); + self.last_frame = Some(now); + self.activity(now); + } + + /// Call on keyboard input, including keys that don't move the cursor. + pub fn activity(&mut self, now: Instant) { + self.last_activity = Some(now); + } + + /// Paint the cursor, returning when another frame is required. + /// + /// `Some(Duration::ZERO)` means use GPUI's next animation frame. A positive + /// delay is the remaining solid blink hold and can use an executor timer. + /// `None` means the hidden/unfocused cursor needs no animation wakeup. + /// Focus changes still need to notify the view to paint the new appearance. + pub fn paint(&mut self, now: Instant, focused: bool, window: &mut Window) -> Option { + let frame = self.frame(now, focused); + let target = self.target?; + if frame.opacity <= 0.0 { + return frame.next; + } + let mut color = target.color; + // Hollow cursors stay fully visible even if the focused overlay uses a + // translucent fill. Their one-pixel perimeter does not obscure text. + color.a = if frame.outline && !focused { + 1.0 + } else { + color.a * frame.opacity + }; + let mut path = if frame.outline { + PathBuilder::stroke(px((f32::from(target.bounds.size.width) / 8.).max(1.))) + } else { + PathBuilder::fill() + }; + path.add_polygon(&frame.points, true); + match path.build() { + Ok(path) => window.paint_path(path, color), + Err(error) => log::debug!("cursor path: {error}"), + } + frame.next + } + + fn jump(&mut self, target: Target, destinations: [[f32; 2]; 4]) { + let mut alignments = [0.; 4]; + let width = f32::from(target.bounds.size.width).max(1.); + let height = f32::from(target.bounds.size.height).max(1.); + let relative = relative_corners(target.shape); + for (index, corner) in self.corners.iter().enumerate() { + let travel = normalized([ + destinations[index][0] - corner.destination[0], + destinations[index][1] - corner.destination[1], + ]); + let direction = normalized(relative[index]); + alignments[index] = travel[0] * direction[0] + travel[1] * direction[1]; + } + let min = alignments.iter().copied().fold(f32::INFINITY, f32::min); + let max = alignments.iter().copied().fold(f32::NEG_INFINITY, f32::max); + for (index, corner) in self.corners.iter_mut().enumerate() { + let destination = destinations[index]; + let jump = [ + (destination[0] - corner.destination[0]) / width, + (destination[1] - corner.destination[1]) / height, + ]; + let alignment = (alignments[index] - min) / (max - min); + let alignment = if alignment.is_finite() { + alignment.clamp(0., 1.) + } else { + 1. + }; + corner.animation_length = if jump[0].abs() <= 2.001 && jump[1].abs() <= 0.001 { + LONG_MOVE.min(SHORT_MOVE) + } else { + // Neovide's default trail_size=1: leading corner duration=0. + LONG_MOVE + (0. - LONG_MOVE) * alignment + }; + corner.x.position = destination[0] - corner.position[0]; + corner.y.position = destination[1] - corner.position[1]; + corner.destination = destination; + } + } + + fn advance_motion(&mut self, now: Instant) -> bool { + let dt = self + .last_frame + .map_or(0., |last| now.saturating_duration_since(last).as_secs_f32()); + self.last_frame = Some(now); + self.corners + .iter_mut() + .fold(false, |moving, corner| corner.update(dt) | moving) + } + + fn frame(&mut self, now: Instant, focused: bool) -> Frame { + let Some(target) = self.target else { + return hidden_frame(); + }; + if target.shape == CursorShape::Hidden { + self.was_focused = focused; + self.last_frame = Some(now); + return hidden_frame(); + } + if focused != self.was_focused { + for (corner, destination) in self.corners.iter_mut().zip(destinations(target)) { + corner.snap(destination); + } + self.activity(now); + } + self.was_focused = focused; + self.last_frame.get_or_insert(now); + if !focused { + // Blurred windows show an unanimated full-cell outline, even if the + // foreground application requested a beam or underline cursor. + let mut full_cell = target; + full_cell.shape = CursorShape::Block; + for (corner, destination) in self.corners.iter_mut().zip(destinations(target)) { + corner.snap(destination); + } + self.last_frame = Some(now); + return Frame { + points: destinations(full_cell).map(|p| point(px(p[0]), px(p[1]))), + opacity: 1., + outline: true, + next: None, + }; + } + let moving = self.advance_motion(now); + let elapsed = now + .saturating_duration_since(self.last_activity.unwrap_or(now)) + .as_secs_f32(); + let (opacity, blink_next) = blink(elapsed); + let fract = [ + f32::from(target.bounds.origin.x).fract(), + f32::from(target.bounds.origin.y).fract(), + ]; + Frame { + // Preserve Neovide's subpixel-origin snapping for crisp stationary + // edges while the four spring positions deform independently. + points: self.corners.map(|corner| { + point( + px((corner.position[0] - fract[0]).round() + fract[0]), + px((corner.position[1] - fract[1]).round() + fract[1]), + ) + }), + opacity, + outline: target.shape == CursorShape::HollowBlock, + next: Some(if moving { Duration::ZERO } else { blink_next }), + } + } +} + +fn hidden_frame() -> Frame { + Frame { + points: [point(px(0.), px(0.)); 4], + opacity: 0., + outline: false, + next: None, + } +} + +fn relative_corners(shape: CursorShape) -> [[f32; 2]; 4] { + STANDARD_CORNERS.map(|[x, y]| match shape { + CursorShape::Beam => [(x + 0.5) / 8. - 0.5, y], + CursorShape::Underline => [x, -((-y + 0.5) / 8. - 0.5)], + _ => [x, y], + }) +} + +fn destinations(target: Target) -> [[f32; 2]; 4] { + let width = f32::from(target.bounds.size.width); + let height = f32::from(target.bounds.size.height); + let center = [ + f32::from(target.bounds.origin.x) + width / 2., + f32::from(target.bounds.origin.y) + height / 2., + ]; + relative_corners(target.shape).map(|[x, y]| [center[0] + x * width, center[1] + y * height]) +} + +fn normalized([x, y]: [f32; 2]) -> [f32; 2] { + let length = x.hypot(y); + if length == 0. { + [0., 0.] + } else { + [x / length, y / length] + } +} + +/// buzzlocker uses cubic ease-out for OUT and a constant 1 for IN. +fn blink(elapsed: f32) -> (f32, Duration) { + if elapsed < BLINK_HOLD { + return (1., Duration::from_secs_f32(BLINK_HOLD - elapsed)); + } + let phase = (elapsed - BLINK_HOLD) % (BLINK_FADE + BLINK_HOLD); + if phase < BLINK_FADE { + let p = phase / BLINK_FADE; + ((1. - p).powi(3), Duration::ZERO) + } else { + (1., Duration::from_secs_f32(BLINK_FADE + BLINK_HOLD - phase)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{rgb, size}; + + fn bounds(x: f32, y: f32) -> Bounds { + Bounds::new(point(px(x), px(y)), size(px(10.), px(20.))) + } + + fn target(cursor: &mut CursorAnimator, x: f32, y: f32, shape: CursorShape, now: Instant) { + cursor.set_target(bounds(x, y), shape, rgb(0xffffff).into(), now); + } + + #[test] + fn blink_matches_buzzlocker_hold_cubic_fade_and_immediate_on() { + assert_eq!(blink(0.).0, 1.); + assert_eq!(blink(0.49).0, 1.); + assert_eq!(blink(0.5).0, 1.); + assert!((blink(0.75).0 - 0.125).abs() < 0.0001); + assert!(blink(0.999).0 < 0.0001); + assert_eq!(blink(1.).0, 1.); + assert_eq!(blink(1.25).0, 1.); + assert!((blink(1.75).0 - 0.125).abs() < 0.0001); + assert_eq!(blink(0.25).1, Duration::from_millis(250)); + } + + #[test] + fn leading_corners_snap_while_trailing_corners_deform() { + let now = Instant::now(); + let mut cursor = CursorAnimator::new(); + target(&mut cursor, 0., 0., CursorShape::Block, now); + cursor.frame(now, true); + target(&mut cursor, 100., 0., CursorShape::Block, now); + let frame = cursor.frame(now + Duration::from_millis(16), true); + assert_eq!(frame.points[1].x, px(110.)); + assert!(frame.points[0].x > px(0.) && frame.points[0].x < px(100.)); + assert_eq!(frame.next, Some(Duration::ZERO)); + for index in 2..100 { + cursor.frame(now + Duration::from_millis(index * 16), true); + } + assert_eq!(cursor.corners[0].position[0], 100.); + } + + #[test] + fn typing_uses_short_move_duration_and_resets_blink() { + let now = Instant::now(); + let mut cursor = CursorAnimator::new(); + target(&mut cursor, 0., 0., CursorShape::Block, now); + cursor.frame(now, true); + let later = now + Duration::from_millis(750); + assert!(cursor.frame(later, true).opacity < 0.2); + target(&mut cursor, 10., 0., CursorShape::Block, later); + assert_eq!(cursor.frame(later, true).opacity, 1.); + assert!( + cursor + .corners + .iter() + .all(|corner| corner.animation_length == SHORT_MOVE) + ); + let mid = cursor.frame(later + Duration::from_millis(8), true); + assert!(mid.points[0].x < px(10.)); + } + + #[test] + fn blur_snaps_to_full_cell_outline_and_stops_animation() { + let now = Instant::now(); + let mut cursor = CursorAnimator::new(); + target(&mut cursor, 0., 0., CursorShape::Beam, now); + cursor.frame(now, true); + target(&mut cursor, 100., 40., CursorShape::Beam, now); + let frame = cursor.frame(now + Duration::from_millis(16), false); + assert!(frame.outline); + assert_eq!(frame.opacity, 1.); + assert_eq!(frame.next, None); + assert_eq!(frame.points[0], point(px(100.), px(40.))); + assert_eq!(frame.points[2], point(px(110.), px(60.))); + let later = cursor.frame(now + Duration::from_secs(4), false); + assert_eq!(later.points, frame.points); + assert_eq!(later.opacity, frame.opacity); + let refocused = cursor.frame(now + Duration::from_secs(5), true); + assert!(!refocused.outline); + assert_eq!(refocused.opacity, 1.); + } + + #[test] + fn hidden_cursor_never_draws_or_schedules_frames() { + let now = Instant::now(); + let mut cursor = CursorAnimator::new(); + target(&mut cursor, 0., 0., CursorShape::Hidden, now); + let frame = cursor.frame(now, true); + assert_eq!(frame.opacity, 0.); + assert_eq!(frame.next, None); + } +} diff --git a/src/label.rs b/src/label.rs new file mode 100644 index 0000000..3654c01 --- /dev/null +++ b/src/label.rs @@ -0,0 +1,155 @@ +//! Single-line chrome labels that keep both ends visible when space is tight. +use gpui::{ + ContentMask, IntoElement, Pixels, ShapedLine, SharedString, TextStyle, Window, canvas, point, + prelude::*, px, +}; +use unicode_segmentation::UnicodeSegmentation; + +/// Fill the parent's allocated label area, inheriting its font, size and color. +pub fn middle_label(text: SharedString) -> impl IntoElement { + canvas( + move |bounds, window, _| { + let style = window.text_style(); + let height = style.line_height_in_pixels(window.rem_size()); + let line = fit_line(text, bounds.size.width, &style, window); + (line, height) + }, + |bounds, (line, height), window, cx| { + if let Some(line) = line { + let origin = bounds.origin + point(px(0.), (bounds.size.height - height) / 2.); + window.with_content_mask(Some(ContentMask { bounds }), |window| { + let _ = line.paint(origin, height, window, cx); + }); + } + }, + ) + .size_full() +} + +fn shape(text: SharedString, style: &TextStyle, window: &Window) -> ShapedLine { + let size = style.font_size.to_pixels(window.rem_size()); + let run = style.to_run(text.len()); + window.text_system().shape_line(text, size, &[run], None) +} + +fn fit_line( + text: SharedString, + available: Pixels, + style: &TextStyle, + window: &Window, +) -> Option { + if available <= px(0.) || text.is_empty() { + return None; + } + let full = shape(text.clone(), style, window); + if full.width <= available { + return Some(full); + } + let ellipsis = shape("…".into(), style, window); + if ellipsis.width > available { + return None; + } + + let boundaries: Vec<_> = text + .grapheme_indices(true) + .map(|(index, _)| index) + .chain(std::iter::once(text.len())) + .collect(); + // Use the existing full-line glyph positions to estimate the retained + // pieces. Sorting once avoids repeatedly scanning every glyph per cut. + let mut glyphs: Vec<_> = full + .runs + .iter() + .flat_map(|run| run.glyphs.iter()) + .map(|glyph| (glyph.index, f32::from(glyph.position.x))) + .collect(); + glyphs.sort_by_key(|&(index, _)| index); + let total = f32::from(full.width); + let mut previous = 0.; + let positions: Vec<_> = boundaries + .iter() + .map(|&boundary| { + let glyph = glyphs.partition_point(|&(index, _)| index < boundary); + let x = glyphs.get(glyph).map_or(total, |&(_, x)| x); + // Bidirectional runs can have nonmonotonic glyph positions. Treat + // these as estimates; the final shortened line is always measured. + previous = x.clamp(previous, total); + previous + }) + .collect(); + let mut budget = f32::from(available - ellipsis.width); + // Usually only one shortened line is shaped. Contextual shaping can alter + // edge widths; allow two bounded corrections rather than shaping each cut. + for _ in 0..3 { + let (prefix, suffix) = middle_split(&positions, budget); + let shortened = format!( + "{}…{}", + &text[..boundaries[prefix]], + &text[boundaries[suffix]..] + ); + let line = shape(shortened.into(), style, window); + if line.width <= available { + return Some(line); + } + budget -= f32::from(line.width - available).max(budget * 0.1).max(1.); + if budget <= 0. { + break; + } + } + Some(ellipsis) +} + +/// Choose whole graphemes from both ends, balancing their measured widths. +/// At least one grapheme remains omitted between the two retained pieces. +fn middle_split(positions: &[f32], budget: f32) -> (usize, usize) { + let last = positions.len().saturating_sub(1); + let mut prefix = 0; + let mut suffix = last; + let total = positions[last]; + while prefix + 1 < suffix { + let left = positions[prefix]; + let right = total - positions[suffix]; + let can_left = positions[prefix + 1] + right <= budget; + let can_right = left + total - positions[suffix - 1] <= budget; + if can_left && (left < right || !can_right) { + prefix += 1; + } else if can_right { + suffix -= 1; + } else { + break; + } + } + (prefix, suffix) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cuts_keep_both_ends_within_the_measured_budget() { + let positions = [0., 4., 10., 14., 18., 23., 30., 35.]; + let (left, right) = middle_split(&positions, 20.); + assert!(left > 0 && right < positions.len() - 1 && left < right); + assert!(positions[left] + positions.last().unwrap() - positions[right] <= 20.); + assert_eq!(middle_split(&positions, 0.), (0, positions.len() - 1)); + } + + #[test] + fn cuts_preserve_combining_characters_and_emoji_sequences() { + let text = "~é/e\u{301}/👩🏽‍💻/終点"; + let boundaries: Vec<_> = text + .grapheme_indices(true) + .map(|(index, _)| index) + .chain(std::iter::once(text.len())) + .collect(); + let positions: Vec<_> = (0..boundaries.len()).map(|i| i as f32).collect(); + for width in 0..boundaries.len() { + let (left, right) = middle_split(&positions, width as f32); + let prefix = &text[..boundaries[left]]; + let suffix = &text[boundaries[right]..]; + assert_eq!(prefix.graphemes(true).count(), left); + assert_eq!(suffix.graphemes(true).count(), boundaries.len() - 1 - right); + } + } +} diff --git a/src/launcher.rs b/src/launcher.rs new file mode 100644 index 0000000..ec83391 --- /dev/null +++ b/src/launcher.rs @@ -0,0 +1,754 @@ +//! Local daemon startup and the server-owned, single-threaded GUI zygote. +//! +//! GPUI, fonts, Wayland, Vulkan, and executors are initialized only in forked GUI +//! children. Forking a process after any of those start threads is unsupported. +use std::{ + fs::{self, DirBuilder, File, OpenOptions}, + io, + os::{ + fd::AsRawFd, + unix::{ + ffi::{OsStrExt, OsStringExt}, + fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, + net::{UnixListener, UnixStream}, + process::CommandExt, + }, + }, + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, + thread, + time::{Duration, Instant}, +}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::protocol::{self, ClientMessage, ServerMessage}; + +const START_TIMEOUT: Duration = Duration::from_secs(10); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); + +pub fn default_socket() -> Result { + let root = if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") { + let runtime = PathBuf::from(runtime); + verify_private_directory(&runtime)?; + runtime.join("psyterm") + } else { + std::env::temp_dir().join(format!("psyterm-{}", uid())) + }; + ensure_private_directory(&root)?; + Ok(root.join("server.sock")) +} + +/// Start exactly one daemon. The daemon has its own lifetime lock; this lock is +/// held only while racing launchers agree on which process starts it. +pub fn ensure_server(socket: &Path) -> Result<()> { + ensure_socket_parent(socket)?; + if probe_server(socket)? { + return Ok(()); + } + let startup_lock = private_file(&suffixed(socket, ".startup.lock"))?; + // SAFETY: flock operates on our live file descriptor and has no pointers. + if unsafe { libc::flock(startup_lock.as_raw_fd(), libc::LOCK_EX) } != 0 { + return Err(io::Error::last_os_error()).context("lock server startup"); + } + if probe_server(socket)? { + return Ok(()); + } + let log_path = suffixed(socket, ".log"); + let mut child = spawn_role("--server", socket, &log_path)?; + let deadline = Instant::now() + START_TIMEOUT; + loop { + if probe_server(socket)? { + return Ok(()); + } + if let Some(status) = child.try_wait()? { + bail!( + "psyTerm server exited ({status}); see {}", + log_path.display() + ); + } + if Instant::now() >= deadline { + // This process is ours and never became available to clients. + let _ = child.kill(); + let _ = child.wait(); + bail!( + "psyTerm server startup timed out; see {}", + log_path.display() + ); + } + thread::sleep(Duration::from_millis(15)); + } +} + +/// Send a command without attaching a GUI or creating a terminal session. +pub fn control(socket: &Path, command: ClientMessage) -> Result { + let stream = UnixStream::connect(socket) + .with_context(|| format!("connect to psyTerm server at {}", socket.display()))?; + let legacy_shutdown = matches!(command, ClientMessage::Shutdown); + let result = control_stream(stream, command, REQUEST_TIMEOUT); + if legacy_shutdown + && protocol::VERSION > 1 + && result + .as_ref() + .is_err_and(|error| error.to_string().contains("protocol")) + { + // Version 1 shares the Hello/Shutdown/Closing wire prefix. Permit only + // an explicit shutdown through that prefix, never old grid decoding. + let stream = UnixStream::connect(socket)?; + return control_stream_version(stream, ClientMessage::Shutdown, REQUEST_TIMEOUT, 1); + } + result +} + +fn probe_server(socket: &Path) -> Result { + match UnixStream::connect(socket) { + Ok(stream) => { + match control_stream(stream, ClientMessage::Ping, Duration::from_millis(500))? { + ServerMessage::Pong => Ok(true), + _ => bail!("psyTerm server did not acknowledge startup probe"), + } + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused + ) => + { + Ok(false) + } + Err(error) => Err(error).with_context(|| format!("probe {}", socket.display())), + } +} + +fn control_stream( + stream: UnixStream, + command: ClientMessage, + timeout: Duration, +) -> Result { + control_stream_version(stream, command, timeout, protocol::VERSION) +} + +fn control_stream_version( + mut stream: UnixStream, + command: ClientMessage, + timeout: Duration, + expected_version: u32, +) -> Result { + verify_peer(&stream)?; + stream.set_read_timeout(Some(timeout))?; + stream.set_write_timeout(Some(timeout))?; + protocol::write_message( + &mut stream, + &ClientMessage::Hello { + version: expected_version, + }, + )?; + match protocol::read_message::(&mut stream)? { + ServerMessage::Hello { version, .. } if version == expected_version => {} + ServerMessage::Hello { version, .. } => bail!( + "server protocol {version} does not match client protocol {}", + expected_version + ), + ServerMessage::Error(error) => bail!( + "{error}. If the server predates this build, end its sessions with psyterm --shutdown and relaunch" + ), + _ => bail!("server did not send a protocol greeting"), + } + protocol::write_message(&mut stream, &command)?; + loop { + let message: ServerMessage = protocol::read_message(&mut stream)?; + match message { + ServerMessage::Pong | ServerMessage::Closing => return Ok(message), + ServerMessage::Error(error) => bail!("{error}"), + _ => {} + } + } +} + +/// Owned by the terminal server. Its GUI children are independent clients and +/// keep running when this helper is stopped; stopping the helper never kills them. +pub struct Zygote { + server_socket: PathBuf, + socket: PathBuf, + child: Child, + ready: bool, + executable: PathBuf, + executable_identity: ExecutableIdentity, +} + +impl Zygote { + pub fn start(server_socket: &Path) -> Result { + ensure_socket_parent(server_socket)?; + let socket = suffixed(server_socket, ".zygote.sock"); + let log_path = suffixed(server_socket, ".zygote.log"); + let executable = executable_path()?; + let executable_identity = ExecutableIdentity::read(&executable)?; + let child = spawn_role_from(&executable, "--zygote", &socket, &log_path)?; + let mut zygote = Self { + server_socket: server_socket.to_owned(), + socket, + child, + ready: false, + executable, + executable_identity, + }; + let deadline = Instant::now() + START_TIMEOUT; + loop { + if let Ok(LaunchResponse::Ready { pid }) = zygote.request(&LaunchRequest::Ping) { + if pid != zygote.child.id() { + bail!( + "a different GUI zygote is already listening at {}", + zygote.socket.display() + ); + } + zygote.ready = true; + return Ok(zygote); + } + if let Some(status) = zygote.child.try_wait()? { + bail!( + "psyTerm zygote exited ({status}); see {}", + log_path.display() + ); + } + if Instant::now() >= deadline { + bail!( + "psyTerm zygote startup timed out; see {}", + log_path.display() + ); + } + thread::sleep(Duration::from_millis(15)); + } + } + + pub fn open_window(&mut self, remote: Option) -> Result<()> { + let executable = executable_path()?; + let identity = ExecutableIdentity::read(&executable)?; + let helper_exited = self.child.try_wait()?.is_some(); + if helper_exited || executable != self.executable || identity != self.executable_identity { + log::info!("Refreshing GUI zygote after executable replacement or helper exit"); + self.stop(); + // Assignment drops the stopped helper only after a replacement is + // ready. If startup fails, a later launch can retry this stopped one. + *self = Self::start(&self.server_socket)?; + } + match self.request(&LaunchRequest::Launch { + server_socket: self.server_socket.clone(), + remote, + })? { + LaunchResponse::Launched { pid } => { + log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id()); + Ok(()) + } + LaunchResponse::Error(error) => bail!("{error}"), + _ => bail!("unexpected GUI zygote reply"), + } + } + + fn request(&self, request: &LaunchRequest) -> Result { + let mut stream = UnixStream::connect(&self.socket)?; + verify_peer(&stream)?; + stream.set_read_timeout(Some(REQUEST_TIMEOUT))?; + stream.set_write_timeout(Some(REQUEST_TIMEOUT))?; + protocol::write_message(&mut stream, request)?; + protocol::read_message(&mut stream) + } + + fn stop(&mut self) { + if matches!(self.child.try_wait(), Ok(Some(_))) { + return; + } + if self.ready { + let _ = self.request(&LaunchRequest::Shutdown); + } + let deadline = Instant::now() + Duration::from_millis(500); + while Instant::now() < deadline { + if matches!(self.child.try_wait(), Ok(Some(_))) { + return; + } + thread::sleep(Duration::from_millis(10)); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + self.ready = false; + } +} + +impl Drop for Zygote { + fn drop(&mut self) { + self.stop(); + } +} + +#[derive(Debug, PartialEq, Eq)] +struct ExecutableIdentity { + device: u64, + inode: u64, + bytes: u64, + modified: std::time::SystemTime, +} + +impl ExecutableIdentity { + fn read(path: &Path) -> Result { + let metadata = + fs::metadata(path).with_context(|| format!("inspect executable {}", path.display()))?; + if !metadata.is_file() { + bail!("{} is not an executable file", path.display()); + } + Ok(Self { + device: metadata.dev(), + inode: metadata.ino(), + bytes: metadata.len(), + modified: metadata.modified()?, + }) + } +} + +#[derive(Debug, Serialize, Deserialize)] +enum LaunchRequest { + Ping, + Launch { + server_socket: PathBuf, + remote: Option, + }, + Shutdown, +} + +#[derive(Debug, Serialize, Deserialize)] +enum LaunchResponse { + Ready { pid: u32 }, + Launched { pid: u32 }, + Error(String), + Stopped, +} + +pub fn run_zygote(socket: &Path) -> Result<()> { + ensure_single_threaded()?; + // SAFETY: the fixed NUL-terminated name fits Linux's 16-byte comm field. + unsafe { + libc::prctl(libc::PR_SET_NAME, c"psyterm-zygote".as_ptr()); + } + ensure_socket_parent(socket)?; + remove_stale_socket(socket)?; + let listener = UnixListener::bind(socket).context("bind GUI zygote socket")?; + fs::set_permissions(socket, fs::Permissions::from_mode(0o600))?; + let _socket_guard = SocketGuard::new(socket)?; + set_child_reaping(true)?; + log::info!("Single-threaded GUI zygote {} ready", std::process::id()); + loop { + let (mut stream, _) = match listener.accept() { + Ok(connection) => connection, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error).context("accept GUI launch request"), + }; + if let Err(error) = verify_peer(&stream) { + log::warn!("Rejected GUI launch peer: {error}"); + continue; + } + stream.set_read_timeout(Some(REQUEST_TIMEOUT))?; + stream.set_write_timeout(Some(REQUEST_TIMEOUT))?; + let request = match protocol::read_message::(&mut stream) { + Ok(request) => request, + Err(error) => { + log::debug!("Incomplete GUI launch request: {error}"); + continue; + } + }; + match request { + LaunchRequest::Ping => protocol::write_message( + &mut stream, + &LaunchResponse::Ready { + pid: std::process::id(), + }, + )?, + LaunchRequest::Shutdown => { + protocol::write_message(&mut stream, &LaunchResponse::Stopped)?; + return Ok(()); + } + LaunchRequest::Launch { + server_socket, + remote, + } => { + if let Err(error) = ensure_single_threaded() { + protocol::write_message( + &mut stream, + &LaunchResponse::Error(error.to_string()), + )?; + continue; + } + // SAFETY: this process is single-threaded (checked above) and + // has never initialized GPUI/Wayland/Vulkan or an executor. All + // Rust allocator/logger locks can only have belonged to this + // thread and are unlocked here. The child closes inherited IPC + // descriptors, resets SIGCHLD, and owns its fresh GUI runtime. + let pid = unsafe { libc::fork() }; + if pid == -1 { + protocol::write_message( + &mut stream, + &LaunchResponse::Error(io::Error::last_os_error().to_string()), + )?; + continue; + } + if pid == 0 { + // SAFETY: this only labels our forked GUI process for tools. + unsafe { + libc::prctl(libc::PR_SET_NAME, c"psyterm-gui".as_ptr()); + } + drop(stream); + drop(listener); + let result = set_child_reaping(false) + .and_then(|()| crate::run_gui(server_socket, remote)); + let code = if let Err(error) = result { + log::error!("GUI startup failed: {error:#}"); + 1 + } else { + 0 + }; + // SAFETY: this fork child must not run parent scope cleanup + // (particularly the shared listening socket's unlink guard). + unsafe { libc::_exit(code) }; + } + protocol::write_message( + &mut stream, + &LaunchResponse::Launched { pid: pid as u32 }, + )?; + } + } + } +} + +fn set_child_reaping(auto_reap: bool) -> Result<()> { + // SAFETY: sigaction is initialized before use, uses SIG_DFL (no callback), + // and points only to stack storage for the duration of these calls. + unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + action.sa_sigaction = libc::SIG_DFL; + libc::sigemptyset(&mut action.sa_mask); + action.sa_flags = if auto_reap { + libc::SA_NOCLDWAIT | libc::SA_RESTART + } else { + 0 + }; + if libc::sigaction(libc::SIGCHLD, &action, std::ptr::null_mut()) == -1 { + return Err(io::Error::last_os_error()).context("configure child reaping"); + } + } + Ok(()) +} + +fn ensure_single_threaded() -> Result<()> { + let count = fs::read_dir("/proc/self/task") + .context("verify zygote thread count")? + .count(); + if count != 1 { + bail!("refusing to fork GUI zygote with {count} threads; initialize GPUI only after fork"); + } + Ok(()) +} + +fn spawn_role(role: &str, socket: &Path, log_path: &Path) -> Result { + spawn_role_from(&executable_path()?, role, socket, log_path) +} + +fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path) -> Result { + let log = private_file(log_path)?; + let mut command = Command::new(executable); + command + .arg(role) + .arg("--socket") + .arg(socket) + .stdin(Stdio::null()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log)); + let managed_helper = role == "--zygote"; + let parent_pid = std::process::id() as libc::pid_t; + // SAFETY: the closure calls only libc syscalls and performs no allocation or + // synchronization between Command's fork and exec. A zygote follows its + // server's lifetime; the server itself intentionally outlives its launcher. + unsafe { + command.pre_exec(move || { + if libc::setsid() == -1 { + return Err(io::Error::last_os_error()); + } + if managed_helper { + if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 { + return Err(io::Error::last_os_error()); + } + if libc::getppid() != parent_pid { + libc::_exit(1); + } + } + Ok(()) + }); + } + command + .spawn() + .with_context(|| format!("launch psyTerm {role}")) +} + +/// Linux marks `/proc/self/exe` with " (deleted)" after atomic replacement. +/// Resolve the new installed path without rewriting a real filename that happens +/// to end with those characters. Server logic remains loaded until shutdown; +/// only newly forked GUI code is refreshed by `Zygote::open_window`. +fn executable_path() -> Result { + resolve_executable_path(std::env::current_exe()?) +} + +fn resolve_executable_path(path: PathBuf) -> Result { + match fs::symlink_metadata(&path) { + Ok(_) => { + if path.is_file() { + return Ok(path); + } + bail!("{} is not an executable file", path.display()); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("inspect current executable path"), + } + if let Some(original) = path.as_os_str().as_bytes().strip_suffix(b" (deleted)") { + let original = PathBuf::from(std::ffi::OsString::from_vec(original.to_vec())); + if original.is_file() { + return Ok(original); + } + } + bail!( + "psyTerm executable {} no longer exists; restart the server from its installed location", + path.display() + ) +} + +fn uid() -> u32 { + // SAFETY: geteuid has no arguments or side effects. + unsafe { libc::geteuid() } +} + +fn suffixed(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + PathBuf::from(name) +} + +fn ensure_socket_parent(socket: &Path) -> Result<()> { + let parent = socket + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .context("socket path must include a private parent directory")?; + ensure_private_directory(parent) +} + +fn ensure_private_directory(path: &Path) -> Result<()> { + match DirBuilder::new().mode(0o700).create(path) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error).with_context(|| format!("create {}", path.display())), + } + verify_private_directory(path) +} + +fn verify_private_directory(path: &Path) -> Result<()> { + let metadata = + fs::symlink_metadata(path).with_context(|| format!("inspect {}", path.display()))?; + if !metadata.is_dir() || metadata.uid() != uid() || metadata.mode() & 0o077 != 0 { + bail!( + "{} must be a real directory owned by your UID with mode 0700", + path.display() + ); + } + Ok(()) +} + +fn private_file(path: &Path) -> Result { + let file = OpenOptions::new() + .read(true) + .append(true) + .create(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path) + .with_context(|| format!("open {}", path.display()))?; + let metadata = file.metadata()?; + if !metadata.is_file() + || metadata.uid() != uid() + || metadata.mode() & 0o077 != 0 + || metadata.nlink() != 1 + { + bail!( + "{} must be a private regular file owned by your UID", + path.display() + ); + } + Ok(file) +} + +fn remove_stale_socket(path: &Path) -> Result<()> { + match UnixStream::connect(path) { + Ok(_) => bail!("GUI zygote is already listening at {}", path.display()), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused + ) => {} + Err(error) => return Err(error).context("inspect previous zygote listener"), + } + match fs::symlink_metadata(path) { + Ok(metadata) => { + if !metadata.file_type().is_socket() || metadata.uid() != uid() { + bail!( + "refusing to remove non-owned/non-socket path {}", + path.display() + ); + } + fs::remove_file(path).context("remove stale zygote socket")?; + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("inspect stale zygote socket"), + } + Ok(()) +} + +pub(crate) fn verify_peer(stream: &UnixStream) -> Result<()> { + let mut credentials: libc::ucred = unsafe { std::mem::zeroed() }; + let mut size = std::mem::size_of::() as libc::socklen_t; + // SAFETY: credentials and size are valid initialized buffers of the stated + // lengths; getsockopt writes only the SO_PEERCRED structure. + let result = unsafe { + libc::getsockopt( + stream.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PEERCRED, + (&mut credentials as *mut libc::ucred).cast(), + &mut size, + ) + }; + if result == -1 { + return Err(io::Error::last_os_error()).context("read socket peer credentials"); + } + if credentials.uid != uid() { + bail!("socket peer belongs to another UID"); + } + Ok(()) +} + +struct SocketGuard { + path: PathBuf, + device: u64, + inode: u64, +} +impl SocketGuard { + fn new(path: &Path) -> Result { + let metadata = fs::symlink_metadata(path)?; + Ok(Self { + path: path.to_owned(), + device: metadata.dev(), + inode: metadata.ino(), + }) + } +} +impl Drop for SocketGuard { + fn drop(&mut self) { + if let Ok(metadata) = fs::symlink_metadata(&self.path) + && metadata.dev() == self.device + && metadata.ino() == self.inode + { + let _ = fs::remove_file(&self.path); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_dir() -> PathBuf { + let path = std::env::temp_dir().join(format!( + "psyterm-launcher-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + ensure_private_directory(&path).unwrap(); + path + } + + #[test] + fn private_paths_reject_symlinks_and_shared_directories() { + let root = test_dir(); + let private = root.join("private"); + ensure_private_directory(&private).unwrap(); + let alias = root.join("alias"); + std::os::unix::fs::symlink(&private, &alias).unwrap(); + assert!(ensure_private_directory(&alias).is_err()); + fs::set_permissions(&private, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(verify_private_directory(&private).is_err()); + let file = root.join("log"); + private_file(&file).unwrap(); + let alias_file = root.join("alias-file"); + std::os::unix::fs::symlink(&file, &alias_file).unwrap(); + assert!(private_file(&alias_file).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn stale_socket_cleanup_never_removes_regular_files() { + let root = test_dir(); + let path = root.join("zygote.sock"); + fs::write(&path, b"keep me").unwrap(); + assert!(remove_stale_socket(&path).is_err()); + assert_eq!(fs::read(&path).unwrap(), b"keep me"); + fs::remove_file(&path).unwrap(); + let listener = UnixListener::bind(&path).unwrap(); + assert!(remove_stale_socket(&path).is_err()); + drop(listener); + remove_stale_socket(&path).unwrap(); + assert!(!path.exists()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn launch_request_round_trip_preserves_remote_without_shell_parsing() { + let request = LaunchRequest::Launch { + server_socket: PathBuf::from("/private/psyterm.sock"), + remote: Some("work-host".into()), + }; + let mut bytes = Vec::new(); + protocol::write_message(&mut bytes, &request).unwrap(); + let decoded: LaunchRequest = protocol::read_message(&mut bytes.as_slice()).unwrap(); + assert!( + matches!(decoded, LaunchRequest::Launch { remote: Some(host), .. } if host == "work-host") + ); + } + + #[test] + fn unix_peer_credentials_match_current_user() { + let (left, _right) = UnixStream::pair().unwrap(); + verify_peer(&left).unwrap(); + } + + #[test] + fn deleted_executable_suffix_resolves_only_when_original_name_is_absent() { + let root = test_dir(); + let original = root.join("psyterm"); + let deleted = root.join("psyterm (deleted)"); + fs::write(&original, b"new executable").unwrap(); + assert_eq!(resolve_executable_path(deleted.clone()).unwrap(), original); + fs::write(&deleted, b"real literal filename").unwrap(); + assert_eq!(resolve_executable_path(deleted.clone()).unwrap(), deleted); + assert!(resolve_executable_path(root.join("missing")).is_err()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn replacement_executable_changes_identity_even_with_same_contents() { + let root = test_dir(); + let original = root.join("psyterm"); + fs::write(&original, b"binary").unwrap(); + let before = ExecutableIdentity::read(&original).unwrap(); + let replacement = root.join("psyterm-new"); + fs::write(&replacement, b"binary").unwrap(); + fs::rename(replacement, &original).unwrap(); + assert_ne!(ExecutableIdentity::read(&original).unwrap(), before); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/src/main.rs b/src/main.rs index 6f16f97..13808d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,126 @@ +mod chrome; +mod client; mod colors; +mod cursor; mod fonts; mod input; +mod label; +mod launcher; +mod pane_name; +mod protocol; mod render; +mod server; mod session; mod terminal; +use anyhow::{Result, bail}; use gpui::{prelude::*, *}; +use std::path::PathBuf; -fn main() -> anyhow::Result<()> { +fn main() -> Result<()> { env_logger::init(); - let (session, events) = session::Session::new()?; + let mut role = "launch"; + let mut socket = None; + let mut remote = None; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--server" => role = "server", + "--zygote" => role = "zygote", + "--gui" => role = "gui", + "--bridge" => role = "bridge", + "--shutdown" => role = "shutdown", + "--list" => role = "list", + "--socket" => { + socket = Some(PathBuf::from( + args.next() + .ok_or_else(|| anyhow::anyhow!("--socket needs a path"))?, + )) + } + "--remote" => { + remote = Some( + args.next() + .ok_or_else(|| anyhow::anyhow!("--remote needs an SSH destination"))?, + ) + } + "--help" | "-h" => { + println!( + "psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a window via the local server's zygote\n psyterm --remote user@host Connect a local GUI to a server over SSH\n psyterm --list List server-owned tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Direct GUI launch (diagnostics; bypass zygote)\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n" + ); + return Ok(()); + } + _ => bail!("unknown argument: {arg}; see --help"), + } + } + let socket = socket.map(Ok).unwrap_or_else(launcher::default_socket)?; + match role { + "server" => { + let zygote_socket = socket.clone(); + let mut zygote: Option = None; + server::run(&socket, move |remote| { + if zygote.is_none() { + zygote = Some(launcher::Zygote::start(&zygote_socket)?); + } + zygote.as_mut().unwrap().open_window(remote) + }) + } + "zygote" => launcher::run_zygote(&socket), + "gui" => { + launcher::ensure_server(&socket)?; + run_gui(socket, remote) + } + "bridge" => client::bridge(&socket), + "shutdown" => { + launcher::control(&socket, protocol::ClientMessage::Shutdown)?; + Ok(()) + } + "list" => list_sessions(&socket), + _ => { + launcher::ensure_server(&socket)?; + launcher::control( + &socket, + protocol::ClientMessage::OpenWindow { target: remote }, + )?; + Ok(()) + } + } +} + +fn list_sessions(socket: &std::path::Path) -> Result<()> { + let mut stream = std::os::unix::net::UnixStream::connect(socket)?; + stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?; + protocol::write_message( + &mut stream, + &protocol::ClientMessage::Hello { + version: protocol::VERSION, + }, + )?; + let hello: protocol::ServerMessage = protocol::read_message(&mut stream)?; + println!("{hello:?}"); + protocol::write_message(&mut stream, &protocol::ClientMessage::List)?; + loop { + match protocol::read_message(&mut stream)? { + protocol::ServerMessage::Snapshot(snapshot) => { + for tab in snapshot.tabs { + println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes); + } + break; + } + protocol::ServerMessage::Error(error) => bail!("{error}"), + _ => {} + } + } + Ok(()) +} + +/// Called directly in a fresh fork of the single-threaded zygote. All GPUI, +/// graphics, font discovery and client I/O initialization happens after fork. +pub(crate) fn run_gui(socket: PathBuf, remote: Option) -> Result<()> { + let (client, updates) = client::Client::connect(&socket, remote.as_deref())?; + let connection: SharedString = remote + .map(|host| format!("SSH · {host}")) + .unwrap_or_else(|| "Local".into()) + .into(); Application::new().run(move |cx: &mut App| { cx.on_window_closed(|cx| { if cx.windows().is_empty() { @@ -17,20 +128,23 @@ fn main() -> anyhow::Result<()> { } }) .detach(); - let bounds = Bounds::centered(None, size(px(960.), px(640.)), cx); + let bounds = Bounds::centered(None, size(px(1000.), px(680.)), cx); cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), titlebar: Some(TitlebarOptions { - title: Some("Terminal".into()), + title: Some("psyTerm".into()), ..Default::default() }), - app_id: Some("dev.buzzert.terminal".into()), + window_decorations: Some(WindowDecorations::Client), + app_id: Some("dev.buzzert.psyterm".into()), ..Default::default() }, - move |window, cx| cx.new(|cx| terminal::TerminalView::new(session, events, window, cx)), + move |window, cx| { + cx.new(|cx| terminal::Workspace::new(client, updates, connection, window, cx)) + }, ) - .expect("could not open terminal window"); + .expect("could not open psyTerm window"); cx.activate(true); }); Ok(()) diff --git a/src/pane_name.rs b/src/pane_name.rs new file mode 100644 index 0000000..e6dc4c8 --- /dev/null +++ b/src/pane_name.rs @@ -0,0 +1,656 @@ +//! Single-line pane-name editing. UTF-8 offsets stay internal; platform input +//! methods use UTF-16 ranges. Editing never sends bytes to the terminal process. +use std::ops::Range; + +const MAX_CHARACTERS: usize = 512; + +#[derive(Debug, Clone)] +pub struct NameEditor { + pub text: String, + anchor: usize, + cursor: usize, + marked: Option>, +} + +impl NameEditor { + /// Starting with the entire current name selected makes typing replace it. + pub fn new(text: &str) -> Self { + let text = clean_text(text) + .chars() + .take(MAX_CHARACTERS) + .collect::(); + let cursor = text.len(); + Self { + text, + anchor: 0, + cursor, + marked: None, + } + } + + /// Selection and cursor offsets used by GPUI's shaped line are UTF-8 bytes. + pub fn selection(&self) -> Range { + self.anchor.min(self.cursor)..self.anchor.max(self.cursor) + } + pub fn cursor(&self) -> usize { + self.cursor + } + pub fn reversed(&self) -> bool { + self.cursor < self.anchor + } + pub fn selection_utf16(&self) -> Range { + self.to_utf16(self.selection()) + } + pub fn marked_utf16(&self) -> Option> { + self.marked.clone().map(|range| self.to_utf16(range)) + } + pub fn text_for_range(&self, range: Range) -> (String, Range) { + let bytes = self.range_from_utf16(range); + (self.text[bytes.clone()].to_owned(), self.to_utf16(bytes)) + } + pub fn byte_offset_for_utf16(&self, offset: usize) -> usize { + utf16_to_byte(&self.text, offset, false) + } + pub fn utf16_offset_for_byte(&self, offset: usize) -> usize { + self.text[..floor_boundary(&self.text, offset)] + .encode_utf16() + .count() + } + + pub fn select_all(&mut self) { + self.anchor = 0; + self.cursor = self.text.len(); + self.marked = None; + } + pub fn set_cursor(&mut self, byte: usize, extend: bool) { + self.cursor = floor_boundary(&self.text, byte); + if !extend { + self.anchor = self.cursor; + } + self.marked = None; + } + pub fn left(&mut self, extend: bool) { + let position = if !extend && self.anchor != self.cursor { + self.selection().start + } else { + self.text[..self.cursor] + .char_indices() + .next_back() + .map_or(0, |(i, _)| i) + }; + self.set_cursor(position, extend); + } + pub fn right(&mut self, extend: bool) { + let position = if !extend && self.anchor != self.cursor { + self.selection().end + } else { + self.text[self.cursor..] + .chars() + .next() + .map_or(self.text.len(), |c| self.cursor + c.len_utf8()) + }; + self.set_cursor(position, extend); + } + pub fn home(&mut self, extend: bool) { + self.set_cursor(0, extend); + } + pub fn end(&mut self, extend: bool) { + self.set_cursor(self.text.len(), extend); + } + pub fn backspace(&mut self) { + if self.anchor == self.cursor { + self.left(true); + } + self.replace(None, ""); + } + pub fn delete(&mut self) { + if self.anchor == self.cursor { + self.right(true); + } + self.replace(None, ""); + } + pub fn unmark(&mut self) { + self.marked = None; + } + + pub fn replace(&mut self, range_utf16: Option>, text: &str) { + self.replace_inner(range_utf16, text); + self.marked = None; + } + pub fn replace_and_mark( + &mut self, + range_utf16: Option>, + text: &str, + selected_utf16: Option>, + ) { + let inserted = self.replace_inner(range_utf16, text); + if inserted.is_empty() { + self.marked = None; + } else { + self.marked = Some(inserted.clone()); + } + if let Some(selected) = selected_utf16 { + let text = &self.text[inserted.clone()]; + let start = utf16_to_byte(text, selected.start, false); + let end = utf16_to_byte(text, selected.end, true); + self.anchor = inserted.start + start; + self.cursor = inserted.start + end; + } + } + + fn replace_inner(&mut self, range_utf16: Option>, text: &str) -> Range { + let range = range_utf16 + .map(|range| self.range_from_utf16(range)) + .or_else(|| self.marked.clone()) + .unwrap_or_else(|| self.selection()); + let kept = + self.text[..range.start].chars().count() + self.text[range.end..].chars().count(); + let replacement: String = clean_text(text) + .chars() + .take(MAX_CHARACTERS.saturating_sub(kept)) + .collect(); + let inserted = range.start..range.start + replacement.len(); + self.text.replace_range(range, &replacement); + self.anchor = inserted.end; + self.cursor = inserted.end; + inserted + } + fn to_utf16(&self, range: Range) -> Range { + self.utf16_offset_for_byte(range.start)..self.utf16_offset_for_byte(range.end) + } + fn range_from_utf16(&self, range: Range) -> Range { + let start = range.start.min(range.end); + let end = range.start.max(range.end); + if start == end { + let at = utf16_to_byte(&self.text, start, false); + at..at + } else { + utf16_to_byte(&self.text, start, false)..utf16_to_byte(&self.text, end, true) + } + } +} + +fn clean_text(text: &str) -> String { + text.chars() + .filter_map(|c| match c { + '\r' | '\n' | '\t' => Some(' '), + c if c.is_control() => None, + c => Some(c), + }) + .collect() +} +fn floor_boundary(text: &str, index: usize) -> usize { + let mut index = index.min(text.len()); + while !text.is_char_boundary(index) { + index -= 1; + } + index +} +fn utf16_to_byte(text: &str, requested: usize, ceil: bool) -> usize { + let mut offset = 0; + for (index, character) in text.char_indices() { + if requested == offset { + return index; + } + let next = offset + character.len_utf16(); + if requested < next { + return if ceil { + index + character.len_utf8() + } else { + index + }; + } + offset = next; + } + text.len() +} + +use crate::chrome; +use gpui::{ + App, Bounds, Context, CursorStyle, ElementInputHandler, EntityInputHandler, FocusHandle, + Focusable, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, Point, Render, + ShapedLine, TextRun, UTF16Selection, UnderlineStyle, Window, canvas, div, fill, font, point, + prelude::*, px, rgb, size, +}; + +const FIELD_HEIGHT: f32 = 24.; +const TEXT_SIZE: f32 = 12.; +const FIELD_PADDING: f32 = 6.; + +type Finish = Box, &mut Window, &mut App)>; + +/// A focused inline editor that keeps all name editing separate from PTY input. +pub struct RenameField { + editor: NameEditor, + focus_handle: FocusHandle, + on_finish: Finish, + last_bounds: Bounds, + last_layout: Option, + scroll: Pixels, + selecting: bool, +} + +impl RenameField { + pub fn new( + initial: String, + on_finish: impl Fn(Option, &mut Window, &mut App) + 'static, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let focus_handle = cx.focus_handle(); + window.focus(&focus_handle); + Self { + editor: NameEditor::new(&initial), + focus_handle, + on_finish: Box::new(on_finish), + last_bounds: Bounds::default(), + last_layout: None, + scroll: px(0.), + selecting: false, + } + } + + pub fn focus(&self, window: &mut Window) { + window.focus(&self.focus_handle); + } + + fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + // Parent terminal key handlers must never see keys typed into this field. + cx.stop_propagation(); + let key = &event.keystroke; + let command = key.modifiers.control || key.modifiers.platform; + match key.key.as_str() { + "enter" => { + // Enter first accepts active IME composition; a subsequent Enter saves. + if self.editor.marked_utf16().is_some() { + self.editor.unmark(); + } else { + (self.on_finish)(Some(self.editor.text.clone()), window, cx); + return; + } + } + "escape" => { + (self.on_finish)(None, window, cx); + return; + } + "left" => self.editor.left(key.modifiers.shift), + "right" => self.editor.right(key.modifiers.shift), + "home" => self.editor.home(key.modifiers.shift), + "end" => self.editor.end(key.modifiers.shift), + "backspace" => self.editor.backspace(), + "delete" => self.editor.delete(), + _ if command && !key.modifiers.alt => match key.key.to_ascii_lowercase().as_str() { + "a" => self.editor.select_all(), + "c" | "x" => { + let selected = self.editor.selection(); + if !selected.is_empty() { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + self.editor.text[selected].to_owned(), + )); + if key.key.eq_ignore_ascii_case("x") { + self.editor.replace(None, ""); + } + } + } + "v" => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + self.editor.replace(None, &text); + } + } + _ => {} + }, + _ if !command && !key.modifiers.alt => { + if let Some(text) = &key.key_char { + self.editor.replace(None, text); + } + } + _ => {} + } + cx.notify(); + } + + fn index_for_point(&self, position: Point) -> usize { + if self.editor.text.is_empty() { + return 0; + } + self.last_layout.as_ref().map_or(0, |line| { + line.closest_index_for_x( + position.x - self.last_bounds.left() - px(FIELD_PADDING) + self.scroll, + ) + }) + } + fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context) { + cx.stop_propagation(); + self.focus(window); + if event.click_count > 1 { + self.editor.select_all(); + } else { + self.editor + .set_cursor(self.index_for_point(event.position), event.modifiers.shift); + } + self.selecting = true; + cx.notify(); + } + fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context) { + if self.selecting && event.dragging() { + cx.stop_propagation(); + self.editor + .set_cursor(self.index_for_point(event.position), true); + cx.notify(); + } + } + fn prepare(&mut self, bounds: Bounds, window: &mut Window) { + self.last_bounds = bounds; + let placeholder = self.editor.text.is_empty(); + let text = if placeholder { + "Automatic name".to_owned() + } else { + self.editor.text.clone() + }; + let mut runs = Vec::new(); + let default = TextRun { + len: text.len(), + font: font(".SystemUIFont"), + color: rgb(if placeholder { + chrome::MUTED + } else { + chrome::TEXT + }) + .into(), + background_color: None, + underline: None, + strikethrough: None, + }; + if let Some(marked) = &self.editor.marked { + for (range, underline) in [ + (0..marked.start, false), + (marked.clone(), true), + (marked.end..text.len(), false), + ] { + if range.is_empty() { + continue; + } + runs.push(TextRun { + len: range.len(), + underline: underline.then_some(UnderlineStyle { + thickness: px(1.), + color: None, + wavy: false, + }), + ..default.clone() + }); + } + } else { + runs.push(default); + } + let line = window + .text_system() + .shape_line(text.into(), px(TEXT_SIZE), &runs, None); + let caret = if placeholder { + px(0.) + } else { + line.x_for_index(self.editor.cursor()) + }; + let width = (bounds.size.width - px(FIELD_PADDING * 2. + 1.)).max(px(1.)); + if caret - self.scroll > width { + self.scroll = caret - width; + } else if caret < self.scroll { + self.scroll = caret; + } + if placeholder { + self.scroll = px(0.); + } + self.last_layout = Some(line); + } +} + +impl Focusable for RenameField { + fn focus_handle(&self, _: &App) -> FocusHandle { + self.focus_handle.clone() + } +} + +impl Render for RenameField { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let prepare = cx.entity(); + let paint = cx.entity(); + div() + .w_full() + .min_w_0() + .h(px(FIELD_HEIGHT)) + .bg(rgb(chrome::CONTROL_BACKGROUND)) + .border_1() + .border_color(rgb(chrome::ACCENT)) + .overflow_hidden() + .cursor(CursorStyle::IBeam) + .track_focus(&self.focus_handle) + .on_key_down(cx.listener(Self::key_down)) + .on_mouse_down(MouseButton::Left, cx.listener(Self::mouse_down)) + .on_mouse_move(cx.listener(Self::mouse_move)) + .on_mouse_up( + MouseButton::Left, + cx.listener(|field, _, _, cx| { + field.selecting = false; + cx.stop_propagation(); + }), + ) + .on_mouse_up_out( + MouseButton::Left, + cx.listener(|field, _, _, _| field.selecting = false), + ) + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .child( + canvas( + move |bounds, window, cx| { + prepare.update(cx, |field, _| field.prepare(bounds, window)) + }, + move |bounds, (), window, cx| { + let field = paint.read(cx); + let focus = field.focus_handle.clone(); + let line = field.last_layout.clone(); + let selected = field.editor.selection(); + let caret = field.editor.cursor(); + let origin = + bounds.origin + point(px(FIELD_PADDING) - field.scroll, px(0.)); + let empty = field.editor.text.is_empty(); + window.handle_input( + &focus, + ElementInputHandler::new(bounds, paint.clone()), + cx, + ); + if let Some(line) = line { + window.with_content_mask( + Some(gpui::ContentMask { bounds }), + |window| { + if !selected.is_empty() { + let start = line.x_for_index(selected.start); + let end = line.x_for_index(selected.end); + window.paint_quad(fill( + Bounds::new( + origin + point(start, px(2.)), + size(end - start, bounds.size.height - px(4.)), + ), + rgb(chrome::BORDER), + )); + } + let _ = line.paint(origin, bounds.size.height, window, cx); + if focus.is_focused(window) { + let x = if empty { + px(0.) + } else { + line.x_for_index(caret) + }; + window.paint_quad(fill( + Bounds::new( + origin + point(x, px(4.)), + size(px(1.), bounds.size.height - px(8.)), + ), + rgb(chrome::TEXT), + )); + } + }, + ); + } + }, + ) + .size_full(), + ) + } +} + +impl EntityInputHandler for RenameField { + fn text_for_range( + &mut self, + range: Range, + actual: &mut Option>, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (text, range) = self.editor.text_for_range(range); + *actual = Some(range); + Some(text) + } + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut Context, + ) -> Option { + Some(UTF16Selection { + range: self.editor.selection_utf16(), + reversed: self.editor.reversed(), + }) + } + fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { + self.editor.marked_utf16() + } + fn unmark_text(&mut self, _: &mut Window, cx: &mut Context) { + self.editor.unmark(); + cx.notify(); + } + fn replace_text_in_range( + &mut self, + range: Option>, + text: &str, + _: &mut Window, + cx: &mut Context, + ) { + self.editor.replace(range, text); + cx.notify(); + } + fn replace_and_mark_text_in_range( + &mut self, + range: Option>, + text: &str, + selected: Option>, + _: &mut Window, + cx: &mut Context, + ) { + self.editor.replace_and_mark(range, text, selected); + cx.notify(); + } + fn bounds_for_range( + &mut self, + range: Range, + _: Bounds, + _: &mut Window, + _: &mut Context, + ) -> Option> { + let line = self.last_layout.as_ref()?; + let start = line.x_for_index(self.editor.byte_offset_for_utf16(range.start)); + let end = line.x_for_index(self.editor.byte_offset_for_utf16(range.end)); + Some(Bounds::new( + self.last_bounds.origin + point(px(FIELD_PADDING) - self.scroll + start, px(0.)), + size((end - start).max(px(1.)), self.last_bounds.size.height), + )) + } + fn character_index_for_point( + &mut self, + position: Point, + _: &mut Window, + _: &mut Context, + ) -> Option { + Some( + self.editor + .utf16_offset_for_byte(self.index_for_point(position)), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn editing_replaces_selection_and_moves_by_unicode_scalars() { + let mut editor = NameEditor::new("old name"); + editor.replace(None, "A🦀界"); + editor.left(false); + editor.backspace(); + assert_eq!(editor.text, "A界"); + assert_eq!(editor.cursor(), 1); + editor.delete(); + assert_eq!(editor.text, "A"); + editor.home(false); + editor.backspace(); + assert_eq!(editor.text, "A"); + editor.right(true); + assert_eq!(editor.selection(), 0..1); + editor.replace(None, "work"); + assert_eq!(editor.text, "work"); + } + + #[test] + fn platform_utf16_ranges_do_not_split_surrogate_pairs_or_utf8() { + let mut editor = NameEditor::new("A🦀界Z"); + assert_eq!(editor.selection_utf16(), 0..5); + assert_eq!(editor.text_for_range(2..3), ("🦀".into(), 1..3)); + editor.replace(Some(1..3), "λ"); + assert_eq!(editor.text, "Aλ界Z"); + assert_eq!(editor.selection_utf16(), 2..2); + editor.set_cursor(2, false); // inside the two-byte lambda + assert_eq!(editor.cursor(), 1); + } + + #[test] + fn composition_replaces_previous_marked_text_and_commits_once() { + let mut editor = NameEditor::new("old"); + editor.replace_and_mark(None, "に", Some(1..1)); + assert_eq!(editor.marked_utf16(), Some(0..1)); + editor.replace_and_mark(None, "日本", Some(2..2)); + assert_eq!(editor.text, "日本"); + assert_eq!(editor.marked_utf16(), Some(0..2)); + editor.replace(None, "日本語"); + assert_eq!(editor.text, "日本語"); + assert_eq!(editor.marked_utf16(), None); + } + + #[test] + fn clearing_restores_empty_name_and_single_line_paste_is_bounded() { + let mut editor = NameEditor::new("old"); + editor.replace(None, "a\nb\t\x1bc"); + assert_eq!(editor.text, "a b c"); + editor.select_all(); + editor.replace(None, &"界".repeat(800)); + assert_eq!(editor.text.chars().count(), MAX_CHARACTERS); + editor.select_all(); + editor.backspace(); + assert_eq!(editor.text, ""); + } + + #[test] + fn reversed_selection_collapses_to_expected_edge() { + let mut editor = NameEditor::new("hello"); + editor.end(false); + editor.left(true); + editor.left(true); + assert!(editor.reversed()); + assert_eq!(editor.selection(), 3..5); + editor.left(false); + assert_eq!(editor.cursor(), 3); + editor.home(false); + editor.right(true); + editor.right(false); + assert_eq!(editor.cursor(), 1); + } +} diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..3b3efb8 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,319 @@ +//! Versioned terminal-server protocol, shared by local and SSH transports. +//! The GUI receives rendered grid state; only the server owns a VTE parser. +use std::io::{Read, Write}; + +use alacritty_terminal::{ + term::cell::Cell, + vte::ansi::{CursorShape, Rgb}, +}; +use anyhow::{Context, Result, bail}; +use bincode::Options; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; + +pub const VERSION: u32 = 2; +pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; +pub type PaneId = u64; +pub type TabId = u64; + +#[derive(Debug, Clone, Serialize, Deserialize)] +// Keep variants append-only: the shutdown command can retire an older server. +pub enum ClientMessage { + Hello { + version: u32, + }, + Attach, + Input { + pane: PaneId, + bytes: Vec, + }, + Resize { + pane: PaneId, + columns: u16, + lines: u16, + cell_width: u16, + cell_height: u16, + }, + Scroll { + pane: PaneId, + kind: ScrollKind, + }, + Selection { + pane: PaneId, + selection: SelectionCommand, + }, + Copy { + pane: PaneId, + }, + NewTab { + cwd: Option, + }, + Split { + pane: PaneId, + cwd: Option, + }, + FocusTab { + tab: TabId, + }, + FocusPane { + pane: PaneId, + }, + ClosePane { + pane: PaneId, + }, + OpenWindow { + target: Option, + }, + Detach, + Shutdown, + Ping, + /// Read current layout without attaching or creating a shell. + List, + /// A blank/absent name returns to program-title/CWD naming. + RenamePane { + pane: PaneId, + name: Option, + }, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub enum ScrollKind { + Delta(i32), + PageUp, + PageDown, + Top, + Bottom, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub enum SelectionKind { + Simple, + Word, + Line, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub enum SelectionSide { + Left, + Right, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub enum SelectionCommand { + Start { + column: u16, + row: u16, + side: SelectionSide, + kind: SelectionKind, + }, + Update { + column: u16, + row: u16, + side: SelectionSide, + }, + Clear, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +// Hello and Closing also retain their v1 wire representation during upgrades. +pub enum ServerMessage { + Hello { version: u32, server_pid: u32 }, + Snapshot(Snapshot), + Clipboard(String), + Error(String), + Pong, + Closing, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Snapshot { + pub revision: u64, + pub tabs: Vec, + pub active_tab: TabId, + /// Only panes in the active tab are transferred. Every pane remains live on the server. + pub panes: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TabInfo { + pub id: TabId, + pub title: String, + pub panes: Vec, + pub active_pane: PaneId, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaneSnapshot { + pub id: PaneId, + /// Effective display name: manual override, program title, then CWD. + pub title: String, + pub manual_title: Option, + pub cwd: String, + pub columns: u16, + pub lines: u16, + pub cell_width: u16, + pub cell_height: u16, + pub cells: Vec, + pub selected: Vec, + pub colors: Vec>, + pub cursor: Cursor, + pub display_offset: u32, + pub mode: u32, + pub exited: bool, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub struct Cursor { + pub column: u16, + /// Viewport-relative row; negative or past the viewport when scrolled away. + pub row: i32, + pub shape: CursorKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CursorKind { + Block, + Underline, + Beam, + HollowBlock, + Hidden, +} + +impl From for CursorKind { + fn from(shape: CursorShape) -> Self { + match shape { + CursorShape::Block => Self::Block, + CursorShape::Underline => Self::Underline, + CursorShape::Beam => Self::Beam, + CursorShape::HollowBlock => Self::HollowBlock, + CursorShape::Hidden => Self::Hidden, + } + } +} + +impl From for CursorShape { + fn from(shape: CursorKind) -> Self { + match shape { + CursorKind::Block => Self::Block, + CursorKind::Underline => Self::Underline, + CursorKind::Beam => Self::Beam, + CursorKind::HollowBlock => Self::HollowBlock, + CursorKind::Hidden => Self::Hidden, + } + } +} + +/// Little-endian u32 byte length followed by bounded bincode 1.3 payload. +pub fn write_message(writer: &mut impl Write, message: &impl Serialize) -> Result<()> { + let bytes = bincode::DefaultOptions::new() + .with_fixint_encoding() + .with_limit(MAX_MESSAGE_BYTES as u64) + .serialize(message) + .context("encode protocol message")?; + if bytes.len() > MAX_MESSAGE_BYTES { + bail!("protocol message is too large"); + } + writer.write_all(&(bytes.len() as u32).to_le_bytes())?; + writer.write_all(&bytes)?; + writer.flush()?; + Ok(()) +} + +pub fn read_message(reader: &mut impl Read) -> Result { + let mut length = [0; 4]; + reader + .read_exact(&mut length) + .context("read protocol frame length")?; + let length = u32::from_le_bytes(length) as usize; + if length == 0 || length > MAX_MESSAGE_BYTES { + bail!("invalid protocol frame length: {length}"); + } + let mut bytes = vec![0; length]; + reader + .read_exact(&mut bytes) + .context("read protocol frame")?; + bincode::DefaultOptions::new() + .with_fixint_encoding() + .with_limit(MAX_MESSAGE_BYTES as u64) + .reject_trailing_bytes() + .deserialize(&bytes) + .context("decode protocol message") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_shutdown_handshake_retains_its_wire_representation() { + fn frame(message: &impl Serialize) -> Vec { + let mut bytes = Vec::new(); + write_message(&mut bytes, message).unwrap(); + bytes + } + + // These literal frames are from protocol v1. The upgrade path only + // exchanges Hello, Shutdown and Closing, never versioned snapshots. + let client_hello = [8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]; + let shutdown = [4, 0, 0, 0, 14, 0, 0, 0]; + let server_hello = [12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0x78, 0x56, 0x34, 0x12]; + let closing = [4, 0, 0, 0, 5, 0, 0, 0]; + assert_eq!(frame(&ClientMessage::Hello { version: 1 }), client_hello); + assert_eq!(frame(&ClientMessage::Shutdown), shutdown); + assert_eq!( + frame(&ServerMessage::Hello { + version: 1, + server_pid: 0x1234_5678, + }), + server_hello + ); + assert_eq!(frame(&ServerMessage::Closing), closing); + assert!(matches!( + read_message::(&mut client_hello.as_slice()).unwrap(), + ClientMessage::Hello { version: 1 } + )); + assert!(matches!( + read_message::(&mut shutdown.as_slice()).unwrap(), + ClientMessage::Shutdown + )); + assert!(matches!( + read_message::(&mut server_hello.as_slice()).unwrap(), + ServerMessage::Hello { + version: 1, + server_pid: 0x1234_5678, + } + )); + assert!(matches!( + read_message::(&mut closing.as_slice()).unwrap(), + ServerMessage::Closing + )); + } + + #[test] + fn rejects_oversized_frames_before_allocating_payload() { + let mut input = ((MAX_MESSAGE_BYTES + 1) as u32) + .to_le_bytes() + .as_slice() + .to_vec(); + assert!(read_message::(&mut input.as_slice()).is_err()); + input = 0u32.to_le_bytes().to_vec(); + assert!(read_message::(&mut input.as_slice()).is_err()); + } + #[test] + fn frames_round_trip_and_reject_trailing_payload() { + let mut bytes = Vec::new(); + write_message( + &mut bytes, + &ClientMessage::Input { + pane: 42, + bytes: b"hello".to_vec(), + }, + ) + .unwrap(); + let result: ClientMessage = read_message(&mut bytes.as_slice()).unwrap(); + assert!(matches!(result, ClientMessage::Input { pane: 42, bytes } if bytes == b"hello")); + let len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) + 1; + bytes[..4].copy_from_slice(&len.to_le_bytes()); + bytes.push(0); + assert!(read_message::(&mut bytes.as_slice()).is_err()); + } +} diff --git a/src/render.rs b/src/render.rs index 57602fd..07b5f03 100644 --- a/src/render.rs +++ b/src/render.rs @@ -157,7 +157,13 @@ impl Renderer { } /// `origin` is the top-left terminal cell, after the view's padding. - pub fn paint(&self, origin: Point, window: &mut Window, cx: &mut App) { + pub fn paint_with_cursor( + &self, + origin: Point, + window: &mut Window, + cx: &mut App, + before_text: impl FnOnce(&mut Window), + ) { let bounds = Bounds::new( origin, size( @@ -190,6 +196,7 @@ impl Renderer { } } }); + before_text(window); for (row_index, row) in self.rows.iter().enumerate() { for text in &row.text { if text.unicode_color.is_some() { diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..0edc989 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,1384 @@ +//! Headless terminal owner. Clients are replaceable views of this process's state. +//! +//! A single actor serializes layout and terminal commands. PTY workers parse +//! bytes independently; per-client writers keep only the newest unsent grid. +use std::{ + collections::{HashMap, VecDeque}, + fs::{self, File, OpenOptions}, + os::{ + fd::AsRawFd, + unix::{ + fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, + net::{UnixListener, UnixStream}, + }, + }, + path::{Path, PathBuf}, + sync::{Arc, Condvar, Mutex, mpsc}, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; + +use alacritty_terminal::{ + event::Event, + grid::{Dimensions, Scroll}, + index::{Column, Line, Point, Side}, + selection::{Selection, SelectionType}, + term::color::COUNT, + tty::Shell, +}; +use anyhow::{Context, Result, ensure}; + +use crate::{ + protocol::{self, *}, + session::Session, +}; + +const FRAME_INTERVAL: Duration = Duration::from_millis(8); +const CWD_REFRESH_INTERVAL: Duration = Duration::from_millis(500); +const MAX_CLIENTS: usize = 64; +const MAX_PANES: usize = 64; +const MAX_GRID_CELLS: usize = 100_000; + +struct Pane { + session: Session, + program_title: Option, + manual_title: Option, + cwd: String, + exited: bool, +} +impl Pane { + fn title(&self) -> String { + self.manual_title + .as_ref() + .or(self.program_title.as_ref()) + .cloned() + .unwrap_or_else(|| { + // Resolve HOME here so SSH clients use the server's home, + // while the snapshot's cwd keeps its full filesystem path. + let home = std::env::var_os("HOME").map(PathBuf::from); + directory_title(&self.cwd, home.as_deref()) + }) + } +} + +fn directory_title(cwd: &str, home: Option<&Path>) -> String { + let relative = home + .filter(|home| home.is_absolute()) + .and_then(|home| Path::new(cwd).strip_prefix(home).ok()); + let title = match relative { + Some(path) if path.as_os_str().is_empty() => "~".to_owned(), + Some(path) => format!("~/{}", path.display()), + None => cwd.to_owned(), + }; + title + .chars() + .filter(|c| !c.is_control()) + .take(512) + .collect() +} + +fn clean_title(title: String) -> Option { + let title: String = title + .chars() + .filter(|c| !c.is_control()) + .take(512) + .collect(); + let title = title.trim(); + (!title.is_empty()).then(|| title.to_owned()) +} +struct Client { + authenticated: bool, + attached: bool, + output: Arc, + writer: JoinHandle<()>, +} + +enum Action { + Connected(u64, UnixStream), + Command(u64, ClientMessage), + Disconnected(u64), + Terminal(PaneId, Event), +} + +#[derive(Default)] +struct PendingOutput { + reliable: VecDeque, + latest: Option>, + closed: bool, +} +#[derive(Default)] +struct Outbox { + pending: Mutex, + ready: Condvar, +} + +impl Outbox { + fn reliable(&self, message: ServerMessage) { + let mut pending = self.pending.lock().unwrap(); + if pending.closed { + return; + } + // Commands from a non-reading peer must not consume unbounded memory. + if pending.reliable.len() >= 128 { + pending.closed = true; + pending.latest = None; + } else { + pending.reliable.push_back(message); + } + self.ready.notify_one(); + } + fn snapshot(&self, snapshot: Arc) { + let mut pending = self.pending.lock().unwrap(); + if !pending.closed { + pending.latest = Some(snapshot); + self.ready.notify_one(); + } + } + fn close(&self) { + let mut pending = self.pending.lock().unwrap(); + pending.closed = true; + pending.latest = None; + self.ready.notify_one(); + } + fn next(&self) -> Option { + let mut pending = self.pending.lock().unwrap(); + loop { + if let Some(message) = pending.reliable.pop_front() { + return Some(message); + } + if pending.closed { + return None; + } + if let Some(snapshot) = pending.latest.take() { + return Some(ServerMessage::Snapshot((*snapshot).clone())); + } + pending = self.ready.wait(pending).unwrap(); + } + } +} + +/// Run the headless server. The owner supplies a server-managed GUI zygote callback. +pub fn run(socket: &Path, open_window: impl FnMut(Option) -> Result<()>) -> Result<()> { + run_with_shell(socket, open_window, None) +} + +fn run_with_shell( + socket: &Path, + mut open_window: impl FnMut(Option) -> Result<()>, + shell: Option, +) -> Result<()> { + let (_socket_guard, listener) = bind_socket(socket)?; + let (sender, receiver) = mpsc::sync_channel(1024); + let accept_sender = sender.clone(); + let accept = thread::Builder::new() + .name("psyterm-accept".into()) + .spawn(move || { + let mut next_client = 1; + for accepted in listener.incoming() { + let stream = match accepted { + Ok(stream) => stream, + Err(error) => { + log::error!("accept: {error}"); + break; + } + }; + if !same_user(&stream) { + continue; + } + let reader = match stream.try_clone() { + Ok(stream) => stream, + Err(_) => continue, + }; + let client = next_client; + next_client += 1; + if accept_sender + .send(Action::Connected(client, stream)) + .is_err() + { + break; + } + let sender = accept_sender.clone(); + thread::spawn(move || read_client(client, reader, sender)); + } + })?; + // The listener is woken explicitly on shutdown; the accept thread exits once + // the actor channel receiver is dropped. + let mut actor = Server { + shell, + panes: HashMap::new(), + tabs: Vec::new(), + active_tab: 0, + next_id: 1, + clients: HashMap::new(), + sender, + revision: 0, + dirty: false, + last_frame: Instant::now() - FRAME_INTERVAL, + last_cwd_refresh: Instant::now(), + }; + let result = actor.run(&receiver, &mut open_window); + drop(receiver); + for client in actor.clients.values() { + client.output.reliable(ServerMessage::Closing); + client.output.close(); + } + for (_, client) in actor.clients.drain() { + let _ = client.writer.join(); + } + // Drop sessions while the daemon is alive so their PTYs/children are reaped. + actor.panes.clear(); + let _ = UnixStream::connect(socket); + let _ = accept.join(); + result +} + +fn read_client(id: u64, mut stream: UnixStream, sender: mpsc::SyncSender) { + // Bound pre-handshake connections. Authenticated peers may remain idle. + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let mut first = true; + loop { + let message = match protocol::read_message(&mut stream) { + Ok(message) => message, + Err(_) => break, + }; + if first { + if !matches!(message, ClientMessage::Hello { .. }) { + break; + } + first = false; + let _ = stream.set_read_timeout(None); + } + let detach = matches!(message, ClientMessage::Detach); + if sender.send(Action::Command(id, message)).is_err() { + break; + } + if detach { + break; + } + } + let _ = stream.shutdown(std::net::Shutdown::Both); + let _ = sender.send(Action::Disconnected(id)); +} + +struct Server { + shell: Option, + panes: HashMap, + tabs: Vec, + active_tab: TabId, + next_id: u64, + clients: HashMap, + sender: mpsc::SyncSender, + revision: u64, + dirty: bool, + last_frame: Instant, + last_cwd_refresh: Instant, +} + +impl Server { + fn run( + &mut self, + receiver: &mpsc::Receiver, + open_window: &mut impl FnMut(Option) -> Result<()>, + ) -> Result<()> { + loop { + let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed()); + let timeout = if self.dirty { + Some( + FRAME_INTERVAL + .saturating_sub(self.last_frame.elapsed()) + .min(until_cwd), + ) + } else if !self.panes.is_empty() { + Some(until_cwd) + } else { + None + }; + let action = if let Some(timeout) = timeout { + match receiver.recv_timeout(timeout) { + Ok(action) => Some(action), + Err(mpsc::RecvTimeoutError::Timeout) => None, + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } else { + match receiver.recv() { + Ok(action) => Some(action), + Err(_) => break, + } + }; + if let Some(action) = action { + match action { + Action::Connected(id, stream) => { + if let Err(error) = self.add_client(id, stream) { + log::warn!("could not attach client: {error}"); + } + } + Action::Disconnected(id) => self.remove_client(id), + Action::Terminal(pane, event) => self.terminal_event(pane, event), + Action::Command(id, command) => { + if matches!(command, ClientMessage::Shutdown) + && self + .clients + .get(&id) + .is_some_and(|client| client.authenticated) + { + break; + } + if let Err(error) = self.command(id, command, open_window) + && let Some(client) = self.clients.get(&id) + { + client + .output + .reliable(ServerMessage::Error(error.to_string())); + } + } + } + } + if self.last_cwd_refresh.elapsed() >= CWD_REFRESH_INTERVAL { + self.refresh_directories(); + self.last_cwd_refresh = Instant::now(); + } + if self.dirty && self.last_frame.elapsed() >= FRAME_INTERVAL { + self.publish(); + self.dirty = false; + self.last_frame = Instant::now(); + } + } + Ok(()) + } + + fn add_client(&mut self, id: u64, mut stream: UnixStream) -> Result<()> { + if self.clients.len() >= MAX_CLIENTS { + let _ = stream.shutdown(std::net::Shutdown::Both); + return Ok(()); + } + stream.set_write_timeout(Some(Duration::from_secs(5)))?; + let output = Arc::new(Outbox::default()); + let writer_output = output.clone(); + let sender = self.sender.clone(); + let writer = thread::Builder::new() + .name("psyterm-client-write".into()) + .spawn(move || { + while let Some(message) = writer_output.next() { + if protocol::write_message(&mut stream, &message).is_err() { + break; + } + } + let _ = stream.shutdown(std::net::Shutdown::Both); + let _ = sender.send(Action::Disconnected(id)); + })?; + self.clients.insert( + id, + Client { + authenticated: false, + attached: false, + output, + writer, + }, + ); + Ok(()) + } + + fn remove_client(&mut self, id: u64) { + if let Some(client) = self.clients.remove(&id) { + client.output.close(); + } + // Deliberately retain every tab, pane, grid and child process. + } + + fn command( + &mut self, + id: u64, + message: ClientMessage, + open_window: &mut impl FnMut(Option) -> Result<()>, + ) -> Result<()> { + let Some(client) = self.clients.get_mut(&id) else { + return Ok(()); + }; + if let ClientMessage::Hello { version } = message { + ensure!(!client.authenticated, "handshake already completed"); + ensure!( + version == VERSION, + "protocol version {version} is unsupported (expected {VERSION})" + ); + client.authenticated = true; + client.output.reliable(ServerMessage::Hello { + version: VERSION, + server_pid: std::process::id(), + }); + return Ok(()); + } + ensure!(client.authenticated, "protocol handshake is required"); + match message { + ClientMessage::Attach => { + client.attached = true; + if self.tabs.is_empty() { + self.new_tab(None)?; + } + // New attachment receives an authoritative snapshot immediately. + self.publish(); + self.last_frame = Instant::now(); + self.dirty = false; + } + ClientMessage::Ping => client.output.reliable(ServerMessage::Pong), + ClientMessage::List => { + let snapshot = self.snapshot(); + self.clients[&id] + .output + .reliable(ServerMessage::Snapshot(snapshot)); + } + ClientMessage::OpenWindow { target } => { + open_window(target)?; + self.clients[&id].output.reliable(ServerMessage::Pong); + } + ClientMessage::Detach => self.remove_client(id), + ClientMessage::Input { pane, bytes } => { + ensure!(bytes.len() <= 1024 * 1024, "input exceeds one MiB"); + let pane = self.pane_mut(pane)?; + ensure!(!pane.exited, "the shell has exited"); + let changed = { + let mut term = pane.session.term.lock(); + let changed = term.grid().display_offset() != 0 || term.selection.is_some(); + term.scroll_display(Scroll::Bottom); + term.selection = None; + changed + }; + pane.session.write(bytes); + self.dirty |= changed; + } + ClientMessage::Resize { + pane, + columns, + lines, + cell_width, + cell_height, + } => { + ensure!( + columns >= 2 + && lines >= 1 + && columns as usize * lines as usize <= MAX_GRID_CELLS, + "invalid terminal dimensions" + ); + let siblings = self + .tabs + .iter() + .find(|tab| tab.panes.contains(&pane)) + .context("unknown pane")?; + let other_cells: usize = siblings + .panes + .iter() + .filter(|id| **id != pane) + .filter_map(|id| self.panes.get(id)) + .map(|pane| { + let size = pane.session.size(); + size.num_cols as usize * size.num_lines as usize + }) + .sum(); + ensure!( + other_cells + columns as usize * lines as usize <= MAX_GRID_CELLS, + "tab grid exceeds {MAX_GRID_CELLS} cells" + ); + self.pane_mut(pane)?.session.resize( + columns as usize, + lines as usize, + cell_width, + cell_height, + ); + self.dirty = true; + } + ClientMessage::Scroll { pane, kind } => { + let scroll = match kind { + ScrollKind::Delta(n) => Scroll::Delta(n), + ScrollKind::PageUp => Scroll::PageUp, + ScrollKind::PageDown => Scroll::PageDown, + ScrollKind::Top => Scroll::Top, + ScrollKind::Bottom => Scroll::Bottom, + }; + self.pane_mut(pane)? + .session + .term + .lock() + .scroll_display(scroll); + self.dirty = true; + } + ClientMessage::Selection { pane, selection } => { + let pane = self.pane_mut(pane)?; + let mut term = pane.session.term.lock(); + let location = |column: u16, row: u16| { + Point::new( + Line( + row.min(term.screen_lines() as u16 - 1) as i32 + - term.grid().display_offset() as i32, + ), + Column((column as usize).min(term.columns() - 1)), + ) + }; + let side = |side| match side { + SelectionSide::Left => Side::Left, + SelectionSide::Right => Side::Right, + }; + match selection { + SelectionCommand::Start { + column, + row, + side: s, + kind, + } => { + let kind = match kind { + SelectionKind::Simple => SelectionType::Simple, + SelectionKind::Word => SelectionType::Semantic, + SelectionKind::Line => SelectionType::Lines, + }; + term.selection = Some(Selection::new(kind, location(column, row), side(s))); + } + SelectionCommand::Update { + column, + row, + side: s, + } => { + let point = location(column, row); + if let Some(selection) = &mut term.selection { + selection.update(point, side(s)); + } + } + SelectionCommand::Clear => term.selection = None, + } + drop(term); + self.dirty = true; + } + ClientMessage::Copy { pane } => { + let text = self + .pane_mut(pane)? + .session + .term + .lock() + .selection_to_string(); + if let Some(text) = text { + self.clients[&id] + .output + .reliable(ServerMessage::Clipboard(text)); + } + } + ClientMessage::NewTab { cwd } => { + self.new_tab(cwd)?; + self.dirty = true; + } + ClientMessage::Split { pane, cwd } => { + let tab = self + .tabs + .iter() + .position(|tab| tab.panes.contains(&pane)) + .context("unknown pane")?; + let occupied: usize = self.tabs[tab] + .panes + .iter() + .filter_map(|id| self.panes.get(id)) + .map(|pane| { + let size = pane.session.size(); + size.num_cols as usize * size.num_lines as usize + }) + .sum(); + ensure!( + occupied + 80 * 24 <= MAX_GRID_CELLS, + "tab grid exceeds {MAX_GRID_CELLS} cells" + ); + let pane = self.new_pane(cwd)?; + self.tabs[tab].panes.push(pane); + self.tabs[tab].active_pane = pane; + self.active_tab = self.tabs[tab].id; + self.dirty = true; + } + ClientMessage::FocusTab { tab } => { + ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab"); + self.active_tab = tab; + self.dirty = true; + } + ClientMessage::FocusPane { pane } => { + let tab = self + .tabs + .iter_mut() + .find(|tab| tab.panes.contains(&pane)) + .context("unknown pane")?; + tab.active_pane = pane; + self.active_tab = tab.id; + self.dirty = true; + } + ClientMessage::ClosePane { pane } => { + ensure!(self.remove_pane(pane), "unknown pane"); + } + ClientMessage::RenamePane { pane, name } => { + self.pane_mut(pane)?.manual_title = name.and_then(clean_title); + self.refresh_directories(); + self.dirty = true; + } + ClientMessage::Hello { .. } | ClientMessage::Shutdown => unreachable!(), + } + Ok(()) + } + + /// The same lifecycle path serves explicit close and a shell's natural exit. + fn remove_pane(&mut self, pane: PaneId) -> bool { + let Some(removed) = self.panes.remove(&pane) else { + return false; + }; + if let Some(tab_index) = self.tabs.iter().position(|tab| tab.panes.contains(&pane)) { + let tab = &mut self.tabs[tab_index]; + let pane_index = tab.panes.iter().position(|id| *id == pane).unwrap(); + tab.panes.remove(pane_index); + if tab.active_pane == pane { + tab.active_pane = tab + .panes + .get(pane_index.min(tab.panes.len().saturating_sub(1))) + .copied() + .unwrap_or(0); + } + if tab.panes.is_empty() { + let removed_tab = self.tabs.remove(tab_index); + if self.active_tab == removed_tab.id { + self.active_tab = self + .tabs + .get(tab_index.min(self.tabs.len().saturating_sub(1))) + .map_or(0, |tab| tab.id); + } + } + } + self.dirty = true; + // No terminal lock is held here. On Event::Exit the I/O thread has + // drained output and will finish, so joining Session cleanup is safe. + drop(removed); + true + } + + fn refresh_directories(&mut self) { + for pane in self.panes.values_mut() { + if let Some(directory) = pane.session.working_directory() { + let directory = directory.to_string_lossy(); + if pane.cwd != directory { + pane.cwd = directory.into_owned(); + self.dirty = true; + } + } + } + } + + fn pane_mut(&mut self, id: PaneId) -> Result<&mut Pane> { + self.panes.get_mut(&id).context("unknown pane") + } + + fn new_pane(&mut self, cwd: Option) -> Result { + ensure!( + self.panes.len() < MAX_PANES, + "at most {MAX_PANES} panes are supported" + ); + let directory = cwd.map(PathBuf::from); + if let Some(directory) = &directory { + ensure!(directory.is_dir(), "working directory does not exist"); + } + let initial_directory = directory + .as_ref() + .and_then(|path| fs::canonicalize(path).ok()) + .or_else(|| std::env::current_dir().ok()) + .unwrap_or_else(|| PathBuf::from("/")); + let (session, events) = if let Some(shell) = &self.shell { + Session::with_shell_and_directory(shell.clone(), directory)? + } else { + Session::in_directory(directory)? + }; + let id = self.next_id; + self.next_id += 1; + let cwd = session + .working_directory() + .unwrap_or(initial_directory) + .to_string_lossy() + .into_owned(); + self.panes.insert( + id, + Pane { + session, + program_title: None, + manual_title: None, + cwd, + exited: false, + }, + ); + let sender = self.sender.clone(); + thread::Builder::new() + .name(format!("psyterm-events-{id}")) + .spawn(move || { + while let Ok(event) = events.recv_blocking() { + if sender.send(Action::Terminal(id, event)).is_err() { + break; + } + } + })?; + Ok(id) + } + + fn new_tab(&mut self, cwd: Option) -> Result<()> { + let pane = self.new_pane(cwd)?; + let id = self.next_id; + self.next_id += 1; + self.tabs.push(TabInfo { + id, + title: "Shell".into(), + panes: vec![pane], + active_pane: pane, + }); + self.active_tab = id; + Ok(()) + } + + fn terminal_event(&mut self, id: PaneId, event: Event) { + if matches!(event, Event::Exit) { + self.remove_pane(id); + return; + } + let Some(pane) = self.panes.get_mut(&id) else { + return; + }; + match event { + Event::Wakeup => pane.session.acknowledge_wakeup(), + Event::Title(title) => pane.program_title = clean_title(title), + Event::ResetTitle => pane.program_title = None, + Event::PtyWrite(text) => pane.session.write(text.into_bytes()), + Event::TextAreaSizeRequest(format) => { + pane.session.write(format(pane.session.size()).into_bytes()) + } + Event::ColorRequest(index, format) => { + let color = if index < COUNT { + pane.session.term.lock().colors()[index] + } else { + None + }; + pane.session.write( + format(color.unwrap_or_else(|| crate::colors::palette(index))).into_bytes(), + ); + } + // ChildExit precedes output draining; remove only on Event::Exit. + Event::ChildExit(_) => { + pane.exited = true; + return; + } + // Desktop clipboard belongs to the client and OSC 52 remains disabled. + _ => {} + } + self.dirty = true; + } + + fn snapshot(&mut self) -> Snapshot { + self.revision += 1; + for tab in &mut self.tabs { + if let Some(pane) = self.panes.get(&tab.active_pane) { + tab.title = pane.title(); + } + } + let visible = self + .tabs + .iter() + .find(|tab| tab.id == self.active_tab) + .map(|tab| tab.panes.clone()) + .unwrap_or_default(); + let panes = visible + .into_iter() + .filter_map(|id| { + self.panes.get(&id).map(|pane| { + let term = pane.session.term.lock(); + let content = term.renderable_content(); + let size = pane.session.size(); + let mut cells = + Vec::with_capacity(size.num_cols as usize * size.num_lines as usize); + let mut selected = Vec::with_capacity(cells.capacity()); + for indexed in content.display_iter { + let mut cell = indexed.cell.clone(); + // Hyperlinks are not displayed by this client version. Avoid + // repeating arbitrary OSC 8 URI payloads in every grid cell. + if cell.hyperlink().is_some() { + cell.set_hyperlink(None); + } + cells.push(cell); + selected.push( + content + .selection + .is_some_and(|selection| selection.contains(indexed.point)), + ); + } + PaneSnapshot { + id, + title: pane.title(), + manual_title: pane.manual_title.clone(), + cwd: pane.cwd.clone(), + columns: size.num_cols, + lines: size.num_lines, + cell_width: size.cell_width, + cell_height: size.cell_height, + cells, + selected, + colors: (0..COUNT).map(|index| content.colors[index]).collect(), + cursor: Cursor { + column: content.cursor.point.column.0 as u16, + row: content.cursor.point.line.0 + content.display_offset as i32, + shape: content.cursor.shape.into(), + }, + display_offset: content.display_offset as u32, + mode: content.mode.bits(), + exited: pane.exited, + } + }) + }) + .collect(); + Snapshot { + revision: self.revision, + tabs: self.tabs.clone(), + active_tab: self.active_tab, + panes, + } + } + + fn publish(&mut self) { + if !self.clients.values().any(|client| client.attached) { + return; + } + let snapshot = Arc::new(self.snapshot()); + for client in self.clients.values().filter(|client| client.attached) { + client.output.snapshot(snapshot.clone()); + } + } +} + +struct SocketGuard { + socket: PathBuf, + _lock: File, +} +impl Drop for SocketGuard { + fn drop(&mut self) { + let _ = fs::remove_file(&self.socket); + } +} + +fn bind_socket(socket: &Path) -> Result<(SocketGuard, UnixListener)> { + let parent = socket.parent().context("socket has no parent directory")?; + if !parent.exists() { + fs::create_dir_all(parent)?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; + } + let lock = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(socket.with_extension("lock"))?; + // SAFETY: flock operates on our live owned file descriptor. + ensure!( + unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, + "another server owns this socket" + ); + if let Ok(metadata) = fs::symlink_metadata(socket) { + // SAFETY: geteuid has no preconditions. + ensure!( + metadata.file_type().is_socket() && metadata.uid() == unsafe { libc::geteuid() }, + "refusing to replace an unowned/non-socket path" + ); + ensure!( + UnixStream::connect(socket).is_err(), + "server is already running" + ); + fs::remove_file(socket)?; + } + let listener = UnixListener::bind(socket).context("bind terminal server socket")?; + fs::set_permissions(socket, fs::Permissions::from_mode(0o600))?; + Ok(( + SocketGuard { + socket: socket.to_owned(), + _lock: lock, + }, + listener, + )) +} + +fn same_user(stream: &UnixStream) -> bool { + #[cfg(target_os = "linux")] + { + let mut credentials = libc::ucred { + pid: 0, + uid: 0, + gid: 0, + }; + let mut len = std::mem::size_of_val(&credentials) as libc::socklen_t; + // SAFETY: arguments point to initialized writable storage of the given length. + let result = unsafe { + libc::getsockopt( + stream.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PEERCRED, + (&mut credentials as *mut libc::ucred).cast(), + &mut len, + ) + }; + result == 0 && credentials.uid == unsafe { libc::geteuid() } + } + #[cfg(not(target_os = "linux"))] + { + let _ = stream; + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT_TEST: AtomicU64 = AtomicU64::new(1); + + struct TestServer { + socket: PathBuf, + thread: Option>>, + } + impl TestServer { + fn start() -> Self { + let directory = std::env::temp_dir().join(format!( + "psyterm-server-test-{}-{}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&directory).unwrap(); + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let socket = directory.join("server.sock"); + let address = socket.clone(); + let thread = thread::spawn(move || { + run_with_shell( + &address, + |_| Ok(()), + Some(Shell::new("/bin/sh".into(), Vec::new())), + ) + }); + let test = Self { + socket, + thread: Some(thread), + }; + let deadline = Instant::now() + Duration::from_secs(5); + while !test.socket.exists() { + assert!(Instant::now() < deadline); + thread::sleep(Duration::from_millis(2)); + } + test + } + fn client(&self) -> UnixStream { + let mut stream = UnixStream::connect(&self.socket).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + protocol::write_message(&mut stream, &ClientMessage::Hello { version: VERSION }) + .unwrap(); + assert!(matches!( + protocol::read_message::(&mut stream).unwrap(), + ServerMessage::Hello { + version: VERSION, + .. + } + )); + stream + } + } + impl Drop for TestServer { + fn drop(&mut self) { + if let Ok(mut stream) = UnixStream::connect(&self.socket) { + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let _ = protocol::write_message( + &mut stream, + &ClientMessage::Hello { version: VERSION }, + ); + let _ = protocol::read_message::(&mut stream); + let _ = protocol::write_message(&mut stream, &ClientMessage::Shutdown); + let _ = protocol::read_message::(&mut stream); + } + if let Some(thread) = self.thread.take() { + thread.join().unwrap().unwrap(); + } + let _ = fs::remove_dir_all(self.socket.parent().unwrap()); + } + } + fn snapshot(stream: &mut UnixStream, accept: impl Fn(&Snapshot) -> bool) -> Snapshot { + loop { + match protocol::read_message(stream).unwrap() { + ServerMessage::Snapshot(snapshot) if accept(&snapshot) => return snapshot, + ServerMessage::Error(error) => panic!("server error: {error}"), + _ => {} + } + } + } + fn send(stream: &mut UnixStream, message: ClientMessage) { + protocol::write_message(stream, &message).unwrap(); + } + fn contains(snapshot: &Snapshot, text: &str) -> bool { + snapshot.panes.iter().any(|pane| { + pane.cells + .iter() + .map(|cell| cell.c) + .collect::() + .contains(text) + }) + } + + #[test] + fn detached_client_keeps_shell_and_grid_and_server_owns_layout() { + let server = TestServer::start(); + let mut first = server.client(); + send(&mut first, ClientMessage::Attach); + let initial = snapshot(&mut first, |snapshot| snapshot.panes.len() == 1); + let pane = initial.panes[0].id; + let tab = initial.active_tab; + send( + &mut first, + ClientMessage::Input { + pane, + bytes: + b"export PSYTERM_TEST_STATE=retained; printf '\\033[2J\\033[HREADY_STATE\\n'\n" + .to_vec(), + }, + ); + snapshot(&mut first, |snapshot| contains(snapshot, "READY_STATE")); + send(&mut first, ClientMessage::Detach); + drop(first); + + let mut second = server.client(); + send(&mut second, ClientMessage::Attach); + let reattached = snapshot(&mut second, |snapshot| contains(snapshot, "READY_STATE")); + assert_eq!(reattached.active_tab, tab); + assert_eq!(reattached.panes[0].id, pane); + send( + &mut second, + ClientMessage::Resize { + pane, + columns: 100, + lines: 30, + cell_width: 9, + cell_height: 20, + }, + ); + snapshot(&mut second, |snapshot| { + snapshot.panes[0].columns == 100 && snapshot.panes[0].lines == 30 + }); + send( + &mut second, + ClientMessage::Input { + pane, + bytes: b"printf '\\033[2J\\033[HSTATE=%s\\n' \"$PSYTERM_TEST_STATE\"; stty size\n" + .to_vec(), + }, + ); + snapshot(&mut second, |snapshot| { + contains(snapshot, "STATE=retained") && contains(snapshot, "30 100") + }); + send( + &mut second, + ClientMessage::Selection { + pane, + selection: SelectionCommand::Start { + column: 0, + row: 0, + side: SelectionSide::Left, + kind: SelectionKind::Simple, + }, + }, + ); + send( + &mut second, + ClientMessage::Selection { + pane, + selection: SelectionCommand::Update { + column: 13, + row: 0, + side: SelectionSide::Right, + }, + }, + ); + send(&mut second, ClientMessage::Copy { pane }); + loop { + if let ServerMessage::Clipboard(text) = protocol::read_message(&mut second).unwrap() { + assert_eq!(text, "STATE=retained"); + break; + } + } + send(&mut second, ClientMessage::Split { pane, cwd: None }); + let split = snapshot(&mut second, |snapshot| snapshot.panes.len() == 2); + assert_eq!(split.tabs[0].panes.len(), 2); + assert_ne!(split.tabs[0].active_pane, pane); + send(&mut second, ClientMessage::NewTab { cwd: None }); + let new_tab = snapshot(&mut second, |snapshot| snapshot.tabs.len() == 2); + assert_ne!(new_tab.active_tab, tab); + assert_eq!(new_tab.panes.len(), 1); + send(&mut second, ClientMessage::FocusTab { tab }); + let focused = snapshot(&mut second, |snapshot| snapshot.active_tab == tab); + assert_eq!(focused.panes.len(), 2); + assert!(contains(&focused, "STATE=retained")); + } + + #[test] + fn handshake_and_size_validation_and_control_clients_do_not_attach() { + let server = TestServer::start(); + let mut client = server.client(); + send(&mut client, ClientMessage::Ping); + assert!(matches!( + protocol::read_message::(&mut client).unwrap(), + ServerMessage::Pong + )); + send(&mut client, ClientMessage::OpenWindow { target: None }); + assert!(matches!( + protocol::read_message::(&mut client).unwrap(), + ServerMessage::Pong + )); + send(&mut client, ClientMessage::List); + let empty = snapshot(&mut client, |_| true); + assert!(empty.tabs.is_empty()); + assert!(empty.panes.is_empty()); + send(&mut client, ClientMessage::Attach); + let state = snapshot(&mut client, |snapshot| !snapshot.panes.is_empty()); + send( + &mut client, + ClientMessage::Resize { + pane: state.panes[0].id, + columns: 0, + lines: 0, + cell_width: 0, + cell_height: 0, + }, + ); + loop { + if matches!( + protocol::read_message::(&mut client).unwrap(), + ServerMessage::Error(_) + ) { + break; + } + } + let mode = fs::metadata(&server.socket).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + + fn input(stream: &mut UnixStream, pane: PaneId, command: &str) { + send( + stream, + ClientMessage::Input { + pane, + bytes: command.as_bytes().to_vec(), + }, + ); + } + + #[test] + fn natural_shell_exit_removes_panes_and_empty_tabs_without_stealing_focus() { + let server = TestServer::start(); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + let initial = snapshot(&mut client, |s| s.panes.len() == 1); + let original = initial.panes[0].id; + let original_tab = initial.active_tab; + send( + &mut client, + ClientMessage::Split { + pane: original, + cwd: None, + }, + ); + let split = snapshot(&mut client, |s| s.panes.len() == 2); + let second = split.tabs[0].active_pane; + assert_ne!(second, original); + + input(&mut client, second, "exit\n"); + let single = snapshot(&mut client, |s| { + s.panes.len() == 1 && s.tabs[0].active_pane == original + }); + assert_eq!(single.active_tab, original_tab); + assert_eq!(single.panes[0].id, original); + + send(&mut client, ClientMessage::NewTab { cwd: None }); + let other = snapshot(&mut client, |s| s.tabs.len() == 2); + let other_tab = other.active_tab; + let other_pane = other.panes[0].id; + input(&mut client, original, "exit\n"); + let preserved = snapshot(&mut client, |s| s.tabs.len() == 1); + assert_eq!(preserved.active_tab, other_tab); + assert_eq!(preserved.panes[0].id, other_pane); + + input(&mut client, other_pane, "exit\n"); + let empty = snapshot(&mut client, |s| s.tabs.is_empty()); + assert!(empty.panes.is_empty()); + assert_eq!(empty.active_tab, 0); + // Removing the final shell leaves this GUI attached to a live server. + send(&mut client, ClientMessage::Ping); + loop { + if matches!( + protocol::read_message::(&mut client).unwrap(), + ServerMessage::Pong + ) { + break; + } + } + send(&mut client, ClientMessage::NewTab { cwd: None }); + let reopened = snapshot(&mut client, |s| s.panes.len() == 1); + assert_ne!(reopened.panes[0].id, original); + } + + #[test] + fn exiting_active_tab_selects_the_adjacent_surviving_tab() { + let server = TestServer::start(); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + snapshot(&mut client, |s| s.tabs.len() == 1); + send(&mut client, ClientMessage::NewTab { cwd: None }); + let middle = snapshot(&mut client, |s| s.tabs.len() == 2); + let middle_tab = middle.active_tab; + let middle_pane = middle.panes[0].id; + send(&mut client, ClientMessage::NewTab { cwd: None }); + let last = snapshot(&mut client, |s| s.tabs.len() == 3); + send(&mut client, ClientMessage::FocusTab { tab: middle_tab }); + snapshot(&mut client, |s| s.active_tab == middle_tab); + input(&mut client, middle_pane, "exit\n"); + let remaining = snapshot(&mut client, |s| s.tabs.len() == 2); + assert_eq!(remaining.active_tab, last.active_tab); + assert!(!remaining.tabs.iter().any(|tab| tab.id == middle_tab)); + } + + #[test] + fn cwd_program_and_manual_names_follow_precedence_and_survive_detach() { + let server = TestServer::start(); + let first_dir = server.socket.parent().unwrap().join("first"); + let second_dir = server.socket.parent().unwrap().join("second"); + fs::create_dir(&first_dir).unwrap(); + fs::create_dir(&second_dir).unwrap(); + let mut client = server.client(); + send( + &mut client, + ClientMessage::NewTab { + cwd: Some(first_dir.to_string_lossy().into_owned()), + }, + ); + send(&mut client, ClientMessage::Attach); + let initial = snapshot(&mut client, |s| s.panes.len() == 1); + let pane = initial.panes[0].id; + assert_eq!(initial.panes[0].title, first_dir.to_string_lossy()); + assert_eq!(initial.panes[0].cwd, first_dir.to_string_lossy()); + assert!(initial.panes[0].manual_title.is_none()); + + // Disable echo and prompts: a subsequent idle `cd` produces no PTY + // output, so the server's directory watcher must publish this update. + input( + &mut client, + pane, + "stty -echo; PS1=; printf '\\033[22;0t\\033]2;Codex\\007'\n", + ); + let titled = snapshot(&mut client, |s| s.panes[0].title == "Codex"); + assert_eq!(titled.tabs[0].title, "Codex"); + send( + &mut client, + ClientMessage::RenamePane { + pane, + name: Some("My work".into()), + }, + ); + snapshot(&mut client, |s| s.panes[0].title == "My work"); + input(&mut client, pane, "printf '\\033]2;Compiler\\007'\n"); + // A fresh client receives the override rather than reconstructing it. + send(&mut client, ClientMessage::Detach); + drop(client); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + let reattached = snapshot(&mut client, |s| !s.panes.is_empty()); + assert_eq!(reattached.panes[0].manual_title.as_deref(), Some("My work")); + assert_eq!(reattached.panes[0].title, "My work"); + send(&mut client, ClientMessage::RenamePane { pane, name: None }); + snapshot(&mut client, |s| s.panes[0].title == "Compiler"); + + input(&mut client, pane, "printf '\\033]2;\\007'\n"); + snapshot(&mut client, |s| { + s.panes[0].title == first_dir.to_string_lossy() + }); + input(&mut client, pane, "printf '\\033]2;Temporary\\007'\n"); + snapshot(&mut client, |s| s.panes[0].title == "Temporary"); + // Restoring the initially absent title exercises Event::ResetTitle, + // distinct from an empty OSC title above. + input(&mut client, pane, "printf '\\033[23;0t'\n"); + snapshot(&mut client, |s| { + s.panes[0].title == first_dir.to_string_lossy() + }); + input( + &mut client, + pane, + &format!("cd '{}'\n", second_dir.display()), + ); + let moved = snapshot(&mut client, |s| { + s.panes[0].cwd == second_dir.to_string_lossy() + }); + assert_eq!(moved.panes[0].title, second_dir.to_string_lossy()); + send( + &mut client, + ClientMessage::RenamePane { + pane, + name: Some("Pinned".into()), + }, + ); + snapshot(&mut client, |s| s.panes[0].title == "Pinned"); + send( + &mut client, + ClientMessage::RenamePane { + pane, + name: Some(" \n\t".into()), + }, + ); + let automatic = snapshot(&mut client, |s| { + s.panes[0].title == second_dir.to_string_lossy() + }); + assert!(automatic.panes[0].manual_title.is_none()); + } + + #[test] + fn displayed_titles_are_bounded_single_line_text() { + assert_eq!( + clean_title(" Codex\n\r\t\u{7} ".into()).as_deref(), + Some("Codex") + ); + assert_eq!(clean_title(" \n\u{7} ".into()), None); + assert_eq!(clean_title("界".repeat(600)).unwrap().chars().count(), 512); + } + + #[test] + fn directory_names_abbreviate_only_the_server_home_directory() { + let home = Some(Path::new("/home/al")); + assert_eq!(directory_title("/home/al", home), "~"); + assert_eq!(directory_title("/home/al/src/界", home), "~/src/界"); + assert_eq!(directory_title("/home/alice/src", home), "/home/alice/src"); + assert_eq!(directory_title("/home/al/src", None), "/home/al/src"); + assert_eq!( + directory_title("/home/al/src", Some(Path::new("/home/al/"))), + "~/src" + ); + assert_eq!(directory_title("/", Some(Path::new("/"))), "~"); + assert_eq!(directory_title("/src", Some(Path::new("/"))), "~/src"); + assert_eq!( + directory_title("/home/al/src", Some(Path::new(""))), + "/home/al/src" + ); + } + + #[test] + fn slow_client_retains_only_latest_snapshot() { + let output = Outbox::default(); + for revision in 1..=1000 { + output.snapshot(Arc::new(Snapshot { + revision, + tabs: Vec::new(), + active_tab: 0, + panes: Vec::new(), + })); + } + output.reliable(ServerMessage::Pong); + assert!(matches!(output.next(), Some(ServerMessage::Pong))); + assert!(matches!( + output.next(), + Some(ServerMessage::Snapshot(Snapshot { revision: 1000, .. })) + )); + output.close(); + assert!(output.next().is_none()); + } +} diff --git a/src/session.rs b/src/session.rs index 4f025cd..b07fb2b 100644 --- a/src/session.rs +++ b/src/session.rs @@ -70,19 +70,32 @@ pub struct Session { // A pidfd identifies this process even after its numerical PID is reused. #[cfg(target_os = "linux")] process: LinuxProcess, + // A pinned proc directory cannot silently resolve to a reused numerical PID. + #[cfg(target_os = "linux")] + proc_directory: Option, worker: Option>, } impl Session { - pub fn new() -> Result<(Self, async_channel::Receiver)> { + pub fn in_directory( + directory: Option, + ) -> Result<(Self, async_channel::Receiver)> { let program = std::env::var("SHELL") .ok() .filter(|shell| !shell.is_empty()) .unwrap_or_else(|| "/bin/sh".into()); - Self::with_shell(Shell::new(program, Vec::new())) + Self::with_shell_and_directory(Shell::new(program, Vec::new()), directory) } + #[cfg(test)] fn with_shell(shell: Shell) -> Result<(Self, async_channel::Receiver)> { + Self::with_shell_and_directory(shell, None) + } + + pub(crate) fn with_shell_and_directory( + shell: Shell, + working_directory: Option, + ) -> Result<(Self, async_channel::Receiver)> { let size = WindowSize { num_cols: 80, num_lines: 24, @@ -100,7 +113,7 @@ impl Session { let options = Options { shell: Some(shell), // None preserves the directory from which the application launched. - working_directory: None, + working_directory, drain_on_exit: true, env: HashMap::from([ ("TERM".into(), "xterm-256color".into()), @@ -110,6 +123,15 @@ impl Session { let pty = tty::new(&options, size, 0).context("Could not start the shell PTY")?; #[cfg(target_os = "linux")] let process = LinuxProcess::new(pty.child().id())?; + #[cfg(target_os = "linux")] + let proc_directory = { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) + .open(format!("/proc/{}", pty.child().id())) + .ok() + }; let event_loop = EventLoop::new(term.clone(), proxy.clone(), pty, true, false) .context("Could not initialize PTY polling")?; let sender = event_loop.channel(); @@ -135,6 +157,8 @@ impl Session { size, #[cfg(target_os = "linux")] process, + #[cfg(target_os = "linux")] + proc_directory, worker: Some(worker), }, rx, @@ -152,6 +176,21 @@ impl Session { self.size } + /// Read the shell's current directory on the server, including `cd` changes. + /// This does not depend on shell integration or a client's local filesystem. + pub fn working_directory(&self) -> Option { + #[cfg(target_os = "linux")] + { + use std::os::fd::AsRawFd; + let directory = self.proc_directory.as_ref()?; + std::fs::read_link(format!("/proc/self/fd/{}/cwd", directory.as_raw_fd())).ok() + } + #[cfg(not(target_os = "linux"))] + { + None + } + } + /// Call when receiving `Event::Wakeup`, before reading the grid for a frame. pub fn acknowledge_wakeup(&self) { self.wakeup_pending.store(false, Ordering::Release); diff --git a/src/terminal.rs b/src/terminal.rs index e7463b3..ec635e3 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,89 +1,112 @@ -//! A single terminal pane. Session owns the PTY; this view only handles presentation/input. -use async_channel::Receiver; -use std::ops::Range; - +//! Display-only workspace and panes. All terminal and multiplexer state is remote. +use crate::{ + chrome, + client::{Client, Updates}, + colors, + cursor::CursorAnimator, + input, + label::middle_label, + pane_name::RenameField, + protocol::{ + ClientMessage, PaneSnapshot, ScrollKind, SelectionCommand, SelectionKind, SelectionSide, + Snapshot, + }, + render::{FONT_SIZE, LINE_HEIGHT, RenderCell, Renderer}, +}; use alacritty_terminal::{ - event::Event, - grid::{Dimensions, Scroll}, - index::{Column, Line, Point as GridPoint, Side}, - selection::{Selection, SelectionType}, - term::TermMode, + term::{TermMode, color::Colors}, vte::ansi::{Color, CursorShape, NamedColor}, }; use gpui::{prelude::*, *}; - -use crate::{ - colors, input, - render::{FONT_SIZE, LINE_HEIGHT, RenderCell, Renderer}, - session::Session, +use std::{ + collections::HashMap, + ops::Range, + sync::Arc, + time::{Duration, Instant}, }; +const PADDING: f32 = 6.; -const PADDING: f32 = 8.; - -pub struct TerminalView { - session: Session, - focus: FocusHandle, - font: Font, - bounds: Bounds, - cell_width: f32, - selecting: bool, - scroll_remainder: f32, - preedit: String, - cursor_bounds: Bounds, - renderer: Renderer, - _events: Task<()>, +pub struct Workspace { + client: Client, + connection: SharedString, + snapshot: Option>, + panes: HashMap>, + error: Option, + _updates: Task<()>, } - -impl TerminalView { +impl Workspace { pub fn new( - session: Session, - events: Receiver, + client: Client, + updates: Updates, + connection: SharedString, window: &mut Window, cx: &mut Context, ) -> Self { - let terminal_font = crate::fonts::terminal_font(window.text_system()); - let font_id = window.text_system().resolve_font(&terminal_font); - let cell_width = window - .text_system() - .advance(font_id, px(FONT_SIZE), 'M') - .map(|advance| f32::from(advance.width)) - .unwrap_or(9.) - .max(1.); - let focus = cx.focus_handle(); - window.focus(&focus); - // Wake on PTY output rather than adding a polling interval to input latency. let task = cx.spawn_in(window, async move |view, cx| { - while let Ok(first) = events.recv().await { - let pending: Vec<_> = std::iter::once(first) - .chain(std::iter::from_fn(|| events.try_recv().ok())) - .take(4096) - .collect(); + while let Some(update) = updates.recv().await { if cx .update(|window, cx| { view.update(cx, |view, cx| { - for event in pending { - match event { - Event::Title(title) => window.set_window_title(&title), - Event::ResetTitle => window.set_window_title("Terminal"), - Event::PtyWrite(text) => view.session.write(text.into_bytes()), - Event::TextAreaSizeRequest(format) => { - view.session.write(format(view.session.size()).into_bytes()) + for text in update.clipboard { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + } + if let Some(error) = update.error { + view.error = Some(error); + } + if let Some(snapshot) = update.snapshot { + let active = snapshot + .tabs + .iter() + .find(|t| t.id == snapshot.active_tab) + .map(|t| t.active_pane); + view.panes + .retain(|id, _| snapshot.panes.iter().any(|p| p.id == *id)); + for (index, data) in snapshot.panes.iter().enumerate() { + if let Some(pane) = view.panes.get(&data.id) { + pane.update(cx, |pane, cx| { + let was_active = pane.active; + pane.active = active == Some(data.id); + pane.snapshot = snapshot.clone(); + pane.index = index; + if pane.active && !was_active { + if let Some(editor) = &pane.rename { + editor.read(cx).focus(window); + } else { + window.focus(&pane.focus); + } + } + // A stale snapshot can precede the FocusPane + // acknowledgement when renaming an inactive + // pane. Cancel only when focus leaves it. + if was_active && !pane.active { + pane.rename = None; + } + cx.notify(); + }); + } else { + let client = view.client.clone(); + let frame = snapshot.clone(); + let pane = cx.new(|cx| { + TerminalPane::new( + client, + frame, + index, + active == Some(data.id), + window, + cx, + ) + }); + view.panes.insert(data.id, pane); } - Event::ColorRequest(index, format) => { - let color = (index - < alacritty_terminal::term::color::COUNT) - .then(|| view.session.term.lock().colors()[index]) - .flatten(); - view.session.write( - format(color.unwrap_or_else(|| colors::palette(index))) - .into_bytes(), - ); - } - Event::Exit => window.remove_window(), - Event::Wakeup => view.session.acknowledge_wakeup(), - // OSC 52 is deliberately not wired to the desktop clipboard. - _ => {} } + let title = snapshot + .tabs + .iter() + .find(|t| t.id == snapshot.active_tab) + .map(|t| t.title.as_str()) + .unwrap_or("Terminal"); + window.set_window_title(&format!("psyTerm — {title}")); + view.snapshot = Some(snapshot); } cx.notify(); }) @@ -92,313 +115,625 @@ impl TerminalView { { break; } - // Give the compositor a turn even when a child continuously writes. futures_lite::future::yield_now().await; } }); Self { - session, + client, + connection, + snapshot: None, + panes: HashMap::new(), + error: None, + _updates: task, + } + } +} +impl Render for Workspace { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let tabs = self + .snapshot + .as_ref() + .map(|s| { + s.tabs + .iter() + .map(|tab| chrome::ChromeTab { + id: tab.id, + label: tab.title.clone().into(), + active: tab.id == s.active_tab, + }) + .collect() + }) + .unwrap_or_default(); + let client = self.client.clone(); + let new_client = self.client.clone(); + let header = chrome::header( + self.connection.clone(), + tabs, + move |tab, _, _| { + let _ = client.send(ClientMessage::FocusTab { tab }); + }, + move |_, _| { + let _ = new_client.send(ClientMessage::NewTab { cwd: None }); + }, + move |window, _| window.remove_window(), + ); + let mut body = div() + .flex() + .flex_1() + .min_h_0() + .gap(px(6.)) + .p(px(chrome::CONTENT_INSET)) + .bg(rgb(chrome::APP_BACKGROUND)); + if let Some(snapshot) = &self.snapshot { + for data in &snapshot.panes { + if let Some(pane) = self.panes.get(&data.id) { + body = body.child(pane.clone()); + } + } + if snapshot.panes.is_empty() { + body = body.child( + div() + .p_4() + .text_color(rgb(chrome::MUTED)) + .child("No sessions. Use + to open a terminal."), + ); + } + } else { + body = body.child( + div() + .p_4() + .text_color(rgb(chrome::MUTED)) + .child("Connecting…"), + ); + } + let mut root = div() + .size_full() + .flex() + .flex_col() + .bg(rgb(chrome::APP_BACKGROUND)) + .child(header) + .child(body); + if let Some(error) = &self.error { + root = root.child( + div() + .px_3() + .py_1() + .text_size(px(12.)) + .text_color(rgb(chrome::TEXT)) + .bg(rgb(chrome::BORDER)) + .child(error.clone()), + ); + } + root + } +} + +struct TerminalPane { + client: Client, + snapshot: Arc, + index: usize, + active: bool, + focus: FocusHandle, + font: Font, + bounds: Bounds, + cell_width: f32, + selecting: bool, + scroll_remainder: f32, + preedit: String, + cursor_bounds: Bounds, + cursor: CursorAnimator, + renderer: Renderer, + rename: Option>, + prepared_revision: Option, + requested_size: Option<(u16, u16)>, + next_frame_pending: bool, + blink_timer: Option>, + _activation: Subscription, +} +impl TerminalPane { + fn new( + client: Client, + snapshot: Arc, + index: usize, + active: bool, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let font = crate::fonts::terminal_font(window.text_system()); + let font_id = window.text_system().resolve_font(&font); + let cell_width = window + .text_system() + .advance(font_id, px(FONT_SIZE), 'M') + .map(|s| f32::from(s.width)) + .unwrap_or(9.) + .max(1.); + let focus = cx.focus_handle(); + if active { + window.focus(&focus); + } + let activation = cx.observe_window_activation(window, |pane, _, cx| { + pane.blink_timer = None; + cx.notify(); + }); + Self { + client, + snapshot, + index, + active, focus, - font: terminal_font, + font, bounds: Bounds::default(), cell_width, selecting: false, scroll_remainder: 0., preedit: String::new(), cursor_bounds: Bounds::default(), + cursor: CursorAnimator::new(), renderer: Renderer::default(), - _events: task, + rename: None, + prepared_revision: None, + requested_size: None, + next_frame_pending: false, + blink_timer: None, + _activation: activation, } } - + fn data(&self) -> &PaneSnapshot { + &self.snapshot.panes[self.index] + } + fn command(&self, command: ClientMessage) { + if let Err(error) = self.client.send(command) { + log::warn!("{error:#}"); + } + } + fn mode(&self) -> TermMode { + TermMode::from_bits_truncate(self.data().mode) + } + fn activity(&mut self, cx: &mut Context) { + self.cursor.activity(Instant::now()); + self.blink_timer = None; + cx.notify(); + } fn send(&mut self, bytes: Vec, cx: &mut Context) { if bytes.is_empty() { return; } - let mut changed = !self.preedit.is_empty(); self.preedit.clear(); - { - let mut term = self.session.term.lock(); - changed |= term.grid().display_offset() != 0 || term.selection.is_some(); - term.scroll_display(Scroll::Bottom); - term.selection = None; - } - self.session.write(bytes); - // Echo arrives through the PTY. Do not draw an unchanged frame first. - if changed { - cx.notify(); + self.activity(cx); + if let Err(error) = self.client.input(self.data().id, bytes) { + log::warn!("{error:#}"); } } + fn begin_rename(&mut self, window: &mut Window, cx: &mut Context) { + self.command(ClientMessage::FocusPane { + pane: self.data().id, + }); + self.preedit.clear(); + self.selecting = false; + let initial = self.data().title.clone(); + let owner = cx.weak_entity(); + let field = cx.new(|cx| { + RenameField::new( + initial, + move |name, window, cx| { + let _ = owner.update(cx, |pane, cx| { + pane.rename = None; + if let Some(name) = name { + pane.command(ClientMessage::RenamePane { + pane: pane.data().id, + name: Some(name), + }); + } + window.focus(&pane.focus); + pane.activity(cx); + }); + }, + window, + cx, + ) + }); + self.rename = Some(field); + cx.notify(); + } - fn key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context) { + fn pane_header(&mut self, cx: &mut Context) -> Div { + let mut header = div() + .flex() + .items_center() + .gap(px(8.)) + .h(px(28.)) + .flex_shrink_0() + .px(px(9.)) + .bg(rgb(chrome::TERMINAL_BACKGROUND)) + .font_family(".SystemUIFont") + .text_size(px(11.)) + .text_color(rgb(if self.active { + chrome::PANE_FOCUS + } else { + chrome::PANE_MUTED + })) + .on_mouse_down( + MouseButton::Left, + cx.listener(|pane, _, window, cx| { + cx.stop_propagation(); + if pane.rename.is_none() { + window.focus(&pane.focus); + } + pane.command(ClientMessage::FocusPane { + pane: pane.data().id, + }); + }), + ); + if let Some(editor) = &self.rename { + header = header + .child(div().flex_1().min_w_0().child(editor.clone())) + .child( + div() + .flex_shrink_0() + .text_color(rgb(chrome::MUTED)) + .child("Enter to save · Esc to cancel"), + ); + } else { + header = header.child( + div() + .flex_1() + .min_w_0() + .h_full() + .overflow_hidden() + .child(middle_label(self.data().title.clone().into())), + ); + } + header + } + + fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + if self.rename.is_some() { + return; + } let key = &event.keystroke; + let pane = self.data().id; + self.activity(cx); if key.modifiers.control && key.modifiers.shift && !key.modifiers.alt && !key.modifiers.platform { - match key.key.as_str() { - "c" | "C" => { - if let Some(text) = self.session.term.lock().selection_to_string() { - cx.write_to_clipboard(ClipboardItem::new_string(text)); - } - cx.stop_propagation(); - return; + let handled = match key.key.to_lowercase().as_str() { + "r" => { + self.begin_rename(window, cx); + true } - "v" | "V" => { + "c" => { + self.command(ClientMessage::Copy { pane }); + true + } + "v" => { if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { - let bracketed = self - .session - .term - .lock() - .mode() - .contains(TermMode::BRACKETED_PASTE); - let text = input::paste_text(&text, bracketed); - self.send(text, cx); + self.send( + input::paste_text( + &text, + self.mode().contains(TermMode::BRACKETED_PASTE), + ), + cx, + ); } - cx.stop_propagation(); - return; + true } - _ => {} + "t" => { + self.command(ClientMessage::NewTab { cwd: None }); + true + } + "d" => { + self.command(ClientMessage::Split { pane, cwd: None }); + true + } + "w" => { + self.command(ClientMessage::ClosePane { pane }); + true + } + "left" | "right" => { + if let Some(tab) = self + .snapshot + .tabs + .iter() + .find(|t| t.id == self.snapshot.active_tab) + && let Some(index) = tab.panes.iter().position(|p| *p == pane) + { + let next = if key.key == "right" { + (index + 1) % tab.panes.len() + } else { + (index + tab.panes.len() - 1) % tab.panes.len() + }; + self.command(ClientMessage::FocusPane { + pane: tab.panes[next], + }); + } + true + } + _ => false, + }; + if handled { + cx.stop_propagation(); + return; } } if key.modifiers.shift && !key.modifiers.control && !key.modifiers.alt && !key.modifiers.platform - && !self - .session - .term - .lock() - .mode() - .contains(TermMode::ALT_SCREEN) + && !self.mode().contains(TermMode::ALT_SCREEN) { - let scroll = match key.key.as_str() { - "pageup" => Some(Scroll::PageUp), - "pagedown" => Some(Scroll::PageDown), - "home" => Some(Scroll::Top), - "end" => Some(Scroll::Bottom), + let kind = match key.key.as_str() { + "pageup" => Some(ScrollKind::PageUp), + "pagedown" => Some(ScrollKind::PageDown), + "home" => Some(ScrollKind::Top), + "end" => Some(ScrollKind::Bottom), _ => None, }; - if let Some(scroll) = scroll { - self.session.term.lock().scroll_display(scroll); - cx.notify(); + if let Some(kind) = kind { + self.command(ClientMessage::Scroll { pane, kind }); cx.stop_propagation(); return; } } - let mode = *self.session.term.lock().mode(); - if let Some(bytes) = input::encode_key(key, mode) { + if let Some(bytes) = input::encode_key(key, self.mode()) { self.send(bytes, cx); cx.stop_propagation(); } } - - fn grid_point(&self, position: Point) -> (GridPoint, Side) { - let term = self.session.term.lock(); - let x = (f32::from(position.x - self.bounds.left()) - PADDING).max(0.) / self.cell_width; - let y = - ((f32::from(position.y - self.bounds.top()) - PADDING).max(0.) / LINE_HEIGHT) as usize; - let column = (x as usize).min(term.columns() - 1); - let line = y.min(term.screen_lines() - 1) as i32 - term.grid().display_offset() as i32; + fn grid_point(&self, position: Point) -> (u16, u16, SelectionSide) { + let x = ((f32::from(position.x - self.bounds.left()) - PADDING).max(0.) / self.cell_width) + .min(f32::from(self.data().columns - 1)); + let y = ((f32::from(position.y - self.bounds.top()) - PADDING).max(0.) / LINE_HEIGHT) + .min(f32::from(self.data().lines - 1)); ( - GridPoint::new(Line(line), Column(column)), + x as u16, + y as u16, if x.fract() < 0.5 { - Side::Left + SelectionSide::Left } else { - Side::Right + SelectionSide::Right }, ) } - fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context) { window.focus(&self.focus); - let (point, side) = self.grid_point(event.position); - let ty = match event.click_count { - 2 => SelectionType::Semantic, - 3.. => SelectionType::Lines, - _ => SelectionType::Simple, + self.activity(cx); + let pane = self.data().id; + self.command(ClientMessage::FocusPane { pane }); + let (column, row, side) = self.grid_point(event.position); + let kind = match event.click_count { + 2 => SelectionKind::Word, + 3.. => SelectionKind::Line, + _ => SelectionKind::Simple, }; - self.session.term.lock().selection = Some(Selection::new(ty, point, side)); + self.command(ClientMessage::Selection { + pane, + selection: SelectionCommand::Start { + column, + row, + side, + kind, + }, + }); self.selecting = true; - cx.notify(); } - - fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context) { + fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, _: &mut Context) { if self.selecting && event.dragging() { - let (point, side) = self.grid_point(event.position); - if let Some(selection) = &mut self.session.term.lock().selection { - selection.update(point, side); - } - cx.notify(); + let (column, row, side) = self.grid_point(event.position); + self.command(ClientMessage::Selection { + pane: self.data().id, + selection: SelectionCommand::Update { column, row, side }, + }); } } - fn scroll(&mut self, event: &ScrollWheelEvent, _: &mut Window, cx: &mut Context) { self.scroll_remainder += match event.delta { - ScrollDelta::Lines(delta) => delta.y * 3., - ScrollDelta::Pixels(delta) => f32::from(delta.y) / LINE_HEIGHT, + ScrollDelta::Lines(d) => d.y * 3., + ScrollDelta::Pixels(d) => f32::from(d.y) / LINE_HEIGHT, }; let lines = self.scroll_remainder.trunc() as i32; self.scroll_remainder -= lines as f32; - if lines != 0 { - let mode = *self.session.term.lock().mode(); - if mode.contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL) - && !event.modifiers.shift - { - let arrow = match (mode.contains(TermMode::APP_CURSOR), lines > 0) { - (true, true) => b"\x1bOA", - (true, false) => b"\x1bOB", - (false, true) => b"\x1b[A", - (false, false) => b"\x1b[B", - }; - self.send(arrow.repeat(lines.unsigned_abs().min(100) as usize), cx); - } else { - self.session - .term - .lock() - .scroll_display(Scroll::Delta(lines)); - cx.notify(); - } + if lines == 0 { + return; } - } - - fn prepare(&mut self, bounds: Bounds, window: &mut Window) { - let prepare_started = std::time::Instant::now(); - self.bounds = bounds; - let columns = ((f32::from(bounds.size.width) - 2. * PADDING) / self.cell_width) - .floor() - .max(2.) as usize; - let lines = ((f32::from(bounds.size.height) - 2. * PADDING) / LINE_HEIGHT) - .floor() - .max(1.) as usize; - self.session.resize( - columns, - lines, - self.cell_width.round() as u16, - LINE_HEIGHT as u16, - ); - let term = self.session.term.lock(); - let content = term.renderable_content(); - let offset = content.display_offset as i32; - let cursor = content.cursor; - self.cursor_bounds = Bounds::new( - bounds.origin - + point( - px(PADDING + cursor.point.column.0 as f32 * self.cell_width), - px(PADDING + (cursor.point.line.0 + offset) as f32 * LINE_HEIGHT), - ), - size(px(self.cell_width), px(LINE_HEIGHT)), - ); - let mut rows = vec![Vec::with_capacity(columns); lines]; - for indexed in content.display_iter { - let (mut foreground, mut background) = - colors::cell_colors(indexed.cell, content.colors); - if content - .selection - .is_some_and(|selection| selection.contains(indexed.point)) - { - foreground = rgb(0xffffff).into(); - background = rgb(0x3c536d).into(); - } - let shape = if indexed.point == cursor.point { - cursor.shape - } else { - CursorShape::Hidden + let mode = self.mode(); + if mode.contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL) + && !event.modifiers.shift + { + let arrow = match (mode.contains(TermMode::APP_CURSOR), lines > 0) { + (true, true) => b"\x1bOA", + (true, false) => b"\x1bOB", + (false, true) => b"\x1b[A", + (false, false) => b"\x1b[B", }; - if shape == CursorShape::Block { - background = colors::resolve(Color::Named(NamedColor::Cursor), content.colors); - foreground = colors::resolve(Color::Named(NamedColor::Background), content.colors); - } - let row = (indexed.point.line.0 + offset) as usize; - rows[row].push(RenderCell { - cell: indexed.cell.clone(), - foreground, - background, - cursor: shape, + self.send(arrow.repeat(lines.unsigned_abs().min(100) as usize), cx); + } else { + self.command(ClientMessage::Scroll { + pane: self.data().id, + kind: ScrollKind::Delta(lines), }); } - drop(term); + } + fn prepare(&mut self, bounds: Bounds, window: &mut Window) { + let columns = ((f32::from(bounds.size.width) - 2. * PADDING) / self.cell_width) + .floor() + .clamp(2., 1000.) as u16; + let lines = ((f32::from(bounds.size.height) - 2. * PADDING) / LINE_HEIGHT) + .floor() + .clamp(1., 500.) as u16; + if self.requested_size != Some((columns, lines)) { + self.requested_size = Some((columns, lines)); + self.command(ClientMessage::Resize { + pane: self.data().id, + columns, + lines, + cell_width: self.cell_width.round() as u16, + cell_height: LINE_HEIGHT as u16, + }); + } + if self.prepared_revision == Some(self.snapshot.revision) && self.bounds == bounds { + return; + } + let started = Instant::now(); + self.bounds = bounds; + let data = self.data(); + let mut palette = Colors::default(); + for (i, color) in data.colors.iter().enumerate() { + palette[i] = *color; + } + let cursor = data.cursor; + let hidden = data.exited || cursor.row < 0 || cursor.row >= i32::from(data.lines); + let wide = data + .cells + .get( + cursor.row.max(0) as usize * usize::from(data.columns) + usize::from(cursor.column), + ) + .is_some_and(|cell| { + cell.flags + .contains(alacritty_terminal::term::cell::Flags::WIDE_CHAR) + }); + let cursor_bounds = Bounds::new( + bounds.origin + + point( + px(PADDING + f32::from(cursor.column) * self.cell_width), + px(PADDING + cursor.row as f32 * LINE_HEIGHT), + ), + size( + px(self.cell_width * if wide { 2. } else { 1. }), + px(LINE_HEIGHT), + ), + ); + let rows = data + .cells + .chunks(usize::from(data.columns)) + .enumerate() + .map(|(row, cells)| { + cells + .iter() + .enumerate() + .map(|(col, cell)| { + let (mut foreground, mut background) = colors::cell_colors(cell, &palette); + if data.selected[row * usize::from(data.columns) + col] { + foreground = rgb(chrome::TEXT).into(); + background = rgb(chrome::BORDER).into(); + } + RenderCell { + cell: cell.clone(), + foreground, + background, + cursor: CursorShape::Hidden, + } + }) + .collect() + }) + .collect(); + let mut cursor_color = colors::resolve(Color::Named(NamedColor::Cursor), &palette); + cursor_color.a = 0.55; + self.cursor_bounds = cursor_bounds; + self.cursor.set_target( + cursor_bounds, + if hidden { + CursorShape::Hidden + } else { + cursor.shape.into() + }, + cursor_color, + Instant::now(), + ); self.renderer .prepare(rows, &self.font, self.cell_width, window); - log::debug!(target: "terminal::timing", "prepare_us={} cells={}", prepare_started.elapsed().as_micros(), columns * lines); + self.prepared_revision = Some(self.snapshot.revision); + log::debug!(target:"psyterm::timing","prepare_us={}",started.elapsed().as_micros()); + } + fn schedule_cursor( + &mut self, + delay: Option, + window: &mut Window, + cx: &mut Context, + ) { + self.blink_timer = None; + match delay { + Some(delay) if delay.is_zero() => { + if !self.next_frame_pending { + self.next_frame_pending = true; + cx.on_next_frame(window, |pane, _, cx| { + pane.next_frame_pending = false; + cx.notify(); + }); + } + } + Some(delay) => { + self.blink_timer = Some(cx.spawn_in(window, async move |pane, cx| { + cx.background_executor().timer(delay).await; + let _ = pane.update(cx, |_, cx| cx.notify()); + })); + } + None => {} + } } } - -impl Render for TerminalView { +impl Render for TerminalPane { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let prepare_view = cx.entity(); - let paint_view = cx.entity(); - div() - .size_full() - .bg(rgb(colors::BACKGROUND)) - .overflow_hidden() - .track_focus(&self.focus) - .cursor(CursorStyle::IBeam) - .on_key_down(cx.listener(Self::key_down)) - .on_mouse_down(MouseButton::Left, cx.listener(Self::mouse_down)) + let prepare = cx.entity(); + let paint = cx.entity(); + let header = self.pane_header(cx); + let content = div().flex_1().min_h_0().min_w_0().overflow_hidden().cursor(CursorStyle::IBeam) + .on_mouse_down(MouseButton::Left,cx.listener(|pane, event, window, cx| { + pane.rename = None; + pane.mouse_down(event, window, cx); + })) .on_mouse_move(cx.listener(Self::mouse_move)) - .on_mouse_up( - MouseButton::Left, - cx.listener(|view, _, _, _| view.selecting = false), - ) - .on_mouse_up_out( - MouseButton::Left, - cx.listener(|view, _, _, _| view.selecting = false), - ) + .on_mouse_up(MouseButton::Left,cx.listener(|pane,_,_,_|pane.selecting=false)) + .on_mouse_up_out(MouseButton::Left,cx.listener(|pane,_,_,_|pane.selecting=false)) .on_scroll_wheel(cx.listener(Self::scroll)) - .child( - canvas( - move |bounds, window, cx| { - prepare_view.update(cx, |view, _| view.prepare(bounds, window)) - }, - move |bounds, (), window, cx| { - let paint_started = std::time::Instant::now(); - let view = paint_view.read(cx); - let focus = view.focus.clone(); - let base_font = view.font.clone(); - let preedit = view.preedit.clone(); - let cursor_bounds = view.cursor_bounds; - window.handle_input( - &focus, - ElementInputHandler::new(bounds, paint_view.clone()), - cx, - ); - window.with_content_mask(Some(ContentMask { bounds }), |window| { - let origin = bounds.origin + point(px(PADDING), px(PADDING)); - paint_view.update(cx, |view, cx| view.renderer.paint(origin, window, cx)); - if !preedit.is_empty() { - let run = TextRun { - len: preedit.len(), - font: base_font.clone(), - color: rgb(colors::FOREGROUND).into(), - background_color: Some(rgb(colors::BACKGROUND).into()), - underline: Some(UnderlineStyle { - thickness: px(1.), - color: None, - wavy: false, - }), - strikethrough: None, - }; - let shaped = window.text_system().shape_line( - preedit.into(), - px(FONT_SIZE), - &[run], - None, - ); - let _ = - shaped.paint(cursor_bounds.origin, px(LINE_HEIGHT), window, cx); + .child(canvas(move |bounds,window,cx|prepare.update(cx,|pane,_|pane.prepare(bounds,window)), + move |bounds,(),window,cx| { + paint.update(cx,|pane,cx| { + let started=Instant::now(); + if pane.rename.is_none() { + window.handle_input(&pane.focus,ElementInputHandler::new(bounds,paint.clone()),cx); + } + let mut delay=None; + window.with_content_mask(Some(ContentMask{bounds}),|window| { + let origin=bounds.origin+point(px(PADDING),px(PADDING)); + let focused=window.is_window_active() && pane.active && pane.rename.is_none(); + pane.renderer.paint_with_cursor(origin,window,cx,|window| { + delay=pane.cursor.paint(Instant::now(),focused,window); + }); + if !pane.preedit.is_empty() { + let run=TextRun{len:pane.preedit.len(),font:pane.font.clone(),color:rgb(chrome::TEXT).into(),background_color:Some(rgb(chrome::TERMINAL_BACKGROUND).into()), + underline:Some(UnderlineStyle{thickness:px(1.),color:None,wavy:false}),strikethrough:None}; + let shaped=window.text_system().shape_line(pane.preedit.clone().into(),px(FONT_SIZE),&[run],None); + let _=shaped.paint_background(pane.cursor_bounds.origin,px(LINE_HEIGHT),window,cx); + let _=shaped.paint(pane.cursor_bounds.origin,px(LINE_HEIGHT),window,cx); } }); - log::debug!(target: "terminal::timing", "paint_us={}", paint_started.elapsed().as_micros()); - }, - ) - .size_full(), - ) + pane.schedule_cursor(delay,window,cx); + log::debug!(target:"psyterm::timing","paint_us={}",started.elapsed().as_micros()); + }); + }).size_full()); + div() + .flex_1() + .min_w_0() + .h_full() + .flex() + .flex_col() + .bg(rgb(chrome::TERMINAL_BACKGROUND)) + .border_1() + .border_color(rgb(if self.active { + chrome::PANE_FOCUS + } else { + chrome::BORDER + })) + .overflow_hidden() + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::key_down)) + .child(header) + .child(content) } } - -impl EntityInputHandler for TerminalView { +impl EntityInputHandler for TerminalPane { fn text_for_range( &mut self, _: Range, @@ -451,7 +786,7 @@ impl EntityInputHandler for TerminalView { cx: &mut Context, ) { self.preedit = text.to_owned(); - cx.notify(); + self.activity(cx); } fn bounds_for_range( &mut self,