diff options
| author | user <user@clank> | 2026-08-13 20:36:45 +0200 |
|---|---|---|
| committer | user <user@clank> | 2026-08-13 20:36:45 +0200 |
| commit | 91f40dccd9def02d147ea41615f7bc159cb306a6 (patch) | |
| tree | 525c568778860b404620ff6d4581e91cb5c07357 | |
| parent | sl0p: the plugins we ship do not ask for permission (diff) | |
| download | sl0ppi-91f40dccd9def02d147ea41615f7bc159cb306a6.tar.gz sl0ppi-91f40dccd9def02d147ea41615f7bc159cb306a6.tar.xz sl0ppi-91f40dccd9def02d147ea41615f7bc159cb306a6.zip | |
sl0p(bar): a new-tab button, and margins that match the pane gap
First pass of the status bar overhaul, in the zjstatus fork plus the layout
that configures it.
margin_left / margin_right: the bar is a full-width pane while every pane above
it is inset by the pane gap, so its ends stuck out past every frame on screen.
The margins are applied by rendering into an inset viewport (inset_state),
which is the same thing click positions are translated by -- so what is drawn
and what is clickable come from one definition. That is the split button's
lesson applied before shipping rather than after.
{new_tab}: a clickable button that opens a tab and focuses it, with no name and
no cwd, i.e. exactly what the `n` binding in TAB mode does. Clicking a tab
already switches to it and double-clicking renames it; making one was the hole
in the strip. Rendering and hit-testing are the same measured string here, so
the button covers exactly the columns it draws.
Both keys are inert when unset, so an unmodified zjstatus config renders
identically.
packaging/checks/status-bar-live.py reads the bar off a real session and
asserts it spans exactly the columns the pane frames span, clicks the + and
expects one more tab, then clicks beside it and expects none. Confirmed by
setting the margins to 0 and watching the span assertion fail: (0, 99) against
the frames' (2, 97).
The check counts painted cells rather than ink, because a bar segment begins
with a padding space inside its coloured pill -- strip the colour and the left
edge reads one column off, which is half the margin being measured.
| -rw-r--r-- | FORKS.md | 17 | ||||
| -rw-r--r-- | Makefile | 1 | ||||
| -rw-r--r-- | config/layouts/default.kdl | 22 | ||||
| -rw-r--r-- | docs/roadmap.md | 42 | ||||
| -rwxr-xr-x | packaging/checks/status-bar-live.py | 296 | ||||
| -rw-r--r-- | sl0pstatus/src/bin/zjstatus.rs | 5 | ||||
| -rw-r--r-- | sl0pstatus/src/config.rs | 187 | ||||
| -rw-r--r-- | sl0pstatus/src/widgets/mod.rs | 1 | ||||
| -rw-r--r-- | sl0pstatus/src/widgets/new_tab.rs | 87 |
9 files changed, 656 insertions, 2 deletions
@@ -56,7 +56,7 @@ monorepo is authoritative for what ships. | upstream version | `0.24.0` | | upstream base commit | `74f36b4` — *chore: bump version to v0.24.0*, 2026-07-15 | | lives at | `sl0pstatus/` | -| patches on top | 1 commit (`sl0p: double-click a tab to rename it`) | +| patches on top | 2 commits (`sl0p: double-click a tab to rename it`, `sl0p: a new-tab button and margins that match the pane gap`) | | builds to | `zjstatus.wasm` (cargo package name is still `zjstatus`) | | standalone repo | `ssh://git@git.sl0p.foo:39327/srv/git/sl0pstatus.git`, branch `sl0p` | @@ -69,6 +69,21 @@ sl0ppij's in-tree one — the plugin API is stable across that gap. Our build reproduces the previously hand-built `zjstatus.wasm` in the live config dir byte-for-byte. +Fork-only config keys, all inert when unset (upstream renders identically): + +| key | what it does | +|---|---| +| `margin_left` / `margin_right` | blank columns at each end, so the bar lines up with panes inset by the pane gap | +| `new_tab` | format for the `{new_tab}` widget, a clickable button that opens and focuses a tab | + +**Its tests do not run under `make test`.** The crate builds for +`wasm32-wasip1` and `.cargo/config.toml` points the test runner at `wasmtime`, +which is not installed here. Run them against the host instead: + +```bash +cd sl0pstatus && cargo test --lib --target x86_64-unknown-linux-gnu +``` + Same rebase procedure as sl0ppij, with `sl0pstatus/` as the prefix. ## Pinned, not forked @@ -105,6 +105,7 @@ check-live: dev ## Drive real sessions and check what the UI actually does packaging/checks/split-button-live.py $(FORK)/target/fastdev/$(BIN_NAME) packaging/checks/split-button-live.py $(FORK)/target/fastdev/$(BIN_NAME) config/config.kdl packaging/checks/plugin-permissions-live.py $(FORK)/target/fastdev/$(BIN_NAME) + packaging/checks/status-bar-live.py $(FORK)/target/fastdev/$(BIN_NAME) ##@ Package diff --git a/config/layouts/default.kdl b/config/layouts/default.kdl index 81ccb53..4d65052 100644 --- a/config/layouts/default.kdl +++ b/config/layouts/default.kdl @@ -38,10 +38,23 @@ layout { color_red "#ff4f58" // 255 79 88 exit_code_error format_left "{mode}{session}" - format_center "{tabs}" + format_center "{tabs}{new_tab}" format_right "{command_git} {datetime}" format_space "#[bg=$bg]" + // ── line up with the panes ────────────────────────────────── + // sl0p fork only. The bar is a full-width pane, but every pane + // above it is inset by the pane gap, so without this the bar's + // ends stick out past every frame on screen. + // + // Keep in step with config.kdl's `gap` x `gap_aspect` + // (1 x 2 = 2 columns). Deliberately not derived automatically: + // the plugin cannot see that config, and guessing it from pane + // geometry would be a magic trick that breaks on the first + // borderless pane. + margin_left "2" + margin_right "2" + // hide the least-important part instead of letting the three // sections collide on a narrow terminal. Priority: center // (tabs) > left (mode) > right (git/clock is the first to go). @@ -99,6 +112,13 @@ layout { tab_fullscreen_indicator "[] " tab_floating_indicator "^ " + // ── new tab button ───────────────────────────────────────── + // sl0p fork only ({new_tab}). Clicking it opens a tab with the + // default layout and focuses it -- the mouse spelling of the + // `n` binding in TAB mode. Styled like an inactive tab so it + // reads as the next thing in the strip rather than as chrome. + new_tab "#[bg=$bg,fg=$dim] + " + // ── git branch of the FOCUSED pane's cwd ──────────────────── // {focused_pane_cwd} (zjstatus 0.24.0+) makes this track // whichever pane you are in rather than the session's cwd. diff --git a/docs/roadmap.md b/docs/roadmap.md index ef71070..3588e95 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -293,6 +293,48 @@ runs without the prompt, then launches the *same file* from outside that dir and asserts it still asks. Confirmed by disabling the rule and watching the first half fail with the exact "asks permission to ... Allow? (y/n)" screen. +## Status bar: first pass of the overhaul + +Two things, both in `sl0pstatus/` (our zjstatus fork) plus the layout that +configures it: + +- **`margin_left` / `margin_right`** — the bar is a full-width pane while every + pane above it is inset by the pane gap, so its ends stuck out past every frame + on screen. The margins pull its content in. They are applied by rendering the + bar into an inset viewport (`ModuleConfig::inset_state`), which is also what + click positions are translated by, so the drawing and the hit-testing cannot + disagree — the lesson from the split button, applied up front this time. +- **`{new_tab}`** — a clickable button that opens a tab and focuses it, the + mouse spelling of the `n` binding in TAB mode. Clicking a tab already switches + to it and double-clicking renames it; making one was the gap. + +Keep `margin_*` in step with `config.kdl`'s `gap` x `gap_aspect` (1 x 2 = 2). +The plugin cannot see that config, and inferring it from pane geometry would +break on the first borderless pane. + +**How to re-run the check**: + +```bash +make check-live # includes packaging/checks/status-bar-live.py +``` + +It reads the bar off a real session and asserts it spans *exactly* the columns +the pane frames span (2..97 at 100 columns), then clicks the `+` and expects one +more tab, and clicks beside it and expects none. Confirmed by setting the +margins to 0 and watching the span assertion fail with `(0, 99)` against the +frames' `(2, 97)`. + +That check tracks painted cells, not ink: a bar segment starts with a padding +space inside its coloured pill, so stripping colour puts the left edge one +column off — the exact size of the thing being measured. + +### Still open on the bar + +The request was "quite a bit of an overhaul", and this is the first pass. Not +done, and worth deciding before more work: whether the bar should be a framed +box in the pane style (rounded corners, its own gap) rather than a single line; +whether it should be multi-row; what else belongs on it. + ## Standing risks **`sl0ppij/target` is a symlink to `~/lol/zellij/target`.** Introduced when the diff --git a/packaging/checks/status-bar-live.py b/packaging/checks/status-bar-live.py new file mode 100755 index 0000000..5a63922 --- /dev/null +++ b/packaging/checks/status-bar-live.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""Live check: the status bar lines up with the panes, and its new-tab button +makes a tab. + +Both are things you can only see on a real session. The bar is a plugin +rendering into a full-width pane, so nothing in the layout file says where its +first column lands -- and the button is a click surface whose only definition of +"where" is the string it drew. + +Usage: status-bar-live.py [path-to-sl0ppij] [path-to-zjstatus.wasm] +""" + +import fcntl +import json +import os +import pty +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import termios +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.abspath(os.path.join(HERE, "../..")) +BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else f"{REPO}/sl0ppij/target/fastdev/sl0ppij") +WASM = os.path.abspath( + sys.argv[2] + if len(sys.argv) > 2 + else f"{REPO}/sl0pstatus/target/wasm32-wasip1/release/zjstatus.wasm" +) +ROWS, COLS = 30, 100 +SESSION = f"sl0ptest-bar-{os.getpid()}" + +# the horizontal pane gap the bar is supposed to match: `gap` x `gap_aspect` +EXPECTED_MARGIN = 2 + + +def screen_cells(raw): + """Very small VT: absolute moves, erases, printable runs, and whether each + cell has a background colour set. + + The background matters. A bar segment usually starts with a padding space + inside its coloured pill, so "where does the bar begin" is a question about + painted cells, not about ink -- strip the colour and the answer is off by + one, which is exactly the size of the thing being measured. + """ + grid, row, col, i, bg = {}, 0, 0, 0, False + while i < len(raw): + ch = raw[i] + if ch == "\x1b": + m = re.match(r"\x1b\[([0-9;?]*)([a-zA-Z])", raw[i:]) + if m: + nums = [int(n) for n in m.group(1).replace("?", "").split(";") if n != ""] + verb, first = m.group(2), (nums[0] if nums else 0) + if verb == "m": + # 0 = reset, 49 = default background, 40-47/100-107 = set, + # 48 = extended (48;5;n or 48;2;r;g;b) + if not nums or 0 in nums or 49 in nums: + bg = False + if any(n == 48 or 40 <= n <= 47 or 100 <= n <= 107 for n in nums): + bg = True + if verb in "Hf": + row = (nums[0] - 1) if nums else 0 + col = (nums[1] - 1) if len(nums) > 1 else 0 + elif verb == "G": + col = max(0, first - 1) + elif verb == "J": + if first == 2: + grid.clear() + else: + for c in range(col, COLS): + grid.pop((row, c), None) + for r in range(row + 1, ROWS): + for c in range(COLS): + grid.pop((r, c), None) + elif verb == "K": + span = range(col, COLS) if first == 0 else range(0, COLS) + for c in span: + grid.pop((row, c), None) + i += m.end() + continue + m = re.match(r"\x1b][^\x07\x1b]*(\x07|\x1b\\)", raw[i:]) + if m: + i += m.end() + continue + i += 1 + continue + if ch == "\r": + col = 0 + elif ch == "\n": + row, col = row + 1, 0 + elif ch >= " ": + grid[(row, col)] = (ch, bg) + col += 1 + i += 1 + return grid + + +def screen_rows(raw): + grid = screen_cells(raw) + return [ + "".join(grid.get((r, c), (" ", False))[0] for c in range(COLS)) for r in range(ROWS) + ] + + +def painted_span(grid, row): + """(first, last) column of `row` that is drawn on: ink or background.""" + painted = [ + c + for c in range(COLS) + if (lambda cell: cell[0] not in (" ", "") or cell[1])(grid.get((row, c), (" ", False))) + ] + return (painted[0], painted[-1]) if painted else (None, None) + + +def repaint(fd): + """Force a full redraw, discard the intermediate one, read only the final.""" + fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", ROWS, COLS - 1, 0, 0)) + time.sleep(0.8) + try: + while os.read(fd, 1 << 20): + pass + except (BlockingIOError, OSError): + pass + fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", ROWS, COLS, 0, 0)) + return "" + + +def read_screen(fd, buffered="", seconds=8, until=None, quiet_for=0.7): + deadline, last = time.time() + seconds, time.time() + while time.time() < deadline: + time.sleep(0.15) + try: + chunk = os.read(fd, 1 << 20).decode("utf8", "replace") + except BlockingIOError: + chunk = "" + except OSError: + break + if chunk: + buffered, last = buffered + chunk, time.time() + continue + if until and until(screen_rows(buffered)): + break + if buffered and time.time() - last >= quiet_for: + break + return buffered, screen_rows(buffered) + + +def bar_row(rows): + """The bar is the last non-blank row: the tab strip and the clock are on it.""" + for y in range(len(rows) - 1, -1, -1): + if rows[y].strip(): + return y, rows[y] + return None, "" + + +def main(): + for path in (BIN, WASM): + if not os.path.isfile(path): + print(f"FAIL: missing {path}") + return 1 + + tmp = tempfile.mkdtemp(prefix="sl0p-bar-") + config_dir = os.path.join(tmp, "config") + shutil.copytree(os.path.join(REPO, "config"), config_dir) + plugins = os.path.join(config_dir, "plugins") + os.makedirs(plugins, exist_ok=True) + shutil.copy(WASM, os.path.join(plugins, "zjstatus.wasm")) + # the shipped config points at ~/.config/sl0ppij; this run is isolated + for name in ("config.kdl", "layouts/default.kdl", "layouts/default.swap.kdl"): + path = os.path.join(config_dir, name) + if not os.path.isfile(path): + continue + with open(path) as f: + text = f.read() + with open(path, "w") as f: + f.write(text.replace("~/.config/sl0ppij", config_dir)) + + env = dict(os.environ) + env.update( + { + "SL0PPIJ_SOCKET_DIR": os.path.join(tmp, "sock"), + "SL0PPIJ_CONFIG_FILE": os.path.join(config_dir, "config.kdl"), + "SL0PPIJ_CONFIG_DIR": config_dir, + "SL0PPIJ_CACHE_DIR": os.path.join(tmp, "cache"), + "XDG_CACHE_HOME": os.path.join(tmp, "cache"), + "TERM": "xterm-256color", + "SHELL": "/bin/sh", + } + ) + + pid, fd = pty.fork() + if pid == 0: + os.execvpe(BIN, [BIN, "-s", SESSION], env) + fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", ROWS, COLS, 0, 0)) + os.set_blocking(fd, False) + + failures = [] + try: + _, rows = read_screen(fd, "", seconds=25, until=lambda r: any("Tab #1" in x for x in r)) + raw, rows = read_screen(fd, repaint(fd), seconds=10) + grid = screen_cells(raw) + y, bar = bar_row(rows) + if y is None or "Tab #1" not in bar: + failures.append("no status bar on screen") + print("\n".join(f"{i:02d}|{r}" for i, r in enumerate(rows))) + return failures + print(f"bar row {y}: {bar.rstrip()!r}") + + # 1. the bar occupies exactly the columns the pane frames do + bar_span = painted_span(grid, y) + frame_rows = [i for i, r in enumerate(rows) if r.lstrip().startswith(("╭", "┌"))] + frame_spans = [ + (r.index(r.lstrip()[0]), len(r.rstrip()) - 1) for i, r in enumerate(rows) if i in frame_rows + ] + frame_span = ( + min(s[0] for s in frame_spans), + max(s[1] for s in frame_spans), + ) if frame_spans else (None, None) + print(f"bar spans columns {bar_span}, pane frames span {frame_span}") + if bar_span != (EXPECTED_MARGIN, COLS - 1 - EXPECTED_MARGIN): + failures.append( + f"bar spans {bar_span}, expected " + f"{(EXPECTED_MARGIN, COLS - 1 - EXPECTED_MARGIN)}" + ) + if frame_span[0] is not None and bar_span != frame_span: + failures.append(f"bar spans {bar_span} but the pane frames span {frame_span}") + + # 2. the new-tab button makes a tab + def tabs(): + out = subprocess.run( + [BIN, "-s", SESSION, "action", "list-tabs", "--json"], + env=env, + capture_output=True, + text=True, + ).stdout + try: + return len(json.loads(out)) + except Exception: + return out.count('"name"') or len(out.strip().splitlines()) + + plus = bar.rfind(" + ") + if plus < 0: + failures.append("no new-tab button drawn on the bar") + return failures + button_col = plus + 1 + print(f"new-tab button at column {button_col}") + before = tabs() + os.write(fd, f"\x1b[<0;{button_col + 1};{y + 1}M".encode()) + os.write(fd, f"\x1b[<0;{button_col + 1};{y + 1}m".encode()) + time.sleep(2) + after = tabs() + print(f"tabs: {before} -> {after}") + if after != before + 1: + failures.append(f"clicking the new-tab button did not add a tab ({before} -> {after})") + + # 3. and a click just left of the tab strip must not: the button is a + # button, not "anywhere on the right half of the bar" + before = tabs() + os.write(fd, f"\x1b[<0;{max(1, plus - 2)};{y + 1}M".encode()) + os.write(fd, f"\x1b[<0;{max(1, plus - 2)};{y + 1}m".encode()) + time.sleep(1.5) + if tabs() != before: + failures.append("a click beside the button also made a tab") + return failures + finally: + subprocess.run([BIN, "-s", SESSION, "kill-session"], env=env, capture_output=True) + try: + os.close(fd) + except OSError: + pass + os.waitpid(pid, os.WNOHANG) + time.sleep(1) + ps = subprocess.run(["ps", "-eo", "pid,comm,args"], capture_output=True, text=True).stdout + for line in ps.splitlines(): + fields = line.split(None, 2) + if len(fields) == 3 and fields[1] == os.path.basename(BIN) and tmp in fields[2]: + try: + os.kill(int(fields[0]), 15) + except (ProcessLookupError, ValueError, PermissionError): + pass + shutil.rmtree(tmp, ignore_errors=True) + + +if __name__ == "__main__": + problems = main() + if problems == 1: + sys.exit(1) + for p in problems: + print(f"FAIL: {p}") + if not problems: + print("ok: the bar lines up with the panes and its + makes a tab") + sys.exit(1 if problems else 0) diff --git a/sl0pstatus/src/bin/zjstatus.rs b/sl0pstatus/src/bin/zjstatus.rs index f9d95c7..d3b7beb 100644 --- a/sl0pstatus/src/bin/zjstatus.rs +++ b/sl0pstatus/src/bin/zjstatus.rs @@ -11,6 +11,7 @@ use zjstatus::{ command::{CommandResult, CommandWidget}, datetime::DateTimeWidget, mode::ModeWidget, + new_tab::NewTabWidget, notification::NotificationWidget, pipe::PipeWidget, session::SessionWidget, @@ -411,6 +412,10 @@ fn register_widgets(configuration: &BTreeMap<String, String>) -> BTreeMap<String ); widget_map.insert("tabs".to_owned(), Arc::new(TabsWidget::new(configuration))); widget_map.insert( + "new_tab".to_owned(), + Arc::new(NewTabWidget::new(configuration)), + ); + widget_map.insert( "notifications".to_owned(), Arc::new(NotificationWidget::new(configuration)), ); diff --git a/sl0pstatus/src/config.rs b/sl0pstatus/src/config.rs index 473ced0..9748abf 100644 --- a/sl0pstatus/src/config.rs +++ b/sl0pstatus/src/config.rs @@ -96,6 +96,19 @@ pub struct ModuleConfig { pub border: BorderConfig, pub format_precedence: Vec<Part>, pub hide_on_overlength: bool, + /// sl0p fork: blank columns kept clear at each end of the bar. + /// + /// The bar is a full-width pane, but the panes above it are inset by the + /// configured pane gap, so a bar that starts in column 0 does not line up + /// with anything -- its ends stick out past every frame on screen. These + /// pull its content in to match. + /// + /// Set them to the horizontal gap, which in sl0ppi's config is + /// `gap` x `gap_aspect` (1 x 2 = 2 columns). They are left UNSTYLED on + /// purpose: the space between panes is terminal background, and the bar's + /// margins are the same space. + pub margin_left: usize, + pub margin_right: usize, } @@ -198,7 +211,16 @@ impl ModuleConfig { let border_config = parse_border_config(config).unwrap_or_default(); + let margin = |key: &str| -> usize { + config + .get(key) + .and_then(|value| value.parse::<usize>().ok()) + .unwrap_or(0) + }; + Ok(Self { + margin_left: margin("margin_left"), + margin_right: margin("margin_right"), left_parts_config: left_parts_config.to_owned(), left_parts: parts_from_config(Some(&left_parts_config.to_owned()), config), center_parts_config: center_parts_config.to_owned(), @@ -217,6 +239,18 @@ impl ModuleConfig { }) } + /// The bar's own viewport: the pane it lives in, less the margins. + /// + /// Everything downstream -- spacing, trimming, widgets, click positions -- + /// works in these coordinates, so the margins exist in exactly one place + /// and cannot be applied to the drawing but forgotten in the hit-testing. + fn inset_state(&self, mut state: ZellijState) -> ZellijState { + state.cols = state + .cols + .saturating_sub(self.margin_left + self.margin_right); + state + } + pub fn handle_mouse_action( &mut self, state: ZellijState, @@ -233,6 +267,17 @@ impl ModuleConfig { Mouse::Hover(_, _) => return, }; + // a click in the margin is a click on nothing, and must not be counted + // as one on the first widget + if click_pos < self.margin_left { + return; + } + let click_pos = click_pos - self.margin_left; + let state = self.inset_state(state); + if click_pos >= state.cols { + return; + } + let is_double_click = register_click_for_double_click( &mut self.last_left_click, &mouse, @@ -393,6 +438,31 @@ impl ModuleConfig { state: ZellijState, widget_map: BTreeMap<String, Arc<dyn Widget>>, ) -> String { + let bar = self.render_bar_content(self.inset_state(state), widget_map); + if self.margin_left == 0 && self.margin_right == 0 { + return bar; + } + // Every line of the bar is inset, not just the first: with a border + // enabled the output is two lines, and a rule that ran the full width + // under a margined bar would look like a mistake. + bar.split('\n') + .map(|line| { + format!( + "{}{}{}", + " ".repeat(self.margin_left), + line, + " ".repeat(self.margin_right) + ) + }) + .collect::<Vec<_>>() + .join("\n") + } + + fn render_bar_content( + &mut self, + state: ZellijState, + widget_map: BTreeMap<String, Arc<dyn Widget>>, + ) -> String { if self.left_parts.is_empty() && self.center_parts.is_empty() && self.right_parts.is_empty() { return "No configuration found. See https://github.com/dj95/zjstatus/wiki/3-%E2%80%90-Configuration for more info".to_string(); @@ -694,6 +764,123 @@ mod sl0p_double_click_tests { )); } + /// A widget that renders a fixed label and records where it was clicked, + /// so a test can ask "which column of the SCREEN reaches column 0 of this + /// widget". + #[derive(Default)] + struct SpyWidget { + label: String, + clicks: std::sync::Mutex<Vec<usize>>, + } + + impl Widget for SpyWidget { + fn process(&self, _name: &str, _state: &ZellijState) -> String { + self.label.clone() + } + fn process_click(&self, _n: &str, _s: &ZellijState, pos: usize, _d: bool) { + self.clicks.lock().unwrap().push(pos); + } + } + + fn bar_with_margins(left: usize, right: usize) -> (ModuleConfig, Arc<SpyWidget>) { + let mut config = BTreeMap::new(); + config.insert("format_left".to_owned(), "{spy}".to_owned()); + config.insert("margin_left".to_owned(), left.to_string()); + config.insert("margin_right".to_owned(), right.to_string()); + let module_config = ModuleConfig::new(&config).unwrap(); + let spy = Arc::new(SpyWidget { + label: "[button]".to_owned(), + clicks: Default::default(), + }); + (module_config, spy) + } + + fn spy_map(spy: Arc<SpyWidget>) -> BTreeMap<String, Arc<dyn Widget>> { + let mut widget_map = BTreeMap::<String, Arc<dyn Widget>>::new(); + widget_map.insert("spy".to_owned(), spy); + widget_map + } + + fn state_with_cols(cols: usize) -> ZellijState { + ZellijState { + cols, + ..Default::default() + } + } + + #[test] + fn margins_inset_the_bar_at_both_ends() { + let (mut config, spy) = bar_with_margins(2, 2); + let rendered = config.render_bar(state_with_cols(40), spy_map(spy)); + assert!( + rendered.starts_with(" [button]"), + "left margin missing: {rendered:?}" + ); + assert!( + rendered.ends_with(" "), + "right margin missing: {rendered:?}" + ); + assert_eq!( + console::measure_text_width(&rendered), + 40, + "the bar must still fill its pane: {rendered:?}" + ); + } + + #[test] + fn a_margined_widget_is_clicked_where_it_is_drawn() { + // the whole point of routing both through inset_state: the button moves + // right by the margin, so the columns that activate it must move too + let (mut config, spy) = bar_with_margins(2, 2); + let widget_map = spy_map(spy.clone()); + let rendered = config.render_bar(state_with_cols(40), widget_map.clone()); + let drawn_at = rendered.find("[button]").expect("button not drawn"); + + config.handle_mouse_action( + state_with_cols(40), + Mouse::LeftClick(0, drawn_at), + widget_map, + ); + + assert_eq!( + *spy.clicks.lock().unwrap(), + vec![0], + "clicking the button's first drawn column should hit its column 0" + ); + } + + #[test] + fn clicks_in_the_margin_hit_nothing() { + let (mut config, spy) = bar_with_margins(2, 2); + let widget_map = spy_map(spy.clone()); + + for column in [0, 1] { + config.handle_mouse_action( + state_with_cols(40), + Mouse::LeftClick(0, column), + widget_map.clone(), + ); + } + + assert!( + spy.clicks.lock().unwrap().is_empty(), + "the margin is not part of any widget: {:?}", + spy.clicks.lock().unwrap() + ); + } + + #[test] + fn without_margins_nothing_changes() { + // upstream behaviour has to be untouched when the option is unset + let (mut config, spy) = bar_with_margins(0, 0); + let widget_map = spy_map(spy.clone()); + let rendered = config.render_bar(state_with_cols(40), widget_map.clone()); + assert!(rendered.starts_with("[button]"), "{rendered:?}"); + + config.handle_mouse_action(state_with_cols(40), Mouse::LeftClick(0, 0), widget_map); + assert_eq!(*spy.clicks.lock().unwrap(), vec![0]); + } + #[test] fn a_triple_click_does_not_fire_a_second_rename() { let mut last = None; diff --git a/sl0pstatus/src/widgets/mod.rs b/sl0pstatus/src/widgets/mod.rs index aa60cc3..8c72ed1 100644 --- a/sl0pstatus/src/widgets/mod.rs +++ b/sl0pstatus/src/widgets/mod.rs @@ -1,6 +1,7 @@ pub mod command; pub mod datetime; pub mod mode; +pub mod new_tab; pub mod notification; pub mod pipe; pub mod session; diff --git a/sl0pstatus/src/widgets/new_tab.rs b/sl0pstatus/src/widgets/new_tab.rs new file mode 100644 index 0000000..deaea84 --- /dev/null +++ b/sl0pstatus/src/widgets/new_tab.rs @@ -0,0 +1,87 @@ +use std::collections::BTreeMap; + +use zellij_tile::shim::new_tab; + +use crate::{config::ZellijState, render::FormattedPart, widgets::widget::Widget}; + +/// sl0p fork: a clickable "new tab" button for the bar. +/// +/// The tab strip is already a mouse surface -- clicking a tab switches to it, +/// double-clicking renames it -- but the one thing you cannot do with the mouse +/// is make a new one, which is the operation a tab strip in every other +/// application offers. `{new_tab}` fills that hole. +/// +/// Configured like every other widget: +/// +/// ```kdl +/// new_tab "#[bg=$bg,fg=$dim] + " +/// ``` +/// +/// Rendering and hit-testing both come from this one string: the button covers +/// exactly the columns it draws, because `process_widget_click` measures the +/// same rendered output it placed. There is nothing here that can drift out of +/// alignment with what you see -- unlike a pane frame's button, whose geometry +/// is computed twice. +pub struct NewTabWidget { + format: FormattedPart, +} + +impl NewTabWidget { + pub fn new(config: &BTreeMap<String, String>) -> Self { + let format = match config.get("new_tab") { + Some(format) => FormattedPart::from_format_string(format, config), + // A default that is visible without any configuration: the widget + // is only rendered if the user puts {new_tab} in a format string, + // so an empty button would just be a confusing dead zone. + None => FormattedPart::from_format_string(" + ", config), + }; + + Self { format } + } +} + +impl Widget for NewTabWidget { + fn process(&self, _name: &str, _state: &ZellijState) -> String { + self.format.format_string(&self.format.content) + } + + fn process_click(&self, _name: &str, _state: &ZellijState, _pos: usize, _is_double_click: bool) { + // No name and no cwd: the same tab the `n` keybinding makes, so the + // button is the mouse spelling of a thing that already exists rather + // than a second, subtly different way to make a tab. The new tab takes + // focus, which is what makes this a button and not a counter. + new_tab(None::<String>, None::<String>); + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn renders_the_configured_button() { + let mut config = BTreeMap::new(); + config.insert("new_tab".to_owned(), "#[fg=#ffffff] + ".to_owned()); + let widget = NewTabWidget::new(&config); + + let output = widget.process("new_tab", &ZellijState::default()); + + assert!( + output.contains(" + "), + "expected the button text in {output:?}" + ); + } + + #[test] + fn renders_something_clickable_without_configuration() { + // an unconfigured {new_tab} must not be a zero-width click target + let widget = NewTabWidget::new(&BTreeMap::new()); + + let output = widget.process("new_tab", &ZellijState::default()); + + assert!( + console::measure_text_width(&output) > 0, + "the default button has no width: {output:?}" + ); + } +} |
