From 5a8da8ab392266d5f3bbf3abed61472d6734f31c Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Tue, 10 Nov 2026 16:34:04 +0100 Subject: feat(windows): preview cards and keystone's workspace icons Each window is a card like the Alt+Tab switcher's: a preview in the window's shape (grim -T on Hyprland's stableId, also for hidden workspaces, refreshed every 5 s), the desktop top left, close top right, the app icon bottom left, each on its own scrim, the title below. Tap focuses, a long press opens the move menu at the press point (the grid re-renders under a title that changes every second, so the card itself may already be gone), and Chrome's image menu is suppressed. Module.image serves module images at /api//image/; windows answers only for a window the last state listed. Workspace tiles, card markers and the move menu use the icons from keystone's Workspaces.qml, falling back to the number; the icon route also searches the theme's places, preferences and categories folders, where two of them live. The workspaces are centred. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 ++ README.md | 5 +- config.toml | 3 ++ deckit/module.py | 3 ++ deckit/modules/windows.py | 38 +++++++++++++-- deckit/server.py | 13 +++++- static/deck.css | 36 +++++++++------ static/modules/windows.js | 115 +++++++++++++++++++++++++++++++++------------- tests/test_server.py | 9 +++- tests/test_windows.py | 29 ++++++++++++ 10 files changed, 202 insertions(+), 54 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0d0bc63..62c163d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,11 @@ Keep the server dependency-free apart from that one package. 2s, and `app.js` covers the page with "The PC is asleep" and drops the lock, so the tablet sleeps too; 15s with no answer at all gives the same overlay as "The PC is not answering". The first plain answer takes both back. +- The Windows tab's previews are `grim -T ` (Hyprland's stableId is + the ext-foreign-toplevel identifier), served at `/api/windows/image/` + through `Module.image`, only for a window the last state listed; the URL + changes every 5s so the browser cache answers in between. Workspace icons + come from keystone's `Workspaces.qml` map (`[windows] workspace_icons`). - Launchers are `[launch] apps`, desktop ids run with `gtk-launch`; label and icon come from the `.desktop` file. The client sends the id, which must be configured and installed. diff --git a/README.md b/README.md index e1784ef..b28e2fc 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,9 @@ launchers included, with a Restart button to apply a save. them key by key and needs only what differs; keystone writes it. - The OBS tab is a stream-deck: scenes, sources, audio sliders, transitions. Long-press a source to open its properties dialog in OBS. -- The Windows tab has workspaces, icon launchers, and a per-window `⋮` menu to - close it or move it to another desktop. +- The Windows tab has keystone's workspace icons, icon launchers, and a + preview card per window (as in the Alt+Tab switcher): tap to focus, × to + close, a long press to move it to another desktop. - The K1C tab follows a Klipper printer through Moonraker (`[k1c] url`): state, progress with the slicer's model preview, temperatures, camera, and a red emergency stop that fires on a press and hold. diff --git a/config.toml b/config.toml index 57a0ce8..39fc22c 100644 --- a/config.toml +++ b/config.toml @@ -79,6 +79,9 @@ shell = "~/Programming/GIT/quickshell/desktop" background = "" [windows] +# keystone's workspace icons (its bar and Alt+Tab show these): a QML map of +# workspace number to icon name. Missing: the tab shows the numbers. +workspace_icons = "~/Programming/GIT/quickshell/shared/Workspaces.qml" # Workspaces shown on the Windows tab, including empty ones. workspaces = [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/deckit/module.py b/deckit/module.py index 9680c58..dec2e04 100644 --- a/deckit/module.py +++ b/deckit/module.py @@ -38,6 +38,9 @@ class Module: # action -> (content type, max bytes): actions that take a raw body, # such as a voice clip, instead of a small JSON object. uploads: dict[str, tuple[str, int]] = field(default_factory=dict) + # key -> (bytes, content type) or None: images served at + # /api//image/, such as a window's preview. + image: Callable[[str], tuple[bytes, str] | None] | None = None start: Callable[[], None] | None = None stop: Callable[[], None] | None = None diff --git a/deckit/modules/windows.py b/deckit/modules/windows.py index 1907b59..a15f44c 100644 --- a/deckit/modules/windows.py +++ b/deckit/modules/windows.py @@ -24,6 +24,7 @@ from pathlib import Path from ..module import Module, ModuleError ADDR = re.compile(r"0x[0-9a-f]{1,16}") +STABLE = re.compile(r"[0-9a-f]{1,16}") # Hyprland's stableId: grim -T's toplevel identifier # The user's own entries first, so they win over the system's, as in a launcher. DESKTOP_BASES = (Path.home() / ".local/share/applications", Path("/usr/share/applications")) @@ -39,6 +40,16 @@ def _popen(cmd): subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +def _shot(stable_id): + """A window's preview, captured even on a hidden workspace (60 ms, ~20 KB).""" + try: + out = subprocess.run(["grim", "-T", stable_id, "-s", "0.3", "-t", "jpeg", "-q", "70", "-"], + capture_output=True, timeout=3).stdout + except (OSError, subprocess.TimeoutExpired): + return None + return (out, "image/jpeg") if out else None + + def _dispatch(cmd): """Run a hyprctl dispatch and wait: the two-step move depends on the order.""" try: @@ -91,6 +102,17 @@ def _desktop_icons(entries: dict) -> dict: return mapping +def workspace_icons(path) -> dict: + """Workspace number -> icon name, from keystone's Workspaces.qml map.""" + # ponytail: a regex over the QML's `1: "web-browser",` lines, read once at + # start; a parser if that file ever stops being a plain map. + try: + text = Path(path).expanduser().read_text() + except OSError: + return {} + return {int(n): name for n, name in re.findall(r'^\s*(\d+):\s*"([A-Za-z0-9._-]+)"', text, re.M)} + + def hypr_lua(cfg: dict) -> bool: mode = cfg.get("hyprland", "auto") if mode == "auto": @@ -119,7 +141,7 @@ def _state(run): except json.JSONDecodeError: return {"windows": [], "workspaces": [], "activeClass": None} wins = sorted( - ({"address": c["address"], "class": c["class"], "title": c["title"], + ({"address": c["address"], "id": c.get("stableId", ""), "class": c["class"], "title": c["title"], "workspace": c["workspace"]["id"], "active": c["address"] == active} for c in clients if c.get("mapped", True) and c["workspace"]["id"] > 0), key=lambda w: (w["workspace"], w["class"])) @@ -134,8 +156,11 @@ def make(cfg: dict) -> Module: lua = hypr_lua(cfg) apps = [str(a) for a in cfg.get("launch", {}).get("apps", [])] workspaces = cfg.get("windows", {}).get("workspaces", list(range(1, 11))) + ws_icons = workspace_icons(cfg.get("windows", {}).get("workspace_icons", "")) entries = _desktop_entries() icons = _desktop_icons(entries) + shot = cfg.get("shot", _shot) + shown = set() # stableIds of the windows the last state listed def workspace(body): n = body.get("n") @@ -176,13 +201,20 @@ def make(cfg: dict) -> Module: def state(): st = _state(run) + shown.clear() + shown.update(w["id"] for w in st["windows"]) for win in st["windows"]: win["icons"] = icons.get(win["class"].lower(), [win["class"].lower()]) known = sorted(set(int(n) for n in workspaces) | set(st["workspaces"])) launches = [{"key": a, "icon": entries[a]["icon"], "label": entries[a]["name"] or a} for a in apps if a in entries] - return {**st, "workspaces": known, "launches": launches} + return {**st, "workspaces": known, "launches": launches, + "wsIcons": {str(n): ws_icons[n] for n in known if n in ws_icons}} + + def image(key): + # Only a window the tablet was shown; never an arbitrary identifier. + return shot(key) if STABLE.fullmatch(key) and key in shown else None - return Module(name="windows", title="Windows", state=state, + return Module(name="windows", title="Windows", state=state, image=image, actions={"workspace": workspace, "focus": focus, "close": close, "move": move, "launch": launch_key}) diff --git a/deckit/server.py b/deckit/server.py index 19edbef..9dd5229 100644 --- a/deckit/server.py +++ b/deckit/server.py @@ -89,7 +89,11 @@ def icon_path(name: str, theme: str | None = None, bases=ICON_BASES): for th in (theme or icon_theme(), "hicolor"): for base in bases: # Themes lay out category/size (candy-icons) or size/category (hicolor). - for sub in ("apps/scalable", "apps/64", "apps/48", "apps/32", "scalable/apps"): + # Apps first; places and preferences hold the workspace icons + # keystone's bar uses (network-server, applications-graphics). + for sub in ("apps/scalable", "apps/64", "apps/48", "apps/32", "scalable/apps", + "places/scalable", "places/48", "scalable/places", + "preferences/scalable", "categories/scalable", "scalable/categories"): path = Path(base) / th / sub / f"{name}.svg" if path.is_file(): return path @@ -207,6 +211,13 @@ class Handler(BaseHTTPRequestHandler): if len(parts) == 2 and parts[1] == "bg": image = background() return self._send(200, image[0], image[1], cache=True) if image else self._send(404) + if len(parts) == 4 and parts[2] == "image": + try: + fn = REGISTRY.get(parts[1]).image + except module.ModuleError: + fn = None + image = fn(parts[3]) if fn else None + return self._send(200, image[0], image[1], cache=True) if image else self._send(404) if len(parts) == 2 and parts[1] == "modules": return self._json(REGISTRY.names()) if len(parts) == 2: diff --git a/static/deck.css b/static/deck.css index 03b9d43..98a2c2a 100644 --- a/static/deck.css +++ b/static/deck.css @@ -305,20 +305,24 @@ select { .wtile.on { background: var(--udt-accent); color: var(--udt-crust); border-color: var(--udt-accent); } .wtile.launch { min-width: 64px; min-height: 64px; padding: 0 12px; } .laticon { display: block; width: 32px; height: 32px; object-fit: contain; } -.windows .winlist { display: flex; flex-direction: column; gap: 6px; margin-bottom: 10px; } -.wrow { - display: flex; - align-items: center; - gap: 8px; - min-height: 44px; - padding: 0 6px 0 10px; - border-radius: 10px; - background: var(--udt-surface1); -} -.wrow.on { color: var(--udt-accent); } -.wt { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; } -.wicon { width: 24px; height: 24px; object-fit: contain; flex: none; } -.wmenu { flex: none; width: 40px; height: 40px; padding: 0; font-size: 1.286rem; line-height: 1; } +.windows .ws { justify-content: center; } +.wgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 16px 14px; } +.wcard { display: flex; flex-direction: column; gap: 6px; padding: 0; font: inherit; background: none; border: 0; color: inherit; cursor: pointer; min-width: 0; } +.wbox { + position: relative; aspect-ratio: 16 / 10; border-radius: 10px; overflow: hidden; + background: var(--udt-surface0); border: 1px solid var(--udt-surface1); + display: flex; align-items: center; justify-content: center; +} +.wcard.cur .wbox { border-color: var(--udt-accent); box-shadow: 0 0 14px color-mix(in srgb, var(--udt-accent) 45%, transparent); } +.wshot { pointer-events: none; -webkit-touch-callout: none; user-select: none; max-width: calc(100% - 8px); max-height: calc(100% - 8px); object-fit: contain; border-radius: 4px; } +/* Each overlay carries its own scrim: it sits on an arbitrary preview. */ +.wws, .wx, .wbox .wicon { position: absolute; background: color-mix(in srgb, var(--udt-base) 75%, transparent); } +.wws { left: 8px; top: 8px; min-width: 34px; height: 34px; border-radius: 8px; display: grid; place-items: center; color: var(--udt-accent); font-size: 0.929rem; } +.wx { right: 8px; top: 8px; width: 40px; height: 40px; border-radius: 20px; display: grid; place-items: center; font-size: 1.6rem; line-height: 1; color: var(--udt-text); } +.wx:active { background: var(--udt-red); } +.wbox .wicon { left: 8px; bottom: 8px; width: 40px; height: 40px; padding: 5px; border-radius: 10px; box-sizing: border-box; } +.wtitle { font-size: 0.929rem; color: var(--udt-subtext0); text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.wcard.cur .wtitle { color: var(--udt-text); } .windows .launches { display: flex; flex-wrap: wrap; gap: 8px; } .wpop { @@ -337,7 +341,6 @@ select { } .wpop-title { font-weight: 600; font-size: 0.929rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .wpop-label { font-size: 0.786rem; text-transform: uppercase; letter-spacing: .08em; color: var(--udt-overlay0); } -.wpop-close { text-align: left; } .wpop-ws { display: flex; flex-wrap: wrap; gap: 6px; } .wpop-ws button { min-width: 44px; min-height: 44px; padding: 0; font-size: 1.143rem; font-weight: 600; } @@ -713,3 +716,6 @@ select { margin: 0 0 6px; font: 200 3rem/1.1 system-ui, sans-serif; letter-spacing: -.02em; color: var(--udt-text); } .assistant .as-hello p { margin: 0; font: 300 1.15rem/1.4 system-ui, sans-serif; color: var(--udt-overlay0); } +.windows .ws .wtile img { width: 32px; height: 32px; object-fit: contain; } +.wws img { width: 22px; height: 22px; object-fit: contain; } +.wpop-ws button img { width: 24px; height: 24px; object-fit: contain; } diff --git a/static/modules/windows.js b/static/modules/windows.js index 7404f03..27e966e 100644 --- a/static/modules/windows.js +++ b/static/modules/windows.js @@ -42,24 +42,20 @@ function closePop() { } } -function openMenu(anchor, win, workspaces) { +function openMenu(anchor, win, workspaces, wsIcons) { closePop(); pop = document.createElement("div"); pop.className = "wpop"; pop.innerHTML = `
-
Move to desktop
`; pop.querySelector(".wpop-title").textContent = win.title || win.class; - pop.querySelector(".wpop-close").onclick = () => { - closePop(); - post("close", { address: win.address }); - }; const targets = pop.querySelector(".wpop-ws"); - for (const n of workspaces ?? []) { + for (const n of (workspaces ?? []).filter((n) => n !== win.workspace)) { const b = document.createElement("button"); - b.textContent = String(n); + wsMark(b, n, wsIcons); + b.setAttribute("aria-label", `Desktop ${n}`); b.onclick = () => { closePop(); post("move", { address: win.address, n }); @@ -67,7 +63,9 @@ function openMenu(anchor, win, workspaces) { targets.append(b); } document.body.append(pop); - const r = anchor.getBoundingClientRect(); + // The press point: the card itself may already be rebuilt (a title that + // changes every second re-renders the grid), and a detached one measures 0. + const r = anchor.getBoundingClientRect ? anchor.getBoundingClientRect() : anchor; const width = pop.offsetWidth; const height = pop.offsetHeight; pop.style.top = `${Math.min(r.bottom + 6, window.innerHeight - height - 8)}px`; @@ -75,9 +73,67 @@ function openMenu(anchor, win, workspaces) { } document.addEventListener("pointerdown", (e) => { - if (pop && !pop.contains(e.target) && !e.target.closest(".wmenu")) closePop(); + if (pop && !pop.contains(e.target)) closePop(); }); +// A workspace's icon from keystone's map, the number when it has none or the +// icon theme lacks it. +function wsMark(box, n, icons) { + box.textContent = String(n); + const name = icons?.[String(n)]; + if (!name) return; + const img = document.createElement("img"); + img.alt = String(n); + img.onload = () => { box.textContent = ""; box.append(img); }; + img.src = `/icons/${name}.svg`; +} + +// Previews are re-captured on the PC every PREVIEW ms; the URL carries the +// period, so within one the browser's cache answers and nothing flickers. +const PREVIEW = 5000; +const previewUrl = (w) => `/api/windows/image/${w.id}?t=${Math.floor(Date.now() / PREVIEW)}`; + +// As the Alt+Tab switcher's card (quickshell window-switcher/WindowCard.qml): +// the preview in its window's shape, the desktop top left, close top right, +// the app's icon bottom left, each on its own scrim; the title below. Tap +// focuses, a long press offers the other desktops. +function card(w, workspaces, wsIcons) { + const c = document.createElement("button"); + c.className = `wcard${w.active ? " cur" : ""}`; + c.setAttribute("aria-label", w.title || w.class); + c.innerHTML = `
+ ×
`; + const shot = c.querySelector(".wshot"); + shot.src = previewUrl(w); + shot.onerror = () => { shot.hidden = true; }; + wsMark(c.querySelector(".wws"), w.workspace, wsIcons); + c.querySelector(".wtitle").textContent = w.title || w.class; + const icon = appIcon(w); + if (icon) c.querySelector(".wbox").append(icon); + c.querySelector(".wx").addEventListener("click", (e) => { + e.stopPropagation(); + post("close", { address: w.address }); + }); + let timer = null; + let long = false; + c.addEventListener("pointerdown", (e) => { + if (e.target.closest(".wx")) return; + long = false; + const at = { left: e.clientX, bottom: e.clientY }; + timer = setTimeout(() => { long = true; openMenu(at, w, workspaces, wsIcons); }, 600); + }); + // Chrome's own long-press menu (copy or share the image) is not wanted here. + c.addEventListener("contextmenu", (e) => e.preventDefault()); + for (const ev of ["pointerup", "pointercancel", "pointerleave"]) { + c.addEventListener(ev, () => clearTimeout(timer)); + } + c.onclick = () => { + if (long) return; + post("focus", { address: w.address }); + }; + return c; +} + function appIcon(w) { if (!w.icons?.length) return null; const img = document.createElement("img"); @@ -105,7 +161,7 @@ export default { el.innerHTML = `

Workspaces

Launches

-

Windows

+

Windows

`; }, @@ -113,12 +169,20 @@ export default { // Polled every second: rebuilding unchanged rows reloads every icon // through its fallbacks, which flickers, so only a change re-renders. const key = JSON.stringify(st); - if (key === el._last) return; + if (key === el._last) { + for (const img of el.querySelectorAll(".wshot")) { + const url = previewUrl({ id: img.closest(".wcard").dataset.id }); + if (!img.src.endsWith(url)) { img.hidden = false; img.src = url; } + } + return; + } el._last = key; const ws = el.querySelector(".ws"); ws.textContent = ""; for (const id of st.workspaces ?? []) { - const b = tile(String(id), () => post("workspace", { n: id })); + const b = tile("", () => post("workspace", { n: id })); + b.setAttribute("aria-label", `Desktop ${id}`); + wsMark(b, id, st.wsIcons); b.classList.toggle("on", (st.windows ?? []).some((w) => w.workspace === id)); ws.append(b); } @@ -145,25 +209,12 @@ export default { launches.append(b); } - const list = el.querySelector(".winlist"); - list.textContent = ""; - for (const w of (st.windows ?? []).slice(0, 12)) { - const row = document.createElement("div"); - row.className = "wrow"; - row.classList.toggle("on", Boolean(w.active)); - const icon = appIcon(w); - if (icon) row.append(icon); - const title = document.createElement("span"); - title.className = "wt"; - title.textContent = w.title || w.class; - title.onclick = () => post("focus", { address: w.address }); - const menu = document.createElement("button"); - menu.className = "wmenu"; - menu.textContent = "⋮"; - menu.setAttribute("aria-label", "Window actions"); - menu.onclick = () => openMenu(menu, w, st.workspaces); - row.append(title, menu); - list.append(row); + const grid = el.querySelector(".wgrid"); + grid.textContent = ""; + for (const w of st.windows ?? []) { + const c = card(w, st.workspaces, st.wsIcons); + c.dataset.id = w.id; + grid.append(c); } }, }; diff --git a/tests/test_server.py b/tests/test_server.py index 054b3a6..0881849 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -57,7 +57,8 @@ class Server(unittest.TestCase): {"ping": lambda body: {"got": body.get("n")}, "boom": lambda body: int(body.get("x")), "put": lambda data: {"len": len(data)}}, - uploads={"put": ("audio/wav", 10)}), + uploads={"put": ("audio/wav", 10)}, + image=lambda key: (b"img", "image/jpeg") if key == "k1" else None), ]) cls.server = srv.UnixHTTPServer(cls.sock, srv.Handler) threading.Thread(target=cls.server.serve_forever, daemon=True).start() @@ -114,6 +115,12 @@ class Server(unittest.TestCase): with mock.patch.dict(srv.CFG, {"assistant": {"background": ""}}): self.assertEqual(self.req("GET", "/api/bg", HOST)[0], 404) + def test_module_images(self): + self.assertEqual(self.req("GET", "/api/demo/image/k1", HOST), (200, b"img")) + self.assertEqual(self.req("GET", "/api/demo/image/k2", HOST)[0], 404) + self.assertEqual(self.req("GET", "/api/nope/image/k1", HOST)[0], 404) + self.assertEqual(self.req("GET", "/api/demo/image/k1", {"Host": "127.0.0.1:8765"})[0], 401) + def test_nerd_font(self): from unittest import mock import tempfile diff --git a/tests/test_windows.py b/tests/test_windows.py index e632406..6950152 100644 --- a/tests/test_windows.py +++ b/tests/test_windows.py @@ -19,12 +19,23 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import json import unittest from unittest import mock import deckit.modules.windows as windows +class WorkspaceIcons(unittest.TestCase): + def test_reads_keystones_map(self): + import tempfile + f = Path(tempfile.mkdtemp()) / "Workspaces.qml" + f.write_text('Singleton {\n readonly property var icons: ({\n 1: "web-browser",\n' + ' 2: "text-editor",\n })\n}\n') + self.assertEqual(windows.workspace_icons(f), {1: "web-browser", 2: "text-editor"}) + self.assertEqual(windows.workspace_icons("/nonexistent"), {}) + + class DesktopIcons(unittest.TestCase): def test_maps_class_and_wmclass(self): import tempfile @@ -100,6 +111,24 @@ class Commands(unittest.TestCase): self.assertEqual(st["launches"], [{"key": "com.obsproject.Studio", "icon": "obs", "label": "OBS Studio"}]) + def test_preview_only_for_a_listed_window(self): + client = {"address": "0x1", "stableId": "18000005", "class": "kitty", "title": "t", + "workspace": {"id": 3}, "mapped": True} + responses = { + ("hyprctl", "clients", "-j"): json.dumps([client]), + ("hyprctl", "activewindow", "-j"): "{}", + ("hyprctl", "workspaces", "-j"): '[{"id": 3}]', + } + shots = [] + m = windows.make({"run": lambda cmd: responses[tuple(cmd)], + "shot": lambda key: shots.append(key) or (b"jpg", "image/jpeg")}) + self.assertIsNone(m.image("18000005")) # not listed yet + self.assertEqual(m.state()["windows"][0]["id"], "18000005") + self.assertEqual(m.image("18000005"), (b"jpg", "image/jpeg")) + for bad in ("deadbeef", "-s", "../x", "18000005 -o"): + self.assertIsNone(m.image(bad)) + self.assertEqual(shots, ["18000005"]) + def test_launch_runs_only_listed_installed_apps(self): entries = {"kitty": {"name": "kitty", "icon": "kitty", "wmclass": None}, "other": {"name": "Other", "icon": None, "wmclass": None}} -- cgit v1.2.3