소스 검색

added gnome 45-50 support, fixed second monitor xray / parallax

UwU 1 개월 전
부모
커밋
403db90922
47개의 변경된 파일과 2924개의 추가작업 그리고 407개의 파일을 삭제
  1. 29 0
      CMakeLists.txt
  2. 3 2
      README.md
  3. 621 0
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js
  4. 9 0
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/metadata.json
  5. 8 0
      src/WallpaperEngine/Application/ApplicationContext.cpp
  6. 3 0
      src/WallpaperEngine/Application/ApplicationContext.h
  7. 483 0
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  8. 79 0
      src/WallpaperEngine/Desktop/GnomeShell.h
  9. 122 0
      src/WallpaperEngine/Desktop/KWinScript.cpp
  10. 24 0
      src/WallpaperEngine/Desktop/KWinScript.h
  11. 44 0
      src/WallpaperEngine/Desktop/WindowState.cpp
  12. 32 0
      src/WallpaperEngine/Desktop/WindowState.h
  13. 7 112
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  14. 4 3
      src/WallpaperEngine/Input/Drivers/KDECursorInput.h
  15. 40 22
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  16. 5 3
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  17. 24 0
      src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp
  18. 24 0
      src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.h
  19. 163 152
      src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp
  20. 22 44
      src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.h
  21. 13 6
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
  22. 31 2
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  23. 2 0
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  24. 1 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp
  25. 127 31
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  26. 15 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  27. 2 1
      src/WallpaperEngine/Render/Drivers/VideoFactories.cpp
  28. 139 9
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  29. 8 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  30. 48 0
      src/WallpaperEngine/Testing/Cases/GnomeSession.cpp
  31. 86 0
      src/gnome_wayland_helper.c
  32. 8 1
      tests/desktops/conftest.py
  33. 1 0
      tests/desktops/fixtures/clickprobe/project.json
  34. 32 0
      tests/desktops/fixtures/clickprobe/scene.json
  35. 258 0
      tests/desktops/test_gnome.py
  36. 93 0
      tests/desktops/test_kde.py
  37. 1 3
      tests/desktops/test_wallpaper.py
  38. 34 1
      tools/desktops/__main__.py
  39. 11 0
      tools/desktops/gnome-lab-extension/lwe-lab@desktops.test/extension.js
  40. 6 0
      tools/desktops/gnome-lab-extension/lwe-lab@desktops.test/metadata.json
  41. 58 0
      tools/desktops/kwin_fake_input.c
  42. 2 0
      tools/desktops/rootfs-fedora-gnome.txt
  43. 2 0
      tools/desktops/rootfs-ubuntu.txt
  44. 7 1
      tools/desktops/runner.py
  45. 156 11
      tools/desktops/session.py
  46. 36 0
      tools/desktops/wayland_window.py
  47. 1 1
      tools/package_release.sh

+ 29 - 0
CMakeLists.txt

@@ -213,6 +213,8 @@ if(WAYLAND_SUPPORT_FOUND)
         src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
         src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
         src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h
+        src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp
+        src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.h
         src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp
         src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.h
         src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
@@ -418,6 +420,12 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Media/MediaSource.cpp
     src/WallpaperEngine/Media/DBusMediaSource.h
     src/WallpaperEngine/Media/DBusMediaSource.cpp
+    src/WallpaperEngine/Desktop/GnomeShell.h
+    src/WallpaperEngine/Desktop/GnomeShell.cpp
+    src/WallpaperEngine/Desktop/WindowState.h
+    src/WallpaperEngine/Desktop/WindowState.cpp
+    src/WallpaperEngine/Desktop/KWinScript.h
+    src/WallpaperEngine/Desktop/KWinScript.cpp
     src/WallpaperEngine/Media/ThumbnailPalette.h
     src/WallpaperEngine/Media/ThumbnailPalette.cpp
 
@@ -681,6 +689,7 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/Localization.cpp
         src/WallpaperEngine/Testing/Cases/ScalingModes.cpp
         src/WallpaperEngine/Testing/Cases/CornerColor.cpp
+        src/WallpaperEngine/Testing/Cases/GnomeSession.cpp
         src/WallpaperEngine/Testing/Cases/JsonVectorParsing.cpp
         src/WallpaperEngine/Testing/Cases/ModuleNamespaceTiming.cpp
         src/WallpaperEngine/Testing/Cases/AudioSensitivity.cpp
@@ -840,6 +849,26 @@ target_link_libraries(linux-wallpaperengine-web-helper PRIVATE
 add_dependencies(linux-wallpaperengine-web-helper libcef_dll_wrapper)
 REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine-web-helper)
 
+# GNOME 45-48: started by the Shell extension so our windows belong to a Shell-spawned client; static so it also
+# runs on the host for Flatpak builds
+include(CheckCSourceCompiles)
+set(CMAKE_REQUIRED_LINK_OPTIONS -static)
+check_c_source_compiles("int main(void) { return 0; }" LWE_CAN_LINK_STATIC)
+unset(CMAKE_REQUIRED_LINK_OPTIONS)
+add_executable(linux-wallpaperengine-gnome-helper src/gnome_wayland_helper.c)
+if(LWE_CAN_LINK_STATIC)
+    target_link_options(linux-wallpaperengine-gnome-helper PRIVATE -static)
+endif()
+set_target_properties(linux-wallpaperengine-gnome-helper PROPERTIES RUNTIME_OUTPUT_DIRECTORY
+    ${TARGET_OUTPUT_DIRECTORY}/gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io)
+
+# ships next to the engine for we_manager to install, copied every build so extension.js changes land
+add_custom_target(gnome-shell-extension ALL
+    COMMAND ${CMAKE_COMMAND} -E copy_directory
+        ${CMAKE_CURRENT_SOURCE_DIR}/gnome-shell-extension ${TARGET_OUTPUT_DIRECTORY}/gnome-shell-extension)
+add_dependencies(gnome-shell-extension linux-wallpaperengine-gnome-helper)
+add_dependencies(linux-wallpaperengine gnome-shell-extension)
+
 # Install the main executable and shared library via install(TARGETS)
 # so that CMake automatically strips/replaces the build-time RPATH.
 install(TARGETS linux-wallpaperengine linux-wallpaperengine-web-helper

+ 3 - 2
README.md

@@ -131,7 +131,7 @@ The KDE Plasma integration (plasma-shell desktop surfaces, cursor tracking throu
 cmake -DCMAKE_BUILD_TYPE='Release' -DDISABLE_KDE_FEATURES=ON ..
 ```
 
-The "pause on fullscreen" feature on KDE Plasma also needs the [KWin Maximize Detector](https://github.com/LS-FCEFyN/Maximize-Detector) script installed separately.
+On KDE Plasma the engine loads KWin scripts of its own for the cursor position and for the windows that pause it (maximized, fullscreen, and focused with `--pause-on-focus`), per screen like Wallpaper Engine; nothing needs installing.
 
 ## Assets
 
@@ -218,6 +218,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--input-file <path>` | Wayland: file a desktop shell writes the left button to as `{"leftDown": true}`, refreshed while it is held (ignored after 2 seconds). For shells that cover the background and swallow its pointer events |
 | `--disable-parallax` | Disable parallax |
 | `--no-fullscreen-pause` | Don't pause while an app is fullscreen |
+| `--pause-on-focus` | Also pause while another application has the focus (Wallpaper Engine's "Other application focused: Pause"; on GNOME and KDE only that monitor) |
 | `--fullscreen-pause-only-active` | Wayland only: pause only when the fullscreen window is active |
 | `--fullscreen-pause-ignore-appid <val>` | Wayland only: ignore fullscreen windows whose app_id contains `<val>`, repeatable |
 | `--audio-screen <screen>` | Only this screen's background produces audio |
@@ -304,6 +305,7 @@ linux-wallpaperengine --disable-object Clock --disable-object 3 2370927443
 ## Wayland and X11
 
 - Wayland: needs a compositor with `wlr-layer-shell-unstable` and `xdg-output-unstable-v1` (the latter for accurate monitor positioning with `--screen-span`). On KDE Plasma the engine uses KWin's `plasma-shell` surfaces and KWin's cursor position on top of that.
+- GNOME on Wayland: Mutter has no layer-shell, so the engine needs its GNOME Shell extension (`gnome-shell-extension/`, installed next to the binary; GNOME 45 to 50, on 45-48 it starts its `linux-wallpaperengine-gnome-helper` from its own folder). Desktop Icons NG works on top of it, clicks on the empty desktop reach the wallpaper like on Windows. Copy `linux-wallpaperengine@wallpaperenginelover.github.io` to `~/.local/share/gnome-shell/extensions/`, run `gnome-extensions enable linux-wallpaperengine@wallpaperenginelover.github.io` and log out and back in once (we_manager offers to do it). Outputs are the connector names (`DP-1`, `HDMI-A-1`).
 - X11: needs XRandr; target monitors with `--screen-root <name>` as reported by `xrandr`. Doesn't work if something else (GNOME, KDE, Nautilus) is already drawing the desktop background/compositing it.
 
 ## Limitations
@@ -312,7 +314,6 @@ The scene renderer follows Wallpaper Engine 2.8 closely, but not everything is t
 
 Platform and setup:
 
-- KDE fullscreen-pause detection is experimental and requires the separate KWin Maximize Detector script.
 - On X11, a compositor or DE drawing its own background will block the wallpaper. Disabling the compositor is currently the only fix.
 - HDR output (`--hdr`) is Wayland only and needs a compositor with the color-management protocol.
 - Some NVIDIA setups hit GLFW/OpenGL init failures; try `__GL_THREADED_OPTIMIZATIONS=0 linux-wallpaperengine` if you run into this.

+ 621 - 0
gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js

@@ -0,0 +1,621 @@
+// Mutter has no layer-shell: turns the engine's per-output toplevels into desktop windows and reports the pointer
+// and per-monitor window states (WE 2.8 rules) a Wayland client can't see.
+
+import Clutter from 'gi://Clutter';
+import Cogl from 'gi://Cogl';
+import GObject from 'gi://GObject';
+import Gio from 'gi://Gio';
+import GLib from 'gi://GLib';
+import Meta from 'gi://Meta';
+import Shell from 'gi://Shell';
+
+import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
+import * as Main from 'resource:///org/gnome/shell/ui/main.js';
+import {WorkspaceBackground} from 'resource:///org/gnome/shell/ui/workspace.js';
+
+const APP_ID = 'linux-wallpaperengine';
+const TITLE_PREFIX = 'linux-wallpaperengine wallpaper ';
+const BUS_NAME = 'org.linuxwallpaperengine.Shell';
+const OBJECT_PATH = '/org/linuxwallpaperengine/Shell';
+const API_VERSION = 1;
+
+const FLAG_FOCUSED = 1;
+const FLAG_MAXIMIZED = 2;
+const FLAG_FULLSCREEN = 4;
+
+const INTERFACE = `
+<node>
+  <interface name="org.linuxwallpaperengine.Shell">
+    <property name="Version" type="u" access="read"/>
+    <property name="Supported" type="b" access="read"/>
+    <property name="NeedsHelper" type="b" access="read"/>
+    <method name="SpawnHelper">
+      <arg type="s" name="socket" direction="in"/>
+    </method>
+    <method name="GetState">
+      <arg type="a(sdd)" name="pointer" direction="out"/>
+      <arg type="a(ssu)" name="windows" direction="out"/>
+    </method>
+    <signal name="PointerMoved">
+      <arg type="a(sdd)" name="pointer"/>
+    </signal>
+    <signal name="DesktopButton">
+      <arg type="b" name="pressed"/>
+    </signal>
+    <signal name="WindowsChanged">
+      <arg type="a(ssu)" name="windows"/>
+    </signal>
+  </interface>
+</node>`;
+
+// Same rounded work-area clip the overview gives workspace backgrounds; bounds and radius are monitor fractions.
+const CLIP_DECLARATIONS = `
+uniform vec4 bounds;
+uniform vec2 radius;
+`;
+
+const CLIP_CODE = `
+vec2 p = cogl_tex_coord_in[0].xy;
+float inside = step(bounds.x, p.x) * step(p.x, bounds.z) * step(bounds.y, p.y) * step(p.y, bounds.w);
+if (radius.x > 0.0 && radius.y > 0.0) {
+    vec2 corner = clamp(p, bounds.xy + radius, bounds.zw - radius);
+    inside *= 1.0 - smoothstep(0.96, 1.0, length((p - corner) / radius));
+}
+cogl_color_out *= inside;
+`;
+
+const OverviewClipEffect = GObject.registerClass(
+class OverviewClipEffect extends Shell.GLSLEffect {
+    _init(params) {
+        super._init(params);
+        this._boundsLocation = this.get_uniform_location('bounds');
+        this._radiusLocation = this.get_uniform_location('radius');
+    }
+
+    vfunc_build_pipeline() {
+        // Cogl samples first, the clip only scales the result
+        this.add_glsl_snippet(Cogl.SnippetHook.FRAGMENT, CLIP_DECLARATIONS, CLIP_CODE, false);
+    }
+
+    setClip(bounds, radius) {
+        this.set_uniform_float(this._boundsLocation, 4, bounds);
+        this.set_uniform_float(this._radiusLocation, 2, radius);
+        this.queue_repaint();
+    }
+});
+
+// 49+: set_type on any MetaWindow. 46-48: only via MetaWaylandClient for Shell-spawned clients (the helper).
+// 45: no Wayland desktop windows, the wallpaper stays lowest in the normal layer like DING.
+const CAN_SET_TYPE = typeof Meta.Window.prototype.set_type === 'function';
+const CAN_MAKE_DESKTOP = typeof Meta.WaylandClient?.prototype.make_desktop === 'function';
+const CAN_HIDE = typeof Meta.WaylandClient?.prototype.hide_from_window_list === 'function';
+const SUPPORTED = CAN_SET_TYPE || CAN_HIDE;
+const HELPER = 'linux-wallpaperengine-gnome-helper';
+// icon extensions using a bottom-layer normal window (DING on Ubuntu 46, its Gtk4 fork)
+const DESKTOP_ICON_APPS = ['com.rastersoft.ding', 'com.desktop.ding'];
+
+function isMaximized(window) {
+    const flags = window.get_maximize_flags ? window.get_maximize_flags() : window.get_maximized();
+    return flags === Meta.MaximizeFlags.BOTH;
+}
+
+function cursorTracker() {
+    return global.backend.get_cursor_tracker?.() ?? Meta.CursorTracker.get_for_display(global.display);
+}
+
+
+function appIdOf(window) {
+    return window.get_sandboxed_app_id() || window.get_gtk_application_id() || window.get_wm_class() || '';
+}
+
+export default class WallpaperEngineExtension extends Extension {
+    enable() {
+        this._wallpapers = new Map();
+        this._watched = new Map();
+        this._windowsJson = '';
+        this._windows = [];
+        this._pointerIdle = 0;
+        this._stateIdle = 0;
+
+        this._dbus = Gio.DBusExportedObject.wrapJSObject(INTERFACE, this);
+        this._dbus.export(Gio.DBus.session, OBJECT_PATH);
+        this._nameId = Gio.bus_own_name_on_connection(Gio.DBus.session, BUS_NAME, Gio.BusNameOwnerFlags.NONE,
+            null, null);
+
+        this._displaySignals = [
+            global.display.connect('window-created', (_display, window) => this._watch(window)),
+            global.display.connect('notify::focus-window', () => this._queueState()),
+            global.display.connect('restacked', () => {
+                this._pruneWallpapers();
+                this._keepBelowDesktopWindows();
+                this._queueState();
+            }),
+        ];
+        this._workspaceSignal = global.workspace_manager.connect('active-workspace-changed',
+            () => this._queueState());
+        this._monitorManager = global.backend.get_monitor_manager();
+        this._monitorSignal = this._monitorManager.connect('monitors-changed', () => {
+            for (const window of this._wallpapers.keys())
+                this._place(window);
+            this._queueState();
+            this._queuePointer();
+        });
+        this._helperClients = new Set();
+        this._raisedIds = new Map();
+        this._shown = new Set();
+        this._cursorTracker = cursorTracker();
+        this._cursorSignal = this._cursorTracker.connect('position-invalidated', () => this._queuePointer());
+        this._leftDown = false;
+        this._leftForwarded = false;
+        this._pointerOverDesktop = false;
+        this._paintSignal = global.stage.connect('after-paint', () => this._pollLeftButton());
+
+        this._overviewClones = new Map();
+        this._overviewSignal = Main.overview.connect('showing', () => this._syncOverview());
+        this._workareaSignal = global.display.connect('workareas-changed', () => this._syncOverview());
+
+        for (const actor of global.get_window_actors())
+            this._watch(actor.meta_window);
+
+        this._queueState();
+    }
+
+    disable() {
+        for (const id of [this._pointerIdle, this._stateIdle]) {
+            if (id)
+                GLib.source_remove(id);
+        }
+        this._pointerIdle = this._stateIdle = 0;
+
+        Main.overview.disconnect(this._overviewSignal);
+        global.display.disconnect(this._workareaSignal);
+        for (const background of [...this._overviewClones.keys()])
+            this._dropOverviewClone(background);
+        this._overviewClones = null;
+
+        this._cursorTracker.disconnect(this._cursorSignal);
+        global.stage.disconnect(this._paintSignal);
+        this._monitorManager.disconnect(this._monitorSignal);
+        global.workspace_manager.disconnect(this._workspaceSignal);
+        for (const id of this._displaySignals)
+            global.display.disconnect(id);
+
+        for (const [window, ids] of this._watched) {
+            for (const id of ids)
+                window.disconnect(id);
+        }
+        this._watched.clear();
+
+        // otherwise they would be plain windows covering the monitor
+        for (const window of this._wallpapers.keys())
+            window.delete(global.display.get_current_time_roundtrip());
+        this._wallpapers.clear();
+
+        Gio.bus_unown_name(this._nameId);
+        this._dbus.unexport();
+        this._dbus = null;
+        this._cursorTracker = this._monitorManager = null;
+        for (const [window, id] of this._raisedIds)
+            window.disconnect(id);
+        this._helperClients = null;
+        this._raisedIds = null;
+        this._shown = null;
+    }
+
+    get Version() {
+        return API_VERSION;
+    }
+
+    get Supported() {
+        return SUPPORTED;
+    }
+
+    get NeedsHelper() {
+        return !CAN_SET_TYPE && CAN_HIDE;
+    }
+
+    // Only ever runs our own helper; callers just pick an engine socket in the runtime folder (Flatpak calls come
+    // through xdg-dbus-proxy, so the caller's pid is meaningless)
+    SpawnHelperAsync([socket], invocation) {
+        try {
+            if (!this.NeedsHelper)
+                throw new Error('this GNOME Shell makes desktop windows without the helper');
+
+            const runtime = `${GLib.get_user_runtime_dir()}/`;
+            const socketName = socket.startsWith(runtime) ? socket.slice(runtime.length) : '';
+            if (!/^(app\/[^/]+\/)?lwe-gnome-\d+\.sock$/.test(socketName))
+                throw new Error(`refusing a helper for ${socket}`);
+
+            const helper = GLib.build_filenamev([this.path, HELPER]);
+
+            const launcher = new Gio.SubprocessLauncher({flags: Gio.SubprocessFlags.NONE});
+            const client = Meta.WaylandClient.new(global.context, launcher);
+            const process = client.spawnv(global.display, [helper, socket]);
+            this._helperClients.add(client);
+            process.wait_async(null, () => this._helperClients?.delete(client));
+            invocation.return_value(null);
+        } catch (error) {
+            invocation.return_error_literal(Gio.DBusError, Gio.DBusError.ACCESS_DENIED, error.message);
+        }
+    }
+
+    GetState() {
+        return [this._pointer(), this._windows];
+    }
+
+    // fractions from the top left, stage and surface coords differ without scale-monitor-framebuffer
+    _pointer() {
+        const [x, y] = global.get_pointer();
+        const result = [];
+
+        for (const [window, connector] of this._wallpapers) {
+            const frame = window.get_frame_rect();
+            if (frame.width > 0 && frame.height > 0)
+                result.push([connector, (x - frame.x) / frame.width, (y - frame.y) / frame.height]);
+        }
+
+        return result;
+    }
+
+    _watch(window) {
+        if (this._watched.has(window))
+            return;
+
+        // title and app id may come after the window exists
+        const check = () => {
+            if (!this._wallpapers.has(window) && this._isWallpaper(window))
+                this._adopt(window);
+            this._queueState();
+        };
+        const ids = [
+            window.connect('notify::wm-class', check),
+            window.connect('notify::title', check),
+            window.connect('notify::minimized', () => this._queueState()),
+            window.connect('notify::maximized-horizontally', () => this._queueState()),
+            window.connect('notify::maximized-vertically', () => this._queueState()),
+            window.connect('notify::fullscreen', () => this._queueState()),
+            window.connect('size-changed', () => {
+                this._queueState();
+                if (this._wallpapers.has(window))
+                    this._queuePointer();
+            }),
+            window.connect('workspace-changed', () => this._queueState()),
+            window.connect('unmanaged', () => {
+                for (const id of this._watched.get(window) ?? [])
+                    window.disconnect(id);
+                this._watched.delete(window);
+                this._raisedIds?.delete(window);
+                this._shown?.delete(window);
+                if (this._wallpapers.delete(window))
+                    this._syncOverview();
+                this._queueState();
+            }),
+        ];
+        this._watched.set(window, ids);
+        check();
+    }
+
+    _isWallpaper(window) {
+        return window.get_client_type() === Meta.WindowClientType.WAYLAND &&
+            window.get_wm_class() === APP_ID &&
+            (window.get_title() ?? '').startsWith(TITLE_PREFIX);
+    }
+
+    _adopt(window) {
+        const connector = window.get_title().slice(TITLE_PREFIX.length);
+        this._wallpapers.set(window, connector);
+
+        // not fullscreen on the engine side (would hide the top bar), the monitor size comes from here
+        if (CAN_SET_TYPE) {
+            window.set_type(Meta.WindowType.DESKTOP);
+            window.hide_from_window_list();
+        } else {
+            const client = [...this._helperClients].find(candidate => candidate.owns_window(window));
+            if (!client) {
+                console.error(`${this.uuid}: ${window.get_title()} is not from a helper connection, it stays a window`);
+                return;
+            }
+            if (CAN_MAKE_DESKTOP) {
+                client.make_desktop(window);
+            } else {
+                this._raisedIds.set(window, window.connect_after('raised', () => window.lower()));
+                this._returnFocus(window, global.display.focus_window);
+            }
+            client.hide_from_window_list(window);
+        }
+        window.stick();
+        // again when shown, Mutter places new windows on the current monitor
+        this._place(window);
+        const shownId = window.connect('shown', () => {
+            window.disconnect(shownId);
+            this._shown.add(window);
+            this._place(window);
+            this._keepBelowDesktopWindows();
+        });
+        this._queuePointer();
+        this._syncOverview();
+    }
+
+    // The overview hides the window group, so a clone over each workspace background keeps it live
+    _syncOverview() {
+        if (!this._overviewClones)
+            return;
+
+        const found = new Set();
+        const walk = actor => {
+            if (actor instanceof WorkspaceBackground) {
+                found.add(actor);
+                this._syncWorkspaceBackground(actor);
+                return;
+            }
+            for (const child of actor.get_children())
+                walk(child);
+        };
+        walk(Main.layoutManager.overviewGroup);
+
+        for (const background of [...this._overviewClones.keys()]) {
+            if (!found.has(background))
+                this._dropOverviewClone(background);
+        }
+    }
+
+    _wallpaperActorOn(monitorIndex) {
+        for (const window of this._wallpapers.keys()) {
+            if (window.get_monitor() === monitorIndex && window.get_compositor_private())
+                return window.get_compositor_private();
+        }
+        return null;
+    }
+
+    _syncWorkspaceBackground(background) {
+        const source = SUPPORTED ? this._wallpaperActorOn(background._monitorIndex) : null;
+        const existing = this._overviewClones.get(background);
+
+        if (existing?.clone.source === source && source) {
+            this._updateOverviewClip(background, existing);
+            return;
+        }
+        if (existing)
+            this._dropOverviewClone(background);
+        if (!source)
+            return;
+
+        const clone = new Clutter.Clone({source, x_expand: true, y_expand: true});
+        const effect = new OverviewClipEffect();
+        clone.add_effect(effect);
+
+        const group = background._backgroundGroup;
+        group.add_child(clone);
+        group.set_child_above_sibling(clone, null);
+
+        const entry = {clone, effect, group, signals: [], content: null, contentSignal: 0};
+        const manager = background._bgManager;
+        // new background actors go on top
+        entry.signals.push([manager, manager.connect('changed', () => {
+            group.set_child_above_sibling(clone, null);
+            this._updateOverviewClip(background, entry);
+        })]);
+        entry.signals.push([background, background.connect('destroy', () => this._dropOverviewClone(background, true))]);
+
+        this._overviewClones.set(background, entry);
+        this._updateOverviewClip(background, entry);
+    }
+
+    _updateOverviewClip(background, entry) {
+        const content = background._bgManager?.backgroundActor?.content;
+        if (!content)
+            return;
+
+        if (entry.content !== content) {
+            if (entry.contentSignal)
+                entry.content.disconnect(entry.contentSignal);
+            entry.content = content;
+            entry.contentSignal = content.connect('notify::rounded-clip-radius',
+                () => this._updateOverviewClip(background, entry));
+        }
+
+        const monitor = Main.layoutManager.monitors[background._monitorIndex];
+        const area = background._workarea;
+        if (!monitor || !area || monitor.width <= 0 || monitor.height <= 0)
+            return;
+
+        const left = (area.x - monitor.x) / monitor.width;
+        const top = (area.y - monitor.y) / monitor.height;
+        const radius = content.rounded_clip_radius;
+        entry.effect.setClip(
+            [left, top, left + area.width / monitor.width, top + area.height / monitor.height],
+            [radius / monitor.width, radius / monitor.height]);
+    }
+
+    // the workspace went away with clone and background
+    _dropOverviewClone(background, destroyed = false) {
+        const entry = this._overviewClones?.get(background);
+        if (!entry)
+            return;
+
+        this._overviewClones.delete(background);
+        if (destroyed)
+            return;
+
+        for (const [object, id] of entry.signals)
+            object.disconnect(id);
+        if (entry.contentSignal)
+            entry.content.disconnect(entry.contentSignal);
+        entry.clone.destroy();
+    }
+
+    // DING shares the wallpaper's layer and later windows land on top; keep the wallpaper lowest, under the icons
+    _keepBelowDesktopWindows() {
+        const stack = global.display.sort_windows_by_stacking(global.display.list_all_windows());
+
+        for (const wallpaper of this._wallpapers.keys()) {
+            const layer = wallpaper.get_layer();
+            const index = stack.indexOf(wallpaper);
+            // lowering re-emits restacked
+            if (stack.slice(0, Math.max(index, 0))
+                .some(window => window.get_layer() === layer && !this._wallpapers.has(window)))
+                wallpaper.lower();
+        }
+    }
+
+    // GNOME 45 drops a gone client's window without 'unmanaged' (Shell 45.2)
+    _pruneWallpapers() {
+        const live = new Set(global.display.list_all_windows());
+
+        for (const window of [...this._wallpapers.keys()]) {
+            if (!this._shown.has(window) || live.has(window))
+                continue;
+
+            for (const id of this._watched.get(window) ?? [])
+                window.disconnect(id);
+            this._watched.delete(window);
+            this._wallpapers.delete(window);
+            this._shown.delete(window);
+            this._raisedIds.delete(window);
+            this._syncOverview();
+        }
+    }
+
+    _returnFocus(window, previous) {
+        const shownId = window.connect('shown', () => {
+            window.disconnect(shownId);
+            if (window.has_focus() && previous && previous !== window && !previous.minimized)
+                previous.activate(global.display.get_current_time_roundtrip());
+        });
+    }
+
+    _place(window) {
+        const connector = this._wallpapers.get(window);
+        const monitor = this._monitorManager.get_monitor_for_connector(connector);
+        if (monitor < 0)
+            return;
+
+        const area = global.display.get_monitor_geometry(monitor);
+        window.move_resize_frame(false, area.x, area.y, area.width, area.height);
+    }
+
+    // Clicks on desktop icons never reach our surface, but WE polls the left button each frame (sub_14010D9B0) and
+    // counts a press over the icon view. Stage events miss Wayland client input, so poll once per painted frame too.
+    _pollLeftButton() {
+        if (this._wallpapers.size === 0)
+            return;
+
+        const [, , mods] = global.get_pointer();
+        const down = (mods & Clutter.ModifierType.BUTTON1_MASK) !== 0;
+        if (down === this._leftDown) {
+            if (!down)
+                this._updatePointerOverDesktop();
+            return;
+        }
+
+        this._leftDown = down;
+
+        // pick before the press, icons react to it (DING starts a rubber band)
+        if (down && !Main.overview.visible && this._pointerOverDesktop) {
+            this._leftForwarded = true;
+            this._dbus?.emit_signal('DesktopButton', new GLib.Variant('(b)', [true]));
+        } else if (!down && this._leftForwarded) {
+            this._leftForwarded = false;
+            this._dbus?.emit_signal('DesktopButton', new GLib.Variant('(b)', [false]));
+        }
+    }
+
+    _updatePointerOverDesktop() {
+        const [x, y] = global.get_pointer();
+        this._pointerOverDesktop = this._overOtherDesktopWindow(x, y);
+    }
+
+    _overOtherDesktopWindow(x, y) {
+        let actor = global.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y);
+        while (actor && !(actor instanceof Meta.WindowActor))
+            actor = actor.get_parent();
+
+        const window = actor?.get_meta_window();
+        return !!window && this._isDesktop(window);
+    }
+
+    // other desktop windows and icon windows
+    _isDesktop(window) {
+        if (this._wallpapers.has(window))
+            return false;
+        return window.get_window_type() === Meta.WindowType.DESKTOP ||
+            DESKTOP_ICON_APPS.includes(window.get_gtk_application_id());
+    }
+
+    _queuePointer() {
+        if (this._pointerIdle || this._wallpapers.size === 0)
+            return;
+
+        // one signal per main loop pass
+        this._pointerIdle = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
+            this._pointerIdle = 0;
+            this._dbus?.emit_signal('PointerMoved', new GLib.Variant('(a(sdd))', [this._pointer()]));
+            return GLib.SOURCE_REMOVE;
+        });
+    }
+
+    _queueState() {
+        if (this._stateIdle)
+            return;
+
+        this._stateIdle = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
+            this._stateIdle = 0;
+            this._updateState();
+            return GLib.SOURCE_REMOVE;
+        });
+    }
+
+    // GNOME 46 can't list logical monitors, only outputs with a wallpaper are reported
+    _connectorsOf(monitorIndex) {
+        return [...new Set(this._wallpapers.values())]
+            .filter(connector => this._monitorManager.get_monitor_for_connector(connector) === monitorIndex);
+    }
+
+    // WE 2.8 (sub_14003D050 / sub_14003BBA0): visible, unminimized windows on the current desktop. Maximized marks its
+    // monitor; the foreground root window marks focused, and fullscreen if not maximized and at least monitor-sized.
+    _collectWindows() {
+        const workspace = global.workspace_manager.get_active_workspace();
+        const focus = global.display.focus_window?.find_root_ancestor() ?? null;
+        const windows = [];
+
+        for (const actor of global.get_window_actors()) {
+            const window = actor.meta_window;
+            if (this._wallpapers.has(window) || window.minimized || !window.showing_on_its_workspace() ||
+                !window.located_on_workspace(workspace) || window.is_override_redirect())
+                continue;
+
+            if (window.get_window_type() === Meta.WindowType.DOCK || this._isDesktop(window))
+                continue;
+
+            const maximized = isMaximized(window);
+            let flags = maximized ? FLAG_MAXIMIZED : 0;
+
+            if (window === focus) {
+                flags |= FLAG_FOCUSED;
+                const frame = window.get_frame_rect();
+                const area = global.display.get_monitor_geometry(window.get_monitor());
+                if (!maximized && (window.is_fullscreen() || (frame.width >= area.width && frame.height >= area.height)))
+                    flags |= FLAG_FULLSCREEN;
+            }
+
+            if (flags === 0)
+                continue;
+
+            for (const connector of this._connectorsOf(window.get_monitor()))
+                windows.push([appIdOf(window), connector, flags]);
+        }
+
+        return windows;
+    }
+
+    _updateState() {
+        const windows = this._collectWindows();
+        const json = JSON.stringify(windows);
+        if (json === this._windowsJson)
+            return;
+
+        this._windowsJson = json;
+        this._windows = windows;
+        this._dbus?.emit_signal('WindowsChanged', new GLib.Variant('(a(ssu))', [windows]));
+    }
+}

+ 9 - 0
gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/metadata.json

@@ -0,0 +1,9 @@
+{
+  "uuid": "linux-wallpaperengine@wallpaperenginelover.github.io",
+  "name": "linux-wallpaperengine",
+  "description": "Puts linux-wallpaperengine's wallpaper windows behind the desktop and tells the engine where the pointer is and which windows are maximized or fullscreen. Without it the engine cannot draw a wallpaper on GNOME Wayland.",
+  "url": "https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde",
+  "session-modes": ["user", "unlock-dialog"],
+  "shell-version": ["45", "46", "47", "48", "49", "50"],
+  "version-name": "1"
+}

+ 8 - 0
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -937,6 +937,14 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.pauseOnFullscreenOnlyWhenActive = true;
 	});
 
+    performanceGroup.add_argument ("--pause-on-focus")
+	.help (
+	    "Also pause while another application has the focus (Wallpaper Engine's \"Other application focused\" "
+	    "set to pause; on GNOME only the outputs it is on pause)"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.render.pauseOnFocus = true; });
+
     performanceGroup.add_argument ("--fullscreen-pause-ignore-appid")
 	.help ("Wayland only: ignore fullscreen windows whose app_id contains this value (repeatable)")
 	.action ([this] (const std::string& value) -> void {

+ 3 - 0
src/WallpaperEngine/Application/ApplicationContext.h

@@ -197,6 +197,8 @@ public:
 	     * Useful for compositors with "virtual" fullscreen windows (e.g. scrollable tiling).
 	     */
 	    bool pauseOnFullscreenOnlyWhenActive;
+	    /** WE's "Other application focused: Pause" (--pause-on-focus) */
+	    bool pauseOnFocus;
 	    /**
 	     * Wayland-only: list of app_id substrings to ignore for fullscreen pause.
 	     * Example: "firefox" will match "org.mozilla.firefox".
@@ -308,6 +310,7 @@ public:
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,
+            .pauseOnFocus = false,
             .fullscreenPauseIgnoreAppIds = {},
             .hdr = false,
             .debug = {

+ 483 - 0
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -0,0 +1,483 @@
+#include "GnomeShell.h"
+
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <optional>
+#include <poll.h>
+#include <string_view>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+using namespace WallpaperEngine::Desktop;
+
+bool WallpaperEngine::Desktop::isGnomeSession () {
+    const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
+
+    if (desktops == nullptr) {
+	return false;
+    }
+
+    std::string_view rest (desktops);
+
+    while (!rest.empty ()) {
+	const auto colon = rest.find (':');
+
+	if (rest.substr (0, colon) == "GNOME") {
+	    return true;
+	}
+
+	if (colon == std::string_view::npos) {
+	    break;
+	}
+
+	rest.remove_prefix (colon + 1);
+    }
+
+    return false;
+}
+
+namespace {
+constexpr int CALL_TIMEOUT_MS = 2000;
+/** caps one frame's drain */
+constexpr int MAX_READS_PER_DISPATCH = 64;
+
+DBusMessage* call (DBusConnection* connection, DBusMessage* message, std::string& error) {
+    DBusError dbusError;
+    dbus_error_init (&dbusError);
+
+    DBusMessage* reply = dbus_connection_send_with_reply_and_block (connection, message, CALL_TIMEOUT_MS, &dbusError);
+    dbus_message_unref (message);
+
+    if (dbus_error_is_set (&dbusError)) {
+	error = dbusError.message;
+	dbus_error_free (&dbusError);
+	return nullptr;
+    }
+
+    return reply;
+}
+
+bool readVariant (DBusMessageIter* iter, int type, void* value) {
+    if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_VARIANT) {
+	return false;
+    }
+
+    DBusMessageIter inner;
+    dbus_message_iter_recurse (iter, &inner);
+
+    if (dbus_message_iter_get_arg_type (&inner) != type) {
+	return false;
+    }
+
+    dbus_message_iter_get_basic (&inner, value);
+    return true;
+}
+
+std::optional<std::vector<GnomeShell::Pointer>> readPointer (DBusMessageIter* iter) {
+    if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_ARRAY) {
+	return std::nullopt;
+    }
+
+    std::vector<GnomeShell::Pointer> result;
+    DBusMessageIter array;
+    dbus_message_iter_recurse (iter, &array);
+
+    for (; dbus_message_iter_get_arg_type (&array) == DBUS_TYPE_STRUCT; dbus_message_iter_next (&array)) {
+	DBusMessageIter fields;
+	const char* output = nullptr;
+	double x = 0.0;
+	double y = 0.0;
+
+	dbus_message_iter_recurse (&array, &fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_STRING) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &output);
+	dbus_message_iter_next (&fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_DOUBLE) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &x);
+	dbus_message_iter_next (&fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_DOUBLE) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &y);
+
+	result.push_back ({ output, { x, y } });
+    }
+
+    return result;
+}
+
+std::optional<std::vector<GnomeShell::Window>> readWindows (DBusMessageIter* iter) {
+    if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_ARRAY) {
+	return std::nullopt;
+    }
+
+    std::vector<GnomeShell::Window> result;
+    DBusMessageIter array;
+    dbus_message_iter_recurse (iter, &array);
+
+    for (; dbus_message_iter_get_arg_type (&array) == DBUS_TYPE_STRUCT; dbus_message_iter_next (&array)) {
+	DBusMessageIter fields;
+	const char* appId = nullptr;
+	const char* output = nullptr;
+	dbus_uint32_t flags = 0;
+
+	dbus_message_iter_recurse (&array, &fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_STRING) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &appId);
+	dbus_message_iter_next (&fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_STRING) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &output);
+	dbus_message_iter_next (&fields);
+	if (dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_UINT32) {
+	    return std::nullopt;
+	}
+	dbus_message_iter_get_basic (&fields, &flags);
+
+	result.push_back ({ appId, output, flags });
+    }
+
+    return result;
+}
+} // namespace
+
+GnomeShell::GnomeShell () {
+    if (!this->connect ()) {
+	return;
+    }
+
+    this->m_available = this->queryState ();
+}
+
+namespace {
+std::string socketDirectory () {
+    std::string dir = std::getenv ("XDG_RUNTIME_DIR") ? std::getenv ("XDG_RUNTIME_DIR") : "/tmp";
+
+    if (const char* flatpakId = std::getenv ("FLATPAK_ID"); flatpakId && access ("/.flatpak-info", F_OK) == 0) {
+	const std::string appDir = dir + "/app/" + flatpakId;
+	std::error_code error;
+
+	if (std::filesystem::is_directory (appDir, error)) {
+	    dir = appDir;
+	}
+    }
+
+    return dir;
+}
+
+int receiveDescriptor (int connection) {
+    char byte = 0;
+    iovec data = { .iov_base = &byte, .iov_len = 1 };
+    union {
+	char buffer[CMSG_SPACE (sizeof (int))];
+	cmsghdr align;
+    } control {};
+    msghdr message = {};
+    message.msg_iov = &data;
+    message.msg_iovlen = 1;
+    message.msg_control = control.buffer;
+    message.msg_controllen = sizeof (control.buffer);
+
+    if (recvmsg (connection, &message, MSG_CMSG_CLOEXEC) != 1) {
+	return -1;
+    }
+
+    const cmsghdr* header = CMSG_FIRSTHDR (&message);
+
+    if (header == nullptr || header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS) {
+	return -1;
+    }
+
+    int fd = -1;
+    std::memcpy (&fd, CMSG_DATA (header), sizeof (int));
+    return fd;
+}
+} // namespace
+
+int GnomeShell::openWaylandSocket () {
+    const std::string path = socketDirectory () + "/lwe-gnome-" + std::to_string (getpid ()) + ".sock";
+    sockaddr_un address = {};
+    address.sun_family = AF_UNIX;
+
+    if (path.size () >= sizeof (address.sun_path)) {
+	this->m_reason = "the runtime folder's path is too long for a socket";
+	return -1;
+    }
+
+    std::strncpy (address.sun_path, path.c_str (), sizeof (address.sun_path) - 1);
+    unlink (path.c_str ());
+
+    const int listener = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    const mode_t mask = umask (0077);
+    const bool bound = listener >= 0 && bind (listener, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0
+	&& listen (listener, 1) == 0;
+    umask (mask);
+
+    if (!bound) {
+	this->m_reason = "cannot listen on " + path + ": " + std::strerror (errno);
+	if (listener >= 0) {
+	    close (listener);
+	}
+	return -1;
+    }
+
+    DBusMessage* request = dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "SpawnHelper");
+    const char* pathArg = path.c_str ();
+    dbus_message_append_args (request, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_INVALID);
+
+    std::string error;
+    DBusMessage* reply = call (this->m_connection, request, error);
+    int fd = -1;
+
+    if (reply == nullptr) {
+	this->m_reason = "the GNOME Shell extension could not start the helper: " + error;
+    } else {
+	dbus_message_unref (reply);
+	pollfd waiting = { .fd = listener, .events = POLLIN, .revents = 0 };
+
+	if (poll (&waiting, 1, CALL_TIMEOUT_MS * 3) == 1) {
+	    this->m_helperConnection = accept4 (listener, nullptr, nullptr, SOCK_CLOEXEC);
+	}
+
+	fd = this->m_helperConnection >= 0 ? receiveDescriptor (this->m_helperConnection) : -1;
+
+	if (fd < 0) {
+	    this->m_reason = "the helper never handed over the Wayland connection";
+	}
+    }
+
+    close (listener);
+    unlink (path.c_str ());
+    return fd;
+}
+
+GnomeShell::~GnomeShell () {
+    if (this->m_helperConnection >= 0) {
+	close (this->m_helperConnection);
+    }
+
+    if (this->m_connection != nullptr) {
+	dbus_connection_remove_filter (this->m_connection, &GnomeShell::filter, this);
+	dbus_connection_close (this->m_connection);
+	dbus_connection_unref (this->m_connection);
+    }
+}
+
+bool GnomeShell::connect () {
+    DBusError error;
+    dbus_error_init (&error);
+
+    // private, so we never eat messages meant for the shared connection
+    this->m_connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
+
+    if (dbus_error_is_set (&error)) {
+	this->m_reason = std::string ("no session bus: ") + error.message;
+	dbus_error_free (&error);
+	this->m_connection = nullptr;
+	return false;
+    }
+
+    dbus_connection_set_exit_on_disconnect (this->m_connection, false);
+
+    DBusMessage* message = dbus_message_new_method_call (
+	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
+    );
+    const char* name = BUS_NAME;
+    dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
+
+    std::string callError;
+    DBusMessage* reply = call (this->m_connection, message, callError);
+
+    if (reply == nullptr) {
+	this->m_reason = "the linux-wallpaperengine GNOME Shell extension is not running (" + callError + ")";
+	return false;
+    }
+
+    const char* owner = nullptr;
+    dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &owner, DBUS_TYPE_INVALID);
+    this->m_owner = owner != nullptr ? owner : "";
+    dbus_message_unref (reply);
+
+    // subscribe before querying so nothing is lost
+    const std::string signals = std::string ("type='signal',sender='") + BUS_NAME + "',interface='" + INTERFACE
+	+ "',path='" + OBJECT_PATH + "'";
+    const std::string ownerChanges
+	= std::string ("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='") + BUS_NAME + "'";
+
+    dbus_bus_add_match (this->m_connection, signals.c_str (), nullptr);
+    dbus_bus_add_match (this->m_connection, ownerChanges.c_str (), nullptr);
+    dbus_connection_add_filter (this->m_connection, &GnomeShell::filter, this, nullptr);
+
+    return true;
+}
+
+bool GnomeShell::queryState () {
+    const char* interface = INTERFACE;
+    std::string error;
+
+    for (const char* property : { "Version", "Supported", "NeedsHelper" }) {
+	DBusMessage* message
+	    = dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, "org.freedesktop.DBus.Properties", "Get");
+	dbus_message_append_args (
+	    message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID
+	);
+
+	DBusMessage* reply = call (this->m_connection, message, error);
+
+	if (reply == nullptr) {
+	    this->m_reason = "the GNOME Shell extension did not answer (" + error + ")";
+	    return false;
+	}
+
+	DBusMessageIter iter;
+	dbus_message_iter_init (reply, &iter);
+
+	if (std::strcmp (property, "Version") == 0) {
+	    dbus_uint32_t version = 0;
+
+	    if (!readVariant (&iter, DBUS_TYPE_UINT32, &version) || version != API_VERSION) {
+		this->m_reason = "the GNOME Shell extension speaks version " + std::to_string (version)
+		    + " of its interface, this engine needs " + std::to_string (API_VERSION)
+		    + " (update the extension, then log out and back in)";
+		dbus_message_unref (reply);
+		return false;
+	    }
+	} else if (std::strcmp (property, "Supported") == 0) {
+	    dbus_bool_t supported = false;
+
+	    if (!readVariant (&iter, DBUS_TYPE_BOOLEAN, &supported) || !supported) {
+		this->m_reason
+		    = "this GNOME Shell can't make desktop windows for the extension (it needs "
+		      "Meta.Window.set_type, GNOME 49 and later, or Meta.WaylandClient.make_desktop, 45 to 48)";
+		dbus_message_unref (reply);
+		return false;
+	    }
+	} else {
+	    dbus_bool_t needsHelper = false;
+
+	    readVariant (&iter, DBUS_TYPE_BOOLEAN, &needsHelper);
+	    this->m_needsHelper = needsHelper;
+	}
+
+	dbus_message_unref (reply);
+    }
+
+    DBusMessage* reply
+	= call (this->m_connection, dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "GetState"), error);
+
+    if (reply == nullptr) {
+	this->m_reason = "the GNOME Shell extension did not answer GetState (" + error + ")";
+	return false;
+    }
+
+    DBusMessageIter iter;
+    dbus_message_iter_init (reply, &iter);
+    auto pointer = readPointer (&iter);
+    dbus_message_iter_next (&iter);
+    auto windows = readWindows (&iter);
+    dbus_message_unref (reply);
+
+    if (!pointer.has_value () || !windows.has_value ()) {
+	this->m_reason = "the GNOME Shell extension sent a state this engine can't read";
+	return false;
+    }
+
+    this->m_pointer = std::move (*pointer);
+    this->m_windows = std::move (*windows);
+    return true;
+}
+
+void GnomeShell::dispatch () {
+    if (this->m_connection == nullptr) {
+	return;
+    }
+
+    // a read pulls in ~2KB at most
+    for (int reads = 0; reads < MAX_READS_PER_DISPATCH; reads++) {
+	if (!dbus_connection_read_write (this->m_connection, 0)) {
+	    sLog.error ("The session bus connection to the GNOME Shell extension dropped");
+	    this->m_vanished = true;
+	    return;
+	}
+
+	bool dispatched = false;
+
+	while (dbus_connection_get_dispatch_status (this->m_connection) == DBUS_DISPATCH_DATA_REMAINS) {
+	    dbus_connection_dispatch (this->m_connection);
+	    dispatched = true;
+	}
+
+	if (!dispatched) {
+	    break;
+	}
+    }
+}
+
+DBusHandlerResult GnomeShell::filter (DBusConnection*, DBusMessage* message, void* data) {
+    if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_SIGNAL) {
+	static_cast<GnomeShell*> (data)->handleSignal (message);
+    }
+
+    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+
+void GnomeShell::handleSignal (DBusMessage* message) {
+    if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged")) {
+	const char* name = nullptr;
+	const char* oldOwner = nullptr;
+	const char* newOwner = nullptr;
+
+	if (dbus_message_get_args (
+		message, nullptr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &oldOwner, DBUS_TYPE_STRING, &newOwner,
+		DBUS_TYPE_INVALID
+	    )
+	    && std::strcmp (name, BUS_NAME) == 0 && newOwner[0] == '\0' && this->m_available) {
+	    sLog.error ("The linux-wallpaperengine GNOME Shell extension went away");
+	    this->m_vanished = true;
+	    this->m_pointer.clear ();
+	    this->m_windows.clear ();
+	    this->m_desktopLeftDown = false;
+	}
+
+	return;
+    }
+
+    // only the owner we checked counts
+    if (const char* sender = dbus_message_get_sender (message); sender == nullptr || this->m_owner != sender) {
+	return;
+    }
+
+    DBusMessageIter iter;
+
+    if (!dbus_message_iter_init (message, &iter)) {
+	return;
+    }
+
+    if (dbus_message_is_signal (message, INTERFACE, "PointerMoved")) {
+	if (auto pointer = readPointer (&iter); pointer.has_value ()) {
+	    this->m_pointer = std::move (*pointer);
+	}
+    } else if (dbus_message_is_signal (message, INTERFACE, "DesktopButton")) {
+	if (dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_BOOLEAN) {
+	    dbus_bool_t pressed = false;
+	    dbus_message_iter_get_basic (&iter, &pressed);
+	    this->m_desktopLeftDown = pressed;
+	}
+    } else if (dbus_message_is_signal (message, INTERFACE, "WindowsChanged")) {
+	if (auto windows = readWindows (&iter); windows.has_value ()) {
+	    this->m_windows = std::move (*windows);
+	}
+    }
+}

+ 79 - 0
src/WallpaperEngine/Desktop/GnomeShell.h

@@ -0,0 +1,79 @@
+#pragma once
+
+#include <dbus/dbus.h>
+#include <glm/vec2.hpp>
+#include <string>
+#include <vector>
+
+#include "WindowState.h"
+
+namespace WallpaperEngine::Desktop {
+/** XDG_CURRENT_DESKTOP lists GNOME */
+bool isGnomeSession ();
+
+/**
+ * Client of our GNOME Shell extension: it makes our toplevels desktop windows and reports the pointer and window
+ * states Mutter hides from Wayland clients. Read only from the render thread via dispatch ().
+ */
+class GnomeShell {
+public:
+    static constexpr const char* BUS_NAME = "org.linuxwallpaperengine.Shell";
+    static constexpr const char* OBJECT_PATH = "/org/linuxwallpaperengine/Shell";
+    static constexpr const char* INTERFACE = "org.linuxwallpaperengine.Shell";
+    /** followed by the output name */
+    static constexpr const char* TITLE_PREFIX = "linux-wallpaperengine wallpaper ";
+    static constexpr const char* APP_ID = "linux-wallpaperengine";
+    static constexpr uint32_t API_VERSION = 1;
+
+    using Window = WindowState;
+
+    struct Pointer {
+	std::string output;
+	/** fraction of the window, from its top left */
+	glm::dvec2 position;
+    };
+
+    GnomeShell ();
+    ~GnomeShell ();
+
+    GnomeShell (const GnomeShell&) = delete;
+    GnomeShell& operator= (const GnomeShell&) = delete;
+
+    [[nodiscard]] bool isAvailable () const { return this->m_available; }
+    [[nodiscard]] const std::string& reason () const { return this->m_reason; }
+    /** disabled or Shell restarted */
+    [[nodiscard]] bool vanished () const { return this->m_vanished; }
+    /** GNOME 45-48: needs a Shell-spawned connection, see openWaylandSocket */
+    [[nodiscard]] bool needsHelper () const { return this->m_needsHelper; }
+    /**
+     * The extension spawns the helper via Meta.WaylandClient, returns the connection it hands over or -1. The
+     * helper lives as long as this object, Mutter drops the client when it exits.
+     */
+    [[nodiscard]] int openWaylandSocket ();
+
+    /** non-blocking */
+    void dispatch ();
+
+    [[nodiscard]] const std::vector<Pointer>& pointer () const { return this->m_pointer; }
+    [[nodiscard]] const std::vector<Window>& windows () const { return this->m_windows; }
+    /** left button held on another desktop window (icons) */
+    [[nodiscard]] bool desktopLeftDown () const { return this->m_desktopLeftDown; }
+
+private:
+    bool connect ();
+    bool queryState ();
+    static DBusHandlerResult filter (DBusConnection* connection, DBusMessage* message, void* data);
+    void handleSignal (DBusMessage* message);
+
+    DBusConnection* m_connection = nullptr;
+    std::string m_owner;
+    std::string m_reason;
+    bool m_available = false;
+    bool m_vanished = false;
+    bool m_needsHelper = false;
+    bool m_desktopLeftDown = false;
+    int m_helperConnection = -1;
+    std::vector<Pointer> m_pointer;
+    std::vector<Window> m_windows;
+};
+} // namespace WallpaperEngine::Desktop

+ 122 - 0
src/WallpaperEngine/Desktop/KWinScript.cpp

@@ -0,0 +1,122 @@
+#include "KWinScript.h"
+
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <unistd.h>
+
+using namespace WallpaperEngine::Desktop;
+
+namespace {
+constexpr int CALL_TIMEOUT_MS = 2000;
+
+std::string scriptDirectory () {
+    const char* runtimeDir = std::getenv ("XDG_RUNTIME_DIR");
+
+    if (runtimeDir == nullptr) {
+	return {};
+    }
+
+    std::string dir = runtimeDir;
+
+    // Flatpak shares only the app's runtime folder; FLATPAK_ID alone can be inherited
+    if (const char* flatpakId = std::getenv ("FLATPAK_ID");
+	flatpakId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
+	const std::string appDir = dir + "/app/" + flatpakId;
+	std::error_code error;
+
+	if (std::filesystem::is_directory (appDir, error)) {
+	    dir = appDir;
+	}
+    }
+
+    return dir;
+}
+
+DBusMessage* callKWin (DBusConnection* connection, DBusMessage* call, const char* what) {
+    DBusError error;
+    dbus_error_init (&error);
+    DBusMessage* reply = dbus_connection_send_with_reply_and_block (connection, call, CALL_TIMEOUT_MS, &error);
+    dbus_message_unref (call);
+
+    if (dbus_error_is_set (&error)) {
+	sLog.error ("KWin script: ", what, ": ", error.message);
+	dbus_error_free (&error);
+	return nullptr;
+    }
+
+    return reply;
+}
+} // namespace
+
+KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, const std::string& source) :
+    m_connection (connection), m_pluginName (std::move (pluginName)) {
+    const std::string dir = scriptDirectory ();
+
+    if (dir.empty ()) {
+	sLog.error ("KWin script ", this->m_pluginName, ": XDG_RUNTIME_DIR is not set");
+	return;
+    }
+
+    this->m_path = dir + "/" + this->m_pluginName + ".js";
+    std::ofstream out (this->m_path, std::ios::trunc);
+
+    if (!out.is_open ()) {
+	sLog.error ("KWin script: could not write ", this->m_path);
+	this->m_path.clear ();
+	return;
+    }
+
+    out << source;
+    out.close ();
+
+    DBusMessage* load
+	= dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "loadScript");
+    const char* pathArg = this->m_path.c_str ();
+    const char* nameArg = this->m_pluginName.c_str ();
+    dbus_message_append_args (load, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
+
+    DBusMessage* reply = callKWin (this->m_connection, load, "loadScript");
+    dbus_int32_t scriptId = -1;
+
+    if (reply != nullptr) {
+	dbus_message_get_args (reply, nullptr, DBUS_TYPE_INT32, &scriptId, DBUS_TYPE_INVALID);
+	dbus_message_unref (reply);
+    }
+
+    if (scriptId < 0) {
+	sLog.error ("KWin refused to load the script ", this->m_pluginName);
+	std::remove (this->m_path.c_str ());
+	this->m_path.clear ();
+	return;
+    }
+
+    const std::string object = "/Scripting/Script" + std::to_string (scriptId);
+    DBusMessage* run = dbus_message_new_method_call ("org.kde.KWin", object.c_str (), "org.kde.kwin.Script", "run");
+
+    if (DBusMessage* runReply = callKWin (this->m_connection, run, "run"); runReply != nullptr) {
+	dbus_message_unref (runReply);
+    }
+
+    this->m_loaded = true;
+}
+
+KWinScript::~KWinScript () {
+    if (this->m_loaded && this->m_connection != nullptr) {
+	DBusMessage* unload
+	    = dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "unloadScript");
+	const char* nameArg = this->m_pluginName.c_str ();
+	dbus_message_append_args (unload, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
+
+	if (DBusMessage* reply = callKWin (this->m_connection, unload, "unloadScript"); reply != nullptr) {
+	    dbus_message_unref (reply);
+	}
+    }
+
+    if (!this->m_path.empty ()) {
+	std::remove (this->m_path.c_str ());
+    }
+}

+ 24 - 0
src/WallpaperEngine/Desktop/KWinScript.h

@@ -0,0 +1,24 @@
+#pragma once
+
+#include <dbus/dbus.h>
+#include <string>
+
+namespace WallpaperEngine::Desktop {
+/** A KWin script loaded over D-Bus for the lifetime of this object */
+class KWinScript {
+public:
+    KWinScript (DBusConnection* connection, std::string pluginName, const std::string& source);
+    ~KWinScript ();
+
+    KWinScript (const KWinScript&) = delete;
+    KWinScript& operator= (const KWinScript&) = delete;
+
+    [[nodiscard]] bool isLoaded () const { return this->m_loaded; }
+
+private:
+    DBusConnection* m_connection;
+    std::string m_pluginName;
+    std::string m_path;
+    bool m_loaded = false;
+};
+} // namespace WallpaperEngine::Desktop

+ 44 - 0
src/WallpaperEngine/Desktop/WindowState.cpp

@@ -0,0 +1,44 @@
+#include "WindowState.h"
+
+#include "WallpaperEngine/Application/ApplicationContext.h"
+
+#include <algorithm>
+#include <cctype>
+
+using namespace WallpaperEngine::Desktop;
+
+namespace {
+bool containsIgnoringCase (const std::string& haystack, const std::string& needle) {
+    return std::ranges::search (
+	       haystack, needle, [] (unsigned char a, unsigned char b) { return std::tolower (a) == std::tolower (b); }
+	   ).begin ()
+	!= haystack.end ();
+}
+} // namespace
+
+bool WallpaperEngine::Desktop::pausesAnyOf (
+    const std::vector<WindowState>& windows, const std::vector<std::string>& outputs,
+    const Application::ApplicationContext& context
+) {
+    const auto& settings = context.settings.render;
+    const uint32_t pausing = (settings.pauseOnFullscreen ? WindowState::Maximized | WindowState::Fullscreen : 0)
+	| (settings.pauseOnFocus ? WindowState::Focused : 0);
+
+    return std::ranges::any_of (windows, [&] (const WindowState& window) {
+	if ((window.flags & pausing) == 0) {
+	    return false;
+	}
+
+	if (settings.pauseOnFullscreenOnlyWhenActive && (window.flags & WindowState::Focused) == 0) {
+	    return false;
+	}
+
+	if (std::ranges::any_of (settings.fullscreenPauseIgnoreAppIds, [&window] (const std::string& ignore) {
+		return !ignore.empty () && containsIgnoringCase (window.appId, ignore);
+	    })) {
+	    return false;
+	}
+
+	return std::ranges::find (outputs, window.output) != outputs.end ();
+    });
+}

+ 32 - 0
src/WallpaperEngine/Desktop/WindowState.h

@@ -0,0 +1,32 @@
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Application {
+class ApplicationContext;
+}
+
+namespace WallpaperEngine::Desktop {
+/** A window reported by the GNOME extension or KWin script, filtered by WE 2.8's rules (sub_14003D050) */
+struct WindowState {
+    enum Flags : uint32_t {
+	Focused = 1,
+	Maximized = 2,
+	/** focused, covers its monitor, not maximized */
+	Fullscreen = 4,
+    };
+
+    std::string appId;
+    /** wl_output name */
+    std::string output;
+    uint32_t flags = 0;
+};
+
+/** WE's per monitor pause: true when a pausing window is on one of outputs */
+bool pausesAnyOf (
+    const std::vector<WindowState>& windows, const std::vector<std::string>& outputs,
+    const Application::ApplicationContext& context
+);
+} // namespace WallpaperEngine::Desktop

+ 7 - 112
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -4,8 +4,6 @@
 
 #include <cstdio>
 #include <cstring>
-#include <filesystem>
-#include <fstream>
 #include <sstream>
 #include <unistd.h>
 
@@ -93,12 +91,6 @@ void KDECursorInput::stopDBus () {
 }
 
 bool KDECursorInput::loadKWinScript () {
-    const char* runtimeDir = std::getenv ("XDG_RUNTIME_DIR");
-    if (runtimeDir == nullptr) {
-	sLog.error ("KDE cursor input: XDG_RUNTIME_DIR is not set");
-	return false;
-    }
-
     const std::string serviceName = std::string (kServiceName) + "_" + std::to_string (getpid ());
 
     std::ostringstream script;
@@ -110,111 +102,14 @@ bool KDECursorInput::loadKWinScript () {
 	   << "workspace.cursorPosChanged.connect(lweReportCursorPos);\n"
 	   << "lweReportCursorPos();\n";
 
-    // inside a Flatpak only the app's own runtime folder is shared with the host, FLATPAK_ID alone can be inherited
-    std::string scriptDir = runtimeDir;
-    if (const char* flatpakId = std::getenv ("FLATPAK_ID");
-	flatpakId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
-	const std::string appDir = scriptDir + "/app/" + flatpakId;
-	std::error_code error;
-
-	if (std::filesystem::is_directory (appDir, error)) {
-	    scriptDir = appDir;
-	}
-    }
-
-    m_scriptPath = scriptDir + "/linux-wallpaperengine-cursor-" + std::to_string (getpid ()) + ".js";
-
-    std::ofstream out (m_scriptPath, std::ios::trunc);
-    if (!out.is_open ()) {
-	sLog.error ("KDE cursor input: could not write KWin script to ", m_scriptPath);
-	return false;
-    }
-    out << script.str ();
-    out.close ();
-
-    m_pluginName = "lwe-cursor-input-" + std::to_string (getpid ());
+    this->m_script = std::make_unique<WallpaperEngine::Desktop::KWinScript> (
+	m_connection, "lwe-cursor-input-" + std::to_string (getpid ()), script.str ()
+    );
 
-    DBusMessage* loadCall
-	= dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "loadScript");
-    if (loadCall == nullptr) {
-	return false;
-    }
-
-    const char* pathArg = m_scriptPath.c_str ();
-    const char* nameArg = m_pluginName.c_str ();
-    dbus_message_append_args (loadCall, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
-
-    DBusError error;
-    dbus_error_init (&error);
-    DBusMessage* reply = dbus_connection_send_with_reply_and_block (m_connection, loadCall, 2000, &error);
-    dbus_message_unref (loadCall);
-
-    if (dbus_error_is_set (&error)) {
-	sLog.error ("KDE cursor input: failed to load KWin script: ", error.message);
-	dbus_error_free (&error);
-	std::remove (m_scriptPath.c_str ());
-	return false;
-    }
-
-    dbus_int32_t scriptId = -1;
-    if (reply != nullptr) {
-	dbus_message_get_args (reply, nullptr, DBUS_TYPE_INT32, &scriptId, DBUS_TYPE_INVALID);
-	dbus_message_unref (reply);
-    }
-
-    if (scriptId < 0) {
-	sLog.error ("KDE cursor input: KWin refused to load the cursor tracking script");
-	std::remove (m_scriptPath.c_str ());
-	return false;
-    }
-
-    const std::string scriptObjectPath = "/Scripting/Script" + std::to_string (scriptId);
-    DBusMessage* runCall
-	= dbus_message_new_method_call ("org.kde.KWin", scriptObjectPath.c_str (), "org.kde.kwin.Script", "run");
-    if (runCall != nullptr) {
-	dbus_error_init (&error);
-	DBusMessage* runReply = dbus_connection_send_with_reply_and_block (m_connection, runCall, 2000, &error);
-	dbus_message_unref (runCall);
-	if (runReply != nullptr) {
-	    dbus_message_unref (runReply);
-	}
-	if (dbus_error_is_set (&error)) {
-	    sLog.error ("KDE cursor input: failed to start the cursor tracking script: ", error.message);
-	    dbus_error_free (&error);
-	}
-    }
-
-    m_scriptLoaded = true;
-    return true;
+    return this->m_script->isLoaded ();
 }
 
-void KDECursorInput::unloadKWinScript () {
-    if (m_scriptLoaded && m_connection != nullptr) {
-	DBusMessage* unloadCall
-	    = dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "unloadScript");
-	if (unloadCall != nullptr) {
-	    const char* nameArg = m_pluginName.c_str ();
-	    dbus_message_append_args (unloadCall, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
-
-	    DBusError error;
-	    dbus_error_init (&error);
-	    DBusMessage* reply = dbus_connection_send_with_reply_and_block (m_connection, unloadCall, 2000, &error);
-	    dbus_message_unref (unloadCall);
-	    if (reply != nullptr) {
-		dbus_message_unref (reply);
-	    }
-	    if (dbus_error_is_set (&error)) {
-		dbus_error_free (&error);
-	    }
-	}
-    }
-
-    if (!m_scriptPath.empty ()) {
-	std::remove (m_scriptPath.c_str ());
-    }
-
-    m_scriptLoaded = false;
-}
+void KDECursorInput::unloadKWinScript () { this->m_script.reset (); }
 
 DBusHandlerResult KDECursorInput::handleMessage (DBusConnection* connection, DBusMessage* message, void* userData) {
     const auto input = static_cast<KDECursorInput*> (userData);
@@ -281,7 +176,7 @@ std::optional<glm::dvec2> KDECursorInput::position () {
 
 	if (!connected) {
 	    sLog.error ("KDE cursor input: DBus connection dropped unexpectedly");
-	    m_scriptLoaded = false;
+	    m_script.reset ();
 	    dbus_connection_unregister_object_path (m_connection, kObjectPath);
 	    dbus_connection_unref (m_connection);
 	    m_connection = nullptr;
@@ -291,6 +186,6 @@ std::optional<glm::dvec2> KDECursorInput::position () {
     return m_pos;
 }
 
-bool KDECursorInput::isInitialized () const { return m_connection != nullptr && m_scriptLoaded; }
+bool KDECursorInput::isInitialized () const { return m_connection != nullptr && m_script && m_script->isLoaded (); }
 
 } // namespace WallpaperEngine::Input::Drivers

+ 4 - 3
src/WallpaperEngine/Input/Drivers/KDECursorInput.h

@@ -5,9 +5,12 @@
 
 #include <dbus/dbus.h>
 #include <glm/vec2.hpp>
+#include <memory>
 #include <optional>
 #include <string>
 
+#include "WallpaperEngine/Desktop/KWinScript.h"
+
 namespace WallpaperEngine::Input::Drivers {
 
 // Background layer-shell surfaces never receive real pointer motion events, and there's no
@@ -41,9 +44,7 @@ private:
     DBusConnection* m_connection = nullptr;
     std::optional<glm::dvec2> m_pos;
 
-    std::string m_scriptPath;
-    std::string m_pluginName;
-    bool m_scriptLoaded = false;
+    std::unique_ptr<WallpaperEngine::Desktop::KWinScript> m_script;
 
     static constexpr const char* kServiceName = "org.linuxwallpaperengine.CursorInput";
     static constexpr const char* kObjectPath = "/org/linuxwallpaperengine/CursorInput";

+ 40 - 22
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -46,22 +46,24 @@ void WaylandMouseInput::pollForwardedInput () {
 
 void WaylandMouseInput::update () {
     if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
-	this->m_pos = { 0, 0 };
+	this->m_globalCursor.reset ();
 	this->m_forwardedLeftDown = false;
 	return;
     }
 
     this->pollForwardedInput ();
 
-    if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) {
-	this->m_pos = m_waylandDriver.viewportInFocus->mousePos;
+    // GNOME Shell signals arrive with the Wayland events
+    if (this->m_waylandDriver.getGnomeShell () != nullptr) {
 	return;
     }
 
 #ifdef ENABLE_KDE_FEATURES
-    if (const auto kdeCursor = this->m_kdeCursor ? this->m_kdeCursor->position () : std::nullopt;
-	kdeCursor.has_value () && this->matchViewport (*kdeCursor)) {
-	return;
+    if (this->m_kdeCursor) {
+	if (const auto kdeCursor = this->m_kdeCursor->position (); kdeCursor.has_value ()) {
+	    this->m_globalCursor = kdeCursor;
+	    return;
+	}
     }
 #endif /* ENABLE_KDE_FEATURES */
 
@@ -77,12 +79,14 @@ void WaylandMouseInput::update () {
 	globalCursor = this->queryX11CursorPosition ();
     }
 #endif /* ENABLE_X11 */
-    if (!globalCursor.has_value () || !this->matchViewport (*globalCursor)) {
-	this->m_pos = { 0, 0 };
-    }
+    this->m_globalCursor = globalCursor;
 }
 
 bool WaylandMouseInput::hasGlobalCursor () const {
+    if (this->m_waylandDriver.getGnomeShell () != nullptr) {
+	return true;
+    }
+
 #ifdef ENABLE_KDE_FEATURES
     if (this->m_kdeCursor && this->m_kdeCursor->isInitialized ()) {
 	return true;
@@ -92,23 +96,31 @@ bool WaylandMouseInput::hasGlobalCursor () const {
     return std::getenv ("HYPRLAND_INSTANCE_SIGNATURE") != nullptr;
 }
 
-bool WaylandMouseInput::matchViewport (const glm::dvec2& globalCursor) {
-    for (const auto* viewport : this->m_waylandDriver.m_screens) {
-	if (!viewport || viewport->size.x <= 0 || viewport->size.y <= 0) {
-	    continue;
-	}
+glm::dvec2
+WaylandMouseInput::positionOn (const WallpaperEngine::Render::Drivers::Output::WaylandOutputViewport& viewport) const {
+    const double scale = viewport.scale;
 
-	const double localX = globalCursor.x - viewport->position.x;
-	const double localY = globalCursor.y - viewport->position.y;
-	if (localX < 0.0 || localY < 0.0 || localX > viewport->size.x || localY > viewport->size.y) {
-	    continue;
+    // WE maps GetCursorPos to each wallpaper window's client coords (sub_140110630), even off that output
+    if (const auto* gnomeShell = this->m_waylandDriver.getGnomeShell ()) {
+	for (const auto& [output, fraction] : gnomeShell->pointer ()) {
+	    if (output == viewport.name) {
+		return { fraction.x * viewport.size.x * scale, (1.0 - fraction.y) * viewport.size.y * scale };
+	    }
 	}
 
-	this->m_pos = { localX * viewport->scale, (viewport->size.y - localY) * viewport->scale };
-	return true;
+	return { 0, 0 };
+    }
+
+    if (this->m_waylandDriver.viewportInFocus == &viewport) {
+	return viewport.mousePos;
+    }
+
+    if (this->m_globalCursor.has_value ()) {
+	const glm::dvec2 local = *this->m_globalCursor - glm::dvec2 (viewport.globalPosition);
+	return { local.x * scale, (viewport.size.y - local.y) * scale };
     }
 
-    return false;
+    return viewport.mousePos;
 }
 
 glm::dvec2 WaylandMouseInput::position () const {
@@ -116,7 +128,8 @@ glm::dvec2 WaylandMouseInput::position () const {
 	return { 0, 0 };
     }
 
-    return this->m_pos;
+    const auto* viewport = this->getActiveOutputViewport ();
+    return viewport != nullptr ? this->positionOn (*viewport) : glm::dvec2 { 0, 0 };
 }
 
 WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
@@ -124,6 +137,11 @@ WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
 	return MouseClickStatus::Clicked;
     }
 
+    // WE counts a press on the desktop icons' window as a desktop press
+    if (const auto* gnomeShell = this->m_waylandDriver.getGnomeShell (); gnomeShell && gnomeShell->desktopLeftDown ()) {
+	return MouseClickStatus::Clicked;
+    }
+
     const auto* viewport = this->getActiveOutputViewport ();
     if (viewport) {
 	return viewport->leftClick;

+ 5 - 3
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h

@@ -30,7 +30,7 @@ public:
     [[nodiscard]] glm::dvec2 position () const override;
     [[nodiscard]] MouseClickStatus leftClick () const override;
     [[nodiscard]] MouseClickStatus rightClick () const override;
-    /** KWin's cursor script runs or Hyprland answers cursor queries */
+    /** KWin script, Hyprland or the GNOME Shell extension provide it */
     [[nodiscard]] bool hasGlobalCursor () const;
 
 private:
@@ -41,12 +41,14 @@ private:
     // over an XWayland-backed window, but that's still better than nothing on compositors with no IPC
     [[nodiscard]] std::optional<glm::dvec2> queryX11CursorPosition () const;
 #endif /* ENABLE_X11 */
-    bool matchViewport (const glm::dvec2& globalCursor);
+    /** the pointer in that output's buffer pixels, y up */
+    [[nodiscard]] glm::dvec2 positionOn (const Render::Drivers::Output::WaylandOutputViewport& viewport) const;
     void pollForwardedInput ();
 
     const WallpaperEngine::Render::Drivers::WaylandOpenGLDriver& m_waylandDriver;
 
-    glm::dvec2 m_pos = {};
+    /** logical global position */
+    std::optional<glm::dvec2> m_globalCursor;
     std::chrono::steady_clock::time_point m_lastGlobalCursorQuery = {};
     std::chrono::steady_clock::time_point m_lastForwardedPoll = {};
     bool m_forwardedLeftDown = false;

+ 24 - 0
src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp

@@ -0,0 +1,24 @@
+#include "GnomeFullScreenDetector.h"
+
+#include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
+
+using namespace WallpaperEngine::Render::Drivers::Detectors;
+
+GnomeFullScreenDetector::GnomeFullScreenDetector (
+    Application::ApplicationContext& appContext, WaylandOpenGLDriver& driver
+) : FullScreenDetector (appContext), m_driver (driver) { }
+
+bool GnomeFullScreenDetector::anythingFullscreen () const {
+    auto* gnomeShell = this->m_driver.getGnomeShell ();
+
+    if (gnomeShell == nullptr) {
+	return false;
+    }
+
+    // while paused the driver doesn't dispatch
+    gnomeShell->dispatch ();
+
+    return Desktop::pausesAnyOf (
+	gnomeShell->windows (), this->m_driver.drawnOutputs (), this->getApplicationContext ()
+    );
+}

+ 24 - 0
src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.h

@@ -0,0 +1,24 @@
+#pragma once
+
+#ifdef ENABLE_WAYLAND
+
+#include "FullScreenDetector.h"
+
+namespace WallpaperEngine::Render::Drivers {
+class WaylandOpenGLDriver;
+}
+
+namespace WallpaperEngine::Render::Drivers::Detectors {
+/** GNOME Wayland: window states come from the Shell extension, paused per monitor like WE */
+class GnomeFullScreenDetector final : public FullScreenDetector {
+public:
+    GnomeFullScreenDetector (Application::ApplicationContext& appContext, WaylandOpenGLDriver& driver);
+
+    [[nodiscard]] bool anythingFullscreen () const override;
+
+private:
+    WaylandOpenGLDriver& m_driver;
+};
+} // namespace WallpaperEngine::Render::Drivers::Detectors
+
+#endif /* ENABLE_WAYLAND */

+ 163 - 152
src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp

@@ -1,229 +1,240 @@
 #include "KDEWaylandFullScreenDetector.h"
 
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 
-#include <algorithm>
-#include <cctype>
-#include <cstring>
-#include <string>
+#include <nlohmann/json.hpp>
+#include <unistd.h>
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
 
-KDEWaylandFullScreenDetector::KDEWaylandFullScreenDetector (Application::ApplicationContext& appContext) :
-    FullScreenDetector (appContext) {
+KDEWaylandFullScreenDetector::KDEWaylandFullScreenDetector (
+    Application::ApplicationContext& appContext, WaylandOpenGLDriver& driver
+) : FullScreenDetector (appContext), m_driver (driver) {
     if (!initializeDBus ()) {
-	sLog.out (
-	    "KDE Wayland maximize detector could not initialize DBus. Falling back to the Wayland fullscreen detector"
-	);
+	sLog.out ("KDE window detection could not set up its D-Bus service, falling back to the Wayland detector");
+	return;
+    }
+
+    this->m_script = std::make_unique<Desktop::KWinScript> (
+	this->m_connection, "lwe-window-states-" + std::to_string (getpid ()), this->scriptSource ()
+    );
+
+    if (!this->m_script->isLoaded ()) {
+	sLog.out ("KDE window detection could not load its KWin script, falling back to the Wayland detector");
+	this->m_script.reset ();
     }
 }
 
-KDEWaylandFullScreenDetector::~KDEWaylandFullScreenDetector () { stopDBus (); }
+KDEWaylandFullScreenDetector::~KDEWaylandFullScreenDetector () {
+    this->m_script.reset ();
+
+    if (this->m_connection != nullptr) {
+	dbus_connection_unregister_object_path (this->m_connection, kObjectPath);
+	dbus_connection_close (this->m_connection);
+	dbus_connection_unref (this->m_connection);
+    }
+}
 
 bool KDEWaylandFullScreenDetector::initializeDBus () {
     DBusError error;
     dbus_error_init (&error);
 
-    m_connection = dbus_bus_get (DBUS_BUS_SESSION, &error);
+    // private: we_manager runs one engine per screen, each with its own service
+    this->m_connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
+
     if (dbus_error_is_set (&error)) {
-	sLog.error ("Failed to connect to the session DBus: ", error.message);
+	sLog.error ("Failed to connect to the session D-Bus: ", error.message);
 	dbus_error_free (&error);
+	this->m_connection = nullptr;
 	return false;
     }
 
-    if (m_connection == nullptr) {
-	sLog.error ("Failed to connect to the session DBus: unknown error");
-	return false;
-    }
-
-    dbus_connection_set_exit_on_disconnect (m_connection, false);
+    dbus_connection_set_exit_on_disconnect (this->m_connection, false);
+    this->m_serviceName = std::string (kServiceName) + "_" + std::to_string (getpid ());
 
     dbus_error_init (&error);
-    const auto requestResult = dbus_bus_request_name (m_connection, kServiceName, DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+    const int requested
+	= dbus_bus_request_name (this->m_connection, this->m_serviceName.c_str (), DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
 
-    if (dbus_error_is_set (&error)) {
-	sLog.error ("Failed to request DBus service ", kServiceName, ": ", error.message);
+    if (dbus_error_is_set (&error) || requested != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
+	sLog.error (
+	    "Could not own the D-Bus name ", this->m_serviceName, dbus_error_is_set (&error) ? ": " : "",
+	    dbus_error_is_set (&error) ? error.message : ""
+	);
 	dbus_error_free (&error);
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
+	dbus_connection_close (this->m_connection);
+	dbus_connection_unref (this->m_connection);
+	this->m_connection = nullptr;
 	return false;
     }
 
-    if (requestResult != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
-	&& requestResult != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) {
-	sLog.error ("DBus service ", kServiceName, " is already owned by another process");
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
-	return false;
-    }
-
-    static constexpr DBusObjectPathVTable objectVTable = {
+    static constexpr DBusObjectPathVTable vtable = {
 	.unregister_function = nullptr,
 	.message_function = &KDEWaylandFullScreenDetector::handleMessage,
     };
 
-    if (!dbus_connection_register_object_path (m_connection, kObjectPath, &objectVTable, this)) {
-	sLog.error ("Failed to register DBus object path for KDE Wayland maximize detector");
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
-	return false;
-    }
+    return dbus_connection_register_object_path (this->m_connection, kObjectPath, &vtable, this);
+}
 
-    return true;
+// WE 2.8 rules (sub_14003D050 / sub_14003BBA0), same as the GNOME extension: visible, unminimized windows on the
+// current desktop; maximized marks its output, the active root window marks focused, and fullscreen if not
+// maximized and at least the output's size
+std::string KDEWaylandFullScreenDetector::scriptSource () const {
+    const std::string service = this->m_serviceName;
+
+    return "const service = '" + service + "';\n" + "const objectPath = '" + kObjectPath + "';\n" + "const method = '"
+	+ kMethodName + "';\n" + "const enginePid = " + std::to_string (getpid ()) + ";\n" + R"(
+const MAXIMIZE_FULL = 3;
+let last = '';
+
+function rootOf(window) {
+    while (window && window.transient && window.transientFor)
+        window = window.transientFor;
+    return window;
+}
+
+function counts(window) {
+    if (!window || window.deleted || !window.managed || window.minimized || window.pid === enginePid)
+        return false;
+    if (window.specialWindow || window.popupWindow || window.desktopWindow || window.dock)
+        return false;
+    if (!window.normalWindow && !window.dialog)
+        return false;
+    return window.onAllDesktops || window.desktops.indexOf(workspace.currentDesktop) >= 0;
 }
 
-void KDEWaylandFullScreenDetector::stopDBus () {
-    if (m_connection != nullptr) {
-	dbus_connection_unregister_object_path (m_connection, kObjectPath);
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
+function report() {
+    const focus = rootOf(workspace.activeWindow);
+    const windows = [];
+
+    for (const window of workspace.windowList()) {
+        if (!counts(window))
+            continue;
+
+        const maximized = window.maximizeMode === MAXIMIZE_FULL;
+        let flags = maximized ? 2 : 0;
+
+        if (window === focus) {
+            flags |= 1;
+            const area = window.output ? window.output.geometry : null;
+            const frame = window.frameGeometry;
+            if (!maximized && (window.fullScreen || (area && frame.width >= area.width && frame.height >= area.height)))
+                flags |= 4;
+        }
+
+        if (flags !== 0)
+            windows.push([window.desktopFileName || window.resourceClass || '', window.output ? window.output.name : '', flags]);
     }
+
+    const json = JSON.stringify(windows);
+    if (json === last)
+        return;
+    last = json;
+    callDBus(service, objectPath, service, method, json);
+}
+
+function watch(window) {
+    window.fullScreenChanged.connect(report);
+    window.maximizedChanged.connect(report);
+    window.minimizedChanged.connect(report);
+    window.outputChanged.connect(report);
+    window.frameGeometryChanged.connect(report);
+    window.desktopsChanged.connect(report);
+}
+
+workspace.windowList().forEach(watch);
+workspace.windowAdded.connect(window => {
+    watch(window);
+    report();
+});
+workspace.windowRemoved.connect(report);
+workspace.windowActivated.connect(report);
+workspace.currentDesktopChanged.connect(report);
+report();
+)";
 }
 
 DBusHandlerResult
 KDEWaylandFullScreenDetector::handleMessage (DBusConnection* connection, DBusMessage* message, void* userData) {
-    const auto detector = static_cast<KDEWaylandFullScreenDetector*> (userData);
-    return detector->handleMessage (message);
+    return static_cast<KDEWaylandFullScreenDetector*> (userData)->handleMessage (message);
 }
 
 DBusHandlerResult KDEWaylandFullScreenDetector::handleMessage (DBusMessage* message) {
-    if (message == nullptr) {
+    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL
+	|| !dbus_message_has_member (message, kMethodName)) {
 	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
     }
 
-    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL) {
-	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-    }
+    const char* json = nullptr;
 
-    if (const auto* currentInterface = dbus_message_get_interface (message);
-	currentInterface == nullptr || std::strcmp (currentInterface, kServiceName) != 0) {
-	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+    if (dbus_message_get_args (message, nullptr, DBUS_TYPE_STRING, &json, DBUS_TYPE_INVALID)) {
+	this->applyWindows (json);
     }
 
-    return handleMethodCall (message) ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-bool KDEWaylandFullScreenDetector::handleMethodCall (DBusMessage* message) {
-    const auto* member = dbus_message_get_member (message);
-    if (member == nullptr) {
-	return false;
+    // callDBus doesn't wait, this only silences the missing-reply log
+    if (DBusMessage* reply = dbus_message_new_method_return (message); reply != nullptr) {
+	dbus_connection_send (this->m_connection, reply, nullptr);
+	dbus_message_unref (reply);
     }
 
-    if (std::strcmp (member, kMethodName) != 0) {
-	return false;
-    }
+    return DBUS_HANDLER_RESULT_HANDLED;
+}
 
-    DBusError error;
-    dbus_error_init (&error);
+bool KDEWaylandFullScreenDetector::applyWindows (const std::string& json) {
+    const auto parsed = nlohmann::json::parse (json, nullptr, false);
 
-    const char* windowKey = nullptr;
-    const char* windowName = nullptr;
-    const char* appId = nullptr;
-    dbus_int32_t pid = 0;
-    dbus_bool_t horizontal = false;
-    dbus_bool_t vertical = false;
-    dbus_bool_t fully = false;
-
-    if (!dbus_message_get_args (
-	    message, &error, DBUS_TYPE_STRING, &windowKey, DBUS_TYPE_STRING, &windowName, DBUS_TYPE_INT32, &pid,
-	    DBUS_TYPE_STRING, &appId, DBUS_TYPE_BOOLEAN, &horizontal, DBUS_TYPE_BOOLEAN, &vertical, DBUS_TYPE_BOOLEAN,
-	    &fully, DBUS_TYPE_INVALID
-	)) {
-	sLog.error ("Invalid KDE Wayland maximize DBus call: ", error.message);
-	dbus_error_free (&error);
+    if (!parsed.is_array ()) {
+	sLog.error ("KDE window detection: the KWin script sent ", json);
 	return false;
     }
 
-    updateWindowState (windowKey, appId, horizontal != false, vertical != false, fully != false);
+    std::vector<Desktop::WindowState> windows;
 
-    if (m_connection != nullptr) {
-	DBusMessage* reply = dbus_message_new_method_return (message);
-	if (reply != nullptr) {
-	    dbus_connection_send (m_connection, reply, nullptr);
-	    dbus_message_unref (reply);
+    for (const auto& entry : parsed) {
+	if (!entry.is_array () || entry.size () != 3 || !entry[0].is_string () || !entry[1].is_string ()
+	    || !entry[2].is_number_unsigned ()) {
+	    continue;
 	}
+
+	windows.push_back ({ entry[0].get<std::string> (), entry[1].get<std::string> (), entry[2].get<uint32_t> () });
     }
 
+    this->m_windows = std::move (windows);
     return true;
 }
 
-bool KDEWaylandFullScreenDetector::updateWindowState (
-    const std::string& windowKey, const std::string& appId, bool horizontal, bool vertical, bool fully
-) {
-    m_windowStates.insert_or_assign (
-	windowKey,
-	WindowState {
-	    .horizontal = horizontal,
-	    .vertical = vertical,
-	    .fully = fully,
-	    .appId = appId,
-	}
-    );
-
-    if (!windowKey.empty ()) {
-	m_activeWindowKey = windowKey;
+void KDEWaylandFullScreenDetector::dispatch () const {
+    if (this->m_connection == nullptr) {
+	return;
     }
-    return true;
-}
 
-bool KDEWaylandFullScreenDetector::anythingFullscreen () const {
-    if (m_connection != nullptr) {
-	if (!dbus_connection_read_write_dispatch (m_connection, 0)) {
-	    sLog.error ("DBus connection dropped unexpectedly");
-	    m_windowStates.clear ();
-	    m_activeWindowKey.clear ();
-	    dbus_connection_unregister_object_path (m_connection, kObjectPath);
-	    dbus_connection_unref (m_connection);
-	    m_connection = nullptr;
+    // a read pulls in ~2KB at most
+    for (int reads = 0; reads < 64; reads++) {
+	if (!dbus_connection_read_write (this->m_connection, 0)) {
+	    break;
 	}
-    }
 
-    const auto& ctx = getApplicationContext ();
+	bool dispatched = false;
 
-    auto isRelevant = [&ctx] (const WindowState& state) {
-	if (!state.fully) {
-	    return false;
+	while (dbus_connection_get_dispatch_status (this->m_connection) == DBUS_DISPATCH_DATA_REMAINS) {
+	    dbus_connection_dispatch (this->m_connection);
+	    dispatched = true;
 	}
 
-	if (!state.appId.empty ()) {
-	    std::string appIdLower = state.appId;
-	    std::transform (appIdLower.begin (), appIdLower.end (), appIdLower.begin (), [] (unsigned char c) {
-		return std::tolower (c);
-	    });
-
-	    for (const auto& ignore : ctx.settings.render.fullscreenPauseIgnoreAppIds) {
-		if (ignore.empty ()) {
-		    continue;
-		}
-
-		std::string ignoreLower = ignore;
-		std::transform (ignoreLower.begin (), ignoreLower.end (), ignoreLower.begin (), [] (unsigned char c) {
-		    return std::tolower (c);
-		});
-
-		if (appIdLower.find (ignoreLower) != std::string::npos) {
-		    return false;
-		}
-	    }
+	if (!dispatched) {
+	    break;
 	}
-	return true;
-    };
-
-    if (ctx.settings.render.pauseOnFullscreenOnlyWhenActive) {
-	const auto activeIt = m_windowStates.find (m_activeWindowKey);
-	return activeIt != m_windowStates.end () && isRelevant (activeIt->second);
     }
+}
 
-    return std::any_of (m_windowStates.begin (), m_windowStates.end (), [&] (const auto& e) {
-	return isRelevant (e.second);
-    });
+bool KDEWaylandFullScreenDetector::anythingFullscreen () const {
+    this->dispatch ();
+    return Desktop::pausesAnyOf (this->m_windows, this->m_driver.drawnOutputs (), this->getApplicationContext ());
 }
 
-bool KDEWaylandFullScreenDetector::isInitialized () const { return m_connection != nullptr; }
+bool KDEWaylandFullScreenDetector::isInitialized () const { return this->m_script != nullptr; }
 
-void KDEWaylandFullScreenDetector::reset () {
-    m_windowStates.clear ();
-    m_activeWindowKey.clear ();
-}
+void KDEWaylandFullScreenDetector::reset () { }
 
-} // namespace WallpaperEngine::Render::Drivers::Detectors
+} // namespace WallpaperEngine::Render::Drivers::Detectors

+ 22 - 44
src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.h

@@ -4,76 +4,54 @@
 #ifdef ENABLE_KDE_FEATURES
 
 #include <dbus/dbus.h>
+#include <memory>
 #include <string>
-#include <unordered_map>
+#include <vector>
 
 #include "FullScreenDetector.h"
+#include "WallpaperEngine/Desktop/KWinScript.h"
+#include "WallpaperEngine/Desktop/WindowState.h"
+
+namespace WallpaperEngine::Render::Drivers {
+class WaylandOpenGLDriver;
+}
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
 
 /**
- * KDE Plasma/KWin fullscreen and maximize detector using D-Bus.
- *
- * Registers itself as a D-Bus service on the session bus so that a companion
- * KWin script can call OnWindowChanged whenever a window's maximize or
- * fullscreen state changes.
- *
- * If D-Bus initialization fails, m_connection is left null and the caller is
- * expected to fall back to WaylandFullScreenDetector instead.
+ * KWin has no wlr foreign toplevel, so a KWin script reports focused/maximized/fullscreen windows per output to
+ * this process over D-Bus. Falls back to WaylandFullScreenDetector when not isInitialized ().
  */
 class KDEWaylandFullScreenDetector final : public FullScreenDetector {
 public:
-    explicit KDEWaylandFullScreenDetector (Application::ApplicationContext& appContext);
+    KDEWaylandFullScreenDetector (Application::ApplicationContext& appContext, WaylandOpenGLDriver& driver);
     ~KDEWaylandFullScreenDetector () override;
 
-    /**
-     * True if a non-ignored window is fullscreen/fully maximized, per the window-state map
-     * populated by OnWindowChanged. When pauseOnFullscreenOnlyWhenActive is set, only the
-     * most-recently-activated window is examined; app IDs in fullscreenPauseIgnoreAppIds
-     * are excluded (substring match).
-     */
     [[nodiscard]] bool anythingFullscreen () const override;
-
     [[nodiscard]] bool isInitialized () const;
-
     void reset () override;
 
-private:
-    struct WindowState {
-	bool horizontal = false; ///< Window spans the full horizontal extent of its output.
-	bool vertical = false; ///< Window spans the full vertical extent of its output.
-	bool fully = false; ///< Window is fully maximized or in true fullscreen mode.
-	std::string appId {}; ///< Wayland app-id / desktop file name, used for ignore-list matching.
-    };
+    /** JSON array of [app id, output, flags], public for tests */
+    bool applyWindows (const std::string& json);
 
-    /** C-linkage trampoline required by the libdbus object-path vtable; forwards to the instance overload. */
+private:
     static DBusHandlerResult handleMessage (DBusConnection* connection, DBusMessage* message, void* userData);
-
     DBusHandlerResult handleMessage (DBusMessage* message);
-
     bool initializeDBus ();
-    void stopDBus ();
-
-    /**
-     * Parses an OnWindowChanged method call. Expected args, in order:
-     * STRING windowKey, STRING windowName, INT32 pid, STRING appId,
-     * BOOLEAN horizontal, BOOLEAN vertical, BOOLEAN fully.
-     */
-    bool handleMethodCall (DBusMessage* message);
-
-    bool updateWindowState (
-	const std::string& windowKey, const std::string& appId, bool horizontal, bool vertical, bool fully
-    );
+    void dispatch () const;
+    [[nodiscard]] std::string scriptSource () const;
 
+    WaylandOpenGLDriver& m_driver;
     mutable DBusConnection* m_connection = nullptr;
-    mutable std::unordered_map<std::string, WindowState> m_windowStates;
-    mutable std::string m_activeWindowKey;
+    std::string m_serviceName;
+    std::unique_ptr<Desktop::KWinScript> m_script;
+    std::vector<Desktop::WindowState> m_windows;
 
     static constexpr const char* kServiceName = "org.linuxwallpaperengine.WaylandDetector";
     static constexpr const char* kObjectPath = "/org/linuxwallpaperengine/WaylandDetector";
-    static constexpr const char* kMethodName = "OnWindowChanged";
+    static constexpr const char* kMethodName = "OnWindows";
 };
 
 } // namespace WallpaperEngine::Render::Drivers::Detectors
 #endif /* ENABLE_KDE_FEATURES */
-#endif /* ENABLE_WAYLAND */
+#endif /* ENABLE_WAYLAND */

+ 13 - 6
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp

@@ -1,4 +1,5 @@
 #include "WaylandFullScreenDetector.h"
+#include "GnomeFullScreenDetector.h"
 
 #ifdef ENABLE_KDE_FEATURES
 #include "KDEWaylandFullScreenDetector.h"
@@ -7,6 +8,7 @@
 
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
+#include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 #include "wlr-foreign-toplevel-management-unstable-v1-protocol.h"
 #include <cstdlib>
 #include <cstring>
@@ -95,11 +97,12 @@ namespace {
 	const WallpaperEngine::Application::ApplicationContext& ctx, const bool fullscreen, const bool activated,
 	const std::string& appId
     ) {
-	if (!fullscreen) {
-	    return false;
-	}
+	const auto& render = ctx.settings.render;
+	const bool focusPauses = render.pauseOnFocus && activated;
+	const bool fullscreenPauses
+	    = render.pauseOnFullscreen && fullscreen && (!render.pauseOnFullscreenOnlyWhenActive || activated);
 
-	if (ctx.settings.render.pauseOnFullscreenOnlyWhenActive && !activated) {
+	if (!focusPauses && !fullscreenPauses) {
 	    return false;
 	}
 
@@ -264,9 +267,13 @@ void WaylandFullScreenDetector::reset () { }
 __attribute__ ((constructor)) void registerWaylandFullscreenDetector () {
     sVideoFactories.registerFullscreenDetector (
 	"wayland", [] (ApplicationContext& context, VideoDriver& driver) -> std::unique_ptr<FullScreenDetector> {
+	    if (auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver); wayland && wayland->getGnomeShell ()) {
+		return std::make_unique<GnomeFullScreenDetector> (context, *wayland);
+	    }
 #ifdef ENABLE_KDE_FEATURES
-	    if (WallpaperEngine::Desktop::isKDESession ()) {
-		auto detector = std::make_unique<KDEWaylandFullScreenDetector> (context);
+	    if (auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver);
+		wayland && WallpaperEngine::Desktop::isKDESession ()) {
+		auto detector = std::make_unique<KDEWaylandFullScreenDetector> (context, *wayland);
 		if (!detector->isInitialized ()) {
 		    return std::make_unique<WaylandFullScreenDetector> (context);
 		}

+ 31 - 2
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -64,9 +64,10 @@ bool X11FullScreenDetector::anythingFullscreen () const {
     }
 
     const Window ourWindow = glfwGetX11Window (dynamic_cast<GLFWOpenGLDriver&> (this->m_driver).getWindow ());
+    const auto& render = this->getApplicationContext ().settings.render;
     bool fullscreen = false;
 
-    for (unsigned int i = 0; i < childCount && !fullscreen; i++) {
+    for (unsigned int i = 0; i < childCount && !fullscreen && render.pauseOnFullscreen; i++) {
 	XWindowAttributes attributes;
 
 	if (!XGetWindowAttributes (this->m_display, children[i], &attributes) || attributes.map_state != IsViewable) {
@@ -85,7 +86,35 @@ bool X11FullScreenDetector::anythingFullscreen () const {
 
     XFree (children);
 
-    return fullscreen;
+    return fullscreen || (render.pauseOnFocus && this->applicationFocused (ourWindow));
+}
+
+bool X11FullScreenDetector::applicationFocused (Window ourWindow) const {
+    const Atom activeAtom = XInternAtom (this->m_display, "_NET_ACTIVE_WINDOW", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    Window active = None;
+
+    if (XGetWindowProperty (
+	    this->m_display, this->m_root, activeAtom, 0, 1, False, XA_WINDOW, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32 && count == 1) {
+	active = *reinterpret_cast<const Window*> (data);
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    // sub_14003D050
+    if (active == None || active == ourWindow || this->isDesktopWindow (active)) {
+	return false;
+    }
+
+    XWindowAttributes attributes;
+    return XGetWindowAttributes (this->m_display, active, &attributes) && attributes.map_state == IsViewable;
 }
 
 bool X11FullScreenDetector::hasFullscreenState (Window client) const {

+ 2 - 0
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h

@@ -26,6 +26,8 @@ namespace Detectors {
 	[[nodiscard]] Window clientOf (Window window) const;
 	[[nodiscard]] bool hasFullscreenState (Window client) const;
 	[[nodiscard]] bool coversScreen (Window client) const;
+	/** _NET_ACTIVE_WINDOW is a visible application window */
+	[[nodiscard]] bool applicationFocused (Window ourWindow) const;
 	void stop ();
 
 	Display* m_display = nullptr;

+ 1 - 1
src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp

@@ -13,7 +13,7 @@ void WaylandOutput::updateViewports () {
     const auto PDRIVER = dynamic_cast<WaylandOpenGLDriver*> (&m_driver);
     glm::ivec2 fullw = { 0, 0 };
     for (const auto& o : PDRIVER->m_screens) {
-	if (!o->layerSurface) {
+	if (!o->hasShellSurface ()) {
 	    continue;
 	}
 

+ 127 - 31
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -1,4 +1,5 @@
 #include "WaylandOutputViewport.h"
+#include "WallpaperEngine/Desktop/GnomeShell.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <unistd.h>
@@ -39,6 +40,48 @@ static void handleLSClosed (void* data, zwlr_layer_surface_v1* surface) {
     viewport->rendering = false;
 }
 
+static void handleXdgSurfaceConfigure (void* data, xdg_surface* surface, uint32_t serial) {
+    const auto viewport = static_cast<WaylandOutputViewport*> (data);
+    const auto pending = viewport->pendingToplevelSize;
+
+    xdg_surface_ack_configure (surface, serial);
+    viewport->toplevelConfigured = true;
+
+    if (pending.x <= 0 || pending.y <= 0 || pending == viewport->size) {
+	return;
+    }
+
+    viewport->size = pending;
+    viewport->logicalSize = pending;
+    viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
+    viewport->resize ();
+}
+
+static void
+handleXdgToplevelConfigure (void* data, xdg_toplevel*, int32_t width, int32_t height, wl_array* /* states */) {
+    static_cast<WaylandOutputViewport*> (data)->pendingToplevelSize = { width, height };
+}
+
+static void handleXdgToplevelClose (void* data, xdg_toplevel*) {
+    const auto viewport = static_cast<WaylandOutputViewport*> (data);
+
+    viewport->closed = true;
+    viewport->rendering = false;
+}
+
+static void handleXdgToplevelBounds (void*, xdg_toplevel*, int32_t, int32_t) { }
+
+static void handleXdgToplevelCapabilities (void*, xdg_toplevel*, wl_array*) { }
+
+constexpr xdg_surface_listener xdgSurfaceListener = { .configure = handleXdgSurfaceConfigure };
+
+constexpr xdg_toplevel_listener xdgToplevelListener = {
+    .configure = handleXdgToplevelConfigure,
+    .close = handleXdgToplevelClose,
+    .configure_bounds = handleXdgToplevelBounds,
+    .wm_capabilities = handleXdgToplevelCapabilities,
+};
+
 static void geometry (
     void* data, wl_output* output, int32_t x, int32_t y, int32_t width_mm, int32_t height_mm, int32_t subpixel,
     const char* make, const char* model, int32_t transform
@@ -58,7 +101,7 @@ static void mode (void* data, wl_output* output, uint32_t flags, int32_t width,
     viewport->size = { width, height };
     viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
 
-    if (viewport->layerSurface) {
+    if (viewport->hasShellSurface ()) {
 	viewport->resize ();
     }
 
@@ -74,7 +117,7 @@ static void scale (void* data, wl_output* wl_output, int32_t scale) {
 
     viewport->scale = scale;
 
-    if (viewport->layerSurface) {
+    if (viewport->hasShellSurface ()) {
 	viewport->resize ();
     }
 
@@ -315,18 +358,6 @@ void WaylandOutputViewport::setupLS () {
 	sLog.exception ("Failed to get a layer surface");
     }
 
-    wl_region* region = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
-    if (m_driver->getApp ().getContext ().settings.mouse.enabled) {
-	wl_region_add (region, 0, 0, INT32_MAX, INT32_MAX);
-    }
-
-    // fully opaque: lets the compositor skip alpha-blending, always a win since wallpapers are the
-    // bottommost visible content
-    wl_region* opaqueRegion = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
-    wl_region_add (opaqueRegion, 0, 0, INT32_MAX, INT32_MAX);
-    wl_surface_set_opaque_region (surface, opaqueRegion);
-    wl_region_destroy (opaqueRegion);
-
     zwlr_layer_surface_v1_set_size (layerSurface, 0, 0);
     zwlr_layer_surface_v1_set_anchor (
 	layerSurface,
@@ -336,8 +367,6 @@ void WaylandOutputViewport::setupLS () {
     zwlr_layer_surface_v1_set_keyboard_interactivity (layerSurface, false);
     zwlr_layer_surface_v1_add_listener (layerSurface, &layerSurfaceListener, this);
     zwlr_layer_surface_v1_set_exclusive_zone (layerSurface, -1);
-    wl_surface_set_input_region (surface, region);
-    wl_region_destroy (region);
 
 #ifdef ENABLE_KDE_FEATURES
     if (m_driver->getWaylandContext ()->plasmaShell) {
@@ -350,12 +379,7 @@ void WaylandOutputViewport::setupLS () {
     }
 #endif
 
-    if (m_driver->isHDRAvailable ()) {
-	this->setupColorManagement ();
-	this->colorSurface = wp_color_manager_v1_get_surface (m_driver->getWaylandContext ()->colorManager, surface);
-	this->applyImageDescription ();
-    }
-
+    this->prepareSurface ();
     wl_surface_commit (surface);
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
 
@@ -364,11 +388,79 @@ void WaylandOutputViewport::setupLS () {
 	return;
     }
 
+    this->createEGLSurface ();
+}
+
+void WaylandOutputViewport::setupToplevel () {
+    auto* context = m_driver->getWaylandContext ();
+
+    surface = wl_compositor_create_surface (context->compositor);
+    xdgSurface = xdg_wm_base_get_xdg_surface (context->xdgWmBase, surface);
+    xdg_surface_add_listener (xdgSurface, &xdgSurfaceListener, this);
+    xdgToplevel = xdg_surface_get_toplevel (xdgSurface);
+    xdg_toplevel_add_listener (xdgToplevel, &xdgToplevelListener, this);
+
+    // the extension matches on these, set before the first commit
+    const std::string title = std::string (WallpaperEngine::Desktop::GnomeShell::TITLE_PREFIX) + this->name;
+    xdg_toplevel_set_app_id (xdgToplevel, WallpaperEngine::Desktop::GnomeShell::APP_ID);
+    xdg_toplevel_set_title (xdgToplevel, title.c_str ());
+    // not fullscreen, Mutter would hide the top bar; the extension places it by the title's output
+
+    this->prepareSurface ();
+    wl_surface_commit (surface);
+
+    for (int i = 0; i < 10 && !toplevelConfigured && !closed; i++) {
+	if (wl_display_roundtrip (context->display) == -1) {
+	    break;
+	}
+    }
+
+    if (closed) {
+	return;
+    }
+
+    if (!toplevelConfigured) {
+	sLog.error ("Output ", this->name, ": the compositor never configured the wallpaper window");
+    }
+
+    // 0x0 configure: use the output's logical size
+    if (this->size.x <= 0 || this->size.y <= 0 || this->pendingToplevelSize.x <= 0) {
+	this->size = this->logicalSize.x > 0 ? this->logicalSize : this->size / glm::max (this->scale, 1);
+	this->logicalSize = this->size;
+	this->viewport = { 0, 0, this->size.x * this->scale, this->size.y * this->scale };
+    }
+
+    this->createEGLSurface ();
+}
+
+void WaylandOutputViewport::prepareSurface () {
+    this->setInputRegion (m_driver->getApp ().getContext ().settings.mouse.enabled);
+
+    // fully opaque: lets the compositor skip alpha-blending, always a win since wallpapers are the
+    // bottommost visible content
+    wl_region* opaqueRegion = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
+    wl_region_add (opaqueRegion, 0, 0, INT32_MAX, INT32_MAX);
+    wl_surface_set_opaque_region (surface, opaqueRegion);
+    wl_region_destroy (opaqueRegion);
+
+    if (m_driver->isHDRAvailable ()) {
+	this->setupColorManagement ();
+	this->colorSurface = wp_color_manager_v1_get_surface (m_driver->getWaylandContext ()->colorManager, surface);
+	this->applyImageDescription ();
+    }
+}
+
+void WaylandOutputViewport::createEGLSurface () {
     eglWindow = wl_egl_window_create (surface, size.x * scale, size.y * scale);
     eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT (
 	m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr
     );
-    wl_surface_commit (surface);
+
+    // Mutter flags an empty commit between a toplevel's configure ack and its first buffer
+    if (!this->xdgToplevel) {
+	wl_surface_commit (surface);
+    }
+
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
     wl_display_flush (m_driver->getWaylandContext ()->display);
 
@@ -418,6 +510,17 @@ void WaylandOutputViewport::makeCurrent () {
     }
 }
 
+void WaylandOutputViewport::setInputRegion (bool everything) {
+    wl_region* region = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
+
+    if (everything) {
+	wl_region_add (region, 0, 0, INT32_MAX, INT32_MAX);
+    }
+
+    wl_surface_set_input_region (this->surface, region);
+    wl_region_destroy (region);
+}
+
 void WaylandOutputViewport::setWantsPointerButtons (bool wants) {
     if (this->surface == nullptr || !m_driver->getApp ().getContext ().settings.mouse.enabled) {
 	return;
@@ -433,14 +536,7 @@ void WaylandOutputViewport::setWantsPointerButtons (bool wants) {
     this->inputPassthrough = passthrough;
 
     // applied by the next commit
-    wl_region* region = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
-
-    if (!passthrough) {
-	wl_region_add (region, 0, 0, INT32_MAX, INT32_MAX);
-    }
-
-    wl_surface_set_input_region (this->surface, region);
-    wl_region_destroy (region);
+    this->setInputRegion (!passthrough);
 
     // the release would go to the desktop now
     this->leftClick = WallpaperEngine::Input::MouseClickStatus::Released;

+ 15 - 1
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h

@@ -22,6 +22,8 @@ struct zxdg_output_v1;
 struct zxdg_output_manager_v1;
 struct wp_color_management_output_v1;
 struct wp_color_management_surface_v1;
+struct xdg_surface;
+struct xdg_toplevel;
 #ifdef ENABLE_KDE_FEATURES
 struct org_kde_plasma_surface;
 #endif
@@ -40,7 +42,6 @@ namespace Output {
 
 	wl_output* output = nullptr;
 	glm::ivec2 size = {};
-	glm::ivec2 position = {};
 	uint32_t waylandName;
 	int scale = 1;
 	bool initialized = false;
@@ -52,6 +53,12 @@ namespace Output {
 	EGLSurface eglSurface = nullptr;
 	wl_surface* surface = nullptr;
 	zwlr_layer_surface_v1* layerSurface = nullptr;
+	/** GNOME: toplevel the Shell extension turns into a desktop window */
+	xdg_surface* xdgSurface = nullptr;
+	xdg_toplevel* xdgToplevel = nullptr;
+	/** 0 = ours to pick */
+	glm::ivec2 pendingToplevelSize = {};
+	bool toplevelConfigured = false;
 	wl_callback* frameCallback = nullptr;
 #ifdef ENABLE_KDE_FEATURES
 	org_kde_plasma_surface* plasmaSurface = nullptr;
@@ -70,7 +77,10 @@ namespace Output {
 	bool hasXdgLogicalPosition = false;
 	zxdg_output_v1* xdgOutput = nullptr;
 
+	/** layer surface or toplevel */
+	[[nodiscard]] bool hasShellSurface () const { return this->layerSurface || this->xdgToplevel; }
 	void setupLS ();
+	void setupToplevel ();
 	void setupXdgOutput (zxdg_output_manager_v1* manager);
 	/** Starts following whether the output runs in HDR (only with --hdr and a compositor that can take PQ) */
 	void setupColorManagement ();
@@ -102,6 +112,10 @@ namespace Output {
 	void resize ();
 
     private:
+	void prepareSurface ();
+	void setInputRegion (bool everything);
+	void createEGLSurface ();
+
 	WaylandOpenGLDriver* m_driver = nullptr;
     };
 } // namespace Output

+ 2 - 1
src/WallpaperEngine/Render/Drivers/VideoFactories.cpp

@@ -84,7 +84,8 @@ std::unique_ptr<Detectors::FullScreenDetector> VideoFactories::createFullscreenD
 ) {
     const auto it = this->m_fullscreenFactories.find (xdgSessionType);
 
-    if (it == this->m_fullscreenFactories.end () || !context.settings.render.pauseOnFullscreen) {
+    if (it == this->m_fullscreenFactories.end ()
+	|| (!context.settings.render.pauseOnFullscreen && !context.settings.render.pauseOnFocus)) {
 	return std::make_unique<Detectors::FullScreenDetector> (context);
     }
 

+ 139 - 9
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -37,7 +37,14 @@ static void handlePointerEnter (
 ) {
     const auto driver = static_cast<WaylandOpenGLDriver*> (data);
     const auto viewport = driver->surfaceToViewport (surface);
+
+    if (viewport == nullptr) {
+	return;
+    }
+
     driver->viewportInFocus = viewport;
+    viewport->mousePos = { wl_fixed_to_double (surface_x) * viewport->scale,
+			   (viewport->size.y - wl_fixed_to_double (surface_y)) * viewport->scale };
     wl_surface_set_buffer_scale (viewport->cursorSurface, viewport->scale);
     wl_surface_attach (viewport->cursorSurface, wl_cursor_image_get_buffer (viewport->pointer->images[0]), 0, 0);
     wl_pointer_set_cursor (
@@ -48,7 +55,13 @@ static void handlePointerEnter (
 }
 
 static void
-handlePointerLeave (void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface) { }
+handlePointerLeave (void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface) {
+    const auto driver = static_cast<WaylandOpenGLDriver*> (data);
+
+    if (driver->viewportInFocus && driver->viewportInFocus->surface == surface) {
+	driver->viewportInFocus = nullptr;
+    }
+}
 
 static void handlePointerAxis (void* data, wl_pointer* wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) { }
 
@@ -152,6 +165,10 @@ constexpr struct wp_image_description_v1_listener hdrDescriptionListener = {
     .ready = hdrDescriptionReady,
 };
 
+static void handleWmBasePing (void*, xdg_wm_base* base, uint32_t serial) { xdg_wm_base_pong (base, serial); }
+
+constexpr xdg_wm_base_listener wmBaseListener = { .ping = handleWmBasePing };
+
 static void
 handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
     const auto driver = static_cast<WaylandOpenGLDriver*> (data);
@@ -169,6 +186,11 @@ handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const cha
     } else if (strcmp (interface, zwlr_layer_shell_v1_interface.name) == 0) {
 	driver->getWaylandContext ()->layerShell
 	    = static_cast<zwlr_layer_shell_v1*> (wl_registry_bind (registry, name, &zwlr_layer_shell_v1_interface, 1));
+    } else if (strcmp (interface, xdg_wm_base_interface.name) == 0) {
+	driver->getWaylandContext ()->xdgWmBase = static_cast<xdg_wm_base*> (
+	    wl_registry_bind (registry, name, &xdg_wm_base_interface, std::min (version, 5u))
+	);
+	xdg_wm_base_add_listener (driver->getWaylandContext ()->xdgWmBase, &wmBaseListener, driver);
     } else if (strcmp (interface, wl_seat_interface.name) == 0) {
 	driver->getWaylandContext ()->seat
 	    = static_cast<wl_seat*> (wl_registry_bind (registry, name, &wl_seat_interface, 1));
@@ -379,6 +401,16 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
 	zwlr_layer_surface_v1_destroy (viewport->layerSurface);
     }
 
+    if (viewport->xdgToplevel) {
+	xdg_toplevel_destroy (viewport->xdgToplevel);
+	viewport->xdgToplevel = nullptr;
+    }
+
+    if (viewport->xdgSurface) {
+	xdg_surface_destroy (viewport->xdgSurface);
+	viewport->xdgSurface = nullptr;
+    }
+
 #ifdef ENABLE_KDE_FEATURES
     if (viewport->plasmaSurface) {
 	org_kde_plasma_surface_destroy (viewport->plasmaSurface);
@@ -407,6 +439,10 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
 	wl_output_release (viewport->output);
     }
 
+    if (this->viewportInFocus == viewport) {
+	this->viewportInFocus = nullptr;
+    }
+
     std::erase (this->m_screens, viewport);
     this->getOutput ().reset ();
     delete viewport;
@@ -423,7 +459,24 @@ WaylandOpenGLDriver::WaylandOpenGLDriver (ApplicationContext& context, Wallpaper
 }
 
 void WaylandOpenGLDriver::initWaylandRegistry () {
-    m_waylandContext.display = wl_display_connect (nullptr);
+    // GNOME 45-48 only accept a Shell-spawned client, connect through its helper
+    if (Desktop::isGnomeSession ()) {
+	this->m_gnomeShell = std::make_unique<Desktop::GnomeShell> ();
+
+	if (this->m_gnomeShell->isAvailable () && this->m_gnomeShell->needsHelper ()) {
+	    const int fd = this->m_gnomeShell->openWaylandSocket ();
+
+	    if (fd < 0) {
+		sLog.exception ("Cannot draw a wallpaper on this GNOME: ", this->m_gnomeShell->reason ());
+	    }
+
+	    m_waylandContext.display = wl_display_connect_to_fd (fd);
+	}
+    }
+
+    if (!m_waylandContext.display) {
+	m_waylandContext.display = wl_display_connect (nullptr);
+    }
 
     if (!m_waylandContext.display) {
 	sLog.exception ("Failed to query wayland display");
@@ -435,9 +488,35 @@ void WaylandOpenGLDriver::initWaylandRegistry () {
     wl_display_dispatch (m_waylandContext.display);
     wl_display_roundtrip (m_waylandContext.display);
 
-    if (!m_waylandContext.compositor || !m_waylandContext.shm || !m_waylandContext.layerShell
-	|| this->m_screens.empty ()) {
-	sLog.exception ("Failed to bind to required interfaces");
+    std::vector<std::string> missing;
+
+    if (!m_waylandContext.compositor) {
+	missing.emplace_back ("wl_compositor");
+    }
+    if (!m_waylandContext.shm) {
+	missing.emplace_back ("wl_shm");
+    }
+    if (this->m_screens.empty ()) {
+	missing.emplace_back ("wl_output (no monitor)");
+    }
+    if (!m_waylandContext.layerShell && !(WallpaperEngine::Desktop::isGnomeSession () && m_waylandContext.xdgWmBase)) {
+	missing.emplace_back (
+	    "zwlr_layer_shell_v1 (wlr-layer-shell, the compositor can't put a surface behind windows)"
+	);
+    }
+
+    if (!missing.empty ()) {
+	for (const auto& interface : missing) {
+	    sLog.error ("The compositor does not offer ", interface);
+	}
+
+	sLog.exception ("Failed to bind to required interfaces: ", missing.front ());
+    }
+
+    if (m_waylandContext.layerShell) {
+	this->m_gnomeShell.reset ();
+    } else {
+	this->initGnomeShell ();
     }
 
     if (m_waylandContext.xdgOutputManager) {
@@ -450,6 +529,27 @@ void WaylandOpenGLDriver::initWaylandRegistry () {
     }
 }
 
+void WaylandOpenGLDriver::initGnomeShell () {
+    if (!this->m_gnomeShell) {
+	this->m_gnomeShell = std::make_unique<Desktop::GnomeShell> ();
+    }
+
+    if (!this->m_gnomeShell->isAvailable ()) {
+	sLog.error (
+	    "GNOME on Wayland has no layer-shell, wallpapers need the linux-wallpaperengine GNOME Shell extension: ",
+	    this->m_gnomeShell->reason ()
+	);
+	sLog.error (
+	    "Install and enable it (we_manager offers it, or copy gnome-shell-extension/ to "
+	    "~/.local/share/gnome-shell/extensions and run gnome-extensions enable "
+	    "linux-wallpaperengine@wallpaperenginelover.github.io), then log out and back in once"
+	);
+	sLog.exception ("Cannot draw a wallpaper on GNOME Wayland without the GNOME Shell extension");
+    }
+
+    sLog.out ("GNOME Shell extension found, the wallpapers are desktop windows");
+}
+
 void WaylandOpenGLDriver::initColorManagement () {
     if (!m_context.settings.render.hdr) {
 	return;
@@ -505,7 +605,11 @@ void WaylandOpenGLDriver::setupOutputLayerSurfaces () {
 	    continue;
 	}
 
-	o->setupLS ();
+	if (m_waylandContext.layerShell) {
+	    o->setupLS ();
+	} else {
+	    o->setupToplevel ();
+	}
 	any = true;
     }
 
@@ -549,7 +653,7 @@ void WaylandOpenGLDriver::setupLateOutputs () {
     // KDE often drops and re-adds outputs while it applies the screen layout at login, and monitors can
     // wake up after we started; the wallpapers stay registered by screen name, only the surface is missing
     for (const auto& o : this->m_screens) {
-	if (o->layerSurface || o->closed || !o->initialized || !isScreenRequested (o->name)) {
+	if (o->hasShellSurface () || o->closed || !o->initialized || !isScreenRequested (o->name)) {
 	    continue;
 	}
 
@@ -559,7 +663,11 @@ void WaylandOpenGLDriver::setupLateOutputs () {
 	    o->setupXdgOutput (m_waylandContext.xdgOutputManager);
 	}
 
-	o->setupLS ();
+	if (m_waylandContext.layerShell) {
+	    o->setupLS ();
+	} else {
+	    o->setupToplevel ();
+	}
     }
 }
 
@@ -611,6 +719,16 @@ void WaylandOpenGLDriver::reapClosedOutputs () {
 }
 
 void WaylandOpenGLDriver::dispatchEventQueue () {
+    if (this->m_gnomeShell) {
+	this->m_gnomeShell->dispatch ();
+
+	if (this->m_gnomeShell->vanished ()) {
+	    sLog.error ("Stopping, the wallpapers can't stay on GNOME without the Shell extension");
+	    m_requestedExit = true;
+	    return;
+	}
+    }
+
     this->reapClosedOutputs ();
 
     if (this->m_layerSurfacesReady) {
@@ -622,7 +740,7 @@ void WaylandOpenGLDriver::dispatchEventQueue () {
     const auto now = std::chrono::steady_clock::now ();
 
     for (const auto& o : this->m_screens) {
-	if (o->layerSurface && !o->closed && now - o->lastSwap > MISSED_FRAME_TIMEOUT) {
+	if (o->hasShellSurface () && !o->closed && now - o->lastSwap > MISSED_FRAME_TIMEOUT) {
 	    o->renderFrame ();
 	}
     }
@@ -697,6 +815,18 @@ void* WaylandOpenGLDriver::getWaylandDisplay () const { return this->m_waylandCo
 
 WaylandOpenGLDriver::WaylandContext* WaylandOpenGLDriver::getWaylandContext () { return &this->m_waylandContext; }
 
+std::vector<std::string> WaylandOpenGLDriver::drawnOutputs () const {
+    std::vector<std::string> outputs;
+
+    for (const auto* viewport : this->m_screens) {
+	if (viewport->hasShellSurface () && !viewport->closed) {
+	    outputs.push_back (viewport->name);
+	}
+    }
+
+    return outputs;
+}
+
 Output::WaylandOutputViewport* WaylandOpenGLDriver::surfaceToViewport (const wl_surface* surface) const {
     for (const auto& o : m_screens) {
 	if (o->surface == surface) {

+ 8 - 0
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h

@@ -11,6 +11,7 @@
 
 #include "WallpaperEngine/Application/ApplicationContext.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Desktop/GnomeShell.h"
 #include "WallpaperEngine/Input/Drivers/WaylandMouseInput.h"
 #include "WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h"
 #include "WallpaperEngine/Render/Drivers/Output/WaylandOutput.h"
@@ -25,6 +26,7 @@ class WallpaperApplication;
 struct zwlr_layer_shell_v1;
 struct zwlr_layer_surface_v1;
 struct zxdg_output_manager_v1;
+struct xdg_wm_base;
 struct wp_color_manager_v1;
 struct wp_image_description_v1;
 #ifdef ENABLE_KDE_FEATURES
@@ -59,6 +61,8 @@ public:
 	wl_compositor* compositor = nullptr;
 	wl_shm* shm = nullptr;
 	zwlr_layer_shell_v1* layerShell = nullptr;
+	/** GNOME only */
+	xdg_wm_base* xdgWmBase = nullptr;
 	wl_seat* seat = nullptr;
 	zxdg_output_manager_v1* xdgOutputManager = nullptr;
 	/** Only bound with --hdr */
@@ -98,9 +102,11 @@ public:
     void onLayerClose (Output::WaylandOutputViewport*);
     /** the cursor position is known without a surface of ours under it */
     [[nodiscard]] bool hasGlobalCursor () const { return this->m_mouseInput.hasGlobalCursor (); }
+    [[nodiscard]] Desktop::GnomeShell* getGnomeShell () const { return this->m_gnomeShell.get (); }
     /** frees the viewports the compositor closed, outside of any event dispatch */
     void reapClosedOutputs ();
     Output::WaylandOutputViewport* surfaceToViewport (const wl_surface*) const;
+    [[nodiscard]] std::vector<std::string> drawnOutputs () const;
 
     Output::WaylandOutputViewport* viewportInFocus = nullptr;
 
@@ -119,6 +125,7 @@ private:
     mutable bool m_requestedExit;
 
     void initWaylandRegistry ();
+    void initGnomeShell ();
     void setupOutputLayerSurfaces ();
     [[nodiscard]] bool isScreenRequested (const std::string& name) const;
     void setupLateOutputs ();
@@ -132,6 +139,7 @@ private:
     uint32_t m_frameCounter = 0;
     bool m_layerSurfacesReady = false;
     ApplicationContext& m_context;
+    std::unique_ptr<Desktop::GnomeShell> m_gnomeShell;
     WaylandMouseInput m_mouseInput;
 
     std::chrono::high_resolution_clock::time_point renderStart = std::chrono::high_resolution_clock::now ();

+ 48 - 0
src/WallpaperEngine/Testing/Cases/GnomeSession.cpp

@@ -0,0 +1,48 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <cstdlib>
+#include <optional>
+#include <string>
+
+#include "WallpaperEngine/Desktop/GnomeShell.h"
+
+using WallpaperEngine::Desktop::isGnomeSession;
+
+namespace {
+bool withDesktop (const char* value) {
+    const char* previous = std::getenv ("XDG_CURRENT_DESKTOP");
+    const std::optional<std::string> saved = previous ? std::optional<std::string> (previous) : std::nullopt;
+
+    if (value) {
+	setenv ("XDG_CURRENT_DESKTOP", value, 1);
+    } else {
+	unsetenv ("XDG_CURRENT_DESKTOP");
+    }
+
+    const bool result = isGnomeSession ();
+
+    if (saved) {
+	setenv ("XDG_CURRENT_DESKTOP", saved->c_str (), 1);
+    } else {
+	unsetenv ("XDG_CURRENT_DESKTOP");
+    }
+
+    return result;
+}
+} // namespace
+
+TEST_CASE ("isGnomeSession finds GNOME anywhere in the XDG_CURRENT_DESKTOP list") {
+    CHECK (withDesktop ("GNOME"));
+    CHECK (withDesktop ("ubuntu:GNOME"));
+    CHECK (withDesktop ("GNOME-Classic:GNOME"));
+    CHECK (withDesktop ("GNOME:extra"));
+}
+
+TEST_CASE ("isGnomeSession only takes whole entries") {
+    CHECK_FALSE (withDesktop (nullptr));
+    CHECK_FALSE (withDesktop (""));
+    CHECK_FALSE (withDesktop ("KDE"));
+    CHECK_FALSE (withDesktop ("GNOME-Flashback"));
+    CHECK_FALSE (withDesktop ("X-Cinnamon"));
+    CHECK_FALSE (withDesktop ("Budgie:GNOME-ish"));
+}

+ 86 - 0
src/gnome_wayland_helper.c

@@ -0,0 +1,86 @@
+/*
+ * linux-wallpaperengine-gnome-helper <socket path>
+ *
+ * GNOME 45-48 only make desktop windows of a client the Shell spawned (MetaWaylandClient owns_window). The extension
+ * spawns this, it passes WAYLAND_SOCKET to the engine on <socket path> and lives until the engine closes it.
+ */
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+int main (int argc, char** argv) {
+    if (argc != 2) {
+	fprintf (stderr, "usage: %s <socket path>\n", argv[0]);
+	return 2;
+    }
+
+    const char* wayland = getenv ("WAYLAND_SOCKET");
+    char* end = NULL;
+    const long fd = wayland ? strtol (wayland, &end, 10) : -1;
+
+    if (fd < 0 || !end || *end != '\0') {
+	fprintf (stderr, "no WAYLAND_SOCKET from the compositor\n");
+	return 2;
+    }
+
+    struct sockaddr_un address = { .sun_family = AF_UNIX };
+
+    if (strlen (argv[1]) >= sizeof (address.sun_path)) {
+	fprintf (stderr, "socket path too long\n");
+	return 2;
+    }
+
+    strcpy (address.sun_path, argv[1]);
+
+    const int engine = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+
+    if (engine < 0 || connect (engine, (struct sockaddr*)&address, sizeof (address)) != 0) {
+	fprintf (stderr, "cannot reach the engine at %s: %s\n", argv[1], strerror (errno));
+	return 1;
+    }
+
+    char byte = 0;
+    struct iovec data = { .iov_base = &byte, .iov_len = 1 };
+    union {
+	char buffer[CMSG_SPACE (sizeof (int))];
+	struct cmsghdr align;
+    } control;
+    memset (&control, 0, sizeof (control));
+
+    struct msghdr message = {
+	.msg_iov = &data,
+	.msg_iovlen = 1,
+	.msg_control = control.buffer,
+	.msg_controllen = sizeof (control.buffer),
+    };
+    struct cmsghdr* header = CMSG_FIRSTHDR (&message);
+    header->cmsg_level = SOL_SOCKET;
+    header->cmsg_type = SCM_RIGHTS;
+    header->cmsg_len = CMSG_LEN (sizeof (int));
+    const int passed = (int)fd;
+    memcpy (CMSG_DATA (header), &passed, sizeof (int));
+
+    if (sendmsg (engine, &message, MSG_NOSIGNAL) != 1) {
+	fprintf (stderr, "cannot hand the connection over: %s\n", strerror (errno));
+	return 1;
+    }
+
+    close (passed);
+
+    // EOF = engine gone
+    for (;;) {
+	const ssize_t got = read (engine, &byte, 1);
+
+	if (got > 0 || (got < 0 && errno == EINTR)) {
+	    continue;
+	}
+
+	break;
+    }
+
+    return 0;
+}

+ 8 - 1
tests/desktops/conftest.py

@@ -14,6 +14,7 @@ import pytest
 REPO = Path(__file__).resolve().parents[2]
 sys.path.insert(0, str(REPO / "tools"))
 
+from desktops.runner import BASE  # noqa: E402
 from desktops.session import KINDS, Session, Unsupported  # noqa: E402
 
 STEAM_ROOTS = (
@@ -40,7 +41,13 @@ def engine():
                                         ("the assets", assets), ("a test wallpaper", wallpaper)) if not value]
     if missing:
         pytest.skip(f"missing {', '.join(missing)}, see tests/desktops/conftest.py")
-    return {"binary": str(binary), "assets": str(assets), "wallpaper": str(wallpaper)}
+    # renamed so we_manager's pkill -f linux-wallpaperengine misses it
+    link = BASE / "lwe-test-engine"
+    link.parent.mkdir(parents=True, exist_ok=True)
+    if not link.is_symlink() or os.readlink(link) != str(binary.resolve()):
+        link.unlink(missing_ok=True)
+        link.symlink_to(binary.resolve())
+    return {"binary": str(link), "assets": str(assets), "wallpaper": str(wallpaper)}
 
 
 @pytest.fixture(scope="session")

+ 1 - 0
tests/desktops/fixtures/clickprobe/project.json

@@ -0,0 +1 @@
+{"file": "scene.json", "type": "scene", "title": "click probe", "general": {"properties": {}}}

+ 32 - 0
tests/desktops/fixtures/clickprobe/scene.json

@@ -0,0 +1,32 @@
+{
+ "version": 3,
+ "camera": {
+  "center": "0 0 -1",
+  "eye": "0 0 0",
+  "up": "0 1 0"
+ },
+ "general": {
+  "orthogonalprojection": {
+   "width": 1920,
+   "height": 1080
+  },
+  "clearcolor": "0 0 0",
+  "bloom": false,
+  "cameraparallax": false
+ },
+ "objects": [
+  {
+   "id": 1,
+   "name": "probe",
+   "image": "models/util/solidlayer.json",
+   "size": "1920 1080",
+   "origin": "960 540 0",
+   "color": "0.2 0.4 0.6",
+   "visible": true,
+   "alpha": {
+    "script": "'use strict';\nexport function cursorDown(event) { console.log('LWE-CLICK down'); }\nexport function cursorUp(event) { console.log('LWE-CLICK up'); }\nexport function update(value) { return value; }\n",
+    "value": 1.0
+   }
+  }
+ ]
+}

+ 258 - 0
tests/desktops/test_gnome.py

@@ -0,0 +1,258 @@
+"""GNOME on Wayland via the Shell extension: desktop window, per monitor pause, desktop menu, extension removal."""
+import time
+from pathlib import Path
+
+import pytest
+
+from conftest import REPO, changed_fraction
+from desktops.runner import terminate
+
+UUID = "linux-wallpaperengine@wallpaperenginelover.github.io"
+WALLPAPER = "global.get_window_actors().map(a => a.meta_window).find(w => w.get_wm_class() === 'linux-wallpaperengine')"
+POINTER = ("const C = imports.gi.Clutter, G = imports.gi.GLib;"
+           "if (!global._lweLabPointer) global._lweLabPointer = C.get_default_backend().get_default_seat()"
+           ".create_virtual_device(C.InputDeviceType.POINTER_DEVICE);"
+           "const pointer = global._lweLabPointer, now = () => G.get_monotonic_time();")
+
+
+CLICK_PROBE = REPO / "tests/desktops/fixtures/clickprobe"
+
+
+def _engine(desktop, engine, log, *extra, wallpaper=None):
+    return desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                           desktop.output_names()[0], "--silent", "--fps", "30", *extra,
+                           str(wallpaper or engine["wallpaper"])],
+                          log=log, env={"LWE_FRAME_STATS": "1", "LWE_SCRIPT_LOG": "1"})
+
+
+def _point(desktop, x, y):
+    """moves the lab's virtual pointer, again until the Shell has it (it sometimes keeps an older position)"""
+    # the hot corner at the start position opens the overview
+    desktop.eval(POINTER + f"pointer.notify_absolute_motion(now(), {x}, {y}); 1")
+    time.sleep(0.5)
+    desktop.eval("Main.overview.hide(); 1")
+    time.sleep(0.5)
+    for _ in range(20):
+        desktop.eval(POINTER + f"pointer.notify_absolute_motion(now(), {x}, {y}); 1")
+        time.sleep(0.25)
+        if desktop.eval("global.get_pointer().slice(0, 2).join(',')") == f'"{x},{y}"':
+            return
+    raise AssertionError(f"the virtual pointer never got to {x},{y}")
+
+
+def _click(desktop, button=1):
+    desktop.eval(POINTER + f"pointer.notify_button(now(), {button}, C.ButtonState.PRESSED); 1")
+    time.sleep(0.3)
+    desktop.eval(POINTER + f"pointer.notify_button(now(), {button}, C.ButtonState.RELEASED); 1")
+
+
+def _frame_lines(log):
+    return Path(log).read_text(errors="replace").count("FRAME-STATS")
+
+
+def _window(desktop, mode, name=None):
+    """a GTK probe window, focused like a user would: Mutter maps it without the focus when the session never saw
+    any input (focus stealing prevention), and WE counts only the focused window as fullscreen"""
+    process = desktop.spawn(name or f"{mode}-probe", ["python3", str(REPO / "tools/desktops/wayland_window.py"), mode])
+    title = f"lwe-{mode}-probe"
+    for _ in range(40):
+        time.sleep(0.25)
+        if desktop.eval(f"const w = global.display.list_all_windows().find(w => w.get_title() === '{title}');"
+                        "if (w) w.activate(global.display.get_current_time_roundtrip()); !!w") == "true":
+            break
+    return process
+
+
+def _renders(log, seconds=5):
+    before = _frame_lines(log)
+    time.sleep(seconds)
+    return _frame_lines(log) > before
+
+
+# 49/50: Meta.Window.set_type, 46-48: helper's Meta.WaylandClient, 45: bottom normal-layer window
+@pytest.fixture(params=["gnome", "gnome49", "gnome48", "gnome47", "gnome46", "gnome45"])
+def gnome(request, desktop_factory):
+    return desktop_factory(request.param)
+
+
+def test_wallpaper_is_a_desktop_window(gnome, engine, tmp_path):
+    process = _engine(gnome, engine, tmp_path / "engine.log")
+    try:
+        time.sleep(8)
+        assert process.poll() is None, (tmp_path / "engine.log").read_text()[-1500:]
+        state = gnome.eval(f"const w = {WALLPAPER}; const r = w.get_frame_rect();"
+                           "[w.get_window_type(), w.skip_taskbar, w.is_fullscreen(), r.width, r.height].join(',')")
+        width, height = gnome.size
+        if gnome.name == "gnome45":
+            # 45: normal window hidden from the window lists, kept in the work area
+            window_type, skip, fullscreen, frame_width, frame_height = state.strip('"').split(",")
+            assert (window_type, skip, fullscreen, frame_width) == ("0", "true", "false", str(width))
+            assert int(frame_height) >= height - 64
+        else:
+            # Meta.WindowType.DESKTOP
+            assert state == f'"1,true,false,{width},{height}"'
+        assert gnome.eval("global.display.get_monitor_in_fullscreen(0)") == "false"
+        assert gnome.eval("Shell.AppSystem.get_default().get_running().length") == "0"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("mode", ["maximized", "fullscreen"])
+def test_covering_window_pauses_rendering(gnome, engine, tmp_path, mode):
+    log = tmp_path / "engine.log"
+    process = _engine(gnome, engine, log)
+    probe = None
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render on GNOME"
+
+        probe = _window(gnome, mode)
+        time.sleep(4)
+        assert not _renders(log), f"still rendering under a {mode} window"
+
+        terminate([probe.pid])
+        probe = None
+        time.sleep(4)
+        assert _renders(log), f"rendering did not resume after the {mode} window"
+
+        normal = _window(gnome, "normal")
+        try:
+            time.sleep(4)
+            assert _renders(log), "a plain window paused the wallpaper"
+        finally:
+            terminate([normal.pid])
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)
+
+
+def test_desktop_menu_opens_over_the_wallpaper(gnome, engine, tmp_path):
+    process = _engine(gnome, engine, tmp_path / "engine.log")
+    try:
+        width, height = gnome.size
+        gnome.eval(POINTER + f"pointer.notify_absolute_motion(now(), {width // 2}, {height // 2}); 1")
+        time.sleep(0.5)
+        gnome.eval("Main.overview.hide(); 1")
+        time.sleep(8)
+        # the lab pointer sometimes lags, resend until the Shell has it
+        target = f"{width // 2},{height // 2}"
+        for _ in range(20):
+            gnome.eval(POINTER + f"pointer.notify_absolute_motion(now(), {width // 2}, {height // 2}); 1")
+            time.sleep(0.25)
+            if gnome.eval("global.get_pointer().slice(0, 2).join(',')") == f'"{target}"':
+                break
+        gnome.shot(tmp_path / "before.png")
+        gnome.eval(POINTER + "pointer.notify_button(now(), 3, C.ButtonState.PRESSED);"
+                   "pointer.notify_button(now() + 20000, 3, C.ButtonState.RELEASED); 1")
+        time.sleep(2)
+        opened = gnome.eval("Main.layoutManager._bgManagers.some(m => m.backgroundActor._backgroundMenu?.isOpen)")
+        gnome.shot(tmp_path / "after.png")
+        gnome.eval("Main.layoutManager._bgManagers.forEach(m => m.backgroundActor._backgroundMenu?.close()); 1")
+        assert opened == "true", "a right click on the wallpaper did not reach GNOME's desktop menu"
+        assert changed_fraction(tmp_path / "before.png", tmp_path / "after.png") > 0.01
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+def test_engine_stops_without_the_extension(gnome, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(gnome, engine, log)
+    try:
+        time.sleep(6)
+        assert process.poll() is None
+        gnome.run(["gnome-extensions", "disable", UUID])
+        process.wait(10)
+        assert "GNOME Shell extension went away" in log.read_text(errors="replace")
+        deadline = time.monotonic() + 10
+        while gnome.eval(f"!!{WALLPAPER}") != "false" and time.monotonic() < deadline:
+            time.sleep(0.5)
+        assert gnome.eval(f"!!{WALLPAPER}") == "false", "the wallpaper window outlived the extension"
+
+        refused = _engine(gnome, engine, tmp_path / "refused.log")
+        assert refused.wait(20) != 0
+        assert "without the GNOME Shell extension" in (tmp_path / "refused.log").read_text(errors="replace")
+    finally:
+        gnome.run(["gnome-extensions", "enable", UUID])
+        if process.poll() is None:
+            process.terminate()
+            process.wait(10)
+
+
+def test_overview_shows_the_live_wallpaper(gnome, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    gnome.eval("Main.overview.show(); 1")
+    time.sleep(3)
+    gnome.shot(tmp_path / "bare.png")
+    gnome.eval("Main.overview.hide(); 1")
+    time.sleep(2)
+
+    process = _engine(gnome, engine, log)
+    try:
+        time.sleep(8)
+        gnome.eval("Main.overview.show(); 1")
+        time.sleep(3)
+        gnome.shot(tmp_path / "overview.png")
+        # only the clones keep frame callbacks coming in the overview
+        assert _renders(log), "the wallpaper stopped rendering in the overview"
+        assert changed_fraction(tmp_path / "bare.png", tmp_path / "overview.png") > 0.2, \
+            "the overview still shows GNOME's own background"
+    finally:
+        gnome.eval("Main.overview.hide(); 1")
+        process.terminate()
+        process.wait(10)
+
+
+def test_focused_window_pauses_with_pause_on_focus(gnome, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(gnome, engine, log, "--pause-on-focus")
+    probe = None
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render on GNOME"
+        probe = _window(gnome, "normal", "focus-probe")
+        time.sleep(4)
+        assert not _renders(log), "--pause-on-focus kept rendering while another application had the focus"
+        terminate([probe.pid])
+        probe = None
+        time.sleep(4)
+        assert _renders(log), "rendering did not resume once the focused window was gone"
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)
+
+
+# DING: own desktop window on GNOME 50, bottom-layer normal one on Ubuntu 46
+@pytest.fixture(params=["gnome-ding", "gnome46-ding", "gnome45-ding"])
+def ding(request, desktop_factory):
+    return desktop_factory(request.param)
+
+
+def test_wallpaper_stays_under_desktop_icons(ding, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(ding, engine, log, "--pause-on-focus", wallpaper=CLICK_PROBE)
+    try:
+        time.sleep(8)
+        order = ding.eval("global.display.sort_windows_by_stacking(global.display.list_all_windows())"
+                          ".map(w => w.get_gtk_application_id() || w.get_wm_class()).join('|')").strip('"').split("|")
+        icons = order.index("com.rastersoft.ding")
+        wallpaper = order.index("linux-wallpaperengine")
+        assert wallpaper < icons, f"the wallpaper is above the desktop icons: {order}"
+
+        # WE counts the icon view as the desktop: clicks reach the wallpaper, focusing it isn't another app
+        width, height = ding.size
+        _point(ding, width // 2, height // 2)
+        _click(ding)
+        time.sleep(1.5)
+        text = log.read_text(errors="replace")
+        assert "LWE-CLICK down" in text and "LWE-CLICK up" in text, "the click on the desktop never reached the wallpaper"
+        assert ding.eval("global.display.focus_window?.get_gtk_application_id() ?? ''") == '"com.rastersoft.ding"'
+        assert _renders(log), "focusing the desktop icons paused the wallpaper"
+    finally:
+        process.terminate()
+        process.wait(10)

+ 93 - 0
tests/desktops/test_kde.py

@@ -0,0 +1,93 @@
+"""KDE Plasma: the KWin window-state script pauses only the affected output."""
+import time
+from pathlib import Path
+
+import pytest
+
+from conftest import REPO
+from desktops.runner import terminate
+
+
+def _engine(desktop, engine, log, output, *extra):
+    return desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root", output, "--silent",
+                           "--fps", "30", *extra, engine["wallpaper"]], log=log, env={"LWE_FRAME_STATS": "1"})
+
+
+def _renders(log, seconds=5):
+    before = Path(log).read_text(errors="replace").count("FRAME-STATS")
+    time.sleep(seconds)
+    return Path(log).read_text(errors="replace").count("FRAME-STATS") > before
+
+
+def _window(desktop, mode):
+    return desktop.spawn(f"{mode}-probe", ["python3", str(REPO / "tools/desktops/wayland_window.py"), mode])
+
+
+@pytest.fixture
+def kde(desktop_factory):
+    return desktop_factory("kde")
+
+
+@pytest.mark.parametrize("mode", ["maximized", "fullscreen"])
+def test_covering_window_pauses_rendering(kde, engine, tmp_path, mode):
+    log = tmp_path / "engine.log"
+    process = _engine(kde, engine, log, kde.output_names()[0])
+    probe = None
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render on KDE"
+        probe = _window(kde, mode)
+        time.sleep(4)
+        assert not _renders(log), f"still rendering under a {mode} window"
+        terminate([probe.pid])
+        probe = None
+        time.sleep(4)
+        assert _renders(log), f"rendering did not resume after the {mode} window"
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("pause_on_focus", [False, True])
+def test_focused_window(kde, engine, tmp_path, pause_on_focus):
+    log = tmp_path / "engine.log"
+    process = _engine(kde, engine, log, kde.output_names()[0], *(["--pause-on-focus"] if pause_on_focus else []))
+    probe = None
+    try:
+        time.sleep(8)
+        probe = _window(kde, "normal")
+        time.sleep(4)
+        if pause_on_focus:
+            assert not _renders(log), "--pause-on-focus kept rendering while another application had the focus"
+        else:
+            assert _renders(log), "a plain window paused the wallpaper"
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)
+
+
+def test_pause_is_per_output(desktop_factory, engine, tmp_path):
+    kde = desktop_factory("kde-dual")
+    outputs = kde.output_names()
+    assert len(outputs) == 2, outputs
+    logs = [tmp_path / f"engine-{output}.log" for output in outputs]
+    # one engine per screen, like we_manager
+    processes = [_engine(kde, engine, log, output) for log, output in zip(logs, outputs)]
+    probe = None
+    try:
+        time.sleep(8)
+        assert all(_renders(log) for log in logs)
+        probe = _window(kde, "maximized")
+        time.sleep(4)
+        rendering = [_renders(log) for log in logs]
+        assert rendering.count(False) == 1, f"a maximized window should pause exactly its own output: {rendering}"
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        for process in processes:
+            process.terminate()
+            process.wait(10)

+ 1 - 3
tests/desktops/test_wallpaper.py

@@ -5,9 +5,7 @@ import pytest
 from conftest import KINDS, Unsupported, changed_fraction
 
 # what is known not to work yet, each reason is a thing to fix: the test starts passing and strict xfail says so
-KNOWN_GAPS = {
-    "gnome": "Mutter has no layer-shell, the Wayland driver cannot create a background surface",
-}
+KNOWN_GAPS = {}
 
 # what the lab cannot show, not the engine
 LAB_LIMITS = {

+ 34 - 1
tools/desktops/__main__.py

@@ -8,14 +8,47 @@ from .session import KINDS, Session, Unsupported
 
 FEDORA_PACKAGES = REPO / "tools/desktops/rootfs-fedora.txt"
 ARCH_PACKAGES = REPO / "tools/desktops/rootfs-arch.txt"
+UBUNTU_PACKAGES = REPO / "tools/desktops/rootfs-ubuntu.txt"
+FEDORA_GNOME_PACKAGES = REPO / "tools/desktops/rootfs-fedora-gnome.txt"
+
+
+def _apt(archive):
+    """an Ubuntu install, from old-releases once the release is out of support"""
+    return ["sh", "-c", f"sed -i 's#http://[a-z]*.ubuntu.com#http://{archive}.ubuntu.com#' /etc/apt/sources.list "
+            "/etc/apt/sources.list.d/*.sources 2>/dev/null; apt-get update -qq && "
+            'DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@"', "apt"]
+
+
+def setup_ding():
+    """Desktop Icons NG for the GNOME 50 lab, from extensions.gnome.org (not packaged in Fedora)"""
+    import json
+    import urllib.request
+    import zipfile
+    from .session import DING_DIR
+    base = "https://extensions.gnome.org"
+    with urllib.request.urlopen(f"{base}/extension-info/?uuid=ding@rastersoft.com&shell_version=50") as reply:
+        info = json.load(reply)
+    archive = DING_DIR.parent / "ding.zip"
+    archive.parent.mkdir(parents=True, exist_ok=True)
+    urllib.request.urlretrieve(base + info["download_url"], archive)
+    with zipfile.ZipFile(archive) as extension:
+        extension.extractall(DING_DIR)
+    subprocess.run(["glib-compile-schemas", str(DING_DIR / "schemas")], check=True)
+    print(f"Desktop Icons NG {info.get('version')} in {DING_DIR}")
 
 
 def setup(which):
     """the rootfs a session runs in where its programs are not installed natively"""
+    if which == "ding":
+        return setup_ding()
     script = str(REPO / "tools/distro_rootfs.sh")
     image, packages, install = {
         "fedora": ("fedora:44", FEDORA_PACKAGES, ["dnf", "install", "-y", "--setopt=install_weak_deps=False"]),
         "arch": ("archlinux:latest", ARCH_PACKAGES, ["pacman", "-Syu", "--noconfirm", "--needed", "--disable-sandbox"]),
+        **{f"gnome{shell}": (f"ubuntu:{release}", UBUNTU_PACKAGES, _apt(archive)) for shell, release, archive in (
+            ("45", "23.10", "old-releases"), ("46", "24.04", "archive"), ("47", "24.10", "old-releases"),
+            ("48", "25.04", "archive"))},
+        "gnome49": ("fedora:43", FEDORA_GNOME_PACKAGES, ["dnf", "install", "-y", "--setopt=install_weak_deps=False"]),
     }[which]
     root = ROOTFS[which]
     if not root.is_dir():
@@ -36,7 +69,7 @@ def main():
     sub = parser.add_subparsers(dest="command", required=True)
     sub.add_parser("list", help="the sessions and where each would run")
     sub.add_parser("setup", help="create the rootfs for sessions that are not installed natively").add_argument(
-        "which", choices=("fedora", "arch"))
+        "which", choices=("fedora", "arch", "gnome45", "gnome46", "gnome47", "gnome48", "gnome49", "ding"))
     start = sub.add_parser("start", help="start a session")
     start.add_argument("name", choices=sorted(KINDS))
     start.add_argument("--size", default="1920x1080")

+ 11 - 0
tools/desktops/gnome-lab-extension/lwe-lab@desktops.test/extension.js

@@ -0,0 +1,11 @@
+import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
+
+export default class LabExtension extends Extension {
+    enable() {
+        global.context.unsafe_mode = true;
+    }
+
+    disable() {
+        global.context.unsafe_mode = false;
+    }
+}

+ 6 - 0
tools/desktops/gnome-lab-extension/lwe-lab@desktops.test/metadata.json

@@ -0,0 +1,6 @@
+{
+  "uuid": "lwe-lab@desktops.test",
+  "name": "lwe lab helper",
+  "description": "Test sessions only: unsafe mode, so the screenshot and Eval D-Bus methods answer the lab's tools",
+  "shell-version": ["45", "46", "47", "48", "49", "50"]
+}

+ 58 - 0
tools/desktops/kwin_fake_input.c

@@ -0,0 +1,58 @@
+/* Drives KWin's pointer via org_kde_kwin_fake_input (needs KWIN_WAYLAND_NO_PERMISSION_CHECKS).
+ * Usage: kwin_fake_input move X Y | down BUTTON | up BUTTON ...   (evdev codes, 272 = left) */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wayland-client.h>
+
+#include "fake-input-client-protocol.h"
+
+static struct org_kde_kwin_fake_input* fake_input;
+
+static void global (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
+    if (strcmp (interface, org_kde_kwin_fake_input_interface.name) == 0) {
+	fake_input = wl_registry_bind (registry, name, &org_kde_kwin_fake_input_interface, version < 4 ? version : 4);
+    }
+}
+
+static void global_remove (void* data, struct wl_registry* registry, uint32_t name) { }
+
+static const struct wl_registry_listener registry_listener = { global, global_remove };
+
+int main (int argc, char** argv) {
+    struct wl_display* display = wl_display_connect (NULL);
+
+    if (!display) {
+	fprintf (stderr, "no Wayland display\n");
+	return 1;
+    }
+
+    wl_registry_add_listener (wl_display_get_registry (display), &registry_listener, NULL);
+    wl_display_roundtrip (display);
+
+    if (!fake_input) {
+	fprintf (stderr, "the compositor offers no org_kde_kwin_fake_input\n");
+	return 1;
+    }
+
+    org_kde_kwin_fake_input_authenticate (fake_input, "lwe-lab", "desktop tests");
+
+    for (int i = 1; i < argc; i++) {
+	if (strcmp (argv[i], "move") == 0 && i + 2 < argc) {
+	    org_kde_kwin_fake_input_pointer_motion_absolute (
+		fake_input, wl_fixed_from_double (atof (argv[i + 1])), wl_fixed_from_double (atof (argv[i + 2]))
+	    );
+	    i += 2;
+	} else if ((strcmp (argv[i], "down") == 0 || strcmp (argv[i], "up") == 0) && i + 1 < argc) {
+	    org_kde_kwin_fake_input_button (fake_input, atoi (argv[i + 1]), strcmp (argv[i], "down") == 0);
+	    i += 1;
+	} else {
+	    fprintf (stderr, "unknown command %s\n", argv[i]);
+	    return 1;
+	}
+	wl_display_roundtrip (display);
+    }
+
+    wl_display_disconnect (display);
+    return 0;
+}

+ 2 - 0
tools/desktops/rootfs-fedora-gnome.txt

@@ -0,0 +1,2 @@
+gnome-shell gjs glib2 dbus-daemon dconf gsettings-desktop-schemas gtk4 python3-gobject python3-dbus
+python3-dbusmock wayland-utils

+ 2 - 0
tools/desktops/rootfs-ubuntu.txt

@@ -0,0 +1,2 @@
+gnome-shell gjs libglib2.0-bin dbus dbus-x11 dconf-service dconf-cli gsettings-desktop-schemas
+gir1.2-gtk-4.0 python3-gi python3-dbus python3-dbusmock wayland-utils xwayland gnome-shell-extension-desktop-icons-ng

+ 7 - 1
tools/desktops/runner.py

@@ -16,6 +16,12 @@ ROOTFS_DIR = Path(os.environ.get("LWE_ROOTFS_DIR", Path.home() / ".local/share/d
 ROOTFS = {
     "fedora": Path(os.environ.get("LWE_FEDORA_ROOTFS", ROOTFS_DIR / "fedora-44-sys")),
     "arch": Path(os.environ.get("LWE_ARCH_ROOTFS", ROOTFS_DIR / "arch-compositors")),
+    # older GNOME Shells for the gnome45..gnome49 sessions
+    "gnome45": ROOTFS_DIR / "ubuntu-23.10-gnome",
+    "gnome46": ROOTFS_DIR / "ubuntu-24.04-gnome",
+    "gnome47": ROOTFS_DIR / "ubuntu-24.10-gnome",
+    "gnome48": ROOTFS_DIR / "ubuntu-25.04-gnome",
+    "gnome49": ROOTFS_DIR / "fedora-43-gnome",
 }
 BIN_DIRS = ("usr/bin", "usr/sbin", "usr/libexec", "bin", "sbin")
 SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
@@ -26,7 +32,7 @@ def proot_binary():
 
 
 class Userland:
-    """native, or the programs of the fedora or arch rootfs"""
+    """native, or the programs of one of the ROOTFS"""
 
     def __init__(self, name):
         self.name = name

+ 156 - 11
tools/desktops/session.py

@@ -27,6 +27,9 @@ class Session:
     # short, Hyprland's IPC socket path has to fit in 108 bytes
     short = ""
     needs = ()
+    userlands = ("native", "fedora", "arch")
+    # downloaded by setup
+    requires = ()
     sysbus = False
     desktop = ""
 
@@ -71,7 +74,9 @@ class Session:
         result = {}
         for name, kind in KINDS.items():
             try:
-                result[name] = Userland.pick(*kind.needs).name
+                result[name] = Userland.pick(*kind.needs, prefer=kind.userlands).name
+                if not all(Path(path).exists() for path in kind.requires):
+                    result[name] = None
             except RuntimeError:
                 result[name] = None
         return result
@@ -92,7 +97,7 @@ class Session:
         shutil.rmtree(self.dir, ignore_errors=True)
         self.run_dir.mkdir(parents=True, mode=0o700)
         self.home.mkdir(parents=True)
-        self.userland = Userland.pick(*self.needs)
+        self.userland = Userland.pick(*self.needs, prefer=self.userlands)
         try:
             self._start_bus()
             if self.sysbus:
@@ -422,20 +427,47 @@ class Kde(Session):
         env = {
             "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": "6",
             "QT_QPA_PLATFORM": "wayland", "KWIN_SCREENSHOT_NO_PERMISSION_CHECKS": "1",
+            # for kwin_fake_input.c
+            "KWIN_WAYLAND_NO_PERMISSION_CHECKS": "1",
         }
         self.session_env.update(env)
         self.spawn("kwin", ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height),
-                            "--socket", "lwe-kde", "--no-lockscreen", "--xwayland"], env)
+                            "--output-count", str(self.outputs), "--socket", "lwe-kde", "--no-lockscreen",
+                            "--xwayland"], env)
         self.session_env["WAYLAND_DISPLAY"] = "lwe-kde"
         self.wait_socket("lwe-kde")
         wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
 
+    def pointer(self, *commands):
+        """KWin's pointer through fake input: "move", x, y (logical, global), "down"/"up", evdev button"""
+        tool = self.dir / "kwin_fake_input"
+        if not tool.exists():
+            build = self.dir / "fake-input"
+            build.mkdir(exist_ok=True)
+            xml = "/usr/share/plasma-wayland-protocols/fake-input.xml"
+            for mode, out in (("client-header", "fake-input-client-protocol.h"), ("private-code", "fake-input.c")):
+                subprocess.run(["wayland-scanner", mode, xml, str(build / out)], check=True)
+            subprocess.run(["cc", "-o", str(tool), str(REPO / "tools/desktops/kwin_fake_input.c"), str(build / "fake-input.c"),
+                            f"-I{build}", "-lwayland-client", "-lm"], check=True)
+        result = self.run([str(tool), *map(str, commands)])
+        if result.returncode != 0:
+            raise RuntimeError(f"kwin_fake_input: {result.stderr.strip()}")
+
     def _shot(self, path):
         result = self.run(["python3", str(REPO / "tools/desktops/kwin_shot.py"), str(path)])
         if result.returncode != 0:
             raise RuntimeError(f"kwin_shot failed: {result.stderr.strip()}")
 
 
+class KdeDual(Kde):
+    """KWin's virtual backend with two outputs, for what happens per output"""
+
+    name, short = "kde-dual", "k2"
+
+    def __init__(self, size=(1280, 720), outputs=2):
+        super().__init__(size, outputs)
+
+
 class Gnome(Session):
     """GNOME Shell as a headless Wayland display server"""
 
@@ -443,22 +475,135 @@ class Gnome(Session):
     needs = ("gnome-shell",)
     sysbus = True
 
+    # lab extension enables unsafe mode for Screenshot/Eval; the build's copy has the helper in it
+    EXTENSIONS = (REPO / "tools/desktops/gnome-lab-extension/lwe-lab@desktops.test",
+                  Path(os.environ.get("LWE_BUILD_OUTPUT", REPO / "build/output"))
+                  / "gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io")
+
+    # (uuid, folder to link, or None if installed in the userland)
+    extra_extensions = ()
+    # put on ~/Desktop, a trailing / makes a folder
+    desktop_files = ()
+
+    def _install_extensions(self):
+        target = self.home / ".local/share/gnome-shell/extensions"
+        target.mkdir(parents=True, exist_ok=True)
+        for source in self.EXTENSIONS:
+            (target / source.name).symlink_to(source)
+        for uuid, folder in self.extra_extensions:
+            if folder is not None:
+                (target / uuid).symlink_to(folder)
+        for name in self.desktop_files:
+            path = self.home / "Desktop" / name
+            path.parent.mkdir(parents=True, exist_ok=True)
+            if name.endswith("/"):
+                path.mkdir(exist_ok=True)
+            else:
+                path.write_text("lab\n")
+        uuids = ", ".join([f"'{source.name}'" for source in self.EXTENSIONS] + [f"'{uuid}'" for uuid, _ in self.extra_extensions])
+        for key, value in (("enabled-extensions", f"[{uuids}]"), ("disable-user-extensions", "false")):
+            result = self.run(["gsettings", "set", "org.gnome.shell", key, value])
+            if result.returncode != 0:
+                raise RuntimeError(f"gsettings {key}: {result.stderr.strip()}")
+
     def _launch(self):
         width, height = self.size
         env = {"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "GNOME", "XDG_SESSION_DESKTOP": "gnome",
                "GNOME_SHELL_SESSION_MODE": "user"}
         self.session_env.update(env)
-        self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--virtual-monitor", f"{width}x{height}",
-                             "--wayland-display", "lwe-gnome"], env)
+        self._install_extensions()
+        monitors = [arg for _ in range(self.outputs) for arg in ("--virtual-monitor", f"{width}x{height}")]
+        # no Xwayland, mutter could pick the real desktop's display number
+        self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--no-x11", *monitors, "--wayland-display",
+                             "lwe-gnome"], env)
         self.session_env["WAYLAND_DISPLAY"] = "lwe-gnome"
         self.wait_socket("lwe-gnome")
-        # mutter picks the first free X display and says which, it can be the number of the desktop's own display
-        log = self.dir / "shell.log"
-        found = wait_for("Xwayland", lambda: re.search(r"public X11 display :(\d+)", log.read_text()) if log.exists() else None, 30)
-        self.info["xwayland_display"] = found.group(1)
+        wait_for("the lab extension", self._unsafe_mode, 40)
+        wait_for("the overview to close", lambda: self.eval("Main.overview.hide(); Main.overview.visible") == "false", 20)
+
+    def _unsafe_mode(self):
+        reply = self.eval("global.context.unsafe_mode")
+        return reply == "true"
+
+    def eval(self, script):
+        """runs JS inside the Shell (unsafe mode only), its JSON result or None"""
+        result = self.run(["gdbus", "call", "--session", "--dest", "org.gnome.Shell", "--object-path", "/org/gnome/Shell",
+                           "--method", "org.gnome.Shell.Eval", script], timeout=20)
+        found = re.match(r"\((true|false), '(.*)'\)$", result.stdout.strip(), re.S)
+        if not found or found.group(1) != "true":
+            return None
+        return found.group(2)
 
     def _shot(self, path):
-        raise Unsupported("GNOME Shell only hands out screenshots to its own tools, capturing needs ScreenCast over PipeWire")
+        result = self.run(["gdbus", "call", "--session", "--dest", "org.gnome.Shell", "--object-path",
+                           "/org/gnome/Shell/Screenshot", "--method", "org.gnome.Shell.Screenshot.Screenshot",
+                           "false", "false", str(path)], timeout=30)
+        if "(true," not in result.stdout:
+            raise RuntimeError(f"Shell screenshot failed: {result.stdout.strip()} {result.stderr.strip()}")
+
+
+class Gnome46(Gnome):
+    """GNOME Shell 46 from the Ubuntu 24.04 rootfs (setup gnome46): no Meta.Window.set_type, the helper path"""
+
+    name, short, desktop = "gnome46", "g4", "GNOME"
+    userlands = ("gnome46",)
+
+
+class Gnome45(Gnome):
+    """GNOME Shell 45 (Ubuntu 23.10): no desktop windows for Wayland clients, the wallpaper is a bottom layer window"""
+
+    name, short, desktop = "gnome45", "g5", "GNOME"
+    userlands = ("gnome45",)
+
+
+class Gnome47(Gnome):
+    """GNOME Shell 47 (Ubuntu 24.10), the helper path"""
+
+    name, short, desktop = "gnome47", "g7", "GNOME"
+    userlands = ("gnome47",)
+
+
+class Gnome48(Gnome):
+    """GNOME Shell 48 (Ubuntu 25.04), the helper path"""
+
+    name, short, desktop = "gnome48", "g8", "GNOME"
+    userlands = ("gnome48",)
+
+
+class Gnome49(Gnome):
+    """GNOME Shell 49 (Fedora 43), the first with Meta.Window.set_type"""
+
+    name, short, desktop = "gnome49", "g9", "GNOME"
+    userlands = ("gnome49",)
+
+
+# DING for GNOME 50 comes from `setup ding`
+DING_DIR = Path.home() / ".local/share/lwe-lab/ding50/ding@rastersoft.com"
+
+
+class GnomeDing(Gnome):
+    """GNOME 50 with Desktop Icons NG, whose desktop window shares the desktop layer with the wallpaper's"""
+
+    name, short = "gnome-ding", "gd"
+    extra_extensions = (("ding@rastersoft.com", DING_DIR),)
+    desktop_files = ("notes.txt", "todo.txt", "Pictures/")
+    requires = (DING_DIR,)
+
+
+class Gnome46Ding(Gnome46):
+    """GNOME 46 with Ubuntu's Desktop Icons NG package"""
+
+    name, short = "gnome46-ding", "g4d"
+    extra_extensions = (("ding@rastersoft.com", None),)
+    desktop_files = GnomeDing.desktop_files
+
+
+class Gnome45Ding(Gnome45):
+    """GNOME 45 with Ubuntu's Desktop Icons NG, both windows in the bottom layer"""
+
+    name, short = "gnome45-ding", "g5d"
+    extra_extensions = (("ding@rastersoft.com", None),)
+    desktop_files = GnomeDing.desktop_files
 
 
 class X11(Session):
@@ -591,5 +736,5 @@ WM_CLASSES = [
 
 KINDS = {
     kind.name: kind
-    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, Gnome, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
+    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
 }

+ 36 - 0
tools/desktops/wayland_window.py

@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""GTK 4 Wayland window (normal/maximized/fullscreen) until killed, for labs without Xwayland."""
+import os
+import signal
+import sys
+
+os.environ["GDK_BACKEND"] = "wayland"
+
+import gi  # noqa: E402
+
+gi.require_version("Gtk", "4.0")
+from gi.repository import GLib, Gtk  # noqa: E402
+
+mode = sys.argv[1] if len(sys.argv) > 1 else "fullscreen"
+
+
+def activate(app):
+    window = Gtk.ApplicationWindow(application=app, title=f"lwe-{mode}-probe")
+    window.set_default_size(640, 480)
+    if mode == "maximized":
+        window.maximize()
+    elif mode == "fullscreen":
+        window.fullscreen()
+    window.present()
+
+
+app = Gtk.Application(application_id="org.lwe.Probe")
+app.connect("activate", activate)
+try:
+    from gi.repository import GLibUnix  # noqa: E402
+
+    GLibUnix.signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, app.quit)
+except (ImportError, AttributeError):
+    # older PyGObject (Ubuntu 24.04) has only the GLib one
+    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, app.quit)
+app.run([])

+ 1 - 1
tools/package_release.sh

@@ -37,7 +37,7 @@ mkdir -p "$pkg"
 cd "$work/install"
 cp -a linux-wallpaperengine linux-wallpaperengine-web-helper liblinux-wallpaperengine-lib.so libcef.so libEGL.so \
     libGLESv2.so libvk_swiftshader.so vk_swiftshader_icd.json chrome-sandbox icudtl.dat v8_context_snapshot.bin \
-    ./*.pak locales "$pkg/"
+    ./*.pak locales gnome-shell-extension "$pkg/"
 
 # GNUInstallDirs puts kissfft in lib64 on Fedora and lib elsewhere, the runpath covers both
 kissfft=(lib*/libkissfft-float.so*)