From 382728c7ab54e4b6ed3e88021dcc432d003e7508 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 8 Nov 2026 16:06:05 +0100 Subject: [PATCH 1/2] 1.0.0-alpha.3: window snapshots for SMBAct's switcher (snapshots, snapshot, event) snapshots.js: the whole buffer the way GNOME's window screenshot takes it, the frame rect cut out in proportion (no client-side shadow), JPEG over a background. A snapshot costs about a frame, so they are cached per window, retaken only when the window was damaged or resized, one per idle turn, never on a timer; a request answers with the cache at once and announces each retaken one; the window that just lost the focus is retaken quietly. scripts/call.py --snapshots takes every window and prints sizes and timings. Same API 1; the new ops are listed in hello. Co-Authored-By: Claude Opus 5.5 --- PROTOCOL.md | 14 +- gnome-shell/smbact@giglabo.com/extension.js | 38 ++- gnome-shell/smbact@giglabo.com/metadata.json | 6 +- gnome-shell/smbact@giglabo.com/snapshots.js | 256 +++++++++++++++++++ scripts/call.py | 46 ++++ 5 files changed, 352 insertions(+), 8 deletions(-) create mode 100644 gnome-shell/smbact@giglabo.com/snapshots.js diff --git a/PROTOCOL.md b/PROTOCOL.md index fe3f2e9..eb96122 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -33,7 +33,8 @@ is not running; GNOME's own allow-lists have the same limit. ``` Error codes: `BAD_REQUEST` (not JSON, missing or wrong arguments), `UNKNOWN_OP`, `NO_WINDOW`, `GRAB_FAILED` -(`grabAccelerator`: the shell refused the accelerator), `FAILED` (the shell threw; `message` has its text). +(`grabAccelerator`: the shell refused the accelerator), `NO_SNAPSHOT` (`snapshot`: none taken yet), `FAILED` (the +shell threw; `message` has its text). Unknown fields in a request are ignored; new optional fields and new operations do not change the API number. A change that breaks an existing operation does, and `hello` reports which API the plugin speaks. @@ -106,6 +107,8 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. | `pointer` | | `{ x, y }` | | `grabAccelerator` | `accelerator` (GTK notation, `x`) | `{ accelerator, action }` | | `ungrabAccelerator` | `accelerator` (as grabbed) | `{ released }` | +| `snapshots` | `ids`, `maxSize?` (px, default 480, at most 1024), `background?` (`#rrggbb`, default white) | `{ snapshots: Snapshot[] }` (the cached ones) | +| `snapshot` | `id` | `{ snapshot }` | - `setState` states: `minimized`, `maximized`, `maximizedHorizontally`, `maximizedVertically`, `fullscreen`, `above`. @@ -122,6 +125,13 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. custom shortcuts: it fires on the desktop and in the overview, never on the lock or login screen. Each press sends an `accelerator` event. It fails with `GRAB_FAILED` when another shortcut (GNOME's own, a custom one, another extension's) has the combination, or when Mutter cannot parse it. Grabbing the same string again is a no-op. +- `snapshots` answers at once with the snapshots it has; the ones that are missing, stale (the window was damaged + or resized since) or of another size are taken one at a time when the shell is idle, and each sends a `snapshot` + event; fetch it with `snapshot`. A snapshot costs the compositor about a frame, so they are never taken on a timer. + The window that just lost the focus is taken quietly (no event) a moment later when its snapshot is stale. + Minimized windows keep their last snapshot. A `Snapshot` is `{ id, mime, data, width, height, fresh }`: `data` is + base64 JPEG of the visible window (the frame rect, without a client-side shadow), scaled to fit `maxSize`, over + `background`; `fresh` is false when the window changed since it was taken. - Grabs belong to the client: the plugin releases all of them when the owner of `com.giglabo.SMBAct` goes away or changes, and when it is disabled. A client that starts again grabs again. - GNOME disables every user extension while the screen is locked and enables them again after the unlock (seen on @@ -139,9 +149,11 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - `focusChanged` with `id` (or `null`). - `accelerator` with `accelerator` (the string given to `grabAccelerator`) and `time` (the key press's timestamp, usable as `activate`'s `time`). +- `snapshot` with `id`: a snapshot asked for with `snapshots` is ready. ## History - API 1 (2026-11): window list, geometry, activation, states, close, displays, pointer, events. - API 1, plugin 1.0.0-alpha.2 (2026-11): `grabAccelerator`, `ungrabAccelerator`, the `accelerator` event (new operations, same API; clients look for them in `hello`'s `ops`). +- API 1, plugin 1.0.0-alpha.3 (2026-11): `snapshots`, `snapshot`, the `snapshot` event. diff --git a/gnome-shell/smbact@giglabo.com/extension.js b/gnome-shell/smbact@giglabo.com/extension.js index c502073..f4605d9 100644 --- a/gnome-shell/smbact@giglabo.com/extension.js +++ b/gnome-shell/smbact@giglabo.com/extension.js @@ -5,6 +5,7 @@ // - windows come from display.list_all_windows(), not global.get_window_actors() (other extensions patch that one); // - activation uses the server's current time (time 0 may not get the focus); // - global hotkeys are Mutter accelerator grabs owned by the current client: released when it goes away; +// - window snapshots cost a frame each: cached, retaken only when stale, one per idle turn (snapshots.js); // - no synchronous work beyond one frame, every request in try/catch, everything undone in disable(): a hang // freezes the desktop and a crash ends the session. import GdkPixbuf from 'gi://GdkPixbuf'; @@ -17,6 +18,7 @@ import St from 'gi://St'; import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; import * as Main from 'resource:///org/gnome/shell/ui/main.js'; import * as Config from 'resource:///org/gnome/shell/misc/config.js'; +import {Snapshots} from './snapshots.js'; const API = 1; const BUS_NAME = 'com.giglabo.SMBAct.Shell'; @@ -126,6 +128,8 @@ class Service { /** accelerator (as the client sent it) -> Mutter action id; action id -> accelerator */ this._grabs = new Map(); this._grabActions = new Map(); + this._snapshots = null; + this._focus = null; this._ops = { hello: () => this._hello(), listWindows: req => this._listWindows(req), @@ -149,6 +153,18 @@ class Service { }, grabAccelerator: req => this._grabAccelerator(req), ungrabAccelerator: req => this._ungrabAccelerator(req), + snapshots: req => { + if (!Array.isArray(req.ids)) + throw badRequest('"ids" must be an array of window ids'); + const ids = req.ids.filter(id => typeof id === 'number' && Number.isFinite(id)); + return {snapshots: this._snapshots.request(ids, req.maxSize, req.background)}; + }, + snapshot: req => { + const snapshot = this._snapshots.get(this._number(req, 'id')); + if (!snapshot) + throw new ShellError('NO_SNAPSHOT', `no snapshot of window ${req.id} yet`); + return {snapshot}; + }, }; } @@ -168,13 +184,20 @@ class Service { this._clientOwner = null; }); const d = global.display; + this._snapshots = new Snapshots(event => this._emit(event), id => this._findWindow(id)); + this._focus = d.focus_window; this._displaySignals = [ d.connect('window-created', (_d, w) => { this._watchWindow(w); this._windowsChanged(); }), d.connect('restacked', () => this._windowsChanged()), - d.connect('notify::focus-window', () => this._emit({type: 'focusChanged', id: d.focus_window?.get_id() ?? null})), + d.connect('notify::focus-window', () => { + const left = this._focus; + this._focus = d.focus_window; + this._snapshots?.focusLeft(left); + this._emit({type: 'focusChanged', id: d.focus_window?.get_id() ?? null}); + }), d.connect('accelerator-activated', (_d, action, ...rest) => this._acceleratorActivated(action, rest[rest.length - 1])), ]; for (const w of allWindows()) @@ -183,6 +206,9 @@ class Service { stop() { this._releaseGrabs(); + this._snapshots?.stop(); + this._snapshots = null; + this._focus = null; for (const id of this._displaySignals) global.display.disconnect(id); this._displaySignals = []; @@ -357,14 +383,18 @@ class Service { const id = req.id; if (typeof id !== 'number' || !Number.isFinite(id)) throw badRequest('"id" must be a number'); - // the compositor's id, or the X11 id of an XWayland window (SMBAct knows its own windows by that) - const windows = allWindows(); - const w = windows.find(x => x.get_id() === id) ?? windows.find(x => x11WindowId(x) === id); + const w = this._findWindow(id); if (!w) throw new ShellError('NO_WINDOW', `no window ${id}`); return w; } + /** The compositor's id, or the X11 id of an XWayland window (SMBAct knows its own windows by that). */ + _findWindow(id) { + const windows = allWindows(); + return windows.find(x => x.get_id() === id) ?? windows.find(x => x11WindowId(x) === id) ?? null; + } + _number(req, key) { const v = req[key]; if (typeof v !== 'number' || !Number.isFinite(v)) diff --git a/gnome-shell/smbact@giglabo.com/metadata.json b/gnome-shell/smbact@giglabo.com/metadata.json index 126b1c6..4c081ab 100644 --- a/gnome-shell/smbact@giglabo.com/metadata.json +++ b/gnome-shell/smbact@giglabo.com/metadata.json @@ -1,9 +1,9 @@ { "uuid": "smbact@giglabo.com", "name": "SMBAct", - "description": "Lets the SMBAct app see and arrange every window on Wayland: the window list, moving and resizing, activation, window states and global hotkeys, over D-Bus. It does nothing on its own; SMBAct installs and uses it.", + "description": "Lets the SMBAct app see and arrange every window on Wayland: the window list, moving and resizing, activation, window states, global hotkeys and window snapshots for its switcher, over D-Bus. It does nothing on its own; SMBAct installs and uses it.", "shell-version": ["46", "47", "48", "49", "50", "51"], "url": "https://github.com/GigLaboCom/smbact-shell", - "version": 2, - "version-name": "1.0.0-alpha.2" + "version": 3, + "version-name": "1.0.0-alpha.3" } diff --git a/gnome-shell/smbact@giglabo.com/snapshots.js b/gnome-shell/smbact@giglabo.com/snapshots.js new file mode 100644 index 0000000..0e780f1 --- /dev/null +++ b/gnome-shell/smbact@giglabo.com/snapshots.js @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Window snapshots for SMBAct's switcher previews (PROTOCOL.md, `snapshots`). A snapshot costs the compositor about one +// frame (paint_to_content + a GPU readback; ~40 ms per window on a software-rendered VM, measured in SMBAct's W2), so: +// - snapshots are cached per window and taken again only when the window was damaged or resized since; +// - a request answers at once with what is cached, and the stale or missing ones are taken one at a time when the +// shell is idle, each announced with an `snapshot` event; +// - the window that just lost the focus is taken quietly a moment later (it is the likeliest next pick), when stale; +// - minimized windows are not painted: their last snapshot stays. +// The frame rect is cut out of the buffer (no client-side shadow), scaled to fit `maxSize` and encoded as JPEG over +// `background` (JPEG has no alpha; GdkPixbuf on GNOME 50 encodes through glycin, which refuses RGBA for JPEG). +import GdkPixbuf from 'gi://GdkPixbuf'; +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; +import Shell from 'gi://Shell'; + +const DEFAULT_MAX_SIZE = 480; +const MAX_MAX_SIZE = 1024; +const DEFAULT_BACKGROUND = 0xffffffff; +const JPEG_QUALITY = '85'; +/** Without a damage signal (an older Mutter), a snapshot counts as stale after this. */ +const MAX_AGE_WITHOUT_DAMAGE_MS = 5000; +const FOCUS_PREWARM_DELAY_MS = 300; + +const tryOr = (fn, fallback = null) => { + try { + return fn(); + } catch { + return fallback; + } +}; + +const compositeToStream = (texture, scale, stream) => new Promise((resolve, reject) => { + Shell.Screenshot.composite_to_stream(texture, 0, 0, -1, -1, scale, null, 0, 0, 1, stream, (_o, res) => { + try { + resolve(Shell.Screenshot.composite_to_stream_finish(res)); + } catch (e) { + reject(e); + } + }); +}); + +/** '#rrggbb' as GdkPixbuf's fill value (0xRRGGBBAA). */ +export const parseBackground = value => { + const m = typeof value === 'string' ? /^#([0-9a-f]{6})$/i.exec(value) : null; + return m ? ((Number.parseInt(m[1], 16) << 8) | 0xff) >>> 0 : DEFAULT_BACKGROUND; +}; + +export const fitTo = (w, h, maxSize) => { + const k = Math.min(1, maxSize / Math.max(w, h)); + return [Math.max(1, Math.round(w * k)), Math.max(1, Math.round(h * k))]; +}; + +export class Snapshots { + /** + * @param {(event: object) => void} emit the plugin's Event signal + * @param {(id: number) => Meta.Window | null} find a window by its id + */ + constructor(emit, find) { + this._emit = emit; + this._find = find; + /** window id -> { data, width, height, maxSize, background, at, dirty } */ + this._cache = new Map(); + /** window id -> { window, actor, ids: [window signal ids], actorIds: [actor signal ids] } */ + this._watched = new Map(); + /** pending captures: window id -> { maxSize, background, notify } */ + this._queue = new Map(); + this._busy = false; + this._idleId = 0; + this._prewarmId = 0; + this._last = {maxSize: DEFAULT_MAX_SIZE, background: DEFAULT_BACKGROUND}; + this._stopped = false; + } + + stop() { + this._stopped = true; + if (this._idleId) + GLib.source_remove(this._idleId); + if (this._prewarmId) + GLib.source_remove(this._prewarmId); + this._idleId = this._prewarmId = 0; + for (const id of [...this._watched.keys()]) + this._unwatch(id); + this._cache.clear(); + this._queue.clear(); + } + + /** `snapshots {ids, maxSize?, background?}`: the cached ones now, the stale ones queued. */ + request(ids, maxSize, background) { + const size = typeof maxSize === 'number' && maxSize > 0 ? Math.min(Math.round(maxSize), MAX_MAX_SIZE) : DEFAULT_MAX_SIZE; + const bg = parseBackground(background); + this._last = {maxSize: size, background: bg}; + const out = []; + for (const requested of ids) { + const w = this._find(requested); + if (!w) + continue; + const id = w.get_id(); + const entry = this._cache.get(id); + const stale = !entry || this._isStale(entry) || entry.maxSize !== size || entry.background !== bg; + if (entry) + out.push(this._describe(id, entry, !stale)); + if (stale) + this._enqueue(id, size, bg, true); + } + return out; + } + + /** `snapshot {id}`: the cached one, or null. */ + get(requested) { + const w = this._find(requested); + const entry = w ? this._cache.get(w.get_id()) : null; + return entry ? this._describe(w.get_id(), entry, !this._isStale(entry)) : null; + } + + /** The focus moved away from `w`: take it again quietly a moment later, if it is stale. */ + focusLeft(w) { + if (!w || this._stopped) + return; + const id = w.get_id(); + if (this._prewarmId) + GLib.source_remove(this._prewarmId); + this._prewarmId = GLib.timeout_add(GLib.PRIORITY_LOW, FOCUS_PREWARM_DELAY_MS, () => { + this._prewarmId = 0; + const entry = this._cache.get(id); + if (!entry || this._isStale(entry)) + this._enqueue(id, this._last.maxSize, this._last.background, false); + return GLib.SOURCE_REMOVE; + }); + } + + /** The window is gone. */ + forget(id) { + this._cache.delete(id); + this._queue.delete(id); + this._unwatch(id); + } + + _describe(id, entry, fresh) { + return {id, mime: 'image/jpeg', data: entry.data, width: entry.width, height: entry.height, fresh}; + } + + _isStale(entry) { + return entry.dirty || (!entry.damageSignal && Date.now() - entry.at > MAX_AGE_WITHOUT_DAMAGE_MS); + } + + _enqueue(id, maxSize, background, notify) { + const pending = this._queue.get(id); + this._queue.set(id, {maxSize, background, notify: notify || (pending?.notify ?? false)}); + this._schedule(); + } + + _schedule() { + if (this._idleId || this._busy || this._stopped || this._queue.size === 0) + return; + this._idleId = GLib.idle_add(GLib.PRIORITY_LOW, () => { + this._idleId = 0; + this._next(); + return GLib.SOURCE_REMOVE; + }); + } + + async _next() { + const first = this._queue.entries().next(); + if (first.done) + return; + const [id, job] = first.value; + this._queue.delete(id); + this._busy = true; + try { + const w = this._find(id); + const shot = w ? await this._capture(w, job.maxSize, job.background) : null; + if (shot && !this._stopped) { + const watch = this._watch(w); + this._cache.set(id, {...shot, maxSize: job.maxSize, background: job.background, at: Date.now(), dirty: false, + damageSignal: watch.damageSignal}); + if (job.notify) + this._emit({type: 'snapshot', id}); + } + } catch (e) { + console.warn(`smbact: snapshot of window ${id} failed: ${e?.message ?? e}`); + } finally { + this._busy = false; + this._schedule(); + } + } + + async _capture(w, maxSize, background) { + if (w.minimized) + return null; + const actor = w.get_compositor_private(); + if (!actor) + return null; + // The whole buffer, the way GNOME's own window screenshot takes it (paint_to_content's clip is not in logical + // actor coordinates on GNOME 50). The visible window is the frame rect inside the buffer rect (a client-side + // shadow lies outside it): cut it out of the image in proportion, whatever the buffer scale is. + const frame = w.get_frame_rect(); + const buffer = w.get_buffer_rect(); + const texture = actor.paint_to_content(null)?.get_texture(); + if (!texture || buffer.width <= 0 || buffer.height <= 0) + return null; + const stream = Gio.MemoryOutputStream.new_resizable(); + const full = await compositeToStream(texture, actor.get_resource_scale(), stream); + tryOr(() => stream.close(null)); + const kx = full.get_width() / buffer.width; + const ky = full.get_height() / buffer.height; + const cx = Math.max(0, Math.round((frame.x - buffer.x) * kx)); + const cy = Math.max(0, Math.round((frame.y - buffer.y) * ky)); + const cw = Math.max(1, Math.min(full.get_width() - cx, Math.round(frame.width * kx))); + const ch = Math.max(1, Math.min(full.get_height() - cy, Math.round(frame.height * ky))); + const pixbuf = cw < full.get_width() || ch < full.get_height() ? full.new_subpixbuf(cx, cy, cw, ch) : full; + const [sw, sh] = fitTo(cw, ch, maxSize); + const small = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, false, 8, sw, sh); + small.fill(background); + pixbuf.composite(small, 0, 0, sw, sh, 0, 0, sw / cw, sh / ch, GdkPixbuf.InterpType.BILINEAR, 255); + const [, bytes] = small.save_to_bufferv('jpeg', ['quality'], [JPEG_QUALITY]); + return {data: GLib.base64_encode(bytes), width: sw, height: sh}; + } + + /** Marks the window's snapshot stale on damage or a new size; returns whether damage is reported at all. */ + _watch(w) { + const id = w.get_id(); + const existing = this._watched.get(id); + if (existing) + return existing; + const stale = () => { + const entry = this._cache.get(id); + if (entry) + entry.dirty = true; + }; + const actor = w.get_compositor_private(); + const actorIds = []; + let damageSignal = false; + if (actor) { + const damageId = tryOr(() => actor.connect('damaged', stale)); + if (damageId) { + actorIds.push(damageId); + damageSignal = true; + } + } + const ids = [w.connect('size-changed', stale), w.connect('unmanaged', () => this.forget(id))]; + const watch = {window: w, actor, ids, actorIds, damageSignal}; + this._watched.set(id, watch); + return watch; + } + + _unwatch(id) { + const watch = this._watched.get(id); + if (!watch) + return; + for (const sid of watch.ids) + tryOr(() => watch.window.disconnect(sid)); + for (const sid of watch.actorIds) + tryOr(() => watch.actor.disconnect(sid)); + this._watched.delete(id); + } +} diff --git a/scripts/call.py b/scripts/call.py index 9a23754..e364d67 100755 --- a/scripts/call.py +++ b/scripts/call.py @@ -9,6 +9,7 @@ scripts/call.py moveResize '{"id": 123, "x": 100, "y": 100, "width": 800, "height": 600}' scripts/call.py --events 10 # print Event signals for 10 seconds scripts/call.py --grab 'j' 30 # hold a hotkey for 30 seconds, print its presses + scripts/call.py --snapshots /tmp/shots 480 # snapshot every listed window into /tmp/shots, print timings scripts/call.py --as-stranger hello # without the name: expect AccessDenied """ import json @@ -26,6 +27,8 @@ def main(argv): if not argv: print(__doc__) return 2 + if argv[0] == "--snapshots": + return snapshots(argv[1] if len(argv) > 1 else "/tmp/smbact-shots", int(argv[2]) if len(argv) > 2 else 480) if argv[0] == "--grab": return grab(argv[1], int(argv[2]) if len(argv) > 2 else 30) if argv[0] == "--events": @@ -54,6 +57,49 @@ def main(argv): return 0 +def snapshots(out_dir, max_size): + """Requests snapshots of every normal window twice: the first answer is empty (nothing cached), the windows come + one by one as `snapshot` events; the second answer has them all, fresh.""" + import base64, os, time + from gi.repository import GLib + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + bus = dbus.SessionBus() + got = bus.request_name(CLIENT, dbus.bus.NAME_FLAG_DO_NOT_QUEUE) + if got not in (dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER, dbus.bus.REQUEST_NAME_REPLY_ALREADY_OWNER): + print(f"cannot own {CLIENT} (is SMBAct running?)", file=sys.stderr) + return 1 + call = bus.get_object(DEST, PATH).get_dbus_method("Call", IFACE) + req = lambda **r: json.loads(call(json.dumps(r))) + windows = [w for w in req(op="listWindows")["result"]["windows"] if w["type"] == "normal" and not w["skipTaskbar"]] + ids = [w["id"] for w in windows] + os.makedirs(out_dir, exist_ok=True) + t0 = time.monotonic() + first = req(op="snapshots", ids=ids, maxSize=max_size, background="#ffffff") + print(json.dumps({"windows": len(ids), "cached at first": len(first["result"]["snapshots"])}), flush=True) + arrived = {} + loop = GLib.MainLoop() + + def on_event(e): + event = json.loads(e) + if event.get("type") == "snapshot": + arrived[event["id"]] = round((time.monotonic() - t0) * 1000) + if len(arrived) == len(ids): + loop.quit() + + bus.add_signal_receiver(on_event, "Event", IFACE, None, PATH) + GLib.timeout_add_seconds(20, loop.quit) + loop.run() + second = req(op="snapshots", ids=ids, maxSize=max_size, background="#ffffff")["result"]["snapshots"] + for snap in second: + title = next((w["title"] for w in windows if w["id"] == snap["id"]), "?") + path = os.path.join(out_dir, f"{snap['id']}.jpg") + data = base64.b64decode(snap["data"]) + open(path, "wb").write(data) + print(json.dumps({"id": snap["id"], "title": title[:40], "size": [snap["width"], snap["height"]], + "kb": round(len(data) / 1024, 1), "fresh": snap["fresh"], "at_ms": arrived.get(snap["id"])})) + return 0 + + def grab(accelerator, seconds): """Grabs belong to the owner of com.giglabo.SMBAct: keep the name (and the grab) while listening.""" from gi.repository import GLib From 22c10a348c5d953d4ea5f85eb39c653eb0284a8b Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 8 Nov 2026 17:01:39 +0100 Subject: [PATCH 2/2] kwin/smbact-kwin.js: the KWin script (Plasma 6), same protocol as the extension A KWin script cannot serve D-Bus calls: SMBAct serves com.giglabo.SMBAct.KWin1 and the script calls in (Hello, Next(reply) -> request long-poll, Event), PROTOCOL.md "KWin transport". All window operations of API 1; no snapshots, accelerator grabs or icon rendering (documented). Window ids: the first 32 bits of KWin's UUID. Releases carry smbact-kwin.js next to the extension zip (pack.sh, release.yml with a VERSION check, SHA256SUMS); CI checks its syntax and snapshots.js'. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +- .github/workflows/release.yml | 11 +- PROTOCOL.md | 32 +++- README.md | 22 ++- kwin/smbact-kwin.js | 303 ++++++++++++++++++++++++++++++++++ scripts/pack.sh | 7 +- 6 files changed, 370 insertions(+), 12 deletions(-) create mode 100644 kwin/smbact-kwin.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab3881a..fe16669 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,9 @@ jobs: run: | cp "gnome-shell/smbact@giglabo.com/extension.js" "$RUNNER_TEMP/extension.mjs" node --check "$RUNNER_TEMP/extension.mjs" + cp "gnome-shell/smbact@giglabo.com/snapshots.js" "$RUNNER_TEMP/snapshots.mjs" + node --check "$RUNNER_TEMP/snapshots.mjs" + node --check kwin/smbact-kwin.js python3 -m py_compile scripts/call.py python3 -c "import json; json.load(open('gnome-shell/smbact@giglabo.com/metadata.json'))" - name: Pack @@ -27,4 +30,6 @@ jobs: - uses: actions/upload-artifact@v4 with: name: smbact-shell-gnome - path: dist/*.zip + path: | + dist/*.zip + dist/smbact-kwin.js diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6ae2d18..35ce571 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,10 +21,15 @@ jobs: echo "tag $GITHUB_REF_NAME does not match metadata.json version-name ($want)" >&2 exit 1 fi + kwin="v$(sed -n 's/^const VERSION = "\(.*\)";$/\1/p' kwin/smbact-kwin.js)" + if [ "$kwin" != "$GITHUB_REF_NAME" ]; then + echo "tag $GITHUB_REF_NAME does not match kwin/smbact-kwin.js VERSION ($kwin)" >&2 + exit 1 + fi - name: Pack run: | scripts/pack.sh - (cd dist && sha256sum ./*.zip > SHA256SUMS && cat SHA256SUMS) + (cd dist && sha256sum ./*.zip ./smbact-kwin.js > SHA256SUMS && cat SHA256SUMS) - name: Release env: GH_TOKEN: ${{ github.token }} @@ -32,6 +37,6 @@ jobs: # a tag with a suffix (v1.0.0-alpha.1, -beta.2, -rc.1) is a pre-release pre="" case "$GITHUB_REF_NAME" in *-*) pre="--prerelease" ;; esac - gh release create "$GITHUB_REF_NAME" dist/*.zip dist/SHA256SUMS $pre \ + gh release create "$GITHUB_REF_NAME" dist/*.zip dist/smbact-kwin.js dist/SHA256SUMS $pre \ --title "smbact-shell $GITHUB_REF_NAME" \ - --notes "GNOME Shell extension smbact@giglabo.com, protocol com.giglabo.SMBAct.Shell1 API 1. See PROTOCOL.md." + --notes "GNOME Shell extension smbact@giglabo.com and the KWin script smbact-kwin.js, protocol API 1. See PROTOCOL.md." diff --git a/PROTOCOL.md b/PROTOCOL.md index eb96122..a185609 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -1,7 +1,8 @@ # Protocol: `com.giglabo.SMBAct.Shell1`, API 1 -How SMBAct talks to its shell plugins. The GNOME Shell extension implements it today; a KWin script will -implement the same operations. SMBAct (a separate program) is the only intended client. +How SMBAct talks to its shell plugins: the GNOME Shell extension (`gnome-shell/`) and the KWin script (`kwin/`, +Plasma 6) implement the same operations with the same JSON; only the transport differs (see "KWin transport"). SMBAct +(a separate program) is the only intended client. ## D-Bus @@ -157,3 +158,30 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - API 1, plugin 1.0.0-alpha.2 (2026-11): `grabAccelerator`, `ungrabAccelerator`, the `accelerator` event (new operations, same API; clients look for them in `hello`'s `ops`). - API 1, plugin 1.0.0-alpha.3 (2026-11): `snapshots`, `snapshot`, the `snapshot` event. + +## KWin transport + +A KWin script cannot own a D-Bus name or serve calls, so the direction turns around. SMBAct owns +`com.giglabo.SMBAct`, serves the interface `com.giglabo.SMBAct.KWin1` on `/com/giglabo/SMBAct/KWin1` and loads +`smbact-kwin.js` into KWin through `org.kde.KWin` `/Scripting` (`loadScript(path, "smbact")`, then +`/Scripting/Script` `run`): no install, no new login. The script calls in: + +| method | | | +|---|---|---| +| `Hello(s hello)` | once, when the script runs | `hello` is the `hello` operation's result (`plugin: "smbact-kwin"`) | +| `Next(s reply) -> s request` | in a loop | hands over the reply to the previous request (empty the first time) and gets the next request; SMBAct holds the call until it has one and answers `{"op":"noop"}` after 15 s (Qt's D-Bus timeout is 25 s) | +| `Event(s event)` | fire and forget | the events above (`windowsChanged` at most every 100 ms and after a drag, `focusChanged`) | + +Requests and replies carry `seq` (the transport pairs them by it; `id` stays a request argument). SMBAct accepts the +calls only from the owner of `org.kde.KWin`. When SMBAct goes away the script's calls fail and its loop ends; SMBAct +unloads it when it quits and loads it again when it starts or when KWin restarts. + +What the KWin script does not have: `snapshots` / `snapshot` (KWin offers window screenshots only through +`org.kde.KWin.ScreenShot2`, which takes a file descriptor and an authorized caller), `grabAccelerator` (on Plasma +SMBAct's own X11 hotkeys fire with any focus: KWin passes key combinations to XWayland apps), `iconPng` (a window's +icon is a QIcon: the script reports `desktopFile` and SMBAct looks the icon up), and the X11 marks (`client`, +`x11Window` are `null`: KWin's scripting API does not tell X11 from Wayland windows; SMBAct matches them against the X +server's own list). Window ids are the first 32 bits of KWin's UUID for the window (stable across reloads). + +- API 1, plugin 1.0.0-alpha.3 (2026-11): the KWin script (`kwin/smbact-kwin.js`). + diff --git a/README.md b/README.md index 2fe3301..39bde2e 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # smbact-shell -Shell plugins for SMBAct, the window management app: a GNOME Shell extension now, -a KWin script later. On a Wayland session only the compositor knows every window, so SMBAct asks it through these -plugins: the window list, moving and resizing, activation, window states, displays. +Shell plugins for SMBAct, the window management app: a GNOME Shell extension and a KWin script (KDE Plasma 6). On a +Wayland session only the compositor knows every window, so SMBAct asks it through these plugins: the window list, +moving and resizing, activation, window states, displays; on GNOME also global hotkeys and window snapshots. The plugins are thin executors. They hold no product logic and do nothing on their own; SMBAct installs them and calls them over D-Bus. The protocol is in [PROTOCOL.md](PROTOCOL.md). @@ -24,10 +24,24 @@ On Wayland a newly installed or updated extension starts after you log out and b Only SMBAct may call it: the extension answers the current owner of the D-Bus name `com.giglabo.SMBAct` and refuses everyone else. +## KWin script + +`kwin/smbact-kwin.js` — KDE Plasma 6 (checked on Plasma 6.6). SMBAct loads it into KWin itself when it starts +(`org.kde.KWin` `/Scripting`), nothing to install and no new login; it unloads it when it quits. A KWin script cannot +serve D-Bus calls, so the script calls SMBAct instead (PROTOCOL.md, "KWin transport"); it answers only to KWin. + +By hand, with something serving `com.giglabo.SMBAct.KWin1` (SMBAct does): + +```bash +qdbus6 org.kde.KWin /Scripting org.kde.kwin.Scripting.loadScript "$PWD/kwin/smbact-kwin.js" smbact +qdbus6 org.kde.KWin /Scripting/Script org.kde.kwin.Script.run +``` + ## Releases A tag `vX.Y.Z` (equal to `version-name` in `metadata.json`; `vX.Y.Z-alpha.N`, `-beta.N`, `-rc.N` become pre-releases) makes GitHub Actions publish -`smbact@giglabo.com.shell-extension.zip` and `SHA256SUMS` as a release. SMBAct pins a tag and checks the sha256. +`smbact@giglabo.com.shell-extension.zip`, `smbact-kwin.js` and `SHA256SUMS` as a release (the KWin script's `VERSION` +must match too). SMBAct pins a tag and checks the sha256 of both. Every push to `main` and every pull request runs the checks and packs the zip (`.github/workflows/`). ## License diff --git a/kwin/smbact-kwin.js b/kwin/smbact-kwin.js new file mode 100644 index 0000000..97d56f0 --- /dev/null +++ b/kwin/smbact-kwin.js @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SMBAct shell plugin for KWin (Plasma 6): the operations of PROTOCOL.md (API 1) as a KWin script. A KWin script +// cannot own a D-Bus name, so the transport turns around (PROTOCOL.md "KWin transport"): SMBAct exports +// com.giglabo.SMBAct.KWin1 on its own connection, loads this script through org.kde.KWin /Scripting, and the script +// asks it for work: `Next(reply) -> request` (SMBAct holds the call until it has a request), `Event(event)`, +// `Hello(hello)`. Requests, replies and events are the same JSON as the GNOME Shell extension's, plus `seq` in a +// request and its reply (the transport pairs them by it). +// A thin executor, like the extension: no decisions, nothing on its own. When SMBAct goes away its calls fail and +// the loop ends; SMBAct unloads and loads the script again when it starts. +const SERVICE = "com.giglabo.SMBAct"; +const PATH = "/com/giglabo/SMBAct/KWin1"; +const IFACE = "com.giglabo.SMBAct.KWin1"; +const API = 1; +const VERSION = "1.0.0-alpha.3"; +/** At most one windowsChanged event this often (a drag moves a window every frame); the end of a drag sends one too. */ +const EVENT_MIN_INTERVAL_MS = 100; + +class ShellError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +const badRequest = (message) => new ShellError("BAD_REQUEST", message); + +/** + * A stable number for a window: the first 32 bits of KWin's UUID, the same across reloads. 32 bits like an X11 id + * (SMBAct's CLI and native paths keep window ids in 32 bits); a clash among a session's windows is about 1 in a million. + */ +function idOf(w) { + return parseInt(String(w.internalId).replace(/[{}-]/g, "").slice(0, 8), 16) >>> 0 || 1; +} + +function rect(r) { + return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }; +} + +function typeOf(w) { + if (w.desktopWindow) return "desktop"; + if (w.dock) return "dock"; + if (w.splash) return "splashscreen"; + if (w.popupMenu || w.dropdownMenu || w.menu || w.comboBox || w.tooltip || w.notification || w.criticalNotification) return "menu"; + if (w.toolbar) return "toolbar"; + if (w.dialog) return w.modal ? "modal-dialog" : "dialog"; + if (w.utility) return "utility"; + if (w.normalWindow) return "normal"; + return "other"; +} + +function windows() { + return workspace.windowList().filter((w) => w.managed !== false && !w.deleted); +} + +function find(id) { + if (typeof id !== "number" || !isFinite(id)) throw badRequest('"id" must be a number'); + const w = windows().find((x) => idOf(x) === id); + if (!w) throw new ShellError("NO_WINDOW", "no window " + id); + return w; +} + +function number(req, key) { + const v = req[key]; + if (typeof v !== "number" || !isFinite(v)) throw badRequest('"' + key + '" must be a number'); + return Math.round(v); +} + +function screenIndex(output) { + const screens = workspace.screens; + for (let i = 0; i < screens.length; i++) if (screens[i] === output) return i; + return 0; +} + +function desktopIndex(w) { + const all = workspace.desktops; + const mine = w.desktops; + if (!mine || mine.length !== 1) return -1; + for (let i = 0; i < all.length; i++) if (all[i] === mine[0]) return i; + return -1; +} + +function describe(w, stack) { + if (!w) return null; + const mode = w.maximizeMode || 0; // 1 vertical, 2 horizontal, 3 both + return { + id: idOf(w), + title: w.caption || "", + wmClass: w.resourceClass || null, + wmClassInstance: w.resourceName || null, + appId: w.desktopFileName || null, + sandboxedAppId: null, + app: w.desktopFileName ? w.desktopFileName + ".desktop" : null, + pid: w.pid || -1, + // KWin's scripting API does not tell X11 from Wayland: SMBAct fills these from the X server's own list + client: null, + x11Window: null, + type: typeOf(w), + frame: rect(w.frameGeometry), + clientRect: rect(w.clientGeometry), + focus: !!w.active, + minimized: !!w.minimized, + maximized: mode === 3, + maximizedHorizontally: (mode & 2) !== 0, + maximizedVertically: (mode & 1) !== 0, + fullscreen: !!w.fullScreen, + above: !!w.keepAbove, + skipTaskbar: !!w.skipTaskbar, + monitor: screenIndex(w.output), + workspace: desktopIndex(w), + onAllWorkspaces: !!w.onAllDesktops, + stack: stack === undefined ? null : stack, + icon: null, // a QIcon, not a file: SMBAct looks the app's icon up by its desktop file + desktopFile: w.desktopFileName || null, + }; +} + +function listWindows() { + const order = workspace.stackingOrder; // bottom to top + const listed = windows(); + const out = []; + for (let i = 0; i < order.length; i++) if (listed.indexOf(order[i]) >= 0) out.push(describe(order[i], i)); + for (const w of listed) if (order.indexOf(w) < 0) out.push(describe(w, null)); + return { windows: out }; +} + +function moveResize(req) { + const w = find(req.id); + let x = number(req, "x"); + let y = number(req, "y"); + let width = number(req, "width"); + let height = number(req, "height"); + if (width <= 0 || height <= 0) throw badRequest('"width" and "height" must be positive'); + if (req.space === "client") { + // the rect is the client area: add this window's decoration around it + const f = w.frameGeometry; + const c = w.clientGeometry; + x -= Math.round(c.x - f.x); + y -= Math.round(c.y - f.y); + width += Math.round(f.width - c.width); + height += Math.round(f.height - c.height); + } else if (req.space !== undefined && req.space !== "frame") { + throw badRequest('"space" is "frame" or "client"'); + } + if (w.fullScreen) w.fullScreen = false; + if (w.maximizeMode) w.setMaximize(false, false); + w.frameGeometry = { x: x, y: y, width: width, height: height }; + return { window: describe(w) }; +} + +function setState(req) { + const w = find(req.id); + if (typeof req.on !== "boolean") throw badRequest('"on" must be true or false'); + const on = req.on; + const mode = w.maximizeMode || 0; + switch (req.state) { + case "minimized": + w.minimized = on; + break; + case "maximized": + w.setMaximize(on, on); + break; + case "maximizedHorizontally": + w.setMaximize((mode & 1) !== 0, on); + break; + case "maximizedVertically": + w.setMaximize(on, (mode & 2) !== 0); + break; + case "fullscreen": + w.fullScreen = on; + break; + case "above": + w.keepAbove = on; + break; + default: + throw badRequest('unknown state "' + req.state + '"'); + } + return { window: describe(w) }; +} + +let shownDesktop = []; + +function showDesktop(req) { + if (typeof req.show !== "boolean") throw badRequest('"show" must be true or false'); + if (req.show) { + const visible = windows().filter((w) => !w.minimized && !w.skipTaskbar && w.normalWindow && (w.onAllDesktops || w.desktops.indexOf(workspace.currentDesktop) >= 0)); + for (const w of visible) w.minimized = true; + shownDesktop = visible.map(idOf); + return { windows: visible.length }; + } + const ids = shownDesktop; + shownDesktop = []; + const restore = windows().filter((w) => ids.indexOf(idOf(w)) >= 0 && w.minimized); + for (const w of restore) w.minimized = false; + return { windows: restore.length }; +} + +function displays() { + const screens = workspace.screens; + const monitors = []; + for (let i = 0; i < screens.length; i++) { + const o = screens[i]; + monitors.push({ + index: i, + geometry: rect(o.geometry), + workArea: rect(workspace.clientArea(KWin.MaximizeArea, o, workspace.currentDesktop)), + scale: o.devicePixelRatio || 1, + primary: i === 0, // KWin has no primary output; the first one is the one Plasma treats as such + }); + } + return { monitors: monitors }; +} + +const OPS = { + hello: () => hello(), + listWindows: () => listWindows(), + getWindow: (req) => ({ window: describe(find(req.id)) }), + activeWindow: () => ({ window: describe(workspace.activeWindow) }), + moveResize: (req) => moveResize(req), + activate: (req) => { + const w = find(req.id); + if (w.minimized) w.minimized = false; + workspace.activeWindow = w; + return { window: describe(w) }; + }, + raise: (req) => { + const w = find(req.id); + workspace.raiseWindow(w); + return { window: describe(w) }; + }, + setState: (req) => setState(req), + close: (req) => { + find(req.id).closeWindow(); + return { closed: true }; + }, + showDesktop: (req) => showDesktop(req), + displays: () => displays(), + pointer: () => ({ x: Math.round(workspace.cursorPos.x), y: Math.round(workspace.cursorPos.y) }), +}; + +function hello() { + return { api: API, plugin: "smbact-kwin", version: VERSION, shell: "KWin", session: "wayland", ops: Object.keys(OPS) }; +} + +function handle(request) { + let req; + try { + req = JSON.parse(request); + } catch (e) { + return { seq: null, ok: false, error: { code: "BAD_REQUEST", message: "the request is not JSON" } }; + } + try { + if (!req || typeof req.op !== "string") throw badRequest('the request needs an "op"'); + const op = OPS[req.op]; + if (!op) throw new ShellError("UNKNOWN_OP", 'unknown op "' + req.op + '"'); + return { seq: req.seq, ok: true, result: op(req) }; + } catch (e) { + return { seq: req && req.seq, ok: false, error: { code: e && e.code ? e.code : "FAILED", message: String(e && e.message ? e.message : e) } }; + } +} + +// ---- events (fire and forget; SMBAct coalesces them) + +let lastWindowsEvent = 0; + +function emit(event) { + callDBus(SERVICE, PATH, IFACE, "Event", JSON.stringify(event)); +} + +function windowsChanged(force) { + const now = Date.now(); + if (!force && now - lastWindowsEvent < EVENT_MIN_INTERVAL_MS) return; + lastWindowsEvent = now; + emit({ type: "windowsChanged" }); +} + +function watch(w) { + const changed = () => windowsChanged(false); + w.frameGeometryChanged.connect(changed); + w.minimizedChanged.connect(() => windowsChanged(true)); + w.captionChanged.connect(changed); + w.maximizedChanged.connect(() => windowsChanged(true)); + w.fullScreenChanged.connect(() => windowsChanged(true)); + w.interactiveMoveResizeFinished.connect(() => windowsChanged(true)); +} + +workspace.windowAdded.connect((w) => { + watch(w); + windowsChanged(true); +}); +workspace.windowRemoved.connect(() => windowsChanged(true)); +workspace.windowActivated.connect((w) => emit({ type: "focusChanged", id: w ? idOf(w) : null })); +for (const w of workspace.windowList()) watch(w); + +// ---- the request loop: each Next carries the previous reply and brings the next request + +function loop(reply) { + callDBus(SERVICE, PATH, IFACE, "Next", reply, (request) => { + const req = String(request || ""); + loop(req === "" || req === '{"op":"noop"}' ? "" : JSON.stringify(handle(req))); + }); +} + +callDBus(SERVICE, PATH, IFACE, "Hello", JSON.stringify(hello()), () => loop("")); diff --git a/scripts/pack.sh b/scripts/pack.sh index 15f26e8..12d86a9 100755 --- a/scripts/pack.sh +++ b/scripts/pack.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Packs the GNOME Shell extension into the zip `gnome-extensions install` takes: -# scripts/pack.sh -> dist/smbact@giglabo.com.shell-extension.zip +# Packs the plugins for a release: +# scripts/pack.sh -> dist/smbact@giglabo.com.shell-extension.zip (the GNOME Shell extension, for `gnome-extensions install`) +# dist/smbact-kwin.js (the KWin script; SMBAct loads it into KWin itself) set -euo pipefail cd "$(dirname "$0")/.." UUID=smbact@giglabo.com @@ -9,4 +10,6 @@ mkdir -p dist rm -f "$OUT" (cd "gnome-shell/$UUID" && zip -q -X -r "../../$OUT" .) zip -q -X -j "$OUT" LICENSE +cp kwin/smbact-kwin.js dist/smbact-kwin.js echo "$OUT" +echo dist/smbact-kwin.js