From 78eab3500478afe73aa6855ed9a1d1632ece7b93 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 22 Nov 2026 19:29:49 +0100 Subject: [PATCH 1/2] =?UTF-8?q?drags:=20dragWatch,=20dragAnswer,=20dragRes?= =?UTF-8?q?toreSize,=20nativeTiling,=20the=20drag=20event=20(GNOME)=20?= =?UTF-8?q?=E2=80=94=20new=20operations,=20API=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The GNOME Shell extension becomes SMBAct's drag source for positioning windows with the mouse: - grab-op-begin / grab-op-end (pointer moves of normal, movable, resizable windows, primary button), the pointer and the modifiers sampled every 16 ms during the drag, hit-tested against SMBAct's zone table (hitTest.js, a port of SMBAct's hit-test; tests/ runs its fixtures, a byte-for-byte copy); events begin / zone / end with SMBAct's DragEvent shapes; Escape told by the button still down at the end (or the window put back); window closed, monitors changed, workspace changed, overview, fullscreen monitor end a drag cancelled. - dragRestoreSize: a placed window gets its size back during Mutter's grab once the pointer is 12 px off the press, under the pointer at its grab point (a one-axis maximize left first; a full maximize is Mutter's). - nativeTiling: org.gnome.mutter edge-tiling held off for the client (the user's own value saved), given back when the client leaves the bus or the extension is disabled; never written while Tiling Assistant / Tiling Shell is active; no fight when somebody else switches it on. - The extension draws nothing (draws: false): SMBAct draws its zone map and footprint itself (an XWayland window shows above a window in Mutter's move grab, checked in SMBAct's VM). - Everything stops with the client and in disable(); try/catch in every handler; nothing new in enable(). - PROTOCOL.md, README, CI runs the tests and checks the new files; scripts/call.py --drag; version 2.2.0 (not released). Checked in SMBAct's GNOME 50 VM (Ubuntu 26.04, two heads): every default zone on both heads for a Wayland and an XWayland window, restore on drag away, Escape, the hold given back on a kill and a screen lock. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 10 +- PROTOCOL.md | 91 ++- README.md | 12 +- gnome-shell/smbact@giglabo.com/dragSource.js | 316 ++++++++ gnome-shell/smbact@giglabo.com/extension.js | 127 +++- gnome-shell/smbact@giglabo.com/hitTest.js | 143 ++++ gnome-shell/smbact@giglabo.com/metadata.json | 6 +- kwin/smbact-kwin.js | 2 +- scripts/call.py | 38 + tests/fixtures/README.md | 9 + tests/fixtures/hit-test.json | 731 +++++++++++++++++++ tests/hit-test.test.mjs | 51 ++ 12 files changed, 1519 insertions(+), 17 deletions(-) create mode 100644 gnome-shell/smbact@giglabo.com/dragSource.js create mode 100644 gnome-shell/smbact@giglabo.com/hitTest.js create mode 100644 tests/fixtures/README.md create mode 100644 tests/fixtures/hit-test.json create mode 100644 tests/hit-test.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fe16669..342e630 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,13 +18,15 @@ jobs: node-version: 22 - name: Syntax 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" + for f in extension snapshots dragSource hitTest; do + cp "gnome-shell/smbact@giglabo.com/$f.js" "$RUNNER_TEMP/$f.mjs" + node --check "$RUNNER_TEMP/$f.mjs" + done 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: Tests + run: node --test tests/*.test.mjs - name: Pack run: scripts/pack.sh - uses: actions/upload-artifact@v4 diff --git a/PROTOCOL.md b/PROTOCOL.md index a76d53b..af5d8a3 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -34,8 +34,9 @@ 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), `NO_SNAPSHOT` (`snapshot`: none taken yet), `FAILED` (the -shell threw; `message` has its text). +(`grabAccelerator`: the shell refused the accelerator), `NO_SNAPSHOT` (`snapshot`: none taken yet), +`TILING_EXTENSION_ACTIVE` (`nativeTiling`: a tiling extension holds the key itself), `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. @@ -120,6 +121,13 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. | `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 }` | +| `dragWatch` | `table` (a zone table, or `null` to stop) | `{ watching, reason?, draws, restoreDuringMove }` | +| `dragAnswer` | `drag`, `allow` | `{ ok }` (`false`: no such drag running) | +| `dragRestoreSize` | `drag`, `width`, `height` | `{ ok }` (`false`: no such drag, or the window is maximized) | +| `nativeTiling` | `suppress?` (`true` hold off, `false` give back, absent: read) | `{ edgeTiling, user, held, saved?, tilingExtension }` | + +The last four are the GNOME Shell extension's only (plugin 2.2.0 and later); see "Window drags" and "Mutter's edge +tiling" below. - `setState` states: `minimized`, `maximized`, `maximizedHorizontally`, `maximizedVertically`, `fullscreen`, `above`. @@ -155,6 +163,79 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - `showDesktop` with `show: true` minimizes the visible windows of the active workspace and remembers them; `false` restores those. +## Window drags (GNOME, plugin 2.2.0) + +SMBAct places a window the user drags to a screen edge or corner (its "positioning with the mouse"). The extension is +its drag source on GNOME: it reports when a window is dragged and which zone of SMBAct's table the pointer is in, and +nothing else. It draws nothing (SMBAct draws its zone map and the footprint itself, `draws: false`) and moves no window +at the end of a drag (SMBAct's own action does, through `moveResize` / `setState`). + +`dragWatch` gives the table; drags are reported only while one is set: + +```json +{ "seq": 3, "space": "logical", "armDelayMs": 0, "sharedEdgeDelayMs": 400, "stickPx": 24, "modifier": "shift", + "zones": [ { "id": "d0/left", "display": "d0", "area": "left", "action": "left-half", + "triggers": [ { "x": 0, "y": 96, "width": 30, "height": 888 } ], "when": "no-modifier", "shared": false } ] } +``` + +- `triggers` are half-open rectangles in the compositor's coordinates; a zone with two (an L-shaped corner) counts in + either. `when`: `plain` (any drag), `modifier` (only while the modifier is held), `no-modifier` (until the modifier + is pressed once during the drag). `shared` zones (on an edge between two monitors) arm after `sharedEdgeDelayMs`, + the others after `armDelayMs`; moving on to a neighbouring zone while one is armed re-arms at once. An armed zone + holds the pointer up to `stickPx` outside its triggers. The rules are SMBAct's hit-test; `hitTest.js` is a port of it + and runs SMBAct's fixtures (`tests/`). +- A drag is a pointer move of a normal, movable, resizable window that is not fullscreen, with the primary button: + `grab-op-begin` with `(op & ~UNCONSTRAINED) === MOVING` (the title bar, a client-side drag, the top bar, Super+drag). + Keyboard moves, resizes and touch drags are not reported. One drag at a time. +- The pointer and the modifiers are sampled every 16 ms during the drag (`global.get_pointer()`); the modifier bits + are shift 1, ctrl 2, alt 4, super 8. + +Events: `{ "type": "drag", "event": }`, where `` is one of + +```json +{ "type": "begin", "drag": 7, "window": { "OwnerHandle": 3306, "Handle": 3209482314 }, "frame": { "x": 900, "y": 300, "width": 640, "height": 467 }, + "pointer": { "x": 1220, "y": 318 }, "press": { "x": 1220, "y": 318 }, "table": 3, "time": 81234.5, "owner": "gedit" } +{ "type": "zone", "drag": 7, "zone": "d0/left", "pointer": { "x": 8, "y": 500 } } +{ "type": "end", "drag": 7, "zone": "d0/left", "cancelled": false, "frame": { "x": -312, "y": 482, "width": 640, "height": 467 }, "pointer": { "x": 8, "y": 500 } } +{ "type": "end", "drag": 7, "zone": null, "cancelled": true, "reason": "escape", "frame": { "x": 900, "y": 300, "width": 640, "height": 467 }, "pointer": { "x": 8, "y": 500 } } +``` + +- `window`: `Handle` is the window's `id` (as in `Window`), `OwnerHandle` its pid; `frame` is the frame at the begin; + `table` the `seq` hit against; `time` the shell's monotonic clock in ms. +- `zone` reports transitions only (armed, re-armed, disarmed with `null`), never the pointer stream. +- `end`: `zone` is the zone of the drop (the armed one, or a fast throw into a zone that arms at once), `null` for + none. `cancelled` when the grab ended with the button still down (Escape) or with the window back where it began + (Mutter puts it back on Escape); then `reason` is `escape` or `put-back`. A drag also ends cancelled when its window + goes away (`window-closed`), the monitors change (`displays-changed`), the workspace changes without the window + (`workspace-changed`), a zone would arm while the overview is open (`overview`) or over a monitor showing a + fullscreen window (`fullscreen`), or the watch stops (`stopped`); `frame` is `null` then. + +`dragAnswer` is SMBAct's answer to `begin` (may this window be placed); `allow: false` keeps the window as it is. +`dragRestoreSize` gives the dragged window a size back: once the pointer is 12 px off the press, the window gets +`width` x `height` during the move, with the pointer at the same share of its width and at the same height in it where +it grabbed it; once per drag. A window maximized both ways is Mutter's to restore (`{ ok: false }`); a one-axis +maximize (how SMBAct holds a full-height half) is left first. + +## Mutter's edge tiling (GNOME, plugin 2.2.0) + +`nativeTiling` holds `org.gnome.mutter edge-tiling` off for the client and gives it back: + +- `suppress: true` saves the user's own value (or that there was none), writes `false` and holds it; repeated calls + keep the first saved value. It is refused with `TILING_EXTENSION_ACTIVE` while an extension that holds the key + itself is active (Ubuntu's Tiling Assistant, `tiling-assistant@ubuntu.com` / `@leleat-on-github`, Tiling Shell): the + write would end up in that extension's own restore record. +- `suppress: false` puts the saved value back (resets the key when there was none), only over its own `false` and + never while such an extension is active. +- When somebody else switches the key on during the hold (Settings, another extension being disabled), the hold ends + without a write: no fight over it. +- The hold belongs to the client, like grabs: it is given back when the owner of `com.giglabo.SMBAct` goes away or + changes, and when the extension is disabled (a screen lock). A client that starts again holds again. +- The reply: `edgeTiling` the effective value, `user` the user's own (`null`: none), `held`, `saved` while held, + `tilingExtension` the uuid of an active extension that holds the key, or `null`. + +The drag watch belongs to the client too: it stops when the client goes away or changes, and when the extension is +disabled. + ## Events `Event` carries `{ "type": ..., ... }`: @@ -164,6 +245,7 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - `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. +- `drag` with `event`: a window drag against the client's zone table (see "Window drags"). ## History @@ -174,6 +256,8 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. - API 1, plugin 2.0.0 (2026-11): the first full release, with SMBAct 2.0.0; the same API as 1.0.0-alpha.3. - API 1, plugin 2.1.0 (2026-11): `connector` in `displays`, `onActiveWorkspace` and (KWin) `tiled` in the window (new optional fields, same API), with SMBAct 2.1.0. +- API 1, plugin 2.2.0 (not released yet): `dragWatch`, `dragAnswer`, `dragRestoreSize`, `nativeTiling`, the `drag` + event (GNOME only; new operations, same API; clients look for them in `hello`'s `ops`). ## KWin transport @@ -197,7 +281,8 @@ What the KWin script does not have: `snapshots` / `snapshot` (KWin offers window 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). +server's own list). Window ids are the first 32 bits of KWin's UUID for the window (stable across reloads). The +window drags and `nativeTiling` (plugin 2.2.0) are the GNOME Shell extension's only so far. - 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 39bde2e..02e2555 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ 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. +moving and resizing, activation, window states, displays; on GNOME also global hotkeys, window snapshots and the window +drags SMBAct places with the mouse. 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). @@ -42,7 +43,14 @@ qdbus6 org.kde.KWin /Scripting/Script org.kde.kwin.Script.run 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`, `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/`). +Every push to `main` and every pull request runs the checks and the tests and packs the zip (`.github/workflows/`). + +## Tests + +`node --test tests/*.test.mjs`: the drag hit-test (`gnome-shell/smbact@giglabo.com/hitTest.js`) against SMBAct's shared +fixtures (`tests/fixtures/`, see its README for where they come from). The rest is checked live in SMBAct's GNOME test +VM (smbact-app `scripts/dev/linux/drag-snap/gnome/`). By hand: `scripts/call.py --drag table.json 60` prints the drag +events against a zone table. ## License diff --git a/gnome-shell/smbact@giglabo.com/dragSource.js b/gnome-shell/smbact@giglabo.com/dragSource.js new file mode 100644 index 0000000..d3b9922 --- /dev/null +++ b/gnome-shell/smbact@giglabo.com/dragSource.js @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// The drag source for SMBAct's positioning with the mouse (PROTOCOL.md, `dragWatch`): tells SMBAct when the user drags a +// window with the pointer and which zone of SMBAct's table the pointer is in. SMBAct decides everything else (which +// windows, which layout, the drop); this file reports transitions and, when asked, gives a placed window its size back +// during the drag. +// - Drags come from global.display's grab-op-begin / grab-op-end (46-51; 51 adds a fourth argument, ignored here). A +// pointer move is (op & ~UNCONSTRAINED) === MOVING: the title bar, a client-side drag, the top bar, Super+drag; +// keyboard moves and resizes are not. +// - The pointer is sampled every 16 ms with global.get_pointer() while a drag runs (the window's position-changed stops +// while the window is held back: the pointer in the top bar, edge resistance); the same call carries the modifiers. +// - Escape and the release both end with grab-op-end: a drag counts as cancelled when the button is still down at the +// end, or when Mutter put the window back where it was. +// - Nothing runs while no table is set; every handler in try/catch; everything undone by stop(). +import GLib from 'gi://GLib'; +import Meta from 'gi://Meta'; +import Mtk from 'gi://Mtk'; +import Clutter from 'gi://Clutter'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import {DragHitTest, MODIFIER_FLAG} from './hitTest.js'; + +const SAMPLE_MS = 16; +/** The pointer must move this far from the press before a placed window gets its size back (SMBAct's MPOS-REST-1). */ +const RESTORE_THRESHOLD = 12; +/** Meta.GrabOp flags (unchanged 46-51). */ +const GRAB_UNCONSTRAINED = 0x400; + +const tryOr = (fn, fallback = null) => { + try { + return fn(); + } catch { + return fallback; + } +}; + +const rect = r => ({x: r.x, y: r.y, width: r.width, height: r.height}); +const sameRect = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; +const nowMs = () => GLib.get_monotonic_time() / 1000; + +const M = Clutter.ModifierType; +const SUPER_MASKS = (M.MOD4_MASK ?? 0) | (M.SUPER_MASK ?? 0); + +/** Clutter modifier state -> SMBAct's flags (shift 1, ctrl 2, alt 4, meta 8). */ +export const flagsOf = mods => + ((mods & M.SHIFT_MASK) ? MODIFIER_FLAG.shift : 0) | + ((mods & M.CONTROL_MASK) ? MODIFIER_FLAG.ctrl : 0) | + ((mods & M.MOD1_MASK) ? MODIFIER_FLAG.alt : 0) | + ((mods & SUPER_MASKS) ? MODIFIER_FLAG.meta : 0); + +const isMaximized = w => tryOr(() => w.maximized_horizontally || w.maximized_vertically, false); +const isFullyMaximized = w => tryOr(() => w.maximized_horizontally && w.maximized_vertically, false); + +/** Leaves a one-axis maximize (a full-height half is a vertical maximize in Mutter), Mutter 46-48 and 49+. */ +const unmaximizeAxes = w => { + const flags = (w.maximized_horizontally ? Meta.MaximizeFlags.HORIZONTAL : 0) | + (w.maximized_vertically ? Meta.MaximizeFlags.VERTICAL : 0); + if (!flags) + return; + if (typeof w.set_unmaximize_flags === 'function') + w.set_unmaximize_flags(flags); + else + w.unmaximize(flags); +}; + +/** A window the user may place by dragging: a normal, movable, resizable, not fullscreen window. */ +const eligible = w => + !!w && w.get_window_type() === Meta.WindowType.NORMAL && tryOr(() => w.allows_move() && w.allows_resize(), false) && + !tryOr(() => w.is_fullscreen(), false); + +const validTable = t => + t && typeof t === 'object' && Array.isArray(t.zones) && typeof t.seq === 'number' && + t.zones.every(z => z && typeof z.id === 'string' && Array.isArray(z.triggers)); + +export class DragSource { + /** + * @param {(event: object) => void} emit sends one DragEvent to the client (wrapped by the caller) + * @param {(level: string, message: string) => void} log + */ + constructor(emit, log) { + this._emit = emit; + this._log = log; + this._table = null; + this._signals = []; + this._session = null; + this._nextDrag = 0; + } + + get watching() { + return this._table !== null; + } + + /** `dragWatch`: the table to hit-test against, null stops. */ + watch(table) { + if (table === null) { + this._cancel('stopped'); + this._disconnect(); + this._table = null; + return {watching: false, reason: 'stopped'}; + } + if (!validTable(table)) + throw new Error('"table" must be a zone table ({seq, zones: [{id, triggers}], ...}) or null'); + this._table = table; + if (!this._signals.length) { + const d = global.display; + this._signals = [ + [d, d.connect('grab-op-begin', (_d, window, op) => this._safe(() => this._begin(window, op)))], + [d, d.connect('grab-op-end', (_d, window) => this._safe(() => this._end(window)))], + [Main.layoutManager, Main.layoutManager.connect('monitors-changed', () => this._safe(() => this._cancel('displays-changed')))], + [global.workspace_manager, global.workspace_manager.connect('active-workspace-changed', () => this._safe(() => this._workspaceChanged()))], + ]; + } + return {watching: true, draws: false, restoreDuringMove: true}; + } + + /** `dragAnswer`: SMBAct's answer to `begin`; `allow: false` keeps this drag's window as it is (no restore). */ + answer(drag, allow) { + const s = this._session; + if (!s || s.drag !== drag) + return {ok: false}; + s.allowed = !!allow; + return {ok: true}; + } + + /** + * `dragRestoreSize`: once the pointer is RESTORE_THRESHOLD px off the press, the window of drag `drag` gets this size + * during the move, the pointer kept at the share of its width where it grabbed it (SMBAct's MPOS-REST-1, -2). Once + * per drag. A maximized window is Mutter's to restore (it un-maximizes it under the pointer itself): `{ok: false}`; + * a one-axis maximize (how a full-height half is held) is left first. + */ + restoreSize(drag, width, height) { + const s = this._session; + if (!s || s.drag !== drag || !s.hit) + return {ok: false}; + if (s.maximizedAtBegin || !(width > 0 && height > 0)) + return {ok: false}; + s.restore = {width: Math.round(width), height: Math.round(height)}; + this._restoreStep(); + return {ok: true}; + } + + /** Everything off (disable(), the client left the bus): no events go out any more. */ + stop() { + this._stopSession(); + this._disconnect(); + this._table = null; + } + + _safe(fn) { + try { + fn(); + } catch (e) { + this._log('warn', `drag source: ${e?.message ?? e}`); + } + } + + _disconnect() { + for (const [obj, id] of this._signals) + tryOr(() => obj.disconnect(id)); + this._signals = []; + } + + _stopSession() { + const s = this._session; + if (!s) + return; + this._session = null; + if (s.timer) + GLib.source_remove(s.timer); + for (const id of s.windowSignals) + tryOr(() => s.window.disconnect(id)); + } + + _begin(window, op) { + if (!this._table || this._session) + return; // one drag at a time + if ((op & ~GRAB_UNCONSTRAINED) !== Meta.GrabOp.MOVING || !eligible(window)) + return; + const [x, y, mods] = global.get_pointer(); + if (!(mods & M.BUTTON1_MASK)) + return; // the primary button only (a touch drag, another button: no session) + const frame = rect(window.get_frame_rect()); + const drag = ++this._nextDrag; + const s = { + drag, + window, + frame, + press: {x, y}, + hit: new DragHitTest(this._table), + table: this._table.seq, + maximizedAtBegin: isFullyMaximized(window), + allowed: null, + restore: null, + restored: false, + timer: 0, + windowSignals: [], + }; + s.windowSignals.push(window.connect('unmanaged', () => this._safe(() => this._cancel('window-closed')))); + this._session = s; + this._emit({ + type: 'begin', + drag, + window: {OwnerHandle: tryOr(() => window.get_pid(), -1), Handle: window.get_id()}, + frame, + pointer: {x, y}, + press: {x, y}, + table: s.table, + time: nowMs(), + owner: tryOr(() => window.get_wm_class(), '') ?? '', + }); + this._sample(x, y, mods); + s.timer = GLib.timeout_add(GLib.PRIORITY_DEFAULT, SAMPLE_MS, () => { + this._safe(() => { + if (this._session === s && s.hit) { + const [px, py, pm] = global.get_pointer(); + this._sample(px, py, pm); + this._restoreStep(); + } + }); + if (this._session === s) + return GLib.SOURCE_CONTINUE; + s.timer = 0; + return GLib.SOURCE_REMOVE; + }); + } + + _sample(x, y, mods) { + const s = this._session; + if (!s?.hit) + return; + const tr = s.hit.sample({x, y, t: nowMs(), flags: flagsOf(mods)}); + if (!tr) + return; + if (tr.zone !== null) { + const reason = this._guard(x, y); + if (reason) { + this._cancel(reason, {x, y}); + return; + } + } + this._emit({type: 'zone', drag: s.drag, zone: tr.zone, pointer: {x, y}}); + } + + /** Why no zone may arm now: the overview is open, the monitor under the pointer shows a fullscreen window. */ + _guard(x, y) { + if (Main.overview.visible) + return 'overview'; + const monitor = tryOr(() => global.display.get_monitor_index_for_rect(new Mtk.Rectangle({x, y, width: 1, height: 1})), -1); + if (monitor >= 0 && tryOr(() => global.display.get_monitor_in_fullscreen(monitor), false)) + return 'fullscreen'; + return null; + } + + /** The restored size, once the pointer is off the press (see restoreSize()). */ + _restoreStep() { + const s = this._session; + if (!s?.hit || !s.restore || s.restored || s.allowed === false) + return; + const [x, y] = global.get_pointer(); + if (Math.hypot(x - s.press.x, y - s.press.y) <= RESTORE_THRESHOLD) + return; + const w = s.window; + if (isFullyMaximized(w)) + return; + s.restored = true; + const {width, height} = s.restore; + const share = s.frame.width > 0 ? Math.min(1, Math.max(0, (s.press.x - s.frame.x) / s.frame.width)) : 0.5; + const grabY = Math.min(Math.max(0, s.press.y - s.frame.y), Math.max(0, height - 1)); + // a resize during Mutter's move grab, as Tiling Assistant does when it untiles a dragged window: a one-axis + // maximize first, else the constraints keep the full height + if (isMaximized(w)) + unmaximizeAxes(w); + w.move_resize_frame(true, Math.round(x - share * width), Math.round(y - grabY), width, height); + } + + _workspaceChanged() { + const s = this._session; + if (s && !tryOr(() => s.window.located_on_workspace(global.workspace_manager.get_active_workspace()), true)) + this._cancel('workspace-changed'); + } + + /** Ends the running drag without a drop (`end` with `cancelled`); the rest of the grab is ignored. */ + _cancel(reason, at = null) { + const s = this._session; + if (!s?.hit) + return; + s.hit = null; + const [x, y] = at ? [at.x, at.y] : global.get_pointer(); + this._emit({type: 'end', drag: s.drag, zone: null, cancelled: true, reason, frame: null, pointer: {x, y}}); + if (reason === 'window-closed' || reason === 'stopped') + this._stopSession(); + } + + _end(window) { + const s = this._session; + if (!s || s.window !== window) + return; + const hit = s.hit; + this._stopSession(); + if (!hit) + return; // cancelled earlier + const [x, y, mods] = global.get_pointer(); + const frame = rect(window.get_frame_rect()); + // Escape ends the grab with the button still down and the window back where it was + const buttonDown = (mods & M.BUTTON1_MASK) !== 0; + const cancelled = buttonDown || sameRect(frame, s.frame); + const zone = cancelled ? null : hit.release({x, y, t: nowMs(), flags: flagsOf(mods)}); + this._emit({ + type: 'end', + drag: s.drag, + zone, + cancelled, + ...(cancelled ? {reason: buttonDown ? 'escape' : 'put-back'} : {}), + frame, + pointer: {x, y}, + }); + } +} diff --git a/gnome-shell/smbact@giglabo.com/extension.js b/gnome-shell/smbact@giglabo.com/extension.js index 40d07fe..5531420 100644 --- a/gnome-shell/smbact@giglabo.com/extension.js +++ b/gnome-shell/smbact@giglabo.com/extension.js @@ -6,6 +6,8 @@ // - 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); +// - window drags are reported against the client's zone table only while it set one (dragSource.js); Mutter's own +// edge tiling is held off only while the client asks, and given back when the client goes away (nativeTiling); // - 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'; @@ -19,6 +21,7 @@ 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'; +import {DragSource} from './dragSource.js'; const API = 1; const BUS_NAME = 'com.giglabo.SMBAct.Shell'; @@ -31,6 +34,13 @@ const EVENT_COALESCE_MS = 100; * login screen or behind a system dialog. */ const HOTKEY_ACTION_MODE = Shell.ActionMode.NORMAL | Shell.ActionMode.OVERVIEW; +/** + * Extensions that hold `org.gnome.mutter edge-tiling` off themselves and tile on their own: the key must not be + * written while one of them is active (the write would end up in their own restore record). + */ +const TILING_EXTENSIONS = ['tiling-assistant@ubuntu.com', 'tiling-assistant@leleat-on-github', 'tilingshell@ferrarodomenico.com']; +/** ExtensionState.ACTIVE (1 in GNOME Shell 46-51). */ +const EXTENSION_ACTIVE = 1; const IFACE_XML = ` @@ -151,6 +161,12 @@ class Service { this._grabActions = new Map(); this._snapshots = null; this._focus = null; + /** Window drags against the client's zone table (dragSource.js); created at the first dragWatch. */ + this._drag = null; + /** org.gnome.mutter, created at the first nativeTiling; `_tilingHold`: what was there before the hold. */ + this._mutterSettings = null; + this._tilingHold = null; + this._tilingChangedId = 0; this._ops = { hello: () => this._hello(), listWindows: req => this._listWindows(req), @@ -186,6 +202,26 @@ class Service { throw new ShellError('NO_SNAPSHOT', `no snapshot of window ${req.id} yet`); return {snapshot}; }, + dragWatch: req => { + if (req.table !== null && typeof req.table !== 'object') + throw badRequest('"table" must be a zone table or null'); + if (req.table === null && !this._drag) + return {watching: false, reason: 'stopped'}; + this._drag ??= new DragSource(event => this._emit({type: 'drag', event}), (level, message) => this._log(level, message)); + try { + return this._drag.watch(req.table); + } catch (e) { + throw badRequest(e.message); + } + }, + dragAnswer: req => { + if (typeof req.allow !== 'boolean') + throw badRequest('"allow" must be true or false'); + return this._drag?.answer(this._number(req, 'drag'), req.allow) ?? {ok: false}; + }, + dragRestoreSize: req => + this._drag?.restoreSize(this._number(req, 'drag'), this._number(req, 'width'), this._number(req, 'height')) ?? {ok: false}, + nativeTiling: req => this._nativeTiling(req), }; } @@ -195,13 +231,13 @@ class Service { 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) => { - // grabs belong to the client that made them: a new owner starts without any + // grabs, the drag watch and the tiling hold belong to the client that made them: a new owner starts without if (this._clientOwner !== owner) - this._releaseGrabs(); + this._releaseClientState(); this._clientOwner = owner; }, () => { - this._releaseGrabs(); + this._releaseClientState(); this._clientOwner = null; }); const d = global.display; @@ -226,7 +262,9 @@ class Service { } stop() { - this._releaseGrabs(); + this._releaseClientState(); + this._drag = null; + this._mutterSettings = null; this._snapshots?.stop(); this._snapshots = null; this._focus = null; @@ -387,6 +425,87 @@ class Service { this._ungrab(accelerator, action); } + /** The client went away or changed (or the extension stops): its grabs, its drag watch and its tiling hold end. */ + _releaseClientState() { + this._releaseGrabs(); + tryOr(() => this._drag?.stop()); + tryOr(() => this._releaseTiling()); + } + + _log(level, message) { + if (level === 'warn') + console.warn(`smbact@giglabo.com: ${message}`); + } + + // ---- Mutter's own edge tiling (nativeTiling): held off while the client asks, given back when it goes away + + _nativeTiling(req) { + if (req.suppress !== undefined && typeof req.suppress !== 'boolean') + throw badRequest('"suppress" must be true or false, or absent to read'); + this._mutterSettings ??= new Gio.Settings({schema_id: 'org.gnome.mutter'}); + const s = this._mutterSettings; + if (req.suppress === true) { + const holder = this._activeTilingExtension(); + if (holder) + throw new ShellError('TILING_EXTENSION_ACTIVE', `${holder} is active and holds edge-tiling itself`); + if (!this._tilingHold) { + // the user's own value (none: the default holds), so the key goes back exactly as it was + const user = s.get_user_value('edge-tiling'); + this._tilingHold = user === null ? {present: false} : {present: true, value: user.get_boolean()}; + this._tilingChangedId = s.connect('changed::edge-tiling', () => tryOr(() => this._tilingChanged())); + } + if (s.get_boolean('edge-tiling')) + s.set_boolean('edge-tiling', false); + } else if (req.suppress === false) { + this._releaseTiling(); + } + return this._tilingState(); + } + + _tilingState() { + const s = this._mutterSettings; + const user = s.get_user_value('edge-tiling'); + return { + edgeTiling: s.get_boolean('edge-tiling'), + user: user === null ? null : user.get_boolean(), + held: this._tilingHold !== null, + ...(this._tilingHold ? {saved: {...this._tilingHold}} : {}), + tilingExtension: this._activeTilingExtension(), + }; + } + + /** Somebody else switched edge tiling back on during the hold: no fight over it, the hold ends without a write. */ + _tilingChanged() { + if (this._tilingHold && this._mutterSettings.get_boolean('edge-tiling')) + this._dropTilingHold(); + } + + _dropTilingHold() { + if (this._tilingChangedId) { + tryOr(() => this._mutterSettings?.disconnect(this._tilingChangedId)); + this._tilingChangedId = 0; + } + const hold = this._tilingHold; + this._tilingHold = null; + return hold; + } + + /** Puts back what the hold found: only over its own `false`, never while a tiling extension holds the key itself. */ + _releaseTiling() { + const hold = this._dropTilingHold(); + const s = this._mutterSettings; + if (!hold || !s || s.get_boolean('edge-tiling') || this._activeTilingExtension()) + return; + if (hold.present) + s.set_boolean('edge-tiling', hold.value); + else + s.reset('edge-tiling'); + } + + _activeTilingExtension() { + return TILING_EXTENSIONS.find(uuid => tryOr(() => Main.extensionManager.lookup(uuid)?.state) === EXTENSION_ACTIVE) ?? null; + } + // ---- operations _hello() { diff --git a/gnome-shell/smbact@giglabo.com/hitTest.js b/gnome-shell/smbact@giglabo.com/hitTest.js new file mode 100644 index 0000000..bb171c1 --- /dev/null +++ b/gnome-shell/smbact@giglabo.com/hitTest.js @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// The hit-test of a window drag (PROTOCOL.md, `dragWatch`): pointer samples in, zone transitions out. A port of the +// reference in SMBAct (app-native/shared/drag-snap/hit-test.ts); every implementation runs the same fixtures +// (tests/fixtures/hit-test.json, a copy of SMBAct's app-native/shared/drag-snap/fixtures/hit-test.json). +// Pure: no gi:// imports, no clock of its own (every sample carries its time), no timers, so node runs its tests. + +/** The modifier bits a sample carries (`flags`): the same numbers as SMBAct's MODIFIER_FLAG. */ +export const MODIFIER_FLAG = Object.freeze({shift: 1, ctrl: 2, alt: 4, meta: 8}); + +const contains = (z, x, y) => + z.triggers.some(r => x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height); + +/** How far the point is from the zone's nearest trigger (0 inside). */ +const distance = (z, x, y) => + Math.min(...z.triggers.map(r => { + const dx = Math.max(r.x - x, 0, x - (r.x + r.width)); + const dy = Math.max(r.y - y, 0, y - (r.y + r.height)); + return Math.hypot(dx, dy); + })); + +export class DragHitTest { + /** @param {object} table the zone table (`dragWatch`'s `table`) */ + constructor(table) { + this._table = table; + this._armed = null; + /** a zone waiting for its pause (a shared edge, or armDelayMs): {zone, since} */ + this._pending = null; + /** the modifier was pressed during this drag: `no-modifier` zones are off for the rest of it */ + this._latched = false; + this._last = null; + } + + get armedZone() { + return this._armed; + } + + _held(flags) { + const m = this._table.modifier; + return !!m && (flags & MODIFIER_FLAG[m]) !== 0; + } + + /** The zone counts with these modifier flags. */ + _allowed(z, flags) { + const held = this._held(flags); + if (z.when === 'modifier') + return held; + if (z.when === 'no-modifier') + return !held && !this._latched; + return true; + } + + /** The zone the pointer is in, as far as the modifier allows. */ + zoneAt(x, y, flags) { + return this._table.zones.find(z => this._allowed(z, flags) && contains(z, x, y)); + } + + /** The armed zone still holds a pointer that left its trigger by at most `stickPx` (and is in no other zone). */ + _sticks(s) { + const stick = this._table.stickPx ?? 0; + const z = this._armed ? this._table.zones.find(x => x.id === this._armed) : undefined; + return z && stick > 0 && this._allowed(z, s.flags) && distance(z, s.x, s.y) <= stick ? z : undefined; + } + + _delayOf(z) { + // moving on to a neighbouring zone while armed re-arms at once + if (this._armed) + return 0; + return z.shared ? this._table.sharedEdgeDelayMs : this._table.armDelayMs; + } + + /** A pointer sample `{x, y, t, flags}`. Returns `{zone}` on a transition, null when the armed zone stays. */ + sample(s) { + this._last = s; + if (this._held(s.flags)) + this._latched = true; + return this._evaluate(s); + } + + /** Re-evaluates the last sample at time `t` (a pending pause may be over). */ + tick(t) { + return this._last ? this._evaluate({...this._last, t}) : null; + } + + /** When tick() should run next, or null when nothing waits. */ + nextDeadline() { + if (!this._pending) + return null; + return this._pending.since + (this._pending.zone.shared ? this._table.sharedEdgeDelayMs : this._table.armDelayMs); + } + + _evaluate(s) { + const z = this.zoneAt(s.x, s.y, s.flags); + if (!z && this._sticks(s)) { + this._pending = null; + return null; + } + if (!z) { + this._pending = null; + if (this._armed !== null) { + this._armed = null; + return {zone: null}; + } + return null; + } + if (z.id === this._armed) { + this._pending = null; + return null; + } + const delay = this._delayOf(z); + if (delay <= 0) { + this._pending = null; + this._armed = z.id; + return {zone: z.id}; + } + if (this._pending?.zone.id !== z.id) { + this._pending = {zone: z, since: s.t}; + return null; + } + if (s.t - this._pending.since >= delay) { + this._pending = null; + this._armed = z.id; + return {zone: z.id}; + } + return null; + } + + /** + * The button went up at `s`: the zone of the drop, or null. The armed zone if the release is still in it; a fast + * throw into a zone that arms without a pause counts too; a zone that needs the modifier needs it held at the + * release; a shared edge never counts unarmed (no drop on the way across). + */ + release(s) { + if (this._held(s.flags)) + this._latched = true; + const z = this.zoneAt(s.x, s.y, s.flags); + if (!z) + return this._sticks(s)?.id ?? null; + if (z.id === this._armed || !z.shared || this._armed !== null) + return z.id; + // a shared edge whose pause ran out between the last sample and the release + return this._pending?.zone.id === z.id && s.t - this._pending.since >= this._table.sharedEdgeDelayMs ? z.id : null; + } +} diff --git a/gnome-shell/smbact@giglabo.com/metadata.json b/gnome-shell/smbact@giglabo.com/metadata.json index 75d9b7a..5175968 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, global hotkeys and window snapshots for its switcher, 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, window snapshots for its switcher and the window drags it places with the mouse, 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": 4, - "version-name": "2.1.0" + "version": 5, + "version-name": "2.2.0" } diff --git a/kwin/smbact-kwin.js b/kwin/smbact-kwin.js index e46a6c5..b06818c 100644 --- a/kwin/smbact-kwin.js +++ b/kwin/smbact-kwin.js @@ -11,7 +11,7 @@ const SERVICE = "com.giglabo.SMBAct"; const PATH = "/com/giglabo/SMBAct/KWin1"; const IFACE = "com.giglabo.SMBAct.KWin1"; const API = 1; -const VERSION = "2.1.0"; +const VERSION = "2.2.0"; /** 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; diff --git a/scripts/call.py b/scripts/call.py index e364d67..62374d9 100755 --- a/scripts/call.py +++ b/scripts/call.py @@ -10,6 +10,8 @@ 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 --drag table.json 60 [WxH] # watch drags against a zone table for 60 s, print the events; + # with WxH every drag also gets dragRestoreSize W, H scripts/call.py --as-stranger hello # without the name: expect AccessDenied """ import json @@ -31,6 +33,8 @@ def main(argv): 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] == "--drag": + return drag(argv[1], int(argv[2]) if len(argv) > 2 else 60, argv[3] if len(argv) > 3 else None) if argv[0] == "--events": from gi.repository import GLib dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) @@ -128,5 +132,39 @@ def on_event(e): return 0 +def drag(table_file, seconds, restore): + """The drag watch belongs to the owner of com.giglabo.SMBAct: keep the name while listening, stop the watch after.""" + import 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) + with open(table_file) as f: + table = json.load(f) + print(call(json.dumps({"op": "dragWatch", "table": table})), flush=True) + size = [int(v) for v in restore.split("x")] if restore else None + t0 = time.monotonic() + + def on_event(e): + event = json.loads(e) + if event.get("type") != "drag": + return + d = event["event"] + print(json.dumps({"at_ms": round((time.monotonic() - t0) * 1000), **d}), flush=True) + if size and d.get("type") == "begin": + print(call(json.dumps({"op": "dragRestoreSize", "drag": d["drag"], "width": size[0], "height": size[1]})), flush=True) + + bus.add_signal_receiver(on_event, "Event", IFACE, None, PATH) + loop = GLib.MainLoop() + GLib.timeout_add_seconds(seconds, loop.quit) + loop.run() + print(call(json.dumps({"op": "dragWatch", "table": None})), flush=True) + return 0 + + if __name__ == "__main__": sys.exit(main(sys.argv[1:])) diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md new file mode 100644 index 0000000..5c8bd4c --- /dev/null +++ b/tests/fixtures/README.md @@ -0,0 +1,9 @@ +# Shared test fixtures + +`hit-test.json` is the contract of the drag hit-test (PROTOCOL.md, `dragWatch`): pointer paths and the zone transitions +they must give. It is a **byte-for-byte copy** of SMBAct's `app-native/shared/drag-snap/fixtures/hit-test.json` +(smbact-app master `d2c7c05`, 2026-11-22, sha256 `adea94a3aec4ca7c12f3d6b2b4d8d1a4304e65a6d2e2c26e0b01ee3725fe3871`). +SMBAct's TypeScript reference (`app-native/shared/drag-snap/hit-test.ts`), smbact-helper's Rust copy +(`cli/crates/winctl/src/drag.rs`) and this extension's `hitTest.js` run the same cases. + +A change to the hit-test changes SMBAct's fixture first; copy it here unchanged and run `node --test tests/*.test.mjs`. diff --git a/tests/fixtures/hit-test.json b/tests/fixtures/hit-test.json new file mode 100644 index 0000000..1a160eb --- /dev/null +++ b/tests/fixtures/hit-test.json @@ -0,0 +1,731 @@ +{ + "comment": "The hit-test contract (docs/mouse-positioning-spec.md MPOS-ARCH-2): every implementation runs these cases. TypeScript: app-native/shared/drag-snap/hit-test.test.ts; Rust: cli/crates/winctl/src/drag.rs (tests). A step is a pointer sample, a tick (a pause may be over) or the release; 'expect' is the transition ('none': the armed zone stays; null: disarmed) or, for a release, the zone of the drop. flags: shift 1, ctrl 2, alt 4, meta 8. stickPx: an armed zone holds a pointer that left its trigger by at most that much (and is in no other zone).", + "tables": { + "edge": { + "seq": 1, + "space": "native", + "armDelayMs": 0, + "sharedEdgeDelayMs": 400, + "modifier": "shift", + "zones": [ + { + "id": "d0/top-left", + "display": "d0", + "area": "top-left", + "action": "top-left", + "triggers": [ + { + "x": 0, + "y": 0, + "width": 96, + "height": 8 + }, + { + "x": 0, + "y": 0, + "width": 8, + "height": 96 + } + ], + "when": "no-modifier", + "shared": false + }, + { + "id": "d0/top", + "display": "d0", + "area": "top", + "action": "maximize", + "triggers": [ + { + "x": 96, + "y": 0, + "width": 808, + "height": 8 + } + ], + "when": "no-modifier", + "shared": false + }, + { + "id": "d0/left", + "display": "d0", + "area": "left", + "action": "left-half", + "triggers": [ + { + "x": 0, + "y": 96, + "width": 8, + "height": 608 + } + ], + "when": "no-modifier", + "shared": false + }, + { + "id": "d0/right/shared", + "display": "d0", + "area": "right", + "action": "right-half", + "triggers": [ + { + "x": 992, + "y": 96, + "width": 8, + "height": 608 + } + ], + "when": "no-modifier", + "shared": true + }, + { + "id": "d0/band-left", + "display": "d0", + "area": "left", + "action": "left-half", + "triggers": [ + { + "x": 64, + "y": 240, + "width": 176, + "height": 320 + } + ], + "when": "modifier", + "shared": false + }, + { + "id": "d1/left/shared", + "display": "d1", + "area": "left", + "action": "left-half", + "triggers": [ + { + "x": 1000, + "y": 96, + "width": 8, + "height": 608 + } + ], + "when": "no-modifier", + "shared": true + } + ], + "stickPx": 24 + }, + "delayed": { + "seq": 2, + "space": "native", + "armDelayMs": 150, + "sharedEdgeDelayMs": 400, + "modifier": null, + "zones": [ + { + "id": "d0/left", + "display": "d0", + "area": "left", + "action": "left-half", + "triggers": [ + { + "x": 0, + "y": 96, + "width": 8, + "height": 608 + } + ], + "when": "plain", + "shared": false + }, + { + "id": "d0/top", + "display": "d0", + "area": "top", + "action": "maximize", + "triggers": [ + { + "x": 96, + "y": 0, + "width": 808, + "height": 8 + } + ], + "when": "plain", + "shared": false + } + ], + "stickPx": 0 + } + }, + "cases": [ + { + "name": "an outer edge arms at once and disarms on leaving", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 500, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 4, + "y": 400, + "t": 10, + "flags": 0, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 4, + "y": 300, + "t": 20, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 50, + "y": 400, + "t": 30, + "flags": 0, + "expect": null + }, + { + "op": "release", + "x": 50, + "y": 400, + "t": 40, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "sliding along the edge re-arms from zone to zone", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 4, + "y": 50, + "t": 10, + "flags": 0, + "expect": "d0/top-left" + }, + { + "op": "sample", + "x": 50, + "y": 4, + "t": 20, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 200, + "y": 4, + "t": 30, + "flags": 0, + "expect": "d0/top" + }, + { + "op": "release", + "x": 200, + "y": 4, + "t": 40, + "flags": 0, + "expect": "d0/top" + } + ] + }, + { + "name": "a fast throw: the release lands in an outer zone no sample saw", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 500, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "release", + "x": 3, + "y": 400, + "t": 50, + "flags": 0, + "expect": "d0/left" + } + ] + }, + { + "name": "a shared edge arms after its pause, also with the pointer at rest", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 996, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 997, + "y": 400, + "t": 200, + "flags": 0, + "expect": "none" + }, + { + "op": "tick", + "t": 399, + "expect": "none" + }, + { + "op": "tick", + "t": 400, + "expect": "d0/right/shared" + }, + { + "op": "release", + "x": 997, + "y": 400, + "t": 450, + "flags": 0, + "expect": "d0/right/shared" + } + ] + }, + { + "name": "crossing a shared edge quickly drops nothing", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 996, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 1004, + "y": 400, + "t": 30, + "flags": 0, + "expect": "none" + }, + { + "op": "release", + "x": 1004, + "y": 400, + "t": 100, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "a shared edge whose pause ran out at the release counts", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 996, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "release", + "x": 996, + "y": 400, + "t": 450, + "flags": 0, + "expect": "d0/right/shared" + } + ] + }, + { + "name": "the modifier pressed on a plain drag hides the zones for the rest of the drag", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 4, + "y": 400, + "t": 10, + "flags": 1, + "expect": null + }, + { + "op": "sample", + "x": 4, + "y": 400, + "t": 20, + "flags": 0, + "expect": "none" + }, + { + "op": "release", + "x": 4, + "y": 400, + "t": 30, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "the band needs the modifier, also at the release", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 100, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 100, + "y": 400, + "t": 10, + "flags": 1, + "expect": "d0/band-left" + }, + { + "op": "release", + "x": 100, + "y": 400, + "t": 20, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "a drop in the band with the modifier held", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 100, + "y": 400, + "t": 0, + "flags": 1, + "expect": "d0/band-left" + }, + { + "op": "sample", + "x": 120, + "y": 420, + "t": 10, + "flags": 1, + "expect": "none" + }, + { + "op": "release", + "x": 120, + "y": 420, + "t": 20, + "flags": 1, + "expect": "d0/band-left" + } + ] + }, + { + "name": "other modifier keys do not count as the modifier", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 100, + "y": 400, + "t": 0, + "flags": 8, + "expect": "none" + }, + { + "op": "sample", + "x": 4, + "y": 400, + "t": 10, + "flags": 8, + "expect": "d0/left" + } + ] + }, + { + "name": "the maximum edge is outside a trigger (half-open rectangles)", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 8, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 7.5, + "y": 400, + "t": 10, + "flags": 0, + "expect": "d0/left" + } + ] + }, + { + "name": "armDelayMs: an outer edge waits too, a release there still counts", + "table": "delayed", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "tick", + "t": 149, + "expect": "none" + }, + { + "op": "tick", + "t": 150, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 4, + "y": 4, + "t": 160, + "flags": 0, + "expect": null + }, + { + "op": "release", + "x": 200, + "y": 4, + "t": 170, + "flags": 0, + "expect": "d0/top" + } + ] + }, + { + "name": "no modifier on the platform: the flags change nothing", + "table": "delayed", + "steps": [ + { + "op": "sample", + "x": 200, + "y": 4, + "t": 0, + "flags": 1, + "expect": "none" + }, + { + "op": "tick", + "t": 150, + "expect": "d0/top" + }, + { + "op": "release", + "x": 200, + "y": 4, + "t": 160, + "flags": 1, + "expect": "d0/top" + } + ] + }, + { + "name": "an armed zone holds the pointer within stickPx, also at the release", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 20, + "y": 400, + "t": 10, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 31, + "y": 400, + "t": 20, + "flags": 0, + "expect": "none" + }, + { + "op": "release", + "x": 31, + "y": 400, + "t": 30, + "flags": 0, + "expect": "d0/left" + } + ] + }, + { + "name": "beyond stickPx the zone lets go", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 33, + "y": 400, + "t": 10, + "flags": 0, + "expect": null + }, + { + "op": "release", + "x": 33, + "y": 400, + "t": 20, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "another zone wins over the sticking one", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 200, + "y": 4, + "t": 0, + "flags": 0, + "expect": "d0/top" + }, + { + "op": "sample", + "x": 200, + "y": 20, + "t": 10, + "flags": 0, + "expect": "none" + }, + { + "op": "sample", + "x": 4, + "y": 20, + "t": 20, + "flags": 0, + "expect": "d0/top-left" + } + ] + }, + { + "name": "sticking never outlives the modifier rule", + "table": "edge", + "steps": [ + { + "op": "sample", + "x": 100, + "y": 400, + "t": 0, + "flags": 1, + "expect": "d0/band-left" + }, + { + "op": "sample", + "x": 250, + "y": 400, + "t": 10, + "flags": 1, + "expect": "none" + }, + { + "op": "sample", + "x": 250, + "y": 400, + "t": 20, + "flags": 0, + "expect": null + } + ] + }, + { + "name": "no stickPx: the edge strip lets go at once", + "table": "delayed", + "steps": [ + { + "op": "sample", + "x": 4, + "y": 400, + "t": 0, + "flags": 0, + "expect": "none" + }, + { + "op": "tick", + "t": 150, + "expect": "d0/left" + }, + { + "op": "sample", + "x": 10, + "y": 400, + "t": 160, + "flags": 0, + "expect": null + } + ] + } + ] +} diff --git a/tests/hit-test.test.mjs b/tests/hit-test.test.mjs new file mode 100644 index 0000000..3eb1771 --- /dev/null +++ b/tests/hit-test.test.mjs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// node --test tests/*.test.mjs: the GNOME Shell extension's hit-test (gnome-shell/smbact@giglabo.com/hitTest.js) against the +// shared fixtures in tests/fixtures/hit-test.json, a byte-for-byte copy of SMBAct's +// app-native/shared/drag-snap/fixtures/hit-test.json (see tests/fixtures/README.md). SMBAct's TypeScript reference +// and smbact-helper's Rust copy run the same file. +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const source = path.join(here, '..', 'gnome-shell', 'smbact@giglabo.com', 'hitTest.js'); +// the extension's files are ES modules named .js (GNOME Shell's rule); node needs .mjs to read one as a module +const copy = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'smbact-shell-')), 'hitTest.mjs'); +fs.copyFileSync(source, copy); +const {DragHitTest} = await import(pathToFileURL(copy).href); + +const fixtures = JSON.parse(fs.readFileSync(path.join(here, 'fixtures', 'hit-test.json'), 'utf8')); + +for (const c of fixtures.cases) { + test(`hit-test: ${c.name}`, () => { + const h = new DragHitTest(fixtures.tables[c.table]); + c.steps.forEach((s, i) => { + const where = `step ${i} (${s.op} ${s.x ?? ''},${s.y ?? ''} t=${s.t})`; + if (s.op === 'release') { + assert.equal(h.release({x: s.x, y: s.y, t: s.t, flags: s.flags ?? 0}), s.expect, where); + return; + } + const tr = s.op === 'tick' ? h.tick(s.t) : h.sample({x: s.x, y: s.y, t: s.t, flags: s.flags ?? 0}); + if (s.expect === 'none') + assert.equal(tr, null, where); + else + assert.deepEqual(tr, {zone: s.expect}, where); + }); + }); +} + +test('hit-test: nextDeadline is the pending pause', () => { + const h = new DragHitTest(fixtures.tables.edge); + assert.equal(h.nextDeadline(), null); + h.sample({x: 996, y: 400, t: 1000, flags: 0}); + assert.equal(h.nextDeadline(), 1400); + h.sample({x: 500, y: 400, t: 1100, flags: 0}); + assert.equal(h.nextDeadline(), null); +}); + +test('hit-test: the fixture file has cases', () => { + assert.ok(fixtures.cases.length >= 10, `only ${fixtures.cases.length} cases`); +}); From 11876cae9b1f55ac47b1f8281006bdc1f298cbf4 Mon Sep 17 00:00:00 2001 From: denis smpio-ubuntu Date: Sun, 22 Nov 2026 20:59:28 +0100 Subject: [PATCH 2/2] =?UTF-8?q?kwin:=20drags=20and=20KWin's=20screen-edge?= =?UTF-8?q?=20tiling=20held=20for=20SMBAct=20(dragWatch,=20dragAnswer,=20d?= =?UTF-8?q?ragRestoreSize,=20nativeTiling,=20the=20drag=20event)=20?= =?UTF-8?q?=E2=80=94=20new=20operations,=20API=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The KWin script becomes SMBAct's drag source on KDE Plasma Wayland, next to the GNOME extension's (one 2.2.0 for both): - Drags from each window's interactiveMoveResizeStarted (with `move`) / Finished: normal, movable, resizable windows that are not fullscreen; a keyboard move is left out (KWin warps the pointer to the window's centre for it). The pointer from workspace.cursorPos on cursorPosChanged (connected during a drag only), a QTimer for a shared edge's pause. - The hit-test ported into the script (a KWin script is one file; no ?., ?? or object spread), run on SMBAct's shared fixtures by tests/kwin.test.mjs, which loads the script unchanged into a fake KWin (workspace, options, callDBus, QTimer) and also covers the drag source, the tiling hold and the watchdog. - No modifiers from KWin: flags 0, dragWatch answers `modifier: false` (plain zones only). Escape = the window back at its first frame after it had left it; KWin's own tile (Shift's custom tile) or maximize at the end = no zone (reasons `tiled` / `maximized`); window closed, outputs changed, desktop changed without the window end it cancelled; KWin's "Switch desktop on edge" carrying the window along keeps the drag going. - dragRestoreSize: frameGeometry written during KWin's move once the pointer is 12 px off (a one-axis maximize left first), checked and written again at most 3 times; KWin keeps the size and the grab share. - nativeTiling on KWin: options.electricBorderTiling / electricBorderMaximize held off in KWin's memory (`options`: which), held again on options.configChanged (the re-read values saved as the originals), given back on suppress: false. kwinrc is never written. - A watchdog (NameHasOwner every 2 s while the script holds something: a failed callDBus reaches no callback) gives the hold back and stops the watch when SMBAct leaves the bus. - PROTOCOL.md ("The KWin script's drags", "KWin's screen-edge tiling"), README, the fixtures' README. Measured in SMBAct's KDE VM (Kubuntu 26.04, Plasma 6.6.6, two outputs): the in-memory switch holds (P-KDE-1), a size written during the move holds (P-KDE-4); SMBAct's live check 53 / 53: every default zone on both outputs for a Wayland and an XWayland window, restore on drag away, Escape, Shift's custom tile, "Apply" during the hold, a kill healed by the watchdog in 2.4 s (smbact-app scripts/dev/linux/drag-snap/kde/). Co-Authored-By: Claude Opus 5.5 --- PROTOCOL.md | 73 +++++- README.md | 16 +- kwin/smbact-kwin.js | 502 ++++++++++++++++++++++++++++++++++++++- tests/fixtures/README.md | 3 +- tests/kwin.test.mjs | 448 ++++++++++++++++++++++++++++++++++ 5 files changed, 1023 insertions(+), 19 deletions(-) create mode 100644 tests/kwin.test.mjs diff --git a/PROTOCOL.md b/PROTOCOL.md index af5d8a3..2497f85 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -121,13 +121,14 @@ XWayland. Rectangles are `{ "x", "y", "width", "height" }`. | `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 }` | -| `dragWatch` | `table` (a zone table, or `null` to stop) | `{ watching, reason?, draws, restoreDuringMove }` | +| `dragWatch` | `table` (a zone table, or `null` to stop) | `{ watching, reason?, draws, restoreDuringMove, modifier? }` | | `dragAnswer` | `drag`, `allow` | `{ ok }` (`false`: no such drag running) | | `dragRestoreSize` | `drag`, `width`, `height` | `{ ok }` (`false`: no such drag, or the window is maximized) | -| `nativeTiling` | `suppress?` (`true` hold off, `false` give back, absent: read) | `{ edgeTiling, user, held, saved?, tilingExtension }` | +| `nativeTiling` (GNOME) | `suppress?` (`true` hold off, `false` give back, absent: read) | `{ edgeTiling, user, held, saved?, tilingExtension }` | +| `nativeTiling` (KWin) | `suppress?` (as above), `options?` (`["electricBorderTiling", "electricBorderMaximize"]`, default both) | `{ electricBorderTiling, electricBorderMaximize, held, saved }` | -The last four are the GNOME Shell extension's only (plugin 2.2.0 and later); see "Window drags" and "Mutter's edge -tiling" below. +The last four come with plugin 2.2.0, in the GNOME Shell extension and the KWin script; see "Window drags", "Mutter's +edge tiling" and "KWin's screen-edge tiling" below. - `setState` states: `minimized`, `maximized`, `maximizedHorizontally`, `maximizedVertically`, `fullscreen`, `above`. @@ -163,12 +164,13 @@ tiling" below. - `showDesktop` with `show: true` minimizes the visible windows of the active workspace and remembers them; `false` restores those. -## Window drags (GNOME, plugin 2.2.0) +## Window drags (plugin 2.2.0) -SMBAct places a window the user drags to a screen edge or corner (its "positioning with the mouse"). The extension is -its drag source on GNOME: it reports when a window is dragged and which zone of SMBAct's table the pointer is in, and -nothing else. It draws nothing (SMBAct draws its zone map and the footprint itself, `draws: false`) and moves no window -at the end of a drag (SMBAct's own action does, through `moveResize` / `setState`). +SMBAct places a window the user drags to a screen edge or corner (its "positioning with the mouse"). The plugin is +its drag source on GNOME and on KDE Plasma: it reports when a window is dragged and which zone of SMBAct's table the +pointer is in, and nothing else. It draws nothing (SMBAct draws its zone map and the footprint itself, `draws: false`) +and moves no window at the end of a drag (SMBAct's own action does, through `moveResize` / `setState`). The rules +below are the GNOME Shell extension's; the KWin script's differences follow them ("The KWin script's drags"). `dragWatch` gives the table; drags are reported only while one is set: @@ -216,6 +218,32 @@ Events: `{ "type": "drag", "event": }`, where `` is one of it grabbed it; once per drag. A window maximized both ways is Mutter's to restore (`{ ok: false }`); a one-axis maximize (how SMBAct holds a full-height half) is left first. +### The KWin script's drags + +The same operations, events and table; what KWin gives a script makes these differences: + +- A drag is a window's `interactiveMoveResizeStarted` with `move` set (the same signal starts resizes) of a normal, + movable, resizable window that is not fullscreen; it ends with `interactiveMoveResizeFinished`. A move started from + the keyboard (the window menu's Move, a shortcut) is not reported: KWin puts the pointer on the window's centre for + it, which a title-bar drag past KWin's threshold never is. +- The pointer comes from `workspace.cursorPos` on every `workspace.cursorPosChanged` (connected during a drag only); a + pause of a shared edge ends on a timer, without pointer motion. `begin`'s `press` is the pointer when KWin started the + move (a few pixels past the real press), `time` is `Date.now()`. +- **No modifiers.** KWin tells a script nothing about keys or buttons: every sample carries flags 0, so the table must + hold only `plain` zones, and `dragWatch` answers `modifier: false`. Shift during a drag is KWin's own: it drops the + window into KWin's custom tile under the pointer, whatever its options say. +- `end` comes after KWin applied its own result. Escape: KWin has put the window back where it began after it had left + that place, and the pointer is elsewhere (`cancelled`, reason `escape`). A KWin tile (Shift's custom tile, or KWin's + own edge tiling when it is not held off) or a KWin maximize at the end ends the drag with `zone: null`, cancelled, + reason `tiled` or `maximized`. A window closed (`window-closed`), the outputs changed (`displays-changed`), the + desktop changed without the window (`workspace-changed`; KWin's "Switch desktop on edge" carries the dragged window + along, and the drag goes on there), a zone over an output showing a fullscreen window (`fullscreen`) and the watch + stopped (`stopped`) end it as on GNOME. There is no overview reason. +- `dragRestoreSize` writes `frameGeometry` during KWin's move once the pointer is 12 px off the start: KWin keeps the + size for the rest of the move and keeps the pointer at the same share of the window where it grabbed it. A one-axis + maximize is left first; a window maximized both ways or in a KWin tile at the start is KWin's to restore + (`{ ok: false }`). Written again (at most 3 times) when KWin did not keep it. + ## Mutter's edge tiling (GNOME, plugin 2.2.0) `nativeTiling` holds `org.gnome.mutter edge-tiling` off for the client and gives it back: @@ -236,6 +264,27 @@ maximize (how SMBAct holds a full-height half) is left first. The drag watch belongs to the client too: it stops when the client goes away or changes, and when the extension is disabled. +## KWin's screen-edge tiling (KWin script, plugin 2.2.0) + +`nativeTiling` holds KWin's own drag tiling off for the client and gives it back: System Settings › Screen Edges, +"Tile: Windows dragged to left or right edge" (`kwinrc [Windows] ElectricBorderTiling`) and "Maximize: Windows dragged +to top edge" (`ElectricBorderMaximize`), both on by default. + +- The script sets KWin's live `options.electricBorderTiling` / `electricBorderMaximize` (`options`: which, default + both). That is KWin's memory only: kwinrc is not written, so System Settings keeps showing both boxes ticked, and + KWin's next start or `reconfigure` reads kwinrc again. +- `suppress: true` saves the value KWin has now and sets `false`; repeated calls keep the first saved value. KWin + re-reads kwinrc on every reconfigure (any "Apply" in System Settings, `options.configChanged`): the hold saves what + KWin brings (the user's choice now) and sets `false` again. +- `suppress: false` puts the saved values back (only `options` when given). +- The hold belongs to the client: a script's call that fails reaches no callback, so while it holds something (the + tiling hold or the drag watch) the script asks the bus every 2 s whether `com.giglabo.SMBAct` has an owner + (`NameHasOwner`); when it has none, the saved values go back and the drag watch stops. The script itself is loaded + by the client and unloaded by it; unloading leaves KWin's options as they are, so the client gives the hold back + first (or lets KWin re-read kwinrc). +- The reply: `electricBorderTiling` and `electricBorderMaximize` as KWin has them now, `held`, `saved` (per held option, + the value it found). + ## Events `Event` carries `{ "type": ..., ... }`: @@ -257,7 +306,8 @@ disabled. - API 1, plugin 2.1.0 (2026-11): `connector` in `displays`, `onActiveWorkspace` and (KWin) `tiled` in the window (new optional fields, same API), with SMBAct 2.1.0. - API 1, plugin 2.2.0 (not released yet): `dragWatch`, `dragAnswer`, `dragRestoreSize`, `nativeTiling`, the `drag` - event (GNOME only; new operations, same API; clients look for them in `hello`'s `ops`). + event, in the GNOME Shell extension and the KWin script (new operations, same API; clients look for them in + `hello`'s `ops`). ## KWin transport @@ -282,7 +332,8 @@ SMBAct's own X11 hotkeys fire with any focus: KWin passes key combinations to XW 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). The -window drags and `nativeTiling` (plugin 2.2.0) are the GNOME Shell extension's only so far. +window drags and `nativeTiling` (plugin 2.2.0) have KWin's differences ("The KWin script's drags", "KWin's +screen-edge tiling"); the drag events go out as `Event` calls like the others. - 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 02e2555..a928f8a 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ 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, window snapshots and the window -drags SMBAct places with the mouse. +moving and resizing, activation, window states, displays, the window drags SMBAct places with the mouse; 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). @@ -29,7 +29,9 @@ everyone else. `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. +serve D-Bus calls, so the script calls SMBAct instead (PROTOCOL.md, "KWin transport"); it answers only to KWin. While +SMBAct handles window drags it holds KWin's screen-edge tiling off in KWin's memory (nothing written to kwinrc) and gives +it back when SMBAct asks or leaves the bus. By hand, with something serving `com.giglabo.SMBAct.KWin1` (SMBAct does): @@ -48,9 +50,11 @@ Every push to `main` and every pull request runs the checks and the tests and pa ## Tests `node --test tests/*.test.mjs`: the drag hit-test (`gnome-shell/smbact@giglabo.com/hitTest.js`) against SMBAct's shared -fixtures (`tests/fixtures/`, see its README for where they come from). The rest is checked live in SMBAct's GNOME test -VM (smbact-app `scripts/dev/linux/drag-snap/gnome/`). By hand: `scripts/call.py --drag table.json 60` prints the drag -events against a zone table. +fixtures (`tests/fixtures/`, see its README for where they come from), and the KWin script (`kwin/smbact-kwin.js`) in a +fake KWin (`tests/kwin.test.mjs`: the same fixtures through its own copy of the hit-test, its drag source, the hold of +KWin's screen-edge tiling, the watchdog). The rest is checked live in SMBAct's test VMs (smbact-app +`scripts/dev/linux/drag-snap/gnome/` and `scripts/dev/linux/drag-snap/kde/`). By hand: `scripts/call.py --drag +table.json 60` prints the GNOME extension's drag events against a zone table. ## License diff --git a/kwin/smbact-kwin.js b/kwin/smbact-kwin.js index b06818c..326cad3 100644 --- a/kwin/smbact-kwin.js +++ b/kwin/smbact-kwin.js @@ -7,6 +7,9 @@ // 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. +// Window drags (plugin 2.2.0, PROTOCOL.md "Window drags"): reported against SMBAct's zone table only while it set one +// (dragWatch); KWin's own screen-edge tiling is held off in memory only while SMBAct asks (nativeTiling) and given back +// when SMBAct asks, or by itself when SMBAct's name leaves the bus (a watchdog: a script's failed call has no callback). const SERVICE = "com.giglabo.SMBAct"; const PATH = "/com/giglabo/SMBAct/KWin1"; const IFACE = "com.giglabo.SMBAct.KWin1"; @@ -14,6 +17,12 @@ const API = 1; const VERSION = "2.2.0"; /** 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; +/** The pointer must move this far from the start of a drag before a placed window gets its size back (MPOS-REST-1). */ +const DRAG_RESTORE_THRESHOLD = 12; +/** How often the script checks that SMBAct is still on the bus while it holds something for it (watchdog). */ +const WATCHDOG_MS = 2000; +/** KWin's options SMBAct may hold off (nativeTiling): the screen-edge tiling and maximize of a dragged window. */ +const TILING_OPTIONS = ["electricBorderTiling", "electricBorderMaximize"]; class ShellError extends Error { constructor(code, message) { @@ -213,6 +222,475 @@ function displays() { return { monitors: monitors }; } +// ---- the drag hit-test: pointer samples in, zone transitions out (PROTOCOL.md "Window drags"). A port of SMBAct's +// reference (app-native/shared/drag-snap/hit-test.ts), the same as the GNOME extension's hitTest.js; every +// implementation runs the same fixtures (tests/fixtures/hit-test.json). Pure: no KWin objects, no clock of its own. +// Written without `?.`, `??` and object spread, as the rest of this file. tests/kwin.test.mjs runs it. + +/** The modifier bits a sample carries (`flags`): the same numbers as SMBAct's MODIFIER_FLAG (always 0 from KWin). */ +const MODIFIER_FLAG = { shift: 1, ctrl: 2, alt: 4, meta: 8 }; + +function zoneContains(z, x, y) { + return z.triggers.some((r) => x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height); +} + +/** How far the point is from the zone's nearest trigger (0 inside). */ +function zoneDistance(z, x, y) { + return z.triggers.reduce((best, r) => { + const dx = Math.max(r.x - x, 0, x - (r.x + r.width)); + const dy = Math.max(r.y - y, 0, y - (r.y + r.height)); + return Math.min(best, Math.hypot(dx, dy)); + }, Infinity); +} + +class DragHitTest { + /** @param {object} table the zone table (`dragWatch`'s `table`) */ + constructor(table) { + this._table = table; + this._armed = null; + /** a zone waiting for its pause (a shared edge, or armDelayMs): {zone, since} */ + this._pending = null; + /** the modifier was pressed during this drag: `no-modifier` zones are off for the rest of it */ + this._latched = false; + this._last = null; + } + + get armedZone() { + return this._armed; + } + + _held(flags) { + const m = this._table.modifier; + return !!m && (flags & MODIFIER_FLAG[m]) !== 0; + } + + /** The zone counts with these modifier flags. */ + _allowed(z, flags) { + const held = this._held(flags); + if (z.when === "modifier") return held; + if (z.when === "no-modifier") return !held && !this._latched; + return true; + } + + /** The zone the pointer is in, as far as the modifier allows. */ + zoneAt(x, y, flags) { + return this._table.zones.find((z) => this._allowed(z, flags) && zoneContains(z, x, y)); + } + + /** The armed zone still holds a pointer that left its trigger by at most `stickPx` (and is in no other zone). */ + _sticks(s) { + const stick = this._table.stickPx || 0; + const armed = this._armed; + const z = armed ? this._table.zones.find((x) => x.id === armed) : undefined; + return z && stick > 0 && this._allowed(z, s.flags) && zoneDistance(z, s.x, s.y) <= stick ? z : undefined; + } + + _delayOf(z) { + // moving on to a neighbouring zone while armed re-arms at once + if (this._armed) return 0; + return z.shared ? this._table.sharedEdgeDelayMs : this._table.armDelayMs; + } + + /** A pointer sample `{x, y, t, flags}`. Returns `{zone}` on a transition, null when the armed zone stays. */ + sample(s) { + this._last = s; + if (this._held(s.flags)) this._latched = true; + return this._evaluate(s); + } + + /** Re-evaluates the last sample at time `t` (a pending pause may be over). */ + tick(t) { + return this._last ? this._evaluate({ x: this._last.x, y: this._last.y, t: t, flags: this._last.flags }) : null; + } + + /** When tick() should run next, or null when nothing waits. */ + nextDeadline() { + if (!this._pending) return null; + return this._pending.since + (this._pending.zone.shared ? this._table.sharedEdgeDelayMs : this._table.armDelayMs); + } + + _evaluate(s) { + const z = this.zoneAt(s.x, s.y, s.flags); + if (!z && this._sticks(s)) { + this._pending = null; + return null; + } + if (!z) { + this._pending = null; + if (this._armed !== null) { + this._armed = null; + return { zone: null }; + } + return null; + } + if (z.id === this._armed) { + this._pending = null; + return null; + } + const delay = this._delayOf(z); + if (delay <= 0) { + this._pending = null; + this._armed = z.id; + return { zone: z.id }; + } + if (!this._pending || this._pending.zone.id !== z.id) { + this._pending = { zone: z, since: s.t }; + return null; + } + if (s.t - this._pending.since >= delay) { + this._pending = null; + this._armed = z.id; + return { zone: z.id }; + } + return null; + } + + /** + * The button went up at `s`: the zone of the drop, or null. The armed zone if the release is still in it; a fast + * throw into a zone that arms without a pause counts too; a zone that needs the modifier needs it held at the + * release; a shared edge never counts unarmed (no drop on the way across). + */ + release(s) { + if (this._held(s.flags)) this._latched = true; + const z = this.zoneAt(s.x, s.y, s.flags); + if (!z) { + const stuck = this._sticks(s); + return stuck ? stuck.id : null; + } + if (z.id === this._armed || !z.shared || this._armed !== null) return z.id; + // a shared edge whose pause ran out between the last sample and the release + return this._pending && this._pending.zone.id === z.id && s.t - this._pending.since >= this._table.sharedEdgeDelayMs ? z.id : null; + } +} + +// ---- window drags (dragWatch): KWin's interactive move of a window, the pointer from workspace.cursorPos +// - A drag is interactiveMoveResizeStarted with `move` (the same signal starts resizes) of a normal, movable, resizable +// window that is not fullscreen. A move started from the keyboard (the window menu's Move, a shortcut) is not one: +// KWin puts the pointer on the window's centre for it, which a title-bar drag past KWin's threshold never is. +// - KWin tells a script nothing about buttons or modifiers: the table may hold only `plain` zones (`modifier: false`). +// Shift during a drag drops the window into KWin's custom tile under the pointer, whatever its options say. +// - interactiveMoveResizeFinished comes after KWin applied its own result: a cancel (Escape) has put the window back +// where it began (`end` cancelled, reason `escape`); a KWin tile or maximize (Shift's custom tile, KWin's own edge +// tiling) ends the drag with no zone (reason `tiled` / `maximized`). +// - A placed window's size comes back during the move when SMBAct asks (dragRestoreSize): a frameGeometry write, which +// KWin keeps for the rest of the move with the pointer at the same share of the window where it grabbed it. + +let dragTable = null; +let dragSession = null; +let nextDragId = 0; + +function validTable(t) { + return ( + !!t && + typeof t === "object" && + Array.isArray(t.zones) && + typeof t.seq === "number" && + t.zones.every((z) => z && typeof z.id === "string" && Array.isArray(z.triggers)) + ); +} + +function point(p) { + return { x: Math.round(p.x), y: Math.round(p.y) }; +} + +function sameRect(a, b) { + return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; +} + +function dragEligible(w) { + return !!w && !!w.move && !!w.normalWindow && w.moveable !== false && w.resizeable !== false && !w.fullScreen && !w.minimized; +} + +function onCurrentDesktop(w) { + return !!w.onAllDesktops || (w.desktops || []).indexOf(workspace.currentDesktop) >= 0; +} + +function dragWatch(req) { + if (req.table === null) { + dragCancel("stopped"); + dragTable = null; + watchdogUpdate(); + return { watching: false, reason: "stopped" }; + } + if (!validTable(req.table)) throw badRequest('"table" must be a zone table ({seq, zones: [{id, triggers}], ...}) or null'); + dragTable = req.table; + watchdogUpdate(); + return { watching: true, draws: false, restoreDuringMove: true, modifier: false }; +} + +function dragAnswer(req) { + if (typeof req.allow !== "boolean") throw badRequest('"allow" must be true or false'); + const s = dragSession; + if (!s || s.drag !== number(req, "drag")) return { ok: false }; + s.allowed = req.allow; + return { ok: true }; +} + +function dragRestoreSize(req) { + const drag = number(req, "drag"); + const width = number(req, "width"); + const height = number(req, "height"); + const s = dragSession; + if (!s || s.drag !== drag || !s.hit || s.maximizedAtBegin || s.tiledAtBegin || !(width > 0 && height > 0)) return { ok: false }; + s.restore = { width: width, height: height, writes: 0, done: false }; + dragRestoreStep(); + return { ok: true }; +} + +function dragStarted(w) { + if (!dragTable || dragSession || !dragEligible(w)) return; + const frame = rect(w.frameGeometry); + const p = point(workspace.cursorPos); + // a keyboard move: KWin has put the pointer on the window's centre + if (Math.abs(p.x - (frame.x + frame.width / 2)) <= 1 && Math.abs(p.y - (frame.y + frame.height / 2)) <= 1) return; + const s = { + drag: ++nextDragId, + window: w, + frame: frame, + press: p, + hit: new DragHitTest(dragTable), + table: dragTable.seq, + maximizedAtBegin: (w.maximizeMode || 0) === 3, + tiledAtBegin: !!w.tile, + left: false, + allowed: null, + restore: null, + timer: null, + }; + dragSession = s; + emit({ + type: "drag", + event: { + type: "begin", + drag: s.drag, + window: { OwnerHandle: w.pid || -1, Handle: idOf(w) }, + frame: frame, + pointer: p, + press: p, + table: s.table, + time: Date.now(), + owner: w.resourceClass ? String(w.resourceClass) : "", + }, + }); + workspace.cursorPosChanged.connect(dragPointer); + dragSample(); +} + +function dragPointer() { + guarded(() => { + const s = dragSession; + // the window left its first place (Escape puts it back there; a window KWin holds in place never left it) + if (s && !s.left && !sameRect(rect(s.window.frameGeometry), s.frame)) s.left = true; + dragSample(); + dragRestoreStep(); + }); +} + +function dragSample() { + const s = dragSession; + if (!s || !s.hit) return; + const p = point(workspace.cursorPos); + dragTransition(s, s.hit.sample({ x: p.x, y: p.y, t: Date.now(), flags: 0 }), p); +} + +/** A transition of the hit-test goes out; a pause still running gets a timer for its end. */ +function dragTransition(s, tr, p) { + if (tr) { + if (tr.zone !== null) { + const reason = dragGuard(p); + if (reason) { + dragCancel(reason, p); + return; + } + } + emit({ type: "drag", event: { type: "zone", drag: s.drag, zone: tr.zone, pointer: p } }); + } + const deadline = s.hit ? s.hit.nextDeadline() : null; + if (deadline === null) { + if (s.timer) s.timer.stop(); + return; + } + if (!s.timer) { + s.timer = new QTimer(); + s.timer.singleShot = true; + s.timer.timeout.connect(() => + guarded(() => { + if (dragSession === s && s.hit) dragTransition(s, s.hit.tick(Date.now()), point(workspace.cursorPos)); + }) + ); + } + s.timer.stop(); + s.timer.start(Math.max(1, Math.ceil(deadline - Date.now()))); +} + +/** Why no zone may arm now: the output under the pointer shows a fullscreen window (MPOS-WIN-7). */ +function dragGuard(p) { + const output = workspace.screenAt ? workspace.screenAt(p) : null; + const full = windows().some((w) => w.fullScreen && !w.minimized && (!output || w.output === output) && onCurrentDesktop(w)); + return full ? "fullscreen" : null; +} + +/** The restored size, once the pointer is off the start of the drag (see dragRestoreSize). */ +function dragRestoreStep() { + const s = dragSession; + if (!s || !s.hit || !s.restore || s.allowed === false) return; + const r = s.restore; + const w = s.window; + if (r.writes > 0 && Math.round(w.frameGeometry.width) === r.width && Math.round(w.frameGeometry.height) === r.height) r.done = true; + // checked on the later samples, written again (at most 3 times) when KWin did not keep it + if (r.done || r.writes >= 3) return; + const p = point(workspace.cursorPos); + if (Math.hypot(p.x - s.press.x, p.y - s.press.y) <= DRAG_RESTORE_THRESHOLD) return; + if ((w.maximizeMode || 0) === 3) return; // KWin restores a maximized window itself when it moves + const share = s.frame.width > 0 ? Math.min(1, Math.max(0, (s.press.x - s.frame.x) / s.frame.width)) : 0.5; + const grabY = Math.min(Math.max(0, s.press.y - s.frame.y), Math.max(0, r.height - 1)); + // a one-axis maximize (SMBAct's halves are vertically maximized windows) first, else KWin keeps the full height + if (w.maximizeMode) w.setMaximize(false, false); + r.writes++; + w.frameGeometry = { x: Math.round(p.x - share * r.width), y: Math.round(p.y - grabY), width: r.width, height: r.height }; +} + +/** Ends the running drag without a drop (`end` cancelled); the rest of KWin's move is ignored. */ +function dragCancel(reason, at) { + const s = dragSession; + if (!s || !s.hit) return; + s.hit = null; + if (s.timer) s.timer.stop(); + emit({ type: "drag", event: { type: "end", drag: s.drag, zone: null, cancelled: true, reason: reason, frame: null, pointer: at || point(workspace.cursorPos) } }); + if (reason === "window-closed" || reason === "stopped") dragStop(); +} + +function dragStop() { + const s = dragSession; + if (!s) return; + dragSession = null; + if (s.timer) s.timer.stop(); + try { + workspace.cursorPosChanged.disconnect(dragPointer); + } catch (e) { + // not connected + } +} + +function dragFinished(w) { + const s = dragSession; + if (!s || s.window !== w) return; + const hit = s.hit; + dragStop(); + if (!hit) return; // cancelled earlier + const p = point(workspace.cursorPos); + const frame = rect(w.frameGeometry); + // Escape: KWin has put the window back where it began after it had left that place, and the pointer is elsewhere + const escaped = !!s.left && sameRect(frame, s.frame) && Math.hypot(p.x - s.press.x, p.y - s.press.y) > 4; + // KWin placed the window itself: a custom tile (Shift held), or its own edge tiling / maximize + const tiled = !!w.tile; + const maximized = (w.maximizeMode || 0) === 3 && !s.maximizedAtBegin; + const cancelled = escaped || tiled || maximized; + const zone = cancelled ? null : hit.release({ x: p.x, y: p.y, t: Date.now(), flags: 0 }); + const event = { type: "end", drag: s.drag, zone: zone, cancelled: cancelled, frame: frame, pointer: p }; + if (cancelled) event.reason = escaped ? "escape" : tiled ? "tiled" : "maximized"; + emit({ type: "drag", event: event }); +} + +function dragDesktopChanged() { + const s = dragSession; + // KWin's "Switch desktop on edge" carries the dragged window along: the drag goes on there (MPOS-KDE-10) + if (s && s.hit && !onCurrentDesktop(s.window)) dragCancel("workspace-changed"); +} + +// ---- KWin's own screen-edge tiling (nativeTiling): held off in memory for SMBAct, never written to kwinrc +// The script's `options` is KWin's live options object: its setters change the running value only. KWin re-reads +// kwinrc on every reconfigure (any "Apply" in System Settings): the hold saves what it brings (the user's choice now) +// and holds it off again. Given back when SMBAct asks, or when SMBAct's name leaves the bus (the watchdog). + +/** What the hold found, per option it holds ({ electricBorderTiling: true, ... }); null while nothing is held. */ +let tilingHold = null; + +function tilingState() { + const saved = {}; + if (tilingHold) for (const k in tilingHold) saved[k] = tilingHold[k]; + return { + electricBorderTiling: !!options.electricBorderTiling, + electricBorderMaximize: !!options.electricBorderMaximize, + held: !!tilingHold, + saved: saved, + }; +} + +function nativeTiling(req) { + if (req.suppress !== undefined && typeof req.suppress !== "boolean") throw badRequest('"suppress" must be true or false, or absent to read'); + let which = TILING_OPTIONS; + if (req.options !== undefined) { + if (!Array.isArray(req.options) || !req.options.every((o) => TILING_OPTIONS.indexOf(o) >= 0)) { + throw badRequest('"options" must list ' + TILING_OPTIONS.join(" and/or ")); + } + which = req.options; + } + if (req.suppress === true) { + tilingHold = tilingHold || {}; + for (const k of which) { + if (!(k in tilingHold)) tilingHold[k] = !!options[k]; + if (options[k]) options[k] = false; + } + } else if (req.suppress === false) { + tilingRelease(req.options === undefined ? null : which); + } + watchdogUpdate(); + return tilingState(); +} + +/** Puts back what the hold found (`which`: those options only; null: all of them). */ +function tilingRelease(which) { + if (!tilingHold) return; + for (const k of TILING_OPTIONS) { + if (!(k in tilingHold) || (which && which.indexOf(k) < 0)) continue; + if (!!options[k] !== tilingHold[k]) options[k] = tilingHold[k]; + delete tilingHold[k]; + } + if (Object.keys(tilingHold).length === 0) tilingHold = null; +} + +options.configChanged.connect(() => + guarded(() => { + if (!tilingHold) return; + // KWin re-read kwinrc: what it brings is the user's choice now, held off again + for (const k in tilingHold) { + tilingHold[k] = !!options[k]; + if (options[k]) options[k] = false; + } + }) +); + +// ---- the watchdog: a failed call to SMBAct reaches no callback, so while the script holds something for SMBAct (the +// tiling hold, the drag watch) it asks the bus every WATCHDOG_MS whether SMBAct is still there; gone: all given back + +let watchdog = null; + +function watchdogUpdate() { + const needed = !!tilingHold || !!dragTable; + if (needed && !watchdog) { + watchdog = new QTimer(); + watchdog.interval = WATCHDOG_MS; + watchdog.timeout.connect(() => + callDBus("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", SERVICE, (has) => { + if (has === false) guarded(clientGone); + }) + ); + watchdog.start(); + } else if (!needed && watchdog) { + watchdog.stop(); + watchdog = null; + } +} + +/** SMBAct left the bus (killed, crashed): its hold and its drag watch end here, as GNOME's extension does. */ +function clientGone() { + tilingRelease(null); + dragCancel("stopped"); + dragTable = null; + watchdogUpdate(); +} + const OPS = { hello: () => hello(), listWindows: () => listWindows(), @@ -238,6 +716,10 @@ const OPS = { showDesktop: (req) => showDesktop(req), displays: () => displays(), pointer: () => ({ x: Math.round(workspace.cursorPos.x), y: Math.round(workspace.cursorPos.y) }), + dragWatch: (req) => dragWatch(req), + dragAnswer: (req) => dragAnswer(req), + dragRestoreSize: (req) => dragRestoreSize(req), + nativeTiling: (req) => nativeTiling(req), }; function hello() { @@ -284,13 +766,31 @@ function watch(w) { w.maximizedChanged.connect(() => windowsChanged(true)); w.fullScreenChanged.connect(() => windowsChanged(true)); w.interactiveMoveResizeFinished.connect(() => windowsChanged(true)); + w.interactiveMoveResizeStarted.connect(() => guarded(() => dragStarted(w))); + w.interactiveMoveResizeFinished.connect(() => guarded(() => dragFinished(w))); +} + +/** Signal handlers never throw into KWin. */ +function guarded(fn) { + try { + fn(); + } catch (e) { + console.warn("smbact-kwin: " + e); + } } workspace.windowAdded.connect((w) => { watch(w); windowsChanged(true); }); -workspace.windowRemoved.connect(() => windowsChanged(true)); +workspace.windowRemoved.connect((w) => { + windowsChanged(true); + guarded(() => { + if (dragSession && dragSession.window === w) dragCancel("window-closed"); + }); +}); +workspace.screensChanged.connect(() => guarded(() => dragCancel("displays-changed"))); +workspace.currentDesktopChanged.connect(() => guarded(() => dragDesktopChanged())); workspace.windowActivated.connect((w) => emit({ type: "focusChanged", id: w ? idOf(w) : null })); for (const w of workspace.windowList()) watch(w); diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 5c8bd4c..c6e1909 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -4,6 +4,7 @@ they must give. It is a **byte-for-byte copy** of SMBAct's `app-native/shared/drag-snap/fixtures/hit-test.json` (smbact-app master `d2c7c05`, 2026-11-22, sha256 `adea94a3aec4ca7c12f3d6b2b4d8d1a4304e65a6d2e2c26e0b01ee3725fe3871`). SMBAct's TypeScript reference (`app-native/shared/drag-snap/hit-test.ts`), smbact-helper's Rust copy -(`cli/crates/winctl/src/drag.rs`) and this extension's `hitTest.js` run the same cases. +(`cli/crates/winctl/src/drag.rs`), this extension's `hitTest.js` and the KWin script's own copy (`kwin/smbact-kwin.js`, +run by `tests/kwin.test.mjs`) run the same cases. A change to the hit-test changes SMBAct's fixture first; copy it here unchanged and run `node --test tests/*.test.mjs`. diff --git a/tests/kwin.test.mjs b/tests/kwin.test.mjs new file mode 100644 index 0000000..0e59ddf --- /dev/null +++ b/tests/kwin.test.mjs @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// node --test tests/*.test.mjs: the KWin script (kwin/smbact-kwin.js) in a fake KWin. The script runs unchanged in a +// node `vm` context with stand-ins for what KWin gives a script (workspace, options, callDBus, QTimer, KWin), so these +// tests cover its drag hit-test against SMBAct's shared fixtures (tests/fixtures/hit-test.json, the same cases as the +// GNOME extension's hitTest.js), the drag source (begin / zone / end, Escape, KWin's own tile, a keyboard move, the +// pause of a shared edge, restore on drag away), the hold of KWin's screen-edge tiling and the watchdog. KWin's real +// behaviour behind these fakes was measured in SMBAct's KDE VM (smbact-app scripts/dev/linux/drag-snap/kde/). +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import vm from 'node:vm'; +import {fileURLToPath} from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const SOURCE = fs.readFileSync(path.join(here, '..', 'kwin', 'smbact-kwin.js'), 'utf8'); +const fixtures = JSON.parse(fs.readFileSync(path.join(here, 'fixtures', 'hit-test.json'), 'utf8')); + +class Signal { + constructor() { + this.handlers = []; + } + connect(f) { + this.handlers.push(f); + } + disconnect(f) { + const i = this.handlers.indexOf(f); + if (i < 0) throw new Error('not connected'); + this.handlers.splice(i, 1); + } + emit(...a) { + for (const f of [...this.handlers]) f(...a); + } +} + +let uuid = 0; +const fakeWindow = (o = {}) => { + const w = { + internalId: `{${(0x10000000 + ++uuid).toString(16)}-0000-0000-0000-000000000000}`, + caption: 'Drag W', + resourceClass: 'drag-probe', + pid: 4242, + normalWindow: true, + moveable: true, + resizeable: true, + fullScreen: false, + minimized: false, + maximizeMode: 0, + tile: null, + move: false, + onAllDesktops: false, + desktops: ['d1'], + output: 'out0', + _frame: {x: 300, y: 150, width: 640, height: 467}, + frameGeometryChanged: new Signal(), + minimizedChanged: new Signal(), + captionChanged: new Signal(), + maximizedChanged: new Signal(), + fullScreenChanged: new Signal(), + interactiveMoveResizeStarted: new Signal(), + interactiveMoveResizeFinished: new Signal(), + writes: [], + setMaximize(v, h) { + this.maximizeMode = (v ? 1 : 0) | (h ? 2 : 0); + }, + ...o, + }; + Object.defineProperty(w, 'frameGeometry', { + get() { + return {...this._frame}; + }, + set(g) { + this.writes.push({...g}); + this._frame = {...g}; + }, + }); + w.clientGeometry = w._frame; + return w; +}; + +/** The script in a fresh fake KWin; returns the handles a test drives it with. */ +const loadScript = ({nameHasOwner = true} = {}) => { + let now = 1000; + const timers = []; + class QTimer { + constructor() { + this.interval = 0; + this.singleShot = false; + this.timeout = new Signal(); + this.due = null; + timers.push(this); + } + start(ms) { + if (ms !== undefined) this.interval = ms; + this.due = now + this.interval; + } + stop() { + this.due = null; + } + } + const events = []; + const calls = []; + let next = null; + let lastReply = null; + const owner = {has: nameHasOwner}; + const callDBus = (service, objPath, iface, method, ...rest) => { + const cb = typeof rest[rest.length - 1] === 'function' ? rest.pop() : null; + calls.push({method, args: rest}); + if (method === 'Hello') cb && cb(); + else if (method === 'Next') { + lastReply = rest[0] ? JSON.parse(rest[0]) : null; + next = cb; + } else if (method === 'Event') events.push(JSON.parse(rest[0])); + else if (method === 'NameHasOwner') cb && cb(owner.has); + }; + const win = fakeWindow(); + const workspace = { + _windows: [win], + windowList() { + return this._windows; + }, + get stackingOrder() { + return this._windows; + }, + screens: [{name: 'out0', geometry: {x: 0, y: 0, width: 1280, height: 800}, devicePixelRatio: 1}], + cursorPos: {x: 620, y: 164}, + currentDesktop: 'd1', + desktops: ['d1', 'd2'], + activeWindow: win, + windowAdded: new Signal(), + windowRemoved: new Signal(), + windowActivated: new Signal(), + screensChanged: new Signal(), + currentDesktopChanged: new Signal(), + cursorPosChanged: new Signal(), + screenAt() { + return 'out0'; + }, + clientArea() { + return {x: 0, y: 0, width: 1280, height: 746}; + }, + raiseWindow() {}, + }; + const options = { + electricBorderTiling: true, + electricBorderMaximize: true, + configChanged: new Signal(), + }; + const ctx = vm.createContext({ + workspace, + options, + callDBus, + QTimer, + KWin: {MaximizeArea: 2}, + console: {log() {}, info() {}, warn() {}}, + Date: {now: () => now}, + }); + vm.runInContext(`${SOURCE}\n;globalThis.__kwin = { DragHitTest: DragHitTest };`, ctx, {filename: 'smbact-kwin.js'}); + const request = (op, args = {}) => { + const cb = next; + assert.ok(cb, 'the script waits for a request'); + next = null; + cb(JSON.stringify({...args, op, seq: calls.length})); + assert.ok(lastReply && lastReply.ok, `${op}: ${JSON.stringify(lastReply)}`); + return lastReply.result; + }; + const advance = (ms) => { + const until = now + ms; + for (;;) { + const due = timers.filter((t) => t.due !== null && t.due <= until).sort((a, b) => a.due - b.due)[0]; + if (!due) break; + now = due.due; + due.due = due.singleShot ? null : now + due.interval; + due.timeout.emit(); + } + now = until; + }; + const pointer = (x, y) => { + workspace.cursorPos = {x, y}; + workspace.cursorPosChanged.emit(); + }; + const drags = () => events.filter((e) => e.type === 'drag').map((e) => e.event); + return {ctx, workspace, options, win, events, drags, calls, request, advance, pointer, owner, hitTest: ctx.__kwin.DragHitTest}; +}; + +/** A table with the left edge, the top edge (maximize) and a shared right edge on one 1280 x 800 output. */ +const TABLE = { + seq: 7, + space: 'logical', + armDelayMs: 0, + sharedEdgeDelayMs: 400, + stickPx: 24, + modifier: null, + zones: [ + {id: 'd0/left', display: 'd0', area: 'left', action: 'left-half', triggers: [{x: 0, y: 96, width: 30, height: 608}], when: 'plain', shared: false}, + {id: 'd0/top', display: 'd0', area: 'top', action: 'maximize', triggers: [{x: 96, y: 0, width: 1088, height: 30}], when: 'plain', shared: false}, + {id: 'd0/right', display: 'd0', area: 'right', action: 'right-half', triggers: [{x: 1250, y: 96, width: 30, height: 608}], when: 'plain', shared: true}, + ], +}; + +/** KWin starts a move of `w`: `move` set, the pointer a little past the press (its drag threshold). */ +const startMove = (k, w = k.win, at = {x: 630, y: 170}) => { + k.workspace.cursorPos = at; + w.move = true; + w.interactiveMoveResizeStarted.emit(); +}; +/** KWin moves the window with the pointer (the grab offset kept), as each motion does. */ +const moveTo = (k, x, y, w = k.win, grab = {x: 330, y: 20}) => { + w._frame = {...w._frame, x: x - grab.x, y: y - grab.y}; + k.pointer(x, y); +}; +const finish = (k, w = k.win) => { + w.move = false; + w.interactiveMoveResizeFinished.emit(); +}; + +for (const c of fixtures.cases) { + test(`kwin hit-test: ${c.name}`, () => { + const {hitTest} = loadScript(); + const h = new hitTest(fixtures.tables[c.table]); + c.steps.forEach((s, i) => { + const where = `step ${i} (${s.op} ${s.x ?? ''},${s.y ?? ''} t=${s.t})`; + if (s.op === 'release') { + assert.equal(h.release({x: s.x, y: s.y, t: s.t, flags: s.flags ?? 0}), s.expect, where); + return; + } + const tr = s.op === 'tick' ? h.tick(s.t) : h.sample({x: s.x, y: s.y, t: s.t, flags: s.flags ?? 0}); + if (s.expect === 'none') assert.equal(tr, null, where); + else assert.deepEqual({...tr}, {zone: s.expect}, where); + }); + }); +} + +test('kwin: hello lists the drag operations', () => { + const k = loadScript(); + const hello = JSON.parse(k.calls.find((c) => c.method === 'Hello').args[0]); + for (const op of ['dragWatch', 'dragAnswer', 'dragRestoreSize', 'nativeTiling']) assert.ok(hello.ops.includes(op), op); + assert.equal(hello.version, '2.2.0'); +}); + +test('kwin: no table, no drag events; dragWatch answers draws false, restore true, no modifier', () => { + const k = loadScript(); + startMove(k); + moveTo(k, 5, 400); + finish(k); + assert.equal(k.drags().length, 0); + assert.deepEqual(k.request('dragWatch', {table: TABLE}), {watching: true, draws: false, restoreDuringMove: true, modifier: false}); + assert.deepEqual(k.request('dragWatch', {table: null}), {watching: false, reason: 'stopped'}); +}); + +test('kwin: a drag to the left edge: begin, zone, end in the zone', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + startMove(k); + moveTo(k, 400, 300); + moveTo(k, 5, 400); + finish(k); + const [begin, zone, end] = k.drags(); + assert.equal(begin.type, 'begin'); + assert.equal(begin.table, 7); + assert.deepEqual(begin.frame, {x: 300, y: 150, width: 640, height: 467}); + assert.equal(begin.window.OwnerHandle, 4242); + // the window's id in the protocol: the first 32 bits of KWin's UUID + assert.equal(begin.window.Handle, parseInt(k.win.internalId.slice(1, 9), 16)); + assert.deepEqual(zone, {type: 'zone', drag: begin.drag, zone: 'd0/left', pointer: {x: 5, y: 400}}); + assert.equal(end.type, 'end'); + assert.equal(end.zone, 'd0/left'); + assert.equal(end.cancelled, false); + // the pointer listener goes with the drag + assert.equal(k.workspace.cursorPosChanged.handlers.length, 0); +}); + +test('kwin: Escape (the window back where it began) ends cancelled, no zone', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + startMove(k); + moveTo(k, 400, 300); + moveTo(k, 5, 400); + k.win._frame = {x: 300, y: 150, width: 640, height: 467}; // KWin's cancel restores the first geometry + finish(k); + const end = k.drags().at(-1); + assert.deepEqual([end.zone, end.cancelled, end.reason], [null, true, 'escape']); +}); + +test("kwin: KWin's custom tile (Shift) or its own maximize at the end: no zone", () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + startMove(k); + moveTo(k, 5, 400); + k.win.tile = {}; + finish(k); + assert.deepEqual([k.drags().at(-1).zone, k.drags().at(-1).reason], [null, 'tiled']); + k.win.tile = null; + startMove(k); + moveTo(k, 600, 5); + k.win.maximizeMode = 3; + finish(k); + assert.deepEqual([k.drags().at(-1).zone, k.drags().at(-1).reason], [null, 'maximized']); +}); + +test('kwin: a resize, a keyboard move and a window that cannot be resized get no drag', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + k.win.interactiveMoveResizeStarted.emit(); // move false: a resize + k.win.interactiveMoveResizeFinished.emit(); + // the window menu's Move: KWin puts the pointer on the window's centre + startMove(k, k.win, {x: 620, y: 384}); + finish(k); + k.win.resizeable = false; + startMove(k); + finish(k); + assert.equal(k.drags().length, 0); +}); + +test('kwin: a shared edge arms after its pause (a timer, no pointer motion needed)', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + startMove(k); + moveTo(k, 1265, 400); + assert.equal(k.drags().length, 1); + k.advance(399); + assert.equal(k.drags().length, 1); + k.advance(2); + assert.deepEqual(k.drags().at(-1), {type: 'zone', drag: 1, zone: 'd0/right', pointer: {x: 1265, y: 400}}); + finish(k); + assert.equal(k.drags().at(-1).zone, 'd0/right'); +}); + +test('kwin: a zone does not arm over a fullscreen window: the drag ends cancelled', () => { + const k = loadScript(); + const full = fakeWindow({fullScreen: true}); + k.workspace._windows.push(full); + k.request('dragWatch', {table: TABLE}); + startMove(k); + moveTo(k, 5, 400); + const end = k.drags().at(-1); + assert.deepEqual([end.type, end.cancelled, end.reason], ['end', true, 'fullscreen']); + finish(k); + assert.equal(k.drags().length, 2); +}); + +test('kwin: the window closed, the outputs changed, the desktop changed without the window: cancelled', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + startMove(k); + k.workspace.windowRemoved.emit(k.win); + assert.equal(k.drags().at(-1).reason, 'window-closed'); + startMove(k); + k.workspace.screensChanged.emit(); + assert.equal(k.drags().at(-1).reason, 'displays-changed'); + finish(k); + // "Switch desktop on edge" carried the window along: the drag goes on (MPOS-KDE-10) + startMove(k); + k.win.desktops = ['d2']; + k.workspace.currentDesktop = 'd2'; + k.workspace.currentDesktopChanged.emit(); + assert.equal(k.drags().at(-1).type, 'begin'); + // the window stayed behind: ends cancelled + k.workspace.currentDesktop = 'd1'; + k.workspace.currentDesktopChanged.emit(); + assert.equal(k.drags().at(-1).reason, 'workspace-changed'); +}); + +test('kwin: dragRestoreSize: the size once the pointer is 12 px off, the grab share kept, a vertical maximize left', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + k.win._frame = {x: 0, y: 0, width: 640, height: 746}; + k.win.maximizeMode = 1; + startMove(k, k.win, {x: 211, y: 14}); + const drag = k.drags()[0].drag; + assert.deepEqual(k.request('dragRestoreSize', {drag, width: 400, height: 300}), {ok: true}); + assert.equal(k.win.writes.length, 0, 'not before the threshold'); + k.pointer(216, 18); + assert.equal(k.win.writes.length, 0); + k.pointer(300, 60); + assert.equal(k.win.maximizeMode, 0); + // the pointer at 211 / 640 of the width and 14 px down, as at the start + assert.deepEqual(k.win.writes, [{x: Math.round(300 - (211 / 640) * 400), y: 60 - 14, width: 400, height: 300}]); + k.pointer(320, 70); + assert.equal(k.win.writes.length, 1, 'kept: not written again'); + assert.deepEqual(k.request('dragRestoreSize', {drag: drag + 1, width: 400, height: 300}), {ok: false}); +}); + +test('kwin: dragRestoreSize is refused for a maximized or tiled window and for a refused drag', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + k.win.maximizeMode = 3; + startMove(k); + assert.deepEqual(k.request('dragRestoreSize', {drag: k.drags().at(-1).drag, width: 400, height: 300}), {ok: false}); + finish(k); + k.win.maximizeMode = 0; + startMove(k); + const drag = k.drags().at(-1).drag; + assert.deepEqual(k.request('dragAnswer', {drag, allow: false}), {ok: true}); + k.request('dragRestoreSize', {drag, width: 400, height: 300}); + k.pointer(800, 500); + assert.equal(k.win.writes.length, 0); +}); + +test("kwin: nativeTiling holds KWin's options off in memory, again after a reconfigure, and gives them back", () => { + const k = loadScript(); + assert.deepEqual(k.request('nativeTiling', {}), {electricBorderTiling: true, electricBorderMaximize: true, held: false, saved: {}}); + const held = k.request('nativeTiling', {suppress: true}); + assert.deepEqual(held, { + electricBorderTiling: false, + electricBorderMaximize: false, + held: true, + saved: {electricBorderTiling: true, electricBorderMaximize: true}, + }); + // "Apply" in System Settings: KWin re-reads kwinrc (the user unticked "Maximize" meanwhile) + k.options.electricBorderTiling = true; + k.options.electricBorderMaximize = false; + k.options.configChanged.emit(); + assert.deepEqual([k.options.electricBorderTiling, k.options.electricBorderMaximize], [false, false]); + const back = k.request('nativeTiling', {suppress: false}); + assert.deepEqual(back, {electricBorderTiling: true, electricBorderMaximize: false, held: false, saved: {}}); +}); + +test('kwin: nativeTiling holds only the options asked for (MPOS-SYS-8)', () => { + const k = loadScript(); + const r = k.request('nativeTiling', {suppress: true, options: ['electricBorderTiling']}); + assert.deepEqual([r.electricBorderTiling, r.electricBorderMaximize, r.saved], [false, true, {electricBorderTiling: true}]); + k.request('nativeTiling', {suppress: true, options: ['electricBorderMaximize']}); + assert.equal(k.options.electricBorderMaximize, false); + k.request('nativeTiling', {suppress: false, options: ['electricBorderMaximize']}); + assert.deepEqual([k.options.electricBorderTiling, k.options.electricBorderMaximize], [false, true]); + k.request('nativeTiling', {suppress: false}); + assert.equal(k.options.electricBorderTiling, true); +}); + +test('kwin: the watchdog gives the hold back and stops the watch when SMBAct leaves the bus', () => { + const k = loadScript(); + k.request('dragWatch', {table: TABLE}); + k.request('nativeTiling', {suppress: true}); + startMove(k); + k.advance(2000); + assert.equal(k.options.electricBorderTiling, false, 'SMBAct still there'); + k.owner.has = false; + k.advance(2000); + assert.deepEqual([k.options.electricBorderTiling, k.options.electricBorderMaximize], [true, true]); + assert.deepEqual([k.drags().at(-1).type, k.drags().at(-1).reason], ['end', 'stopped']); + // no watch any more: the next drag reports nothing + const n = k.drags().length; + startMove(k); + moveTo(k, 5, 400); + finish(k); + assert.equal(k.drags().length, n); +});