From 467b605aa6fec28b5e75d1e27814f178cddd3082 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 8 Nov 2026 13:38:06 +0100 Subject: [PATCH 1/3] GNOME Shell extension and protocol, API 1 com.giglabo.SMBAct.Shell1 over D-Bus (JSON in Call, Event signal): window list with icons and X11 ids, getWindow, activeWindow, moveResize (two steps, so windows with resize increments keep the position), activate, raise, setState (minimized, maximized, horizontal / vertical, fullscreen, above), close, showDesktop, displays, pointer; windowsChanged / focusChanged events. Only the owner of com.giglabo.SMBAct may call. GNOME Shell 46-51. scripts/pack.sh builds the zip for gnome-extensions install; scripts/call.py calls the extension by hand. Checked on GNOME Shell 50.1 (Ubuntu 26.04), Wayland, two monitors at mixed scales. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + PROTOCOL.md | 126 ++++++ README.md | 30 +- gnome-shell/smbact@giglabo.com/extension.js | 453 +++++++++++++++++++ gnome-shell/smbact@giglabo.com/metadata.json | 9 + scripts/call.py | 55 +++ scripts/pack.sh | 12 + 7 files changed, 685 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 PROTOCOL.md create mode 100644 gnome-shell/smbact@giglabo.com/extension.js create mode 100644 gnome-shell/smbact@giglabo.com/metadata.json create mode 100755 scripts/call.py create mode 100755 scripts/pack.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..849ddff --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +dist/ diff --git a/PROTOCOL.md b/PROTOCOL.md new file mode 100644 index 0000000..bae6147 --- /dev/null +++ b/PROTOCOL.md @@ -0,0 +1,126 @@ +# 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. + +## D-Bus + +| | | +|---|---| +| Bus | session | +| Name (owned by the plugin) | `com.giglabo.SMBAct.Shell` | +| Object | `/com/giglabo/SMBAct/Shell1` | +| Interface | `com.giglabo.SMBAct.Shell1` | +| Method | `Call(in s request, out s reply)` | +| Signal | `Event(s event)` | + +Requests and replies are JSON strings, so a client needs nothing beyond string calls. + +**Who may call.** Only the current owner of the well-known name `com.giglabo.SMBAct` (SMBAct requests it with +`DO_NOT_QUEUE`). Every other caller gets the D-Bus error `org.freedesktop.DBus.Error.AccessDenied`. This keeps +unrelated programs out while SMBAct runs. It does not stop a program of the same user that takes the name while SMBAct +is not running; GNOME's own allow-lists have the same limit. + +## Requests and replies + +```json +{ "op": "moveResize", "id": 2653220665, "x": 90, "y": 80, "width": 640, "height": 420 } +``` + +```json +{ "ok": true, "result": { "window": { ... } } } +{ "ok": false, "error": { "code": "NO_WINDOW", "message": "no window 2653220665" } } +``` + +Error codes: `BAD_REQUEST` (not JSON, missing or wrong arguments), `UNKNOWN_OP`, `NO_WINDOW`, `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. + +## Coordinates + +Logical pixels of the compositor's layout (Mutter's stage), the same space as Electron's DIPs for windows under +XWayland. Rectangles are `{ "x", "y", "width", "height" }`. + +## Window + +```json +{ + "id": 2653220665, + "title": "Licenses — Mozilla Firefox", + "wmClass": "firefox", + "wmClassInstance": "Navigator", + "appId": "org.mozilla.firefox", + "sandboxedAppId": null, + "app": "firefox.desktop", + "pid": 3068, + "client": "wayland", + "x11Window": null, + "type": "normal", + "frame": { "x": 67, "y": 32, "width": 1213, "height": 768 }, + "clientRect": { "x": 67, "y": 69, "width": 1213, "height": 731 }, + "focus": true, + "minimized": false, + "maximized": true, + "maximizedHorizontally": true, + "maximizedVertically": true, + "fullscreen": false, + "above": false, + "skipTaskbar": false, + "monitor": 0, + "workspace": 0, + "onAllWorkspaces": false, + "stack": 4, + "icon": "/usr/share/icons/hicolor/48x48/apps/firefox.png" +} +``` + +- `id`: the compositor's window id, unique in the session (fits in a JSON number). +- `client`: `wayland` or `x11`; `x11Window`: the X11 window id of an XWayland window, else `null`. +- `type`: `normal`, `dialog`, `modal-dialog`, `utility`, `splashscreen`, `menu`, `toolbar`, `desktop`, `dock`, or + `other`. The plugin lists every managed window; the client picks what it shows. +- `frame`: the visible window including server-side decorations; `clientRect`: the client area (larger than `frame` + when the window draws its own shadow). +- `stack`: position in the stacking order, 0 = bottom. +- `icon`: a file path from the icon theme (only when asked for, see `listWindows`), or `null`. + +## Operations (API 1) + +| op | arguments | result | +|---|---|---| +| `hello` | | `{ api, plugin, version, shell, session, ops }` | +| `listWindows` | `icons?` (bool), `iconSize?` (px, default 48) | `{ windows: Window[] }` | +| `getWindow` | `id` | `{ window }` | +| `activeWindow` | | `{ window }` (`null` when nothing has focus) | +| `moveResize` | `id`, `x`, `y`, `width`, `height` | `{ window }` | +| `activate` | `id`, `time?` | `{ window }` | +| `raise` | `id` | `{ window }` | +| `setState` | `id`, `state`, `on` | `{ window }` | +| `close` | `id`, `force?` | `{ closed: true }` | +| `showDesktop` | `show` | `{ windows }` (how many were minimized or restored) | +| `displays` | | `{ monitors: [{ index, geometry, workArea, scale, primary }] }` | +| `pointer` | | `{ x, y }` | + +- `setState` states: `minimized`, `maximized`, `maximizedHorizontally`, `maximizedVertically`, `fullscreen`, + `above`. +- `moveResize` leaves maximized and fullscreen first, then moves and resizes in two steps, so windows with resize + increments (terminals) keep the requested position. +- Wayland windows apply a new geometry or state asynchronously (the client acknowledges it about a frame later), so + the `window` in the reply of `moveResize` and `setState` may still show the previous geometry; read it again + with `getWindow` (or wait for `windowsChanged`) when the new one matters. +- `activate` uses the server's current time unless `time` is given (an input event's timestamp). +- `close` asks the window to close; `force` kills its client. +- `showDesktop` with `show: true` minimizes the visible windows of the active workspace and remembers them; `false` + restores those. + +## Events + +`Event` carries `{ "type": ..., ... }`: + +- `windowsChanged`: a window appeared, went away, moved, resized or changed state (coalesced, at most every 100 ms). +- `focusChanged` with `id` (or `null`). + +## History + +- API 1 (2026-11): window list, geometry, activation, states, close, displays, pointer, events. diff --git a/README.md b/README.md index 4f249e5..4e8777c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,30 @@ # smbact-shell -SMBAct shell plugins: a GNOME Shell extension (and later a KWin script) that lets SMBAct see and arrange every window on Wayland. GPL-2.0-or-later. + +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. + +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). + +## GNOME Shell extension + +`gnome-shell/smbact@giglabo.com/` — GNOME Shell 46 to 51. + +SMBAct installs it for you. By hand: + +```bash +scripts/pack.sh +gnome-extensions install --force dist/smbact@giglabo.com.shell-extension.zip +gnome-extensions enable smbact@giglabo.com +``` + +On Wayland a newly installed or updated extension starts after you log out and back in. + +Only SMBAct may call it: the extension answers the current owner of the D-Bus name `com.giglabo.SMBAct` and refuses +everyone else. + +## License + +GPL-2.0-or-later (see [LICENSE](LICENSE)). SMBAct itself is a separate program that talks to these plugins over +D-Bus. diff --git a/gnome-shell/smbact@giglabo.com/extension.js b/gnome-shell/smbact@giglabo.com/extension.js new file mode 100644 index 0000000..ca01f1d --- /dev/null +++ b/gnome-shell/smbact@giglabo.com/extension.js @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// SMBAct shell plugin for GNOME Shell 46-51: the D-Bus service com.giglabo.SMBAct.Shell1, API 1 (PROTOCOL.md). +// A thin executor for the SMBAct app: it lists windows and carries out window operations; every decision stays in +// the app. Rules it follows (all seen on GNOME 50): +// - 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); +// - 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 Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; +import Meta from 'gi://Meta'; +import Shell from 'gi://Shell'; +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'; + +const API = 1; +const BUS_NAME = 'com.giglabo.SMBAct.Shell'; +const OBJECT_PATH = '/com/giglabo/SMBAct/Shell1'; +/** Only the current owner of this name may call (the SMBAct app requests it). */ +const CLIENT_NAME = 'com.giglabo.SMBAct'; +const EVENT_COALESCE_MS = 100; + +const IFACE_XML = ` + + + + + + + + + + +`; + +class ShellError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +const badRequest = message => new ShellError('BAD_REQUEST', message); + +// ---- Mutter 46-50 differences (49 reworked maximizing, 50 dropped the X11 backend) + +const isWayland = () => typeof Meta.is_wayland_compositor !== 'function' || Meta.is_wayland_compositor(); + +const maximizeFlags = w => { + if (typeof w.get_maximize_flags === 'function') + return w.get_maximize_flags(); + return w.get_maximized(); // Mutter <= 48: the flags themselves +}; + +const setMaximized = (w, flags, on) => { + const both = flags === Meta.MaximizeFlags.BOTH; + if (typeof w.set_maximize_flags === 'function') { // Mutter 49+ + if (on) + both ? w.maximize() : w.set_maximize_flags(flags); + else + both ? w.unmaximize() : w.set_unmaximize_flags(flags); + } else if (on) { + w.maximize(flags); + } else { + w.unmaximize(flags); + } +}; + +const WINDOW_TYPES = new Map([ + [Meta.WindowType.NORMAL, 'normal'], + [Meta.WindowType.DIALOG, 'dialog'], + [Meta.WindowType.MODAL_DIALOG, 'modal-dialog'], + [Meta.WindowType.UTILITY, 'utility'], + [Meta.WindowType.SPLASHSCREEN, 'splashscreen'], + [Meta.WindowType.MENU, 'menu'], + [Meta.WindowType.DROPDOWN_MENU, 'menu'], + [Meta.WindowType.POPUP_MENU, 'menu'], + [Meta.WindowType.TOOLBAR, 'toolbar'], + [Meta.WindowType.DESKTOP, 'desktop'], + [Meta.WindowType.DOCK, 'dock'], +]); + +const rect = r => ({x: r.x, y: r.y, width: r.width, height: r.height}); + +const tryOr = (fn, fallback = null) => { + try { + return fn(); + } catch { + return fallback; + } +}; + +/** The X11 window id of an XWayland window: the first word of its description ("0xc00020 (title)"). */ +const x11WindowId = w => { + if (w.get_client_type() !== Meta.WindowClientType.X11) + return null; + const m = /^0x[0-9a-f]+/i.exec(tryOr(() => w.get_description(), '') ?? ''); + return m ? Number.parseInt(m[0], 16) : null; +}; + +const allWindows = () => + typeof global.display.list_all_windows === 'function' + ? global.display.list_all_windows() + : global.get_window_actors().map(a => a.meta_window).filter(Boolean); + +class Service { + constructor(extension) { + this._extension = extension; + this._clientOwner = null; + this._iconTheme = null; + this._iconCache = new Map(); + this._shownDesktop = []; + this._windowSignals = new Map(); + this._displaySignals = []; + this._eventTimer = 0; + this._ops = { + hello: () => this._hello(), + listWindows: req => this._listWindows(req), + getWindow: req => ({window: this._describe(this._window(req))}), + activeWindow: () => ({window: this._describe(global.display.focus_window)}), + moveResize: req => this._moveResize(req), + activate: req => this._activate(req), + raise: req => { + const w = this._window(req); + w.raise(); + return {window: this._describe(w)}; + }, + setState: req => this._setState(req), + close: req => this._close(req), + showDesktop: req => this._showDesktop(req), + displays: () => this._displays(), + pointer: () => { + const [x, y] = global.get_pointer(); + return {x, y}; + }, + }; + } + + start() { + this._dbus = Gio.DBusExportedObject.wrapJSObject(IFACE_XML, this); + this._dbus.export(Gio.DBus.session, OBJECT_PATH); + this._nameId = Gio.bus_own_name_on_connection(Gio.DBus.session, BUS_NAME, Gio.BusNameOwnerFlags.NONE, null, null); + this._watchId = Gio.bus_watch_name_on_connection(Gio.DBus.session, CLIENT_NAME, Gio.BusNameWatcherFlags.NONE, + (_c, _name, owner) => { + this._clientOwner = owner; + }, + () => { + this._clientOwner = null; + }); + const d = global.display; + 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})), + ]; + for (const w of allWindows()) + this._watchWindow(w); + } + + stop() { + for (const id of this._displaySignals) + global.display.disconnect(id); + this._displaySignals = []; + for (const [w, ids] of this._windowSignals) { + for (const id of ids) + tryOr(() => w.disconnect(id)); + } + this._windowSignals.clear(); + if (this._eventTimer) { + GLib.source_remove(this._eventTimer); + this._eventTimer = 0; + } + if (this._watchId) { + Gio.bus_unwatch_name(this._watchId); + this._watchId = 0; + } + if (this._nameId) { + Gio.bus_unown_name(this._nameId); + this._nameId = 0; + } + this._dbus?.unexport(); + this._dbus = null; + this._iconCache.clear(); + this._iconTheme = null; + } + + // ---- D-Bus + + CallAsync([request], invocation) { + if (!this._clientOwner || invocation.get_sender() !== this._clientOwner) { + invocation.return_dbus_error('org.freedesktop.DBus.Error.AccessDenied', 'Call is not allowed'); + return; + } + let reply; + try { + let req; + try { + req = JSON.parse(request); + } catch { + throw badRequest('the request is not JSON'); + } + if (!req || typeof req !== 'object' || typeof req.op !== 'string') + throw badRequest('the request needs an "op"'); + const op = this._ops[req.op]; + if (!op) + throw new ShellError('UNKNOWN_OP', `unknown op "${req.op}"`); + reply = {ok: true, result: op(req)}; + } catch (e) { + reply = {ok: false, error: {code: e instanceof ShellError ? e.code : 'FAILED', message: `${e?.message ?? e}`}}; + } + invocation.return_value(new GLib.Variant('(s)', [JSON.stringify(reply)])); + } + + _emit(event) { + tryOr(() => this._dbus?.emit_signal('Event', new GLib.Variant('(s)', [JSON.stringify(event)]))); + } + + _windowsChanged() { + if (this._eventTimer) + return; + this._eventTimer = GLib.timeout_add(GLib.PRIORITY_DEFAULT, EVENT_COALESCE_MS, () => { + this._eventTimer = 0; + this._emit({type: 'windowsChanged'}); + return GLib.SOURCE_REMOVE; + }); + } + + _watchWindow(w) { + if (this._windowSignals.has(w)) + return; + const changed = () => this._windowsChanged(); + const ids = [ + w.connect('position-changed', changed), + w.connect('size-changed', changed), + w.connect('notify::minimized', changed), + w.connect('notify::title', changed), + w.connect('unmanaged', () => { + for (const id of this._windowSignals.get(w) ?? []) + tryOr(() => w.disconnect(id)); + this._windowSignals.delete(w); + changed(); + }), + ]; + this._windowSignals.set(w, ids); + } + + // ---- operations + + _hello() { + return { + api: API, + plugin: this._extension.metadata.uuid, + version: this._extension.metadata['version-name'] ?? String(this._extension.metadata.version ?? ''), + shell: Config.PACKAGE_VERSION, + session: isWayland() ? 'wayland' : 'x11', + ops: Object.keys(this._ops), + }; + } + + _window(req) { + const id = req.id; + if (typeof id !== 'number' || !Number.isFinite(id)) + throw badRequest('"id" must be a number'); + const w = allWindows().find(x => x.get_id() === id); + if (!w) + throw new ShellError('NO_WINDOW', `no window ${id}`); + return w; + } + + _number(req, key) { + const v = req[key]; + if (typeof v !== 'number' || !Number.isFinite(v)) + throw badRequest(`"${key}" must be a number`); + return Math.round(v); + } + + _icon(w, size) { + const app = tryOr(() => Shell.WindowTracker.get_default().get_window_app(w)); + const wmClass = tryOr(() => w.get_wm_class(), '') ?? ''; + const key = `${tryOr(() => app?.get_id(), '')}|${wmClass}|${size}`; + if (this._iconCache.has(key)) + return this._iconCache.get(key); + this._iconTheme ??= new St.IconTheme(); + const lookup = gicon => tryOr(() => (gicon ? this._iconTheme.lookup_by_gicon(gicon, size, 0)?.get_filename() : null)); + let file = lookup(tryOr(() => app?.get_icon())); + // Apps without a .desktop file get a generic icon from the shell: try the icon theme by WM class instead. + if ((!file || file.includes('application-x-executable')) && wmClass) { + const byClass = lookup(new Gio.ThemedIcon({name: wmClass.toLowerCase()})); + file = byClass ?? file; + } + this._iconCache.set(key, file ?? null); + return file ?? null; + } + + _describe(w, stack = null, icons = false, iconSize = 48) { + if (!w) + return null; + const frame = w.get_frame_rect(); + const flags = tryOr(() => maximizeFlags(w), 0) ?? 0; + const workspace = tryOr(() => w.get_workspace()); + return { + id: w.get_id(), + title: w.get_title() ?? '', + wmClass: tryOr(() => w.get_wm_class()), + wmClassInstance: tryOr(() => w.get_wm_class_instance()), + appId: tryOr(() => w.get_gtk_application_id()), + sandboxedAppId: tryOr(() => w.get_sandboxed_app_id()), + app: tryOr(() => Shell.WindowTracker.get_default().get_window_app(w)?.get_id()), + pid: tryOr(() => w.get_pid(), -1), + client: w.get_client_type() === Meta.WindowClientType.WAYLAND ? 'wayland' : 'x11', + x11Window: x11WindowId(w), + type: WINDOW_TYPES.get(w.get_window_type()) ?? 'other', + frame: rect(frame), + clientRect: rect(tryOr(() => w.frame_rect_to_client_rect(frame), frame)), + focus: w.has_focus(), + minimized: w.minimized, + maximized: flags === Meta.MaximizeFlags.BOTH, + maximizedHorizontally: (flags & Meta.MaximizeFlags.HORIZONTAL) !== 0, + maximizedVertically: (flags & Meta.MaximizeFlags.VERTICAL) !== 0, + fullscreen: tryOr(() => w.is_fullscreen(), false), + above: tryOr(() => w.is_above(), false), + skipTaskbar: w.is_skip_taskbar(), + monitor: w.get_monitor(), + workspace: workspace ? workspace.index() : -1, + onAllWorkspaces: tryOr(() => w.is_on_all_workspaces(), false), + stack, + icon: icons ? this._icon(w, iconSize) : null, + }; + } + + _listWindows(req) { + const icons = req.icons === true; + const size = typeof req.iconSize === 'number' && req.iconSize > 0 ? Math.min(Math.round(req.iconSize), 512) : 48; + const stacked = global.display.sort_windows_by_stacking(allWindows()); + return {windows: stacked.map((w, i) => this._describe(w, i, icons, size))}; + } + + _moveResize(req) { + const w = this._window(req); + const [x, y, width, height] = ['x', 'y', 'width', 'height'].map(k => this._number(req, k)); + if (width <= 0 || height <= 0) + throw badRequest('"width" and "height" must be positive'); + if (tryOr(() => w.is_fullscreen(), false)) + w.unmake_fullscreen(); + if (maximizeFlags(w)) + setMaximized(w, Meta.MaximizeFlags.BOTH, false); + // Two steps: a window with resize increments (a terminal) ignores the position of a combined move-resize + // whose size it has to round. + w.move_frame(true, x, y); + w.move_resize_frame(true, x, y, width, height); + return {window: this._describe(w)}; + } + + _activate(req) { + const w = this._window(req); + const time = typeof req.time === 'number' && req.time > 0 ? req.time : global.display.get_current_time_roundtrip(); + Main.activateWindow(w, time); + return {window: this._describe(w)}; + } + + _setState(req) { + const w = this._window(req); + if (typeof req.on !== 'boolean') + throw badRequest('"on" must be true or false'); + const on = req.on; + switch (req.state) { + case 'minimized': + on ? w.minimize() : w.unminimize(); + break; + case 'maximized': + setMaximized(w, Meta.MaximizeFlags.BOTH, on); + break; + case 'maximizedHorizontally': + setMaximized(w, Meta.MaximizeFlags.HORIZONTAL, on); + break; + case 'maximizedVertically': + setMaximized(w, Meta.MaximizeFlags.VERTICAL, on); + break; + case 'fullscreen': + on ? w.make_fullscreen() : w.unmake_fullscreen(); + break; + case 'above': + on ? w.make_above() : w.unmake_above(); + break; + default: + throw badRequest(`unknown state "${req.state}"`); + } + return {window: this._describe(w)}; + } + + _close(req) { + const w = this._window(req); + if (req.force === true) + w.kill(); + else + w.delete(global.display.get_current_time_roundtrip()); + return {closed: true}; + } + + _showDesktop(req) { + if (typeof req.show !== 'boolean') + throw badRequest('"show" must be true or false'); + if (req.show) { + const ws = global.workspace_manager.get_active_workspace(); + const visible = allWindows().filter(w => + !w.minimized && !w.is_skip_taskbar() && w.get_window_type() === Meta.WindowType.NORMAL && + tryOr(() => w.located_on_workspace(ws), false)); + for (const w of visible) + w.minimize(); + this._shownDesktop = visible.map(w => w.get_id()); + return {windows: visible.length}; + } + const ids = new Set(this._shownDesktop); + this._shownDesktop = []; + const restore = allWindows().filter(w => ids.has(w.get_id()) && w.minimized); + for (const w of restore) + w.unminimize(); + return {windows: restore.length}; + } + + _displays() { + const d = global.display; + const ws = global.workspace_manager.get_active_workspace(); + const monitors = []; + for (let i = 0; i < d.get_n_monitors(); i++) { + monitors.push({ + index: i, + geometry: rect(d.get_monitor_geometry(i)), + workArea: rect(ws.get_work_area_for_monitor(i)), + scale: d.get_monitor_scale(i), + primary: i === d.get_primary_monitor(), + }); + } + return {monitors}; + } +} + +export default class SMBActShellExtension extends Extension { + enable() { + this._service = new Service(this); + this._service.start(); + } + + disable() { + this._service?.stop(); + this._service = null; + } +} diff --git a/gnome-shell/smbact@giglabo.com/metadata.json b/gnome-shell/smbact@giglabo.com/metadata.json new file mode 100644 index 0000000..da6b0b0 --- /dev/null +++ b/gnome-shell/smbact@giglabo.com/metadata.json @@ -0,0 +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 and window states, 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": 1, + "version-name": "1.0.0" +} diff --git a/scripts/call.py b/scripts/call.py new file mode 100755 index 0000000..fe8c1d7 --- /dev/null +++ b/scripts/call.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +"""Call the SMBAct shell plugin by hand, the way SMBAct does: own com.giglabo.SMBAct on the session bus, then send +com.giglabo.SMBAct.Shell1.Call with a JSON request and print the JSON reply. Needs python3-dbus. Only while SMBAct is +not running (it owns the name then). + + scripts/call.py hello + scripts/call.py listWindows '{"icons": true}' + 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 --as-stranger hello # without the name: expect AccessDenied +""" +import json +import sys + +import dbus +import dbus.mainloop.glib + +DEST, PATH, IFACE, CLIENT = "com.giglabo.SMBAct.Shell", "/com/giglabo/SMBAct/Shell1", "com.giglabo.SMBAct.Shell1", "com.giglabo.SMBAct" + + +def main(argv): + stranger = "--as-stranger" in argv + argv = [a for a in argv if a != "--as-stranger"] + if not argv: + print(__doc__) + return 2 + if argv[0] == "--events": + from gi.repository import GLib + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + bus = dbus.SessionBus() + bus.add_signal_receiver(lambda e: print(e, flush=True), "Event", IFACE, None, PATH) + loop = GLib.MainLoop() + GLib.timeout_add_seconds(int(argv[1]) if len(argv) > 1 else 10, loop.quit) + loop.run() + return 0 + bus = dbus.SessionBus() + if not stranger: + 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 + request = json.loads(argv[1]) if len(argv) > 1 else {} + request["op"] = argv[0] + try: + reply = bus.get_object(DEST, PATH).get_dbus_method("Call", IFACE)(json.dumps(request)) + except dbus.DBusException as e: + print(json.dumps({"dbusError": e.get_dbus_name(), "message": e.get_dbus_message()})) + return 1 + print(reply) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/pack.sh b/scripts/pack.sh new file mode 100755 index 0000000..15f26e8 --- /dev/null +++ b/scripts/pack.sh @@ -0,0 +1,12 @@ +#!/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 +set -euo pipefail +cd "$(dirname "$0")/.." +UUID=smbact@giglabo.com +OUT="dist/$UUID.shell-extension.zip" +mkdir -p dist +rm -f "$OUT" +(cd "gnome-shell/$UUID" && zip -q -X -r "../../$OUT" .) +zip -q -X -j "$OUT" LICENSE +echo "$OUT" From f154d58cda3297350d241877836aab77b90a0177 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 8 Nov 2026 13:45:50 +0100 Subject: [PATCH 2/3] GitHub Actions: checks and pack on push / PR, release with sha256 on tags ci.yml: syntax of extension.js, call.py and metadata.json, then the zip as an artifact. release.yml: a tag vX.Y.Z (must equal metadata.json version-name) publishes the zip and SHA256SUMS as a GitHub release, which SMBAct pins. getWindow / activeWindow take icons too, moveResize takes a client rect (space: client), iconPng turns an SVG icon into PNG. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 30 ++++++++++++++++ .github/workflows/release.yml | 34 ++++++++++++++++++ PROTOCOL.md | 12 ++++--- README.md | 6 ++++ gnome-shell/smbact@giglabo.com/extension.js | 39 ++++++++++++++++++--- 5 files changed, 112 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ab3881a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Syntax + run: | + cp "gnome-shell/smbact@giglabo.com/extension.js" "$RUNNER_TEMP/extension.mjs" + node --check "$RUNNER_TEMP/extension.mjs" + python3 -m py_compile scripts/call.py + python3 -c "import json; json.load(open('gnome-shell/smbact@giglabo.com/metadata.json'))" + - name: Pack + run: scripts/pack.sh + - uses: actions/upload-artifact@v4 + with: + name: smbact-shell-gnome + path: dist/*.zip diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bd51e8d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,34 @@ +name: release + +# A tag vX.Y.Z publishes the extension zip and its sha256 as a GitHub release. SMBAct pins a tag and checks the +# sha256 of the zip it downloads. The tag must match "version-name" in metadata.json. +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Tag matches metadata.json + run: | + want="v$(python3 -c "import json; print(json.load(open('gnome-shell/smbact@giglabo.com/metadata.json'))['version-name'])")" + if [ "$want" != "$GITHUB_REF_NAME" ]; then + echo "tag $GITHUB_REF_NAME does not match metadata.json version-name ($want)" >&2 + exit 1 + fi + - name: Pack + run: | + scripts/pack.sh + (cd dist && sha256sum ./*.zip > SHA256SUMS && cat SHA256SUMS) + - name: Release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" dist/*.zip dist/SHA256SUMS \ + --title "smbact-shell $GITHUB_REF_NAME" \ + --notes "GNOME Shell extension smbact@giglabo.com, protocol com.giglabo.SMBAct.Shell1 API 1. See PROTOCOL.md." diff --git a/PROTOCOL.md b/PROTOCOL.md index bae6147..3ffc630 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -83,7 +83,8 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - `frame`: the visible window including server-side decorations; `clientRect`: the client area (larger than `frame` when the window draws its own shadow). - `stack`: position in the stacking order, 0 = bottom. -- `icon`: a file path from the icon theme (only when asked for, see `listWindows`), or `null`. +- `icon`: a file path from the icon theme, PNG when the theme has one (only when asked for, see `listWindows`), or + `null`. `iconPng` turns any icon file (SVG too) into PNG bytes. ## Operations (API 1) @@ -91,19 +92,22 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. |---|---|---| | `hello` | | `{ api, plugin, version, shell, session, ops }` | | `listWindows` | `icons?` (bool), `iconSize?` (px, default 48) | `{ windows: Window[] }` | -| `getWindow` | `id` | `{ window }` | -| `activeWindow` | | `{ window }` (`null` when nothing has focus) | -| `moveResize` | `id`, `x`, `y`, `width`, `height` | `{ window }` | +| `getWindow` | `id`, `icons?`, `iconSize?` | `{ window }` | +| `activeWindow` | `icons?`, `iconSize?` | `{ window }` (`null` when nothing has focus) | +| `moveResize` | `id`, `x`, `y`, `width`, `height`, `space?` (`frame` default, or `client`) | `{ window }` | | `activate` | `id`, `time?` | `{ window }` | | `raise` | `id` | `{ window }` | | `setState` | `id`, `state`, `on` | `{ window }` | | `close` | `id`, `force?` | `{ closed: true }` | | `showDesktop` | `show` | `{ windows }` (how many were minimized or restored) | | `displays` | | `{ monitors: [{ index, geometry, workArea, scale, primary }] }` | +| `iconPng` | `path` (an `icon` path), `size?` (px, default 48) | `{ png, width, height }` (`png`: base64 PNG bytes) | | `pointer` | | `{ x, y }` | - `setState` states: `minimized`, `maximized`, `maximizedHorizontally`, `maximizedVertically`, `fullscreen`, `above`. +- `moveResize` takes the frame rect, or with `space: "client"` the client rect (the compositor converts it with the + window's own decorations and shadow). - `moveResize` leaves maximized and fullscreen first, then moves and resizes in two steps, so windows with resize increments (terminals) keep the requested position. - Wayland windows apply a new geometry or state asynchronously (the client acknowledges it about a frame later), so diff --git a/README.md b/README.md index 4e8777c..5c70e74 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,12 @@ 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. +## Releases + +A tag `vX.Y.Z` (equal to `version-name` in `metadata.json`) makes GitHub Actions publish +`smbact@giglabo.com.shell-extension.zip` and `SHA256SUMS` as a release. SMBAct pins a tag and checks the sha256. +Every push to `main` and every pull request runs the checks and packs the zip (`.github/workflows/`). + ## License GPL-2.0-or-later (see [LICENSE](LICENSE)). SMBAct itself is a separate program that talks to these plugins over diff --git a/gnome-shell/smbact@giglabo.com/extension.js b/gnome-shell/smbact@giglabo.com/extension.js index ca01f1d..2d14449 100644 --- a/gnome-shell/smbact@giglabo.com/extension.js +++ b/gnome-shell/smbact@giglabo.com/extension.js @@ -6,9 +6,11 @@ // - activation uses the server's current time (time 0 may not get the focus); // - 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'; import Gio from 'gi://Gio'; import GLib from 'gi://GLib'; import Meta from 'gi://Meta'; +import Mtk from 'gi://Mtk'; import Shell from 'gi://Shell'; import St from 'gi://St'; import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; @@ -118,8 +120,8 @@ class Service { this._ops = { hello: () => this._hello(), listWindows: req => this._listWindows(req), - getWindow: req => ({window: this._describe(this._window(req))}), - activeWindow: () => ({window: this._describe(global.display.focus_window)}), + getWindow: req => ({window: this._describe(this._window(req), null, req.icons === true, this._iconSize(req))}), + activeWindow: req => ({window: this._describe(global.display.focus_window, null, req.icons === true, this._iconSize(req))}), moveResize: req => this._moveResize(req), activate: req => this._activate(req), raise: req => { @@ -131,6 +133,7 @@ class Service { close: req => this._close(req), showDesktop: req => this._showDesktop(req), displays: () => this._displays(), + iconPng: req => this._iconPng(req), pointer: () => { const [x, y] = global.get_pointer(); return {x, y}; @@ -286,7 +289,11 @@ class Service { if (this._iconCache.has(key)) return this._iconCache.get(key); this._iconTheme ??= new St.IconTheme(); - const lookup = gicon => tryOr(() => (gicon ? this._iconTheme.lookup_by_gicon(gicon, size, 0)?.get_filename() : null)); + // A PNG first (SMBAct stores icons as PNG), any format after that. + const lookup = gicon => (gicon + ? tryOr(() => this._iconTheme.lookup_by_gicon(gicon, size, St.IconLookupFlags.NO_SVG)?.get_filename()) ?? + tryOr(() => this._iconTheme.lookup_by_gicon(gicon, size, 0)?.get_filename()) + : null); let file = lookup(tryOr(() => app?.get_icon())); // Apps without a .desktop file get a generic icon from the shell: try the icon theme by WM class instead. if ((!file || file.includes('application-x-executable')) && wmClass) { @@ -333,18 +340,30 @@ class Service { }; } + _iconSize(req) { + return typeof req.iconSize === 'number' && req.iconSize > 0 ? Math.min(Math.round(req.iconSize), 512) : 48; + } + _listWindows(req) { const icons = req.icons === true; - const size = typeof req.iconSize === 'number' && req.iconSize > 0 ? Math.min(Math.round(req.iconSize), 512) : 48; + const size = this._iconSize(req); const stacked = global.display.sort_windows_by_stacking(allWindows()); return {windows: stacked.map((w, i) => this._describe(w, i, icons, size))}; } _moveResize(req) { const w = this._window(req); - const [x, y, width, height] = ['x', 'y', 'width', 'height'].map(k => this._number(req, k)); + let [x, y, width, height] = ['x', 'y', 'width', 'height'].map(k => this._number(req, k)); if (width <= 0 || height <= 0) throw badRequest('"width" and "height" must be positive'); + if (req.space === 'client') { + // The rect is the client area: Mutter knows this window's decorations and shadow. + const r = new Mtk.Rectangle({x, y, width, height}); + const f = w.client_rect_to_frame_rect(r); + [x, y, width, height] = [f.x, f.y, f.width, f.height]; + } else if (req.space !== undefined && req.space !== 'frame') { + throw badRequest('"space" is "frame" or "client"'); + } if (tryOr(() => w.is_fullscreen(), false)) w.unmake_fullscreen(); if (maximizeFlags(w)) @@ -402,6 +421,16 @@ class Service { return {closed: true}; } + // An icon file as PNG bytes (base64), for icons the theme has as SVG only. Small and rare: the client caches by path. + _iconPng(req) { + if (typeof req.path !== 'string' || !req.path.startsWith('/')) + throw badRequest('"path" must be an absolute file path'); + const size = typeof req.size === 'number' && req.size > 0 ? Math.min(Math.round(req.size), 256) : 48; + const pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(req.path, size, size); + const [, bytes] = pixbuf.save_to_bufferv('png', [], []); + return {png: GLib.base64_encode(bytes), width: pixbuf.get_width(), height: pixbuf.get_height()}; + } + _showDesktop(req) { if (typeof req.show !== 'boolean') throw badRequest('"show" must be true or false'); From 236d3e9fc163d35e6f7161b7bc7ebf7696767827 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 8 Nov 2026 14:03:19 +0100 Subject: [PATCH 3/3] Accept the X11 id of an XWayland window as "id" SMBAct knows its own windows by their X11 ids. Co-Authored-By: Claude Opus 5.5 --- PROTOCOL.md | 3 ++- gnome-shell/smbact@giglabo.com/extension.js | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/PROTOCOL.md b/PROTOCOL.md index 3ffc630..5917ff5 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -76,7 +76,8 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. } ``` -- `id`: the compositor's window id, unique in the session (fits in a JSON number). +- `id`: the compositor's window id, unique in the session (fits in a JSON number). Requests also accept the X11 id + of an XWayland window as `id`. - `client`: `wayland` or `x11`; `x11Window`: the X11 window id of an XWayland window, else `null`. - `type`: `normal`, `dialog`, `modal-dialog`, `utility`, `splashscreen`, `menu`, `toolbar`, `desktop`, `dock`, or `other`. The plugin lists every managed window; the client picks what it shows. diff --git a/gnome-shell/smbact@giglabo.com/extension.js b/gnome-shell/smbact@giglabo.com/extension.js index 2d14449..0b09119 100644 --- a/gnome-shell/smbact@giglabo.com/extension.js +++ b/gnome-shell/smbact@giglabo.com/extension.js @@ -269,7 +269,9 @@ class Service { const id = req.id; if (typeof id !== 'number' || !Number.isFinite(id)) throw badRequest('"id" must be a number'); - const w = allWindows().find(x => x.get_id() === id); + // 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); if (!w) throw new ShellError('NO_WINDOW', `no window ${id}`); return w;