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.
This commit is contained in:
Generated
+26
-14
@@ -538,6 +538,15 @@ version = "0.22.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bincode"
|
||||||
|
version = "1.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bindgen"
|
name = "bindgen"
|
||||||
version = "0.71.1"
|
version = "0.71.1"
|
||||||
@@ -4007,6 +4016,23 @@ dependencies = [
|
|||||||
"cc",
|
"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]]
|
[[package]]
|
||||||
name = "pxfm"
|
name = "pxfm"
|
||||||
version = "0.1.30"
|
version = "0.1.30"
|
||||||
@@ -5366,20 +5392,6 @@ dependencies = [
|
|||||||
"winapi-util",
|
"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]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "1.0.69"
|
version = "1.0.69"
|
||||||
|
|||||||
+4
-1
@@ -1,5 +1,5 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "terminal"
|
name = "psyterm"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
@@ -7,11 +7,14 @@ publish = false
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
alacritty_terminal = "=0.26.0"
|
alacritty_terminal = "=0.26.0"
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
bincode = "1.3"
|
||||||
async-channel = "2"
|
async-channel = "2"
|
||||||
gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] }
|
gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
env_logger = "0.11"
|
env_logger = "0.11"
|
||||||
futures-lite = "2"
|
futures-lite = "2"
|
||||||
|
unicode-segmentation = "1"
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
# Terminal
|
# psyTerm
|
||||||
|
|
||||||
A small GPU-rendered terminal built with [GPUI 0.2.2](https://gpui.rs/) and
|
A Wayland terminal and multiplexer built with [GPUI 0.2.2](https://gpui.rs/)
|
||||||
[alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/).
|
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
|
A separate server owns terminal emulation, shells, tabs, panes, and scrollback.
|
||||||
state machine, VTE parser, scrollback, PTY, and shell I/O; GPUI provides the window,
|
GUI processes display its snapshots and send input commands. Closing a window
|
||||||
text rendering, and desktop input.
|
detaches it; the shells keep running for the next local or remote connection.
|
||||||
|
|
||||||
## Build and run
|
## Build and run
|
||||||
|
|
||||||
Use a recent stable Rust toolchain; development currently uses Rust 1.96. Launch
|
Use recent stable Rust (development uses 1.96) and Linux 5.3 or newer. GUI
|
||||||
from Linux 5.3 or newer (pidfd-based shell cleanup), in a running Wayland desktop with `WAYLAND_DISPLAY` set and a working Vulkan
|
processes require a running Wayland desktop and a working Vulkan driver.
|
||||||
driver. This build enables GPUI's Wayland backend only.
|
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:
|
Representative Fedora dependencies:
|
||||||
|
|
||||||
@@ -30,120 +31,205 @@ sudo apt install build-essential cmake pkg-config \
|
|||||||
fonts-dejavu-core
|
fonts-dejavu-core
|
||||||
```
|
```
|
||||||
|
|
||||||
The package names follow the relevant portions of
|
These are the relevant portions of [Zed's Linux dependency script](https://github.com/zed-industries/zed/blob/main/script/linux).
|
||||||
[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.
|
||||||
Your GPU may need its vendor's Vulkan driver instead of Mesa. GPUI 0.2.2 also
|
Use your GPU vendor's Vulkan driver where appropriate.
|
||||||
links the XKB X11 library even when only its Wayland window backend is enabled.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo run --locked
|
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
|
The default command starts or reuses a local server, asks its zygote to fork a
|
||||||
directory. The child receives `TERM=xterm-256color` and `COLORTERM=truecolor`.
|
GUI, and returns. Running it again opens another view of the same workspace.
|
||||||
Run `exit` or close the window to end the session. To select another shell:
|
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
|
```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,
|
Sockets and log files are private to the current UID; peers are checked with
|
||||||
check that the process has access to your Wayland session and that Vulkan works
|
Linux credentials. Server and zygote logs are beside the socket as
|
||||||
on that desktop. To inspect the renderer's CPU work without enabling logs from
|
`server.sock.log` and `server.sock.zygote.log`.
|
||||||
all dependencies:
|
|
||||||
|
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
|
```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
|
SSH starts `psyterm --bridge` on the remote host, which starts or reuses that
|
||||||
our preparation and painting callbacks. These exclude GPU execution, compositor
|
host's server. stdout carries only framed protocol bytes. No TCP listener or
|
||||||
scheduling, and presentation; they are not measurements of total input latency.
|
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 |
|
| Input | Action |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Drag with the left mouse button | Select text |
|
| Click a tab | Switch the server's active tab |
|
||||||
| Double-click / triple-click | Select a word / line |
|
| `+` or Ctrl+Shift+T | Create a tab |
|
||||||
| Ctrl+Shift+C | Copy the selection |
|
| Ctrl+Shift+D | Add a pane beside the focused pane |
|
||||||
| Ctrl+Shift+V | Paste, respecting bracketed-paste mode |
|
| 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 |
|
| Mouse wheel / touchpad | Scroll terminal history |
|
||||||
| Shift+PageUp / Shift+PageDown | Scroll one page |
|
| Shift+PageUp / PageDown | Scroll one page |
|
||||||
| Shift+Home / Shift+End | Jump to the oldest history / live screen |
|
| Shift+Home / End | Jump to oldest history / live screen |
|
||||||
|
|
||||||
Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows,
|
Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows,
|
||||||
navigation keys, and function keys are sent to the terminal application.
|
navigation keys, and function keys reach the terminal application.
|
||||||
In alternate-screen applications, Shift+navigation is passed through and the
|
Alternate-screen applications receive shifted navigation; the wheel sends
|
||||||
wheel sends arrow keys when the application enables alternate scrolling.
|
arrow keys when the application enables alternate scrolling.
|
||||||
|
|
||||||
The renderer supports ANSI and 256-color palettes, truecolor, bold/italic/dim,
|
Each pane has a name above its terminal content. The server chooses a manual
|
||||||
underlining, reverse video, selection, wide characters and combining marks.
|
name first, then the running program's OSC title, then the shell's current
|
||||||
Window resizing updates both the terminal grid and PTY size. Alternate-screen
|
directory. Automatic directory names abbreviate the server’s home directory
|
||||||
applications use Alacritty's terminal modes. Scrollback retains up to 10,000
|
with `~`; pane headers and equal-width tabs truncate long names in the middle.
|
||||||
lines by default. The view selects an installed font in this order: Hermit
|
It checks shell directories every 500 ms, including while the shell is idle. Manual names survive program title changes and client disconnects;
|
||||||
(including its Hurmit Nerd Font variants), SF Mono, Noto Sans Mono, Iosevka,
|
returning to automatic naming uses the latest program title or directory.
|
||||||
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.
|
|
||||||
|
|
||||||
## 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 |
|
| `server.rs`, `session.rs` | Authoritative workspace, PTYs, child processes, parser, terminal grids, selection, scrolling, and resize |
|
||||||
| `src/session.rs` | One shell, PTY event loop, terminal grid, resize, and shutdown |
|
| `protocol.rs`, `client.rs` | Versioned bounded messages, local socket / SSH transport, snapshot delivery |
|
||||||
| `src/terminal.rs` | One terminal view: focus, selection, scrollback, clipboard, text input, and render coordination |
|
| `launcher.rs` | Server startup, private paths, lifecycle locks, and the server-owned GUI zygote |
|
||||||
| `src/render.rs` | Cached terminal text layout and batched drawing |
|
| `terminal.rs` | Snapshot-only GUI workspace and panes, input, focus, and animation scheduling |
|
||||||
| `src/input.rs` | Xterm-style key encoding and paste framing |
|
| `pane_name.rs`, `label.rs` | Pane name editor, Unicode composition, and middle-truncated labels |
|
||||||
| `src/colors.rs` | Default palette, runtime color overrides, and cell color attributes |
|
| `render.rs`, `cursor.rs` | Cached text and batched drawing; cursor motion and blink |
|
||||||
| `src/fonts.rs` | Preferred installed fonts and verified fixed-pitch fallback |
|
| `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
|
The server starts the zygote on demand and manages its lifetime. The zygote
|
||||||
can compose multiple views and sessions while reusing the parser and PTY code.
|
checks that it is single-threaded and forks GUI children **before** GPUI,
|
||||||
Persistent multiplexing would add a session owner outside the window lifecycle.
|
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
|
Snapshot queues retain the newest frame for a slow client rather than an
|
||||||
are coalesced, and the UI yields between event batches so a busy child cannot
|
unbounded backlog. GUI rows keep their shaped text until the snapshot changes.
|
||||||
monopolize the UI task. There is no periodic redraw polling. Typing requests a
|
ASCII runs, Unicode glyphs, backgrounds, and decorations are batched; cursor
|
||||||
new frame when shell output arrives, or immediately if it changes selection,
|
animation reuses prepared terminal rows. Blink holds use timed wakeups, and
|
||||||
scrollback position, or input-method composition.
|
inactive cursors schedule no animation frames.
|
||||||
|
|
||||||
The renderer retains shaped text for unchanged rows. It groups adjacent ASCII
|
The project uses published crates, with no local Alacritty checkout required.
|
||||||
cells into text runs, while keeping wide and combining-character cells aligned
|
The small [vendored xattr patch](vendor/xattr/PATCH.md) fixes GPUI's transitive
|
||||||
to terminal columns. Blank margins are skipped, and matching backgrounds and
|
Linux `ENOATTR` compatibility issue. `Cargo.lock` records dependency versions.
|
||||||
text decorations are merged into spans to reduce drawing work.
|
|
||||||
|
|
||||||
The build uses published crates and does not require a local Alacritty checkout.
|
## Development
|
||||||
`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 and scope
|
The development profile retains debug information and assertions with level-1
|
||||||
|
optimization, plus level-2 optimization for GPUI and shaping crates. Preserve
|
||||||
The development profile retains debug information and assertions, with level-1
|
these settings when evaluating responsiveness; full-grid shaping and scene
|
||||||
optimization and level-2 optimization for GPUI and the font-shaping crates.
|
construction are expensive in a completely unoptimized build.
|
||||||
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.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo fmt --check
|
cargo fmt --check
|
||||||
cargo check --locked
|
cargo check --locked
|
||||||
cargo test --locked
|
cargo test --locked
|
||||||
cargo clippy --locked --all-targets -- -D warnings
|
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
|
`prepare_us` and `paint_us` measure CPU callback time in microseconds. They
|
||||||
resizing, and PTY lifecycle. They do not replace testing rendering and input
|
exclude GPU execution, compositor scheduling, and presentation, so they are
|
||||||
under a real compositor.
|
not end-to-end input-latency measurements.
|
||||||
|
|
||||||
This first version has a single shell and window. It does not yet provide panes,
|
Tests cover protocol framing, socket ownership, binary bridge flushing,
|
||||||
tabs, session persistence, configuration files, application mouse reporting,
|
key/paste encoding, palettes, fonts, cursor curves, rendering assembly, PTY
|
||||||
the Kitty keyboard protocol, OSC 52 clipboard access, or clickable hyperlinks.
|
lifecycle, and server reattachment/layout behavior. Pane tests cover natural
|
||||||
macOS is an intended next target and has not been validated. Font shaping,
|
shell exit, empty-tab removal, focus preservation, idle directory changes,
|
||||||
input methods, and terminal application compatibility still need broader
|
program/manual name precedence, title resets, and rename persistence. Editor
|
||||||
desktop testing.
|
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.
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
+198
@@ -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<ChromeTab>,
|
||||||
|
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> {
|
||||||
|
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,
|
||||||
|
}],
|
||||||
|
|_, _, _| {},
|
||||||
|
|_, _| {},
|
||||||
|
|_, _| {},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+289
@@ -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<Arc<Snapshot>>,
|
||||||
|
pub clipboard: VecDeque<String>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Updates {
|
||||||
|
signal: async_channel::Receiver<()>,
|
||||||
|
pending: Arc<Mutex<Update>>,
|
||||||
|
}
|
||||||
|
impl Updates {
|
||||||
|
pub async fn recv(&self) -> Option<Update> {
|
||||||
|
self.signal.recv().await.ok()?;
|
||||||
|
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Client(Arc<Connection>);
|
||||||
|
struct Connection {
|
||||||
|
commands: mpsc::Sender<ClientMessage>,
|
||||||
|
socket: Option<UnixStream>,
|
||||||
|
ssh: Mutex<Option<Child>>,
|
||||||
|
}
|
||||||
|
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<dyn Read + Send>, Box<dyn Write + Send>, _, _) =
|
||||||
|
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<dyn Read + Send>;
|
||||||
|
let writer = Box::new(child.stdin.take().unwrap()) as Box<dyn Write + Send>;
|
||||||
|
(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<dyn Read + Send>,
|
||||||
|
Box::new(stream.try_clone()?) as Box<dyn Write + Send>,
|
||||||
|
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::<ServerMessage>(&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<u8>) -> 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<u8>,
|
||||||
|
flushes: usize,
|
||||||
|
}
|
||||||
|
impl Write for Output {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||||
|
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'");
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -9,8 +9,8 @@ use alacritty_terminal::{
|
|||||||
};
|
};
|
||||||
use gpui::Hsla;
|
use gpui::Hsla;
|
||||||
|
|
||||||
pub const BACKGROUND: u32 = 0x181a1f;
|
pub const BACKGROUND: u32 = 0x080917;
|
||||||
pub const FOREGROUND: u32 = 0xd8dee9;
|
pub const FOREGROUND: u32 = 0xf3f1f8;
|
||||||
|
|
||||||
const ANSI: [u32; 16] = [
|
const ANSI: [u32; 16] = [
|
||||||
0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, 0x5c6370,
|
0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, 0x5c6370,
|
||||||
|
|||||||
+446
@@ -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<Pixels>,
|
||||||
|
shape: CursorShape,
|
||||||
|
color: Hsla,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct CursorAnimator {
|
||||||
|
corners: [Corner; 4],
|
||||||
|
target: Option<Target>,
|
||||||
|
last_frame: Option<Instant>,
|
||||||
|
last_activity: Option<Instant>,
|
||||||
|
was_focused: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Frame {
|
||||||
|
points: [Point<Pixels>; 4],
|
||||||
|
opacity: f32,
|
||||||
|
outline: bool,
|
||||||
|
next: Option<Duration>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Pixels>,
|
||||||
|
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<Duration> {
|
||||||
|
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<Pixels> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+155
@@ -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<ShapedLine> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+754
@@ -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<PathBuf> {
|
||||||
|
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<ServerMessage> {
|
||||||
|
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<bool> {
|
||||||
|
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<ServerMessage> {
|
||||||
|
control_stream_version(stream, command, timeout, protocol::VERSION)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control_stream_version(
|
||||||
|
mut stream: UnixStream,
|
||||||
|
command: ClientMessage,
|
||||||
|
timeout: Duration,
|
||||||
|
expected_version: u32,
|
||||||
|
) -> Result<ServerMessage> {
|
||||||
|
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::<ServerMessage>(&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<Self> {
|
||||||
|
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<String>) -> 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<LaunchResponse> {
|
||||||
|
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<Self> {
|
||||||
|
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<String>,
|
||||||
|
},
|
||||||
|
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::<LaunchRequest>(&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<Child> {
|
||||||
|
spawn_role_from(&executable_path()?, role, socket, log_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path) -> Result<Child> {
|
||||||
|
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<PathBuf> {
|
||||||
|
resolve_executable_path(std::env::current_exe()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_executable_path(path: PathBuf) -> Result<PathBuf> {
|
||||||
|
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<File> {
|
||||||
|
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::<libc::ucred>() 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<Self> {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+121
-7
@@ -1,15 +1,126 @@
|
|||||||
|
mod chrome;
|
||||||
|
mod client;
|
||||||
mod colors;
|
mod colors;
|
||||||
|
mod cursor;
|
||||||
mod fonts;
|
mod fonts;
|
||||||
mod input;
|
mod input;
|
||||||
|
mod label;
|
||||||
|
mod launcher;
|
||||||
|
mod pane_name;
|
||||||
|
mod protocol;
|
||||||
mod render;
|
mod render;
|
||||||
|
mod server;
|
||||||
mod session;
|
mod session;
|
||||||
mod terminal;
|
mod terminal;
|
||||||
|
|
||||||
|
use anyhow::{Result, bail};
|
||||||
use gpui::{prelude::*, *};
|
use gpui::{prelude::*, *};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
fn main() -> anyhow::Result<()> {
|
fn main() -> Result<()> {
|
||||||
env_logger::init();
|
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<launcher::Zygote> = 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<String>) -> 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| {
|
Application::new().run(move |cx: &mut App| {
|
||||||
cx.on_window_closed(|cx| {
|
cx.on_window_closed(|cx| {
|
||||||
if cx.windows().is_empty() {
|
if cx.windows().is_empty() {
|
||||||
@@ -17,20 +128,23 @@ fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.detach();
|
.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(
|
cx.open_window(
|
||||||
WindowOptions {
|
WindowOptions {
|
||||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||||
titlebar: Some(TitlebarOptions {
|
titlebar: Some(TitlebarOptions {
|
||||||
title: Some("Terminal".into()),
|
title: Some("psyTerm".into()),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}),
|
}),
|
||||||
app_id: Some("dev.buzzert.terminal".into()),
|
window_decorations: Some(WindowDecorations::Client),
|
||||||
|
app_id: Some("dev.buzzert.psyterm".into()),
|
||||||
..Default::default()
|
..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);
|
cx.activate(true);
|
||||||
});
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -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<Range<usize>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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::<String>();
|
||||||
|
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<usize> {
|
||||||
|
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<usize> {
|
||||||
|
self.to_utf16(self.selection())
|
||||||
|
}
|
||||||
|
pub fn marked_utf16(&self) -> Option<Range<usize>> {
|
||||||
|
self.marked.clone().map(|range| self.to_utf16(range))
|
||||||
|
}
|
||||||
|
pub fn text_for_range(&self, range: Range<usize>) -> (String, Range<usize>) {
|
||||||
|
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<Range<usize>>, text: &str) {
|
||||||
|
self.replace_inner(range_utf16, text);
|
||||||
|
self.marked = None;
|
||||||
|
}
|
||||||
|
pub fn replace_and_mark(
|
||||||
|
&mut self,
|
||||||
|
range_utf16: Option<Range<usize>>,
|
||||||
|
text: &str,
|
||||||
|
selected_utf16: Option<Range<usize>>,
|
||||||
|
) {
|
||||||
|
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<Range<usize>>, text: &str) -> Range<usize> {
|
||||||
|
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<usize>) -> Range<usize> {
|
||||||
|
self.utf16_offset_for_byte(range.start)..self.utf16_offset_for_byte(range.end)
|
||||||
|
}
|
||||||
|
fn range_from_utf16(&self, range: Range<usize>) -> Range<usize> {
|
||||||
|
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<dyn Fn(Option<String>, &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<Pixels>,
|
||||||
|
last_layout: Option<ShapedLine>,
|
||||||
|
scroll: Pixels,
|
||||||
|
selecting: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenameField {
|
||||||
|
pub fn new(
|
||||||
|
initial: String,
|
||||||
|
on_finish: impl Fn(Option<String>, &mut Window, &mut App) + 'static,
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) -> 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<Self>) {
|
||||||
|
// 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<Pixels>) -> 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<Self>) {
|
||||||
|
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<Self>) {
|
||||||
|
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<Pixels>, 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<Self>) -> 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<usize>,
|
||||||
|
actual: &mut Option<Range<usize>>,
|
||||||
|
_: &mut Window,
|
||||||
|
_: &mut Context<Self>,
|
||||||
|
) -> Option<String> {
|
||||||
|
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<Self>,
|
||||||
|
) -> Option<UTF16Selection> {
|
||||||
|
Some(UTF16Selection {
|
||||||
|
range: self.editor.selection_utf16(),
|
||||||
|
reversed: self.editor.reversed(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
|
||||||
|
self.editor.marked_utf16()
|
||||||
|
}
|
||||||
|
fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||||
|
self.editor.unmark();
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
fn replace_text_in_range(
|
||||||
|
&mut self,
|
||||||
|
range: Option<Range<usize>>,
|
||||||
|
text: &str,
|
||||||
|
_: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) {
|
||||||
|
self.editor.replace(range, text);
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
fn replace_and_mark_text_in_range(
|
||||||
|
&mut self,
|
||||||
|
range: Option<Range<usize>>,
|
||||||
|
text: &str,
|
||||||
|
selected: Option<Range<usize>>,
|
||||||
|
_: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) {
|
||||||
|
self.editor.replace_and_mark(range, text, selected);
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
fn bounds_for_range(
|
||||||
|
&mut self,
|
||||||
|
range: Range<usize>,
|
||||||
|
_: Bounds<Pixels>,
|
||||||
|
_: &mut Window,
|
||||||
|
_: &mut Context<Self>,
|
||||||
|
) -> Option<Bounds<Pixels>> {
|
||||||
|
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<Pixels>,
|
||||||
|
_: &mut Window,
|
||||||
|
_: &mut Context<Self>,
|
||||||
|
) -> Option<usize> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+319
@@ -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<u8>,
|
||||||
|
},
|
||||||
|
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<String>,
|
||||||
|
},
|
||||||
|
Split {
|
||||||
|
pane: PaneId,
|
||||||
|
cwd: Option<String>,
|
||||||
|
},
|
||||||
|
FocusTab {
|
||||||
|
tab: TabId,
|
||||||
|
},
|
||||||
|
FocusPane {
|
||||||
|
pane: PaneId,
|
||||||
|
},
|
||||||
|
ClosePane {
|
||||||
|
pane: PaneId,
|
||||||
|
},
|
||||||
|
OpenWindow {
|
||||||
|
target: Option<String>,
|
||||||
|
},
|
||||||
|
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<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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<TabInfo>,
|
||||||
|
pub active_tab: TabId,
|
||||||
|
/// Only panes in the active tab are transferred. Every pane remains live on the server.
|
||||||
|
pub panes: Vec<PaneSnapshot>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct TabInfo {
|
||||||
|
pub id: TabId,
|
||||||
|
pub title: String,
|
||||||
|
pub panes: Vec<PaneId>,
|
||||||
|
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<String>,
|
||||||
|
pub cwd: String,
|
||||||
|
pub columns: u16,
|
||||||
|
pub lines: u16,
|
||||||
|
pub cell_width: u16,
|
||||||
|
pub cell_height: u16,
|
||||||
|
pub cells: Vec<Cell>,
|
||||||
|
pub selected: Vec<bool>,
|
||||||
|
pub colors: Vec<Option<Rgb>>,
|
||||||
|
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<CursorShape> 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<CursorKind> 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<T: DeserializeOwned>(reader: &mut impl Read) -> Result<T> {
|
||||||
|
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<u8> {
|
||||||
|
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::<ClientMessage>(&mut client_hello.as_slice()).unwrap(),
|
||||||
|
ClientMessage::Hello { version: 1 }
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
read_message::<ClientMessage>(&mut shutdown.as_slice()).unwrap(),
|
||||||
|
ClientMessage::Shutdown
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
read_message::<ServerMessage>(&mut server_hello.as_slice()).unwrap(),
|
||||||
|
ServerMessage::Hello {
|
||||||
|
version: 1,
|
||||||
|
server_pid: 0x1234_5678,
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
read_message::<ServerMessage>(&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::<ClientMessage>(&mut input.as_slice()).is_err());
|
||||||
|
input = 0u32.to_le_bytes().to_vec();
|
||||||
|
assert!(read_message::<ClientMessage>(&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::<ClientMessage>(&mut bytes.as_slice()).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-1
@@ -157,7 +157,13 @@ impl Renderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `origin` is the top-left terminal cell, after the view's padding.
|
/// `origin` is the top-left terminal cell, after the view's padding.
|
||||||
pub fn paint(&self, origin: Point<Pixels>, window: &mut Window, cx: &mut App) {
|
pub fn paint_with_cursor(
|
||||||
|
&self,
|
||||||
|
origin: Point<Pixels>,
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut App,
|
||||||
|
before_text: impl FnOnce(&mut Window),
|
||||||
|
) {
|
||||||
let bounds = Bounds::new(
|
let bounds = Bounds::new(
|
||||||
origin,
|
origin,
|
||||||
size(
|
size(
|
||||||
@@ -190,6 +196,7 @@ impl Renderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
before_text(window);
|
||||||
for (row_index, row) in self.rows.iter().enumerate() {
|
for (row_index, row) in self.rows.iter().enumerate() {
|
||||||
for text in &row.text {
|
for text in &row.text {
|
||||||
if text.unicode_color.is_some() {
|
if text.unicode_color.is_some() {
|
||||||
|
|||||||
+1384
File diff suppressed because it is too large
Load Diff
+42
-3
@@ -70,19 +70,32 @@ pub struct Session {
|
|||||||
// A pidfd identifies this process even after its numerical PID is reused.
|
// A pidfd identifies this process even after its numerical PID is reused.
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
process: LinuxProcess,
|
process: LinuxProcess,
|
||||||
|
// A pinned proc directory cannot silently resolve to a reused numerical PID.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
proc_directory: Option<std::fs::File>,
|
||||||
worker: Option<JoinHandle<()>>,
|
worker: Option<JoinHandle<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
pub fn new() -> Result<(Self, async_channel::Receiver<Event>)> {
|
pub fn in_directory(
|
||||||
|
directory: Option<std::path::PathBuf>,
|
||||||
|
) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||||
let program = std::env::var("SHELL")
|
let program = std::env::var("SHELL")
|
||||||
.ok()
|
.ok()
|
||||||
.filter(|shell| !shell.is_empty())
|
.filter(|shell| !shell.is_empty())
|
||||||
.unwrap_or_else(|| "/bin/sh".into());
|
.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<Event>)> {
|
fn with_shell(shell: Shell) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||||
|
Self::with_shell_and_directory(shell, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_shell_and_directory(
|
||||||
|
shell: Shell,
|
||||||
|
working_directory: Option<std::path::PathBuf>,
|
||||||
|
) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||||
let size = WindowSize {
|
let size = WindowSize {
|
||||||
num_cols: 80,
|
num_cols: 80,
|
||||||
num_lines: 24,
|
num_lines: 24,
|
||||||
@@ -100,7 +113,7 @@ impl Session {
|
|||||||
let options = Options {
|
let options = Options {
|
||||||
shell: Some(shell),
|
shell: Some(shell),
|
||||||
// None preserves the directory from which the application launched.
|
// None preserves the directory from which the application launched.
|
||||||
working_directory: None,
|
working_directory,
|
||||||
drain_on_exit: true,
|
drain_on_exit: true,
|
||||||
env: HashMap::from([
|
env: HashMap::from([
|
||||||
("TERM".into(), "xterm-256color".into()),
|
("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")?;
|
let pty = tty::new(&options, size, 0).context("Could not start the shell PTY")?;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
let process = LinuxProcess::new(pty.child().id())?;
|
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)
|
let event_loop = EventLoop::new(term.clone(), proxy.clone(), pty, true, false)
|
||||||
.context("Could not initialize PTY polling")?;
|
.context("Could not initialize PTY polling")?;
|
||||||
let sender = event_loop.channel();
|
let sender = event_loop.channel();
|
||||||
@@ -135,6 +157,8 @@ impl Session {
|
|||||||
size,
|
size,
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
process,
|
process,
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
proc_directory,
|
||||||
worker: Some(worker),
|
worker: Some(worker),
|
||||||
},
|
},
|
||||||
rx,
|
rx,
|
||||||
@@ -152,6 +176,21 @@ impl Session {
|
|||||||
self.size
|
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<std::path::PathBuf> {
|
||||||
|
#[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.
|
/// Call when receiving `Event::Wakeup`, before reading the grid for a frame.
|
||||||
pub fn acknowledge_wakeup(&self) {
|
pub fn acknowledge_wakeup(&self) {
|
||||||
self.wakeup_pending.store(false, Ordering::Release);
|
self.wakeup_pending.store(false, Ordering::Release);
|
||||||
|
|||||||
+629
-294
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user