diff --git a/plugins/examples/pane-hints/README.md b/plugins/examples/pane-hints/README.md new file mode 100644 index 0000000..44d6498 --- /dev/null +++ b/plugins/examples/pane-hints/README.md @@ -0,0 +1,77 @@ +# pane-hints + +Show large numbers **over the panes themselves**, then focus a pane by number. +This window-only plugin uses temporary CSS hints and a small native input bar, +not a pane list. Tested with desktop Tern 0.9.4. + +1. On macOS, press **Ctrl+Cmd+G** together, or run **Show pane numbers** from the command palette. +2. Type a number displayed over a pane and press **Enter** to focus it. +3. **Escape** cancels and removes the numbers without changing focus. + +![Large numeric hints on two tiled panes and a picture-in-picture pane](screenshots/pane-hints.png) + +Numbers follow the split tree (left/top before right/bottom), then floating +panes in their layout order. Other tabs and parked panes are excluded. Zoomed +layouts only offer the focused tiled pane and floating panes; hidden panes +retain their positions, so visible numbers need not start at 1. Multi-digit +numbers are accepted (`1`, `10`, `12`); leading zeroes also work. + +The original pane IDs are captured when hints open. Closing/creating a pane, +changing tabs, or changing pane focus invalidates the hints. A remaining +input bar can be dismissed with Escape. Selection also rechecks the layout +order and zoom state before focusing. A reorder that preserves focus has no +SDK event: its hints may remain until Enter, at which point the stale choice +is rejected rather than redirected to another program. No global number or Escape bindings are installed, and selection +keys are consumed by the native input bar, not the terminal. + +## Install from a checkout + +```sh +tern plugin link /path/to/tern-sdk/plugins/examples/pane-hints +``` + +To add an optional tmux-style **Ctrl+A → q** shortcut, merge this entry into +Tern's existing `settings.json`. The default **Ctrl+Cmd+G** remains available: + +```json +{ + "keybinds": { + "ctrl+a>q": "plugin.pane-hints.show" + } +} +``` + +## Implementation limits + +This is a prototype for +[stencil-hq/tern-sdk#103](https://github.com/stencil-hq/tern-sdk/issues/103). +`tern.css` can render generated content over existing panes, but the native +chrome selectors and their ordering are not a stable plugin API. The current +implementation targets `#panel > .tn-stage > section.tn-pane`, in the all-window `session:panes()` order, including hidden tabs and parked +panes. The displayed numbers independently follow the active split tree and floats. It uses `:first-of-type` for the first hint +because `:nth-of-type(1)` did not draw the first generated glyph in the tested +build. Recheck the rendered numbers and their targets after Tern upgrades. + +The public prompt API has no change callback or dismiss handle, so choosing +still requires **Enter** and there is no automatic timeout. A native pane-hint +action would remove the private CSS dependency and could support immediate +single-key selection. Parked-pane restoration is not included. + +## Verify + +`verify.py` starts an isolated desktop window and daemon under a temporary +directory and leaves the normal Tern profile alone. It requires Python 3, Pillow (`python3 -m pip install Pillow`), +and a logged-in Tern desktop installation; allow two to three minutes. + +```sh +python3 plugins/examples/pane-hints/verify.py +luau-lsp analyze --definitions=@tern=plugins/tern.d.luau \ + plugins/examples/pane-hints/window.luau +``` + +The integration check covers keyboard invocation, no-list presentation, +selection/cancellation, selection mapping with 12 panes, zoom, floating panes, other-tab +and parked-pane exclusion, disappearing targets, and selection-key isolation. +Rendered-image checks verify large bright glyphs at visible pane centers, +including a tab whose panes follow hidden and parked nodes. Also manually +inspect a mixed split and floating layout to verify the actual digit values. diff --git a/plugins/examples/pane-hints/plugin.toml b/plugins/examples/pane-hints/plugin.toml new file mode 100644 index 0000000..8e927d3 --- /dev/null +++ b/plugins/examples/pane-hints/plugin.toml @@ -0,0 +1,6 @@ +schema = 1 +id = "pane-hints" +name = "Pane Hints" +version = "0.2.0" +description = "Show large numbers over panes and select one by number." +window = "window.luau" diff --git a/plugins/examples/pane-hints/screenshots/pane-hints.png b/plugins/examples/pane-hints/screenshots/pane-hints.png new file mode 100644 index 0000000..a5d49a0 Binary files /dev/null and b/plugins/examples/pane-hints/screenshots/pane-hints.png differ diff --git a/plugins/examples/pane-hints/verify.py b/plugins/examples/pane-hints/verify.py new file mode 100644 index 0000000..70e5302 --- /dev/null +++ b/plugins/examples/pane-hints/verify.py @@ -0,0 +1,241 @@ +"""Exercise the real plugin in a disposable desktop Tern profile (Python 3).""" +import json +import os +from pathlib import Path +import shutil +import shlex +import subprocess +import tempfile +import time +from unittest.mock import Mock, patch + +from PIL import Image + +TERN = shutil.which("tern") +assert TERN, "Put the Tern desktop CLI on PATH" +PLUGIN = Path(__file__).resolve().parent + + +def wait_for(predicate, seconds=15): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.1) + raise AssertionError("Timed out waiting for Tern") + + +def stop_window(process, env, endpoint): + # A failed graceful shutdown must not skip reaping our GUI child. + try: + for args in ([TERN, "kill", "session", "Default"], + [TERN, "ctl", "--control", endpoint, "quit"]): + try: + subprocess.run(args, env=env, capture_output=True, timeout=15) + except subprocess.TimeoutExpired: + print("WARN: graceful test shutdown timed out", flush=True) + finally: + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + +def check_cleanup_timeout(): + child = Mock() + child.wait.side_effect = [subprocess.TimeoutExpired("test-window", 10), + subprocess.TimeoutExpired("test-window", 10), 0] + with patch.object(subprocess, "run", side_effect=subprocess.TimeoutExpired("shutdown", 15)) as run: + stop_window(child, {}, "/unused-test-endpoint") + assert run.call_count == 2 + child.terminate.assert_called_once_with() + child.kill.assert_called_once_with() + assert child.wait.call_count == 3 + print("PASS: shutdown timeouts still terminate and reap the test window", flush=True) + + +def main(): + with tempfile.TemporaryDirectory(prefix="tern-pane-hints-test-") as temp: + profile = Path(temp) + endpoint = str(profile / "window.sock") + env = dict(os.environ) + for key in list(env): + if key.startswith("TERN_"): + del env[key] + env.update(TERN_CONFIG_DIR=temp, TERN_DAEMON_SOCKET=str(profile / "daemon.sock"), + STENCIL_LOG_DIR=str(profile / "logs")) + (profile / "plugins").mkdir() + (profile / "plugins/pane-hints.path").write_text(str(PLUGIN) + "\n") + (profile / "settings.json").write_text(json.dumps({"pane_headers": "Always"})) + + def ctl(*args): + result = subprocess.run([TERN, "ctl", "--control", endpoint, *args], + env=env, capture_output=True, text=True, + check=False, timeout=25) + assert result.returncode == 0, (args, result.stdout, result.stderr) + reply = json.loads(result.stdout) + assert reply.get("ok"), reply + return reply + + def state(): + return ctl("state") + + def hints(expected=None): + ctl("key", "Ctrl+Meta+g") + wait_for(lambda: state()["picker"] is not None) + assert state()["picker"]["mode"] == "prompt" + assert ctl("tree", ".tn-pl-list")["count"] == 0, "No pane list should be shown" + sheet = next(s for s in ctl("css")["sheets"] + if s["name"] == "plugin:local:pane-hints:hints") + if expected is None: + assert sheet["rules"] > 2 + else: + # Use the fixture's known count, not transient animation nodes. + assert sheet["rules"] == expected + 2, ("Unexpected numbered rules", sheet["rules"], expected) + + def check_visible_numbers(): + # Generated glyphs are absent from the accessibility/layout text. + # Inspect the actual rendered center of each visible pane instead. + shot = ctl("shot", "pane-hints-regression") + image = Image.open(profile / shot["png"]).convert("RGB") + dump = ctl("dump", "#panel > .tn-stage > section.tn-pane") + scale = dump["header"]["viewport"]["deviceScaleFactor"] + visible = [e for e in dump["elements"] if e["visible"]] + assert visible + for element in visible: + x, y, width, height = element["rect"] + cx, cy = (x + width / 2) * scale, (y + height / 2) * scale + crop = image.crop((int(cx - 50 * scale), int(cy - 65 * scale), + int(cx + 50 * scale), int(cy + 65 * scale))) + pixels = crop.load() + bright = sum(min(pixels[x, y]) > 235 + for y in range(crop.height) for x in range(crop.width)) + assert bright > 300 * scale * scale, ("Missing large pane number", element["nth"], bright) + + def choose(index, count): + ctl("type", json.dumps(str(index).zfill(len(str(count))))) + ctl("key", "Enter") + wait_for(lambda: state()["picker"] is None) + sheet = next(s for s in ctl("css")["sheets"] + if s["name"] == "plugin:local:pane-hints:hints") + assert sheet["rules"] == 0, "Overlays must be removed after choosing" + + with (profile / "process.log").open("w") as log: + process = subprocess.Popen([TERN, "--control", endpoint, temp], + env=env, cwd=temp, stdout=log, stderr=log) + try: + wait_for(lambda: Path(endpoint).exists(), 30) + ctl("ready") + assert len(state()["panes"]) == 1, "Expected a fresh isolated window" + ctl("split", "right") + ctl("split", "down") + initial = state() + ids = [p["id"] for p in initial["panes"]] + hints() + check_visible_numbers() + choose(1, 3) + assert state()["focused"]["id"] == ids[0] + hints() + ctl("key", "Escape") + assert state()["focused"]["id"] == ids[0] + assert state()["picker"] is None + hints() + ctl("key", "9") + ctl("key", "Enter") + assert state()["focused"]["id"] == ids[0] + assert state()["picker"] is None + print("PASS: shortcut, prompt without list, selection, cancel, invalid number", flush=True) + + # Grow the largest pane each time, so small repeated splits do not + # hit the native minimum-size limit before the multi-digit case. + for _ in range(9): + panes = state()["panes"] + biggest = max(range(len(panes)), key=lambda i: panes[i]["cols"] * panes[i]["rows"]) + hints() + choose(biggest + 1, len(panes)) + pane = panes[biggest] + ctl("split", "right" if pane["cols"] > pane["rows"] * 2 else "down") + panes = state()["panes"] + assert len(panes) == 12 + hints() + choose(10, 12) + assert state()["focused"]["id"] == panes[9]["id"] + hints() + choose(1, 12) + assert state()["focused"]["id"] == panes[0]["id"] + ctl("zoom") + hints() + ctl("key", "Escape") + ctl("zoom") + print("PASS: selection mapping with 12 panes, distinct 01 and 10, prompt in zoom", flush=True) + + # Other tabs and parked panes must not leak into the current list. + # Floats are rendered after tiled panes and must select the + # same program as their overlay number. + before_float = state()["focused"]["id"] + ctl("pip", "float", "tr") + hints() + choose(12, 12) + assert state()["focused"]["id"] == before_float + ctl("pip", "dock", "right") + print("PASS: floating pane selection targets the floating program", flush=True) + ctl("tab", "new") + other_id = state()["focused"]["id"] + hints(expected=1) + assert len(state()["panes"]) == 1 + check_visible_numbers() + choose(2, 2) # Only number 1 is valid in this tab. + assert state()["focused"]["id"] == other_id + ctl("tab", "1") + ctl("plugins", "run", "park_pane") + hints(expected=11) + assert len(state()["panes"]) == 11 + focus_before_invalid = state()["focused"]["id"] + choose(12, 12) # The parked twelfth pane must not be selectable. + assert state()["focused"]["id"] == focus_before_invalid + assert state()["park"]["pile"]["cards"] == 1 + assert state()["focused"]["id"] != other_id + print("PASS: other tabs and parked panes excluded", flush=True) + + # A raw reader proves digit+Enter are consumed by the picker, + # rather than accidentally submitted to the focused program. + ctl("tab", "2") + ctl("split", "right") + surviving = state()["focused"]["id"] + hints() + check_visible_numbers() + assert len(state()["panes"]) == 2 + subprocess.run([TERN, "close", str(other_id)], env=env, + capture_output=True, text=True, check=True, timeout=15) + wait_for(lambda: len(state()["panes"]) == 1) + if state()["picker"] is not None: + choose(1, 2) + assert state()["focused"]["id"] == surviving + print("PASS: closing a target while choosing does not misdirect focus", flush=True) + output = profile / "input.json" + ready = profile / "reader-ready" + code = ("import os,tty,termios,select,json; " + "old=termios.tcgetattr(0); tty.setraw(0); " + f"open({str(ready)!r},'w').close(); " + "data=os.read(0,32) if select.select([0],[],[],12)[0] else b''; " + "termios.tcsetattr(0,termios.TCSANOW,old); " + f"open({str(output)!r},'w').write(json.dumps(list(data)))") + ctl("run", json.dumps("python3 -c " + shlex.quote(code))) + wait_for(ready.exists) + hints() + choose(1, 1) + wait_for(output.exists, 20) + assert json.loads(output.read_text()) == [], output.read_text() + print("PASS: selection keys do not reach the terminal", flush=True) + finally: + stop_window(process, env, endpoint) + + +if __name__ == "__main__": + check_cleanup_timeout() + main() diff --git a/plugins/examples/pane-hints/window.luau b/plugins/examples/pane-hints/window.luau new file mode 100644 index 0000000..1bedfca --- /dev/null +++ b/plugins/examples/pane-hints/window.luau @@ -0,0 +1,158 @@ +--!strict +-- Temporary large numbers over existing panes, with a native number prompt. +-- No global digit bindings: numbers and Escape belong to the prompt only. + +local function collect(tree: TabTree, ids: { number }) + if tree.pane then + table.insert(ids, tree.pane) + else + for index = 1, 2 do + local child = tree[index] + if child then + collect(child, ids) + end + end + end +end + +-- Tern 0.9.4 retains all window panes in session:panes() order, including +-- hidden tabs and parked panes. Display numbers still follow the split tree. +-- The selectors are private chrome structure: verify them after Tern upgrades. +local active = 0 +local showing = false + +local function clear() + active += 1 + showing = false + tern.css("hints", "") +end + +local function show(cx: WindowCx) + clear() + local token = active + local focused = cx.session:focused() + local tab = if focused then cx.session:tab_of(focused) else nil + local layout = if tab then cx.session:layout(tab) else nil + if not tab or not layout then + cx:toast("info", "No active tab to select a pane from") + return + end + + local ids: { number } = {} + collect(layout.root, ids) + for _, float in layout.floats do + table.insert(ids, float.pane) + end + + local positions: { [number]: number } = {} + for position, pane in cx.session:panes() do + positions[pane.pane] = position + end + local panes: { [number]: number } = {} + local rules = { [[ +#panel > .tn-stage > section.tn-pane::after { + position: absolute; inset: 0; + display: flex; align-items: center; justify-content: center; + font-size: 120px; font-weight: 800; + color: #ffffff; background: rgba(0, 0, 0, 0.35); + z-index: 999; pointer-events: none; +} +#pick .tn-pk { + position: absolute !important; left: 50% !important; top: auto !important; bottom: 24px !important; + transform: translateX(-50%) !important; width: 440px !important; height: 96px !important; min-height: 0 !important; max-height: 96px !important; +} +]] } + for index, id in ids do + local pane = cx.session:pane(id) + if pane and pane.tab == tab and not pane.parked then + -- Zoom keeps hidden leaves in the DOM; keep their selector positions, + -- but only offer the focused tiled pane and floating panes. + if not layout.zoomed or id == layout.focus or pane.floating then + panes[index] = id + -- The renderer needs :first-of-type for the first generated glyph. + local domIndex = positions[id] + local position = if domIndex == 1 then ":first-of-type" else string.format(":nth-of-type(%d)", domIndex) + table.insert(rules, string.format( + "#panel > .tn-stage > section.tn-pane%s::after { content: '%d'; }", + position, index + )) + end + end + end + if next(panes) == nil then + cx:toast("info", "No visible panes in this tab") + return + end + + showing = true + tern.css("hints", table.concat(rules, "\n")) + cx:prompt({ + placeholder = "Pane number → Enter · Esc to cancel", + action = "focus pane", + }):next(function(value: string?, err: string?, nextCx: WindowCx?) + if token ~= active then + return -- Layout/focus changed or another invocation replaced this one. + end + clear() + if not nextCx then + return + end + if err then + nextCx:toast("error", "Could not select a pane", err) + return + end + if value == nil then + return + end + local number = if string.match(value, "^%d+$") then tonumber(value) else nil + local id = if number then panes[number] else nil + if not id then + nextCx:toast("info", "Enter one of the displayed pane numbers") + return + end + local pane = nextCx.session:pane(id) + local current = nextCx.session:focused() + if not pane or pane.parked or pane.tab ~= tab then + nextCx:toast("info", "That pane is no longer in this tab") + return + end + if not current or nextCx.session:tab_of(current) ~= tab then + return + end + local now = nextCx.session:layout(tab) + local currentIds: { number } = {} + if now then + collect(now.root, currentIds) + for _, float in now.floats do + table.insert(currentIds, float.pane) + end + end + if not now or now.zoomed ~= layout.zoomed or #currentIds ~= #ids then + return + end + for index, oldId in ids do + if currentIds[index] ~= oldId then + nextCx:toast("info", "Pane layout changed; show numbers again") + return + end + end + nextCx.layout:focus(id) + end) +end + +-- A stale nth-of-type hint could point at a different pane after a mutation. +-- Remove hints rather than renumbering while the user is typing a choice. +for _, event in { "pane_created", "pane_closed", "tab_created", "tab_closed", "focus" } do + tern.on(event, function() + if showing then + clear() + end + end) +end + +tern.command({ + id = "show", + title = "Show pane numbers", + keys = { "ctrl+cmd+g" }, + run = show, +})