Forráskód Böngészése

Desktop icons over the wallpaper on XFCE and COSMIC, WE frame limiter, light shaft and volumetrics parity, videosequence playlists

- XFCE: the icons of xfdesktop stay visible above the wallpaper (the window is turned into a key colour, read through Composite/Damage and drawn over the frame, the settings are restored after a crash)
- COSMIC: default layer is background so cosmic-files' icons are not covered, the pointer comes from the compositor's cursor capture (ext-image-capture-source / ext-image-copy-capture)
- --frame-limiter budget|fixed: WE's one second frame budget ported from the main loop, FRAME-STATS now shows median, p99 and jitter
- Playlists: videosequence plays a video to its end before moving on, beginfirst + playintro keep the first item out of the rotation, a single item keeps looping
- Shape layers with point0..3 (light shafts) are drawn as the quad through those points, like WE
- Volumetrics jitter and march follow WE's fxc/DXVK operation order, bit exact against a replay of live WE
- A global pause stops every video player and resumes in place
- Automute detector no longer blocks the render loop when the audio server stops answering
- GNOME session helper shared with COSMIC detection, Xcomposite/Xdamage added to the build deps
- Release test rig: desktop icons check and matrix, extension updater for golden disks, video sequence and pause probes, new unit tests (FramePacer, AutomuteDetector)
UwU 1 hónapja
szülő
commit
7bf52ed6
48 módosított fájl, 3022 hozzáadás és 86 törlés
  1. 4 4
      .github/workflows/cmake.yml
  2. 15 2
      CMakeLists.txt
  3. 7 9
      README.md
  4. 109 0
      protocols/ext-image-capture-source-v1.xml
  5. 456 0
      protocols/ext-image-copy-capture-v1.xml
  6. 32 4
      src/WallpaperEngine/Application/ApplicationContext.cpp
  7. 8 0
      src/WallpaperEngine/Application/ApplicationContext.h
  8. 78 0
      src/WallpaperEngine/Application/FramePacer.h
  9. 69 7
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  10. 4 0
      src/WallpaperEngine/Application/WallpaperApplication.h
  11. 47 9
      src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp
  12. 4 0
      src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h
  13. 8 2
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  14. 1 0
      src/WallpaperEngine/Desktop/GnomeShell.h
  15. 11 1
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  16. 74 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  17. 11 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  18. 627 0
      src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp
  19. 71 0
      src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.h
  20. 68 0
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  21. 10 0
      src/WallpaperEngine/Render/Drivers/Output/X11Output.h
  22. 35 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  23. 7 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  24. 52 0
      src/WallpaperEngine/Render/Objects/CImage.cpp
  25. 1 0
      src/WallpaperEngine/Render/Objects/CImage.h
  26. 37 7
      src/WallpaperEngine/Render/RenderContext.cpp
  27. 68 22
      src/WallpaperEngine/Render/Volumetrics.cpp
  28. 8 0
      src/WallpaperEngine/Render/Wallpapers/CVideo.cpp
  29. 4 0
      src/WallpaperEngine/Render/Wallpapers/CVideo.h
  30. 438 0
      src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp
  31. 79 0
      src/WallpaperEngine/Testing/Cases/FramePacer.cpp
  32. 11 2
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  33. 2 0
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h
  34. 42 0
      tools/check_video_sequence.sh
  35. 14 4
      tools/linuxvm/RELEASE_TESTING.md
  36. 1 1
      tools/linuxvm/clean_install_check.sh
  37. 116 0
      tools/linuxvm/desktop_icons_check.sh
  38. 89 0
      tools/linuxvm/desktop_icons_matrix.sh
  39. 2 1
      tools/linuxvm/profiles/steamdeck.sh
  40. 12 3
      tools/linuxvm/release_check.sh
  41. 1 1
      tools/linuxvm/update_check.sh
  42. 7 5
      tools/linuxvm/update_golden_extension.sh
  43. 1 1
      tools/linuxvm/wem_check.sh
  44. 3 0
      tools/wecompare/README.md
  45. 115 0
      tools/wecompare/live_trail_probe.py
  46. 31 0
      tools/wecompare/wine/ours_pause.py
  47. 17 0
      tools/wecompare/wine/rdscripts/rd_disasm.py
  48. 115 0
      tools/wecompare/wine/we_pause.sh

+ 4 - 4
.github/workflows/cmake.yml

@@ -97,7 +97,7 @@ jobs:
           languages: 'cpp'
 
       - name: Install dependencies
-        run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libdbus-1-dev libnode-dev wayland-scanner++ wayland-protocols libwayland-dev
+        run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libdbus-1-dev libnode-dev wayland-scanner++ wayland-protocols libwayland-dev
 
       - name: Configure CMake
         run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{matrix.build_type}} -DDISABLE_KDE_FEATURES=${{matrix.disable_kde}} -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache
@@ -233,7 +233,7 @@ jobs:
             image: fedora:44
             install: >-
               dnf -y install git gcc gcc-c++ make cmake pkgconf-pkg-config binutils tar gzip
-              libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel libXxf86vm-devel
+              libXrandr-devel libXinerama-devel libXcomposite-devel libXdamage-devel libXcursor-devel libXi-devel libXxf86vm-devel
               mesa-libGL-devel mesa-libEGL-devel glew-devel freeglut-devel sdl2-compat-devel lz4-devel
               zlib-ng-compat-devel ffmpeg-free-devel glm-devel glfw-devel mpv-devel pulseaudio-libs-devel
               freetype-devel harfbuzz-devel dbus-devel wayland-devel wayland-protocols-devel fftw-devel gmp-devel
@@ -292,7 +292,7 @@ jobs:
           DEBIAN_FRONTEND: noninteractive
         run: >-
           apt-get update && apt-get -y install --no-install-recommends git ca-certificates curl build-essential
-          cmake pkg-config patchelf python3 binutils libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev
+          cmake pkg-config patchelf python3 binutils libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev
           libgl-dev libegl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev
           libavutil-dev libswscale-dev libswresample-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev
           libpulse-dev libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libnode-dev libwayland-dev
@@ -446,7 +446,7 @@ jobs:
           key: ${{ github.job }}-ubuntu-24.04-${{ matrix.build_type }}
 
       - name: Install dependencies
-        run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libdbus-1-dev libnode-dev wayland-scanner++ wayland-protocols libwayland-dev
+        run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libdbus-1-dev libnode-dev wayland-scanner++ wayland-protocols libwayland-dev
 
       - name: Configure CMake
         # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.

+ 15 - 2
CMakeLists.txt

@@ -219,7 +219,8 @@ if(WAYLAND_SUPPORT_FOUND)
     # COSMIC's window state: cosmic-comp has no wlr foreign toplevel, it speaks ext-foreign-toplevel-list plus its own
     # toplevel info extension (which refers to the workspace interfaces)
     set(COSMIC_PROTOCOL_SOURCES)
-    foreach(proto cosmic-toplevel-info-unstable-v1 cosmic-workspace-unstable-v1 ext-foreign-toplevel-list-v1 ext-workspace-v1)
+    foreach(proto cosmic-toplevel-info-unstable-v1 cosmic-workspace-unstable-v1 ext-foreign-toplevel-list-v1 ext-workspace-v1
+            ext-image-capture-source-v1 ext-image-copy-capture-v1)
         add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/${proto}-protocol.h
             COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/${proto}.xml ${WAYLAND_OUTPUT_DIR}/${proto}-protocol.h)
         add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/${proto}-protocol.c
@@ -315,7 +316,17 @@ if(X11_SUPPORT_FOUND)
         ${X11_LIBRARIES}
         ${X11_Xrandr_LIB}
         ${X11_Xext_LIB})
+    if(X11_Xcomposite_FOUND AND X11_Xdamage_FOUND)
+        set(X11_ICONS_SOURCES
+            src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp
+            src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.h)
+        set(X11_LIBRARIES ${X11_LIBRARIES} ${X11_Xcomposite_LIB} ${X11_Xdamage_LIB})
+        add_compile_definitions(HAVE_X11_DESKTOP_ICONS)
+    else()
+        message(WARNING "Xcomposite or Xdamage is missing, desktop icons stay under the wallpaper on XFCE")
+    endif()
     set(X11_SOURCES
+        ${X11_ICONS_SOURCES}
         src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
         src/WallpaperEngine/Render/Drivers/Output/X11Output.h
         src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
@@ -741,6 +752,7 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/DmabufChannel.cpp
         src/WallpaperEngine/Testing/Cases/DynamicValueListeners.cpp
         src/WallpaperEngine/Testing/Cases/Example.cpp
+        src/WallpaperEngine/Testing/Cases/FramePacer.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.h
         src/WallpaperEngine/Testing/Input/TestingMouseInput.cpp
@@ -790,7 +802,8 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/ScriptWatchdog.cpp
         src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
         src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
-        src/WallpaperEngine/Testing/Cases/SplitLayout.cpp)
+        src/WallpaperEngine/Testing/Cases/SplitLayout.cpp
+        src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp)
 endif()
 
 # the one file that derives from a V8 class: libnode is built without RTTI and exports no typeinfo of V8's classes

+ 7 - 9
README.md

@@ -99,31 +99,31 @@ Control:
 Its `libnode-dev` (Node.js 12) is too old for the scripting and its FFmpeg 4.4 too old for the audio code, use the portable build (see Installing) or 24.04.
 ```bash
 sudo apt-get update
-sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libwayland-dev wayland-protocols libegl1-mesa-dev
+sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libwayland-dev wayland-protocols libegl1-mesa-dev
 ```
 
 ### Ubuntu 24.04
 ```bash
 sudo apt-get update
-sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libwayland-dev wayland-protocols libegl1-mesa-dev libnode-dev
+sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libwayland-dev wayland-protocols libegl1-mesa-dev libnode-dev
 ```
 
 ### Fedora 44
 ```bash
-sudo dnf install gcc g++ cmake pkg-config libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel mesa-libGL-devel mesa-libEGL-devel glew-devel freeglut-devel SDL2-devel lz4-devel ffmpeg-free-devel libXxf86vm-devel glm-devel glfw-devel mpv-devel pulseaudio-libs-devel fftw-devel freetype-devel harfbuzz-devel gmp-devel dbus-devel wayland-devel wayland-protocols-devel nodejs24-devel
+sudo dnf install gcc g++ cmake pkg-config libXrandr-devel libXinerama-devel libXcomposite-devel libXdamage-devel libXcursor-devel libXi-devel mesa-libGL-devel mesa-libEGL-devel glew-devel freeglut-devel SDL2-devel lz4-devel ffmpeg-free-devel libXxf86vm-devel glm-devel glfw-devel mpv-devel pulseaudio-libs-devel fftw-devel freetype-devel harfbuzz-devel gmp-devel dbus-devel wayland-devel wayland-protocols-devel nodejs24-devel
 ```
 If you already have Node.js 22, use `nodejs22-devel` instead, Fedora's nodejs -devel packages can't be installed side by side. `ffmpeg` and `ffmpeg-free` conflict, with RPM Fusion's full ffmpeg install its `ffmpeg-devel` instead.
 
 ### Arch Linux
 ```bash
-sudo pacman -S --needed git base-devel cmake pkg-config glew freeglut sdl2 lz4 ffmpeg glm glfw mpv libpulse fftw freetype2 harfbuzz dbus libxrandr libxinerama libxcursor libxi libxxf86vm wayland wayland-protocols mesa gmp nss at-spi2-core libcups libxcomposite libxdamage libxkbcommon pango cairo alsa-lib libdrm libxshmfence
+sudo pacman -S --needed git base-devel cmake pkg-config glew freeglut sdl2 lz4 ffmpeg glm glfw mpv libpulse fftw freetype2 harfbuzz dbus libxrandr libxinerama libxcomposite libxdamage libxcursor libxi libxxf86vm wayland wayland-protocols mesa gmp nss at-spi2-core libcups libxcomposite libxdamage libxkbcommon pango cairo alsa-lib libdrm libxshmfence
 ```
 The second half of that list is what the bundled CEF links against, a desktop install usually has it already. Arch's `nodejs` package has the headers but no `libnode`, the AUR's `libnode` package (a Node.js built with `--shared`) provides it, e.g. `paru -S libnode`.
 
 ### ALT Linux
 ```bash
 sudo epm update
-sudo epm install gcc-c++ make cmake libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel libGL-devel libGLEW-devel freeglut-devel libSDL2-devel liblz4-devel libavcodec-devel libavformat-devel libavutil-devel libswscale-devel libXxf86vm-devel libglm-devel libglfw3-devel libmpv-devel mpv libpulseaudio-devel libpulseaudio libfftw3-devel libpng-devel libffi-devel libswresample-devel libgmpxx-devel libfreetype-devel libharfbuzz-devel libdbus-devel
+sudo epm install gcc-c++ make cmake libXrandr-devel libXinerama-devel libXcomposite-devel libXdamage-devel libXcursor-devel libXi-devel libGL-devel libGLEW-devel freeglut-devel libSDL2-devel liblz4-devel libavcodec-devel libavformat-devel libavutil-devel libswscale-devel libXxf86vm-devel libglm-devel libglfw3-devel libmpv-devel mpv libpulseaudio-devel libpulseaudio libfftw3-devel libpng-devel libffi-devel libswresample-devel libgmpxx-devel libfreetype-devel libharfbuzz-devel libdbus-devel
 ```
 
 ## Installing
@@ -278,6 +278,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--speed <factor>` | Global playback speed multiplier |
 | `--hwdec <backend>` | mpv hardware decoding for videos: `auto` (default), `no`, `vaapi-copy`, `nvdec-copy`, ... Try `no` if videos crash on NVIDIA |
 | `--web-frames <auto\|shm\|dmabuf>` | how web wallpapers hand their frames over: `dmabuf` shares the browser's GPU buffers (Wayland and X11, much less CPU at high resolutions), `shm` reads every frame back, `auto` (default) picks dmabuf where it works and falls back to shm |
+| `--frame-limiter <budget\|fixed>` | how the FPS limit paces frames: `budget` (default, like Wallpaper Engine) shares a one second budget between the frames of that second, `fixed` sleeps the same time after every frame. Only matters for things that count whole frames, like rope trails |
 | `--video-start <time>`, `--video-end <time>` | Video wallpapers only: loop just this part of the video, in seconds, `m:ss` or `h:mm:ss` (either one alone leaves that side at the video's start/end) |
 | `--video-segments <start-end,...>` | Video wallpapers only: play these parts one after the other and skip everything between them, e.g. `"2:00-3:00,4:00-5:00"`; an empty side is the video's start/end (`"4:00-"`) |
 | `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control`, `/tmp/lwe-control-<uid>` without it |
@@ -404,6 +405,7 @@ linux-wallpaperengine --disable-object Clock --disable-object 3 2370927443
 - 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.
+- XFCE (xfdesktop) draws an opaque desktop window over the root window, which the wallpaper goes above, so its icons would be hidden. The engine keeps them: while it runs, xfdesktop's background is set to black (xfconf, `image-style`/`color-style`/`rgba1` of every monitor and workspace, the old values are saved and put back on exit, also after a crash), the window's pixels are read through the Composite extension whenever it changes and everything that is not black is drawn over the wallpaper frame. xfdesktop keeps handling every click. Needs the Composite and Damage extensions (always there on Xorg); `LWE_DESKTOP_ICONS=off` leaves xfdesktop alone and the icons under the wallpaper. A desktop that never picked a wallpaper gets `xfce-shapes.svg` (or the first of xfce's own pictures) afterwards, xfdesktop's built-in default can't be set again. Other desktops with an opaque desktop window (MATE, LXQt) still hide their icons.
 
 ## Limitations
 
@@ -423,10 +425,6 @@ Text:
 
 - Without Segoe UI Emoji installed (see Fonts), emoji come from the Twemoji font in Wallpaper Engine's assets and are drawn as their colour bitmap; Wallpaper Engine itself draws nothing for them without that font.
 
-Scripting (SceneScript):
-
-- Property scripts inside a `createLayer` config aren't registered.
-
 ## Credits
 
 - [RePKG](https://github.com/notscuffed/repkg) - texture flag insights

+ 109 - 0
protocols/ext-image-capture-source-v1.xml

@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="ext_image_capture_source_v1">
+  <copyright>
+    Copyright © 2022 Andri Yngvason
+    Copyright © 2024 Simon Ser
+
+    Permission is hereby granted, free of charge, to any person obtaining a
+    copy of this software and associated documentation files (the "Software"),
+    to deal in the Software without restriction, including without limitation
+    the rights to use, copy, modify, merge, publish, distribute, sublicense,
+    and/or sell copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice (including the next
+    paragraph) shall be included in all copies or substantial portions of the
+    Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+    DEALINGS IN THE SOFTWARE.
+  </copyright>
+
+  <description summary="opaque image capture source objects">
+    This protocol serves as an intermediary between capturing protocols and
+    potential image capture sources such as outputs and toplevels.
+
+    This protocol may be extended to support more image capture sources in the
+    future, thereby adding those image capture sources to other protocols that
+    use the image capture source object without having to modify those
+    protocols.
+
+    Warning! The protocol described in this file is currently in the testing
+    phase. Backward compatible changes may be added together with the
+    corresponding interface version bump. Backward incompatible changes can
+    only be done by creating a new major version of the extension.
+  </description>
+
+  <interface name="ext_image_capture_source_v1" version="1" frozen="true">
+    <description summary="opaque image capture source object">
+      The image capture source object is an opaque descriptor for a capturable
+      resource.  This resource may be any sort of entity from which an image
+      may be derived.
+
+      Note, because ext_image_capture_source_v1 objects are created from multiple
+      independent factory interfaces, the ext_image_capture_source_v1 interface is
+      frozen at version 1.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="delete this object">
+        Destroys the image capture source. This request may be sent at any time
+        by the client.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="ext_output_image_capture_source_manager_v1" version="1">
+    <description summary="image capture source manager for outputs">
+      A manager for creating image capture source objects for wl_output objects.
+    </description>
+
+    <request name="create_source">
+      <description summary="create source object for output">
+        Creates a source object for an output. Images captured from this source
+        will show the same content as the output. Some elements may be omitted,
+        such as cursors and overlays that have been marked as transparent to
+        capturing.
+      </description>
+      <arg name="source" type="new_id" interface="ext_image_capture_source_v1"/>
+      <arg name="output" type="object" interface="wl_output"/>
+    </request>
+
+    <request name="destroy" type="destructor">
+      <description summary="delete this object">
+        Destroys the manager. This request may be sent at any time by the client
+        and objects created by the manager will remain valid after its
+        destruction.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="ext_foreign_toplevel_image_capture_source_manager_v1" version="1">
+    <description summary="image capture source manager for foreign toplevels">
+      A manager for creating image capture source objects for
+      ext_foreign_toplevel_handle_v1 objects.
+    </description>
+
+    <request name="create_source">
+      <description summary="create source object for foreign toplevel">
+        Creates a source object for a foreign toplevel handle. Images captured
+        from this source will show the same content as the toplevel.
+      </description>
+      <arg name="source" type="new_id" interface="ext_image_capture_source_v1"/>
+      <arg name="toplevel_handle" type="object" interface="ext_foreign_toplevel_handle_v1"/>
+    </request>
+
+    <request name="destroy" type="destructor">
+      <description summary="delete this object">
+        Destroys the manager. This request may be sent at any time by the client
+        and objects created by the manager will remain valid after its
+        destruction.
+      </description>
+    </request>
+  </interface>
+</protocol>

+ 456 - 0
protocols/ext-image-copy-capture-v1.xml

@@ -0,0 +1,456 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="ext_image_copy_capture_v1">
+  <copyright>
+    Copyright © 2021-2023 Andri Yngvason
+    Copyright © 2024 Simon Ser
+
+    Permission is hereby granted, free of charge, to any person obtaining a
+    copy of this software and associated documentation files (the "Software"),
+    to deal in the Software without restriction, including without limitation
+    the rights to use, copy, modify, merge, publish, distribute, sublicense,
+    and/or sell copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice (including the next
+    paragraph) shall be included in all copies or substantial portions of the
+    Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+    DEALINGS IN THE SOFTWARE.
+  </copyright>
+
+  <description summary="image capturing into client buffers">
+    This protocol allows clients to ask the compositor to capture image sources
+    such as outputs and toplevels into user submitted buffers.
+
+    Warning! The protocol described in this file is currently in the testing
+    phase. Backward compatible changes may be added together with the
+    corresponding interface version bump. Backward incompatible changes can
+    only be done by creating a new major version of the extension.
+  </description>
+
+  <interface name="ext_image_copy_capture_manager_v1" version="1">
+    <description summary="manager to inform clients and begin capturing">
+      This object is a manager which offers requests to start capturing from a
+      source.
+    </description>
+
+    <enum name="error">
+      <entry name="invalid_option" value="1" summary="invalid option flag"/>
+    </enum>
+
+    <enum name="options" bitfield="true">
+      <entry name="paint_cursors" value="1" summary="paint cursors onto captured frames"/>
+    </enum>
+
+    <request name="create_session">
+      <description summary="capture an image capture source">
+        Create a capturing session for an image capture source.
+
+        If the paint_cursors option is set, cursors shall be composited onto
+        the captured frame. The cursor must not be composited onto the frame
+        if this flag is not set.
+
+        If the options bitfield is invalid, the invalid_option protocol error
+        is sent.
+      </description>
+      <arg name="session" type="new_id" interface="ext_image_copy_capture_session_v1"/>
+      <arg name="source" type="object" interface="ext_image_capture_source_v1"/>
+      <arg name="options" type="uint" enum="options"/>
+    </request>
+
+    <request name="create_pointer_cursor_session">
+      <description summary="capture the pointer cursor of an image capture source">
+        Create a cursor capturing session for the pointer of an image capture
+        source.
+      </description>
+      <arg name="session" type="new_id" interface="ext_image_copy_capture_cursor_session_v1"/>
+      <arg name="source" type="object" interface="ext_image_capture_source_v1"/>
+      <arg name="pointer" type="object" interface="wl_pointer"/>
+    </request>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the manager">
+        Destroy the manager object.
+
+        Other objects created via this interface are unaffected.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="ext_image_copy_capture_session_v1" version="1">
+    <description summary="image copy capture session">
+      This object represents an active image copy capture session.
+
+      After a capture session is created, buffer constraint events will be
+      emitted from the compositor to tell the client which buffer types and
+      formats are supported for reading from the session. The compositor may
+      re-send buffer constraint events whenever they change.
+
+      To advertise buffer constraints, the compositor must send in no
+      particular order: zero or more shm_format and dmabuf_format events, zero
+      or one dmabuf_device event, and exactly one buffer_size event. Then the
+      compositor must send a done event.
+
+      When the client has received all the buffer constraints, it can create a
+      buffer accordingly, attach it to the capture session using the
+      attach_buffer request, set the buffer damage using the damage_buffer
+      request and then send the capture request.
+    </description>
+
+    <enum name="error">
+      <entry name="duplicate_frame" value="1"
+        summary="create_frame sent before destroying previous frame"/>
+    </enum>
+
+    <event name="buffer_size">
+      <description summary="image capture source dimensions">
+        Provides the dimensions of the source image in buffer pixel coordinates.
+
+        The client must attach buffers that match this size.
+      </description>
+      <arg name="width" type="uint" summary="buffer width"/>
+      <arg name="height" type="uint" summary="buffer height"/>
+    </event>
+
+    <event name="shm_format">
+      <description summary="shm buffer format">
+        Provides the format that must be used for shared-memory buffers.
+
+        This event may be emitted multiple times, in which case the client may
+        choose any given format.
+      </description>
+      <arg name="format" type="uint" enum="wl_shm.format" summary="shm format"/>
+    </event>
+
+    <event name="dmabuf_device">
+      <description summary="dma-buf device">
+        This event advertises the device buffers must be allocated on for
+        dma-buf buffers.
+
+        In general the device is a DRM node. The DRM node type (primary vs.
+        render) is unspecified. Clients must not rely on the compositor sending
+        a particular node type. Clients cannot check two devices for equality
+        by comparing the dev_t value.
+      </description>
+      <arg name="device" type="array" summary="device dev_t value"/>
+    </event>
+
+    <event name="dmabuf_format">
+      <description summary="dma-buf format">
+        Provides the format that must be used for dma-buf buffers.
+
+        The client may choose any of the modifiers advertised in the array of
+        64-bit unsigned integers.
+
+        This event may be emitted multiple times, in which case the client may
+        choose any given format.
+      </description>
+      <arg name="format" type="uint" summary="drm format code"/>
+      <arg name="modifiers" type="array" summary="drm format modifiers"/>
+    </event>
+
+    <event name="done">
+      <description summary="all constraints have been sent">
+        This event is sent once when all buffer constraint events have been
+        sent.
+
+        The compositor must always end a batch of buffer constraint events with
+        this event, regardless of whether it sends the initial constraints or
+        an update.
+      </description>
+    </event>
+
+    <event name="stopped">
+      <description summary="session is no longer available">
+        This event indicates that the capture session has stopped and is no
+        longer available. This can happen in a number of cases, e.g. when the
+        underlying source is destroyed, if the user decides to end the image
+        capture, or if an unrecoverable runtime error has occurred.
+
+        The client should destroy the session after receiving this event.
+      </description>
+    </event>
+
+    <request name="create_frame">
+      <description summary="create a frame">
+        Create a capture frame for this session.
+
+        At most one frame object can exist for a given session at any time. If
+        a client sends a create_frame request before a previous frame object
+        has been destroyed, the duplicate_frame protocol error is raised.
+      </description>
+      <arg name="frame" type="new_id" interface="ext_image_copy_capture_frame_v1"/>
+    </request>
+
+    <request name="destroy" type="destructor">
+      <description summary="delete this object">
+        Destroys the session. This request can be sent at any time by the
+        client.
+
+        This request doesn't affect ext_image_copy_capture_frame_v1 objects created by
+        this object.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="ext_image_copy_capture_frame_v1" version="1">
+    <description summary="image capture frame">
+      This object represents an image capture frame.
+
+      The client should attach a buffer, damage the buffer, and then send a
+      capture request.
+
+      If the capture is successful, the compositor must send the frame metadata
+      (transform, damage, presentation_time in any order) followed by the ready
+      event.
+
+      If the capture fails, the compositor must send the failed event.
+    </description>
+
+    <enum name="error">
+      <entry name="no_buffer" value="1" summary="capture sent without attach_buffer"/>
+      <entry name="invalid_buffer_damage" value="2" summary="invalid buffer damage"/>
+      <entry name="already_captured" value="3" summary="capture request has been sent"/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy this object">
+        Destroys the frame. This request can be sent at any time by the
+        client.
+      </description>
+    </request>
+
+    <request name="attach_buffer">
+      <description summary="attach buffer to session">
+        Attach a buffer to the session.
+
+        The wl_buffer.release request is unused.
+
+        The new buffer replaces any previously attached buffer.
+
+        This request must not be sent after capture, or else the
+        already_captured protocol error is raised.
+      </description>
+      <arg name="buffer" type="object" interface="wl_buffer"/>
+    </request>
+
+    <request name="damage_buffer">
+      <description summary="damage buffer">
+        Apply damage to the buffer which is to be captured next. This request
+        may be sent multiple times to describe a region.
+
+        The client indicates the accumulated damage since this wl_buffer was
+        last captured. During capture, the compositor will update the buffer
+        with at least the union of the region passed by the client and the
+        region advertised by ext_image_copy_capture_frame_v1.damage.
+
+        When a wl_buffer is captured for the first time, or when the client
+        doesn't track damage, the client must damage the whole buffer.
+
+        This is for optimisation purposes. The compositor may use this
+        information to reduce copying.
+
+        These coordinates originate from the upper left corner of the buffer.
+
+        If x or y are strictly negative, or if width or height are negative or
+        zero, the invalid_buffer_damage protocol error is raised.
+
+        This request must not be sent after capture, or else the
+        already_captured protocol error is raised.
+      </description>
+      <arg name="x" type="int" summary="region x coordinate"/>
+      <arg name="y" type="int" summary="region y coordinate"/>
+      <arg name="width" type="int" summary="region width"/>
+      <arg name="height" type="int" summary="region height"/>
+    </request>
+
+    <request name="capture">
+      <description summary="capture a frame">
+        Capture a frame.
+
+        Unless this is the first successful captured frame performed in this
+        session, the compositor may wait an indefinite amount of time for the
+        source content to change before performing the copy.
+
+        This request may only be sent once, or else the already_captured
+        protocol error is raised. A buffer must be attached before this request
+        is sent, or else the no_buffer protocol error is raised.
+      </description>
+    </request>
+
+    <event name="transform">
+      <description summary="buffer transform">
+        This event is sent before the ready event and holds the transform that
+        the compositor has applied to the buffer contents.
+      </description>
+      <arg name="transform" type="uint" enum="wl_output.transform"/>
+    </event>
+
+    <event name="damage">
+      <description summary="buffer damaged region">
+        This event is sent before the ready event. It may be generated multiple
+        times to describe a region.
+
+        The first captured frame in a session will always carry full damage.
+        Subsequent frames' damaged regions describe which parts of the buffer
+        have changed since the last ready event.
+
+        These coordinates originate in the upper left corner of the buffer.
+      </description>
+      <arg name="x" type="int" summary="damage x coordinate"/>
+      <arg name="y" type="int" summary="damage y coordinate"/>
+      <arg name="width" type="int" summary="damage width"/>
+      <arg name="height" type="int" summary="damage height"/>
+    </event>
+
+    <event name="presentation_time">
+      <description summary="presentation time of the frame">
+        This event indicates the time at which the frame is presented to the
+        output in system monotonic time. This event is sent before the ready
+        event.
+
+        The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
+        each component being an unsigned 32-bit value. Whole seconds are in
+        tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
+        and the additional fractional part in tv_nsec as nanoseconds. Hence,
+        for valid timestamps tv_nsec must be in [0, 999999999].
+      </description>
+      <arg name="tv_sec_hi" type="uint"
+           summary="high 32 bits of the seconds part of the timestamp"/>
+      <arg name="tv_sec_lo" type="uint"
+           summary="low 32 bits of the seconds part of the timestamp"/>
+      <arg name="tv_nsec" type="uint"
+           summary="nanoseconds part of the timestamp"/>
+    </event>
+
+    <event name="ready">
+      <description summary="frame is available for reading">
+        Called as soon as the frame is copied, indicating it is available
+        for reading.
+
+        The buffer may be re-used by the client after this event.
+
+        After receiving this event, the client must destroy the object.
+      </description>
+    </event>
+
+    <enum name="failure_reason">
+      <entry name="unknown" value="0">
+        <description summary="unknown runtime error">
+          An unspecified runtime error has occurred. The client may retry.
+        </description>
+      </entry>
+      <entry name="buffer_constraints" value="1">
+        <description summary="buffer constraints mismatch">
+          The buffer submitted by the client doesn't match the latest session
+          constraints. The client should re-allocate its buffers and retry.
+        </description>
+      </entry>
+      <entry name="stopped" value="2">
+        <description summary="session is no longer available">
+          The session has stopped. See ext_image_copy_capture_session_v1.stopped.
+        </description>
+      </entry>
+    </enum>
+
+    <event name="failed">
+      <description summary="capture failed">
+        This event indicates that the attempted frame copy has failed.
+
+        After receiving this event, the client must destroy the object.
+      </description>
+      <arg name="reason" type="uint" enum="failure_reason"/>
+    </event>
+  </interface>
+
+  <interface name="ext_image_copy_capture_cursor_session_v1" version="1">
+    <description summary="cursor capture session">
+      This object represents a cursor capture session. It extends the base
+      capture session with cursor-specific metadata.
+    </description>
+
+    <enum name="error">
+      <entry name="duplicate_session" value="1" summary="get_capture_session sent twice"/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="delete this object">
+        Destroys the session. This request can be sent at any time by the
+        client.
+
+        This request doesn't affect ext_image_copy_capture_frame_v1 objects created by
+        this object.
+      </description>
+    </request>
+
+    <request name="get_capture_session">
+      <description summary="get image copy capturer session">
+        Gets the image copy capture session for this cursor session.
+
+        The session will produce frames of the cursor image. The compositor may
+        pause the session when the cursor leaves the captured area.
+
+        This request must not be sent more than once, or else the
+        duplicate_session protocol error is raised.
+      </description>
+      <arg name="session" type="new_id" interface="ext_image_copy_capture_session_v1"/>
+    </request>
+
+    <event name="enter">
+      <description summary="cursor entered captured area">
+        Sent when a cursor enters the captured area. It shall be generated
+        before the "position" and "hotspot" events when and only when a cursor
+        enters the area.
+
+        The cursor enters the captured area when the cursor image intersects
+        with the captured area. Note, this is different from e.g.
+        wl_pointer.enter.
+      </description>
+    </event>
+
+    <event name="leave">
+      <description summary="cursor left captured area">
+        Sent when a cursor leaves the captured area. No "position" or "hotspot"
+        event is generated for the cursor until the cursor enters the captured
+        area again.
+      </description>
+    </event>
+
+    <event name="position">
+      <description summary="position changed">
+        Cursors outside the image capture source do not get captured and no
+        event will be generated for them.
+
+        The given position is the position of the cursor's hotspot and it is
+        relative to the main buffer's top left corner in transformed buffer
+        pixel coordinates. The coordinates may be negative or greater than the
+        main buffer size.
+      </description>
+      <arg name="x" type="int" summary="position x coordinates"/>
+      <arg name="y" type="int" summary="position y coordinates"/>
+    </event>
+
+    <event name="hotspot">
+      <description summary="hotspot changed">
+        The hotspot describes the offset between the cursor image and the
+        position of the input device.
+
+        The given coordinates are the hotspot's offset from the origin in
+        buffer coordinates.
+
+        Clients should not apply the hotspot immediately: the hotspot becomes
+        effective when the next ext_image_copy_capture_frame_v1.ready event is received.
+
+        Compositors may delay this event until the client captures a new frame.
+      </description>
+      <arg name="x" type="int" summary="hotspot x coordinates"/>
+      <arg name="y" type="int" summary="hotspot y coordinates"/>
+    </event>
+  </interface>
+</protocol>

+ 32 - 4
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -141,6 +141,11 @@ ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (
     settings.order = settingsJson ? settingsJson->optional<std::string> ("order", "sequential") : "sequential";
     settings.updateOnPause = settingsJson ? settingsJson->optional<bool> ("updateonpause", false) : false;
     settings.videoSequence = settingsJson ? settingsJson->optional<bool> ("videosequence", false) : false;
+    // wallpaper64 sub_140075A90 only reads beginfirst in timer mode and playintro with beginfirst on
+    if (settingsJson && settings.mode == "timer") {
+	settings.beginFirst = settingsJson->optional<bool> ("beginfirst", false);
+	settings.playIntro = settings.beginFirst && settingsJson->optional<bool> ("playintro", false);
+    }
     return settings;
 }
 
@@ -1010,15 +1015,22 @@ void ApplicationContext::loadSettingsFromArgv () {
     backgroundGroup.add_argument ("--layer")
 	.help (
 	    "Wayland-only: which wlr-layer-shell layer to anchor the wallpaper to "
-	    "(background, bottom, top, overlay). Default: bottom. On KDE 'background' shares a layer with "
+	    "(auto, background, bottom, top, overlay). Default: auto, which is bottom, except on COSMIC where it is "
+	    "background: cosmic-files draws the desktop's icons on the bottom layer, above a wallpaper there (the "
+	    "wallpaper then gets no pointer input, pass bottom to get it back and lose the icons). On KDE 'background' "
+	    "shares a layer with "
 	    "plasmashell's desktop window, which covers the wallpaper whenever it maps after it (e.g. at login). "
 	    "Use 'background' on niri to pair with the `place-within-backdrop` layer-rule, "
 	    "otherwise the wallpaper will be cloned to every workspace in the overview."
 	)
-	.choices ("background", "bottom", "top", "overlay")
-	.default_value (std::string ("bottom"))
+	.choices ("auto", "background", "bottom", "top", "overlay")
+	.default_value (std::string ("auto"))
 	.action ([this] (const std::string& value) -> void {
-	    if (value == "background") {
+	    this->settings.render.wayland.layerAuto = value == "auto";
+
+	    if (value == "auto") {
+		this->settings.render.wayland.layer = WAYLAND_LAYER_BOTTOM;
+	    } else if (value == "background") {
 		this->settings.render.wayland.layer = WAYLAND_LAYER_BACKGROUND;
 	    } else if (value == "bottom") {
 		this->settings.render.wayland.layer = WAYLAND_LAYER_BOTTOM;
@@ -1136,6 +1148,22 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.webFrames = value;
 	});
 
+    performanceGroup.add_argument ("--frame-limiter")
+	.help (
+	    "How the FPS limit paces frames: budget (default, like Wallpaper Engine: a one second budget shared by the "
+	    "frames of that second, so a long frame or a short sleep is made up by the next ones) or fixed (every "
+	    "frame "
+	    "sleeps 1/fps minus its own work, frames come out perfectly even). Only changes the timing of things that "
+	    "count whole frames, like rope trails"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    if (value != "budget" && value != "fixed") {
+		sLog.exception ("Invalid --frame-limiter value: ", value, " (budget or fixed)");
+	    }
+
+	    this->settings.render.frameLimiter = value;
+	});
+
     performanceGroup.add_argument ("--no-fullscreen-pause")
 	.help ("Prevents the background pausing when an app is fullscreen")
 	.flag ()

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

@@ -62,6 +62,10 @@ public:
 	std::string order = "sequential";
 	bool updateOnPause = false;
 	bool videoSequence = false;
+	bool beginFirst = false;
+	bool playIntro = false;
+
+	[[nodiscard]] bool hasIntro () const { return this->mode == "timer" && this->beginFirst && this->playIntro; }
     };
 
     struct PlaylistDefinition {
@@ -155,6 +159,7 @@ public:
 	    WallpaperEngine::VideoPlayback::VideoSegments videoSegments;
 	    std::string hwdec;
 	    std::string webFrames;
+	    std::string frameLimiter;
 	    bool freezeAnimations;
 	    bool pauseOnFullscreen;
 	    // only fullscreen toplevels that are also activated count (scrollable tiling compositors)
@@ -192,6 +197,7 @@ public:
 
 	    struct {
 		WAYLAND_LAYER layer;
+		bool layerAuto;
 	    } wayland;
 	} render;
 
@@ -264,6 +270,7 @@ public:
             .videoSegments = {},
             .hwdec = "auto",
             .webFrames = "auto",
+            .frameLimiter = "budget",
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,
@@ -297,6 +304,7 @@ public:
             },
             .wayland = {
                 .layer = WAYLAND_LAYER_BOTTOM,
+                .layerAuto = true,
             },
         },
         .audio = {

+ 78 - 0
src/WallpaperEngine/Application/FramePacer.h

@@ -0,0 +1,78 @@
+#pragma once
+
+#include <algorithm>
+#include <chrono>
+#include <utility>
+
+namespace WallpaperEngine::Application {
+/** WE's frame limiter (main loop sub_140110630): a one second budget shared by fps frames instead of a fixed 1/fps
+ * sleep. Each frame sleeps its share of what is left of the budget minus the time it already worked, so a frame that
+ * ran long or a sleep that came back short is made up by the frames after it. The window starts over when the budget
+ * runs out or after fps frames */
+class FramePacer {
+public:
+    using Duration = std::chrono::nanoseconds;
+
+    struct Stats {
+	int frames = 0;
+	int late = 0;
+	Duration work {}, workMax {};
+	Duration asked {}, slept {}, overshootMax {};
+    };
+
+    /** work: time since the previous frame finished sleeping. Returns how long to sleep now, never negative. fixed
+     * sleeps 1/fps minus the work of that frame alone, nothing is made up later */
+    Duration beginSleep (Duration work, int fps, bool fixed = false) {
+	fps = std::max (1, fps);
+
+	if (fixed) {
+	    const auto asked = std::max (Duration::zero (), WINDOW / fps - work);
+
+	    this->m_stats.frames++;
+	    this->m_stats.late += asked == Duration::zero () ? 1 : 0;
+	    this->m_stats.work += work;
+	    this->m_stats.workMax = std::max (this->m_stats.workMax, work);
+	    this->m_stats.asked += asked;
+	    this->m_asked = asked;
+
+	    return asked;
+	}
+
+	this->m_budget -= work;
+
+	if (this->m_budget < Duration::zero () || this->m_index >= fps - 1) {
+	    this->m_budget = WINDOW;
+	    this->m_index = 0;
+	} else {
+	    this->m_index++;
+	}
+
+	const auto asked = std::max (Duration::zero (), this->m_budget / (fps - this->m_index) - work);
+
+	this->m_stats.frames++;
+	this->m_stats.late += asked == Duration::zero () ? 1 : 0;
+	this->m_stats.work += work;
+	this->m_stats.workMax = std::max (this->m_stats.workMax, work);
+	this->m_stats.asked += asked;
+	this->m_asked = asked;
+
+	return asked;
+    }
+
+    void endSleep (Duration slept) {
+	this->m_budget -= slept;
+	this->m_stats.slept += slept;
+	this->m_stats.overshootMax = std::max (this->m_stats.overshootMax, slept - this->m_asked);
+    }
+
+    Stats takeStats () { return std::exchange (this->m_stats, Stats {}); }
+
+private:
+    static constexpr Duration WINDOW = std::chrono::seconds (1);
+
+    Duration m_budget = WINDOW;
+    int m_index = 0;
+    Duration m_asked {};
+    Stats m_stats;
+};
+}

+ 69 - 7
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -428,7 +428,10 @@ WallpaperApplication::buildPlaylistOrder (const ApplicationContext::PlaylistDefi
     std::iota (order.begin (), order.end (), 0);
 
     if (definition.settings.order == "random") {
-	std::shuffle (order.begin (), order.end (), this->m_playlistRng);
+	std::shuffle (
+	    order.begin () + (definition.settings.hasIntro () && order.size () > 1 ? 1 : 0), order.end (),
+	    this->m_playlistRng
+	);
     }
 
     return order;
@@ -456,6 +459,7 @@ void WallpaperApplication::initializePlaylists () {
 
 	state.definition = playlist;
 	state.order = this->buildPlaylistOrder (playlist);
+	state.introPlaying = playlist.settings.hasIntro () && playlist.items.size () > 1;
 
 	if (state.order.empty ()) {
 	    return;
@@ -539,7 +543,10 @@ bool WallpaperApplication::selectNextCandidate (ActivePlaylist& playlist, std::s
     while (attempts < playlist.order.size ()) {
 	const auto candidateIndex = playlist.order[candidateOrderIndex];
 
-	if (!playlist.failedIndices.contains (candidateIndex)) {
+	const bool skippedIntro = candidateIndex == 0 && playlist.definition.settings.hasIntro ()
+	    && playlist.order.size () > 1 && !playlist.introPlaying;
+
+	if (!skippedIntro && !playlist.failedIndices.contains (candidateIndex)) {
 	    outOrderIndex = candidateOrderIndex;
 	    return true;
 	}
@@ -559,12 +566,19 @@ void WallpaperApplication::advancePlaylist (
     }
 
     playlist.orderIndex = (playlist.orderIndex + 1) % playlist.order.size ();
+    playlist.introPlaying = false;
+
+    const bool intro = playlist.definition.settings.hasIntro () && playlist.order.size () > 1;
 
     if (playlist.orderIndex == 0) {
 	playlist.failedIndices.clear ();
 
 	if (playlist.definition.settings.order == "random") {
-	    std::shuffle (playlist.order.begin (), playlist.order.end (), this->m_playlistRng);
+	    std::shuffle (playlist.order.begin () + (intro ? 1 : 0), playlist.order.end (), this->m_playlistRng);
+	}
+
+	if (intro) {
+	    playlist.orderIndex = 1;
 	}
     }
 
@@ -661,10 +675,32 @@ void WallpaperApplication::updatePlaylists () {
 	    continue;
 	}
 
+	// WE only writes a playlist of more than one item into its config (the UI's `1 < items.length`), a single
+	// wallpaper is a plain selection that loops, so one item keeps looping here too
 	if (playlist.definition.items.size () <= 1) {
 	    continue;
 	}
 
+	// videosequence (sub_140076BE0, sub_140067720): a video of a timer playlist plays once and the playlist moves
+	// on when it ends, the timer never takes it away. The playintro item is treated the same while it is the first
+	// one shown
+	if ((playlist.definition.settings.videoSequence || playlist.introPlaying) && this->m_renderContext) {
+	    const auto& wallpapers = this->m_renderContext->getWallpapers ();
+	    const auto current = wallpapers.find (screen);
+
+	    if (current != wallpapers.end () && current->second->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
+		const auto video = current->second->as<WallpaperEngine::Render::Wallpapers::CVideo> ();
+
+		video->setLoop (false);
+
+		if (video->hasEnded ()) {
+		    this->advancePlaylist (screen, playlist, now);
+		}
+
+		continue;
+	    }
+	}
+
 	if (now < playlist.nextSwitch) {
 	    continue;
 	}
@@ -3040,11 +3076,37 @@ void WallpaperApplication::render () {
 	    }
 	}
 
-	const float minimumTime = 1.0f / std::max (1, this->frameRateLimit ());
-	const float frameTime = m_videoDriver->getRenderTime () - rawTimeNow;
+	const auto frameDone = std::chrono::steady_clock::now ();
+	const auto pause = this->m_framePacer.beginSleep (
+	    frameDone - this->m_frameEnd, this->frameRateLimit (),
+	    this->m_context.settings.render.frameLimiter == "fixed"
+	);
+
+	if (pause > std::chrono::nanoseconds::zero ()) {
+	    std::this_thread::sleep_for (pause);
+	}
+
+	this->m_frameEnd = std::chrono::steady_clock::now ();
+	this->m_framePacer.endSleep (this->m_frameEnd - frameDone);
 
-	if (frameTime < minimumTime) {
-	    std::this_thread::sleep_for (std::chrono::duration<float> (minimumTime - frameTime));
+	static const bool paceStats = std::getenv ("LWE_FRAME_STATS") != nullptr;
+	static auto paceWindowStart = this->m_frameEnd;
+
+	if (paceStats && this->m_frameEnd - paceWindowStart >= std::chrono::seconds (2)) {
+	    const auto stats = this->m_framePacer.takeStats ();
+	    const auto millis = [] (std::chrono::nanoseconds time) {
+		return std::chrono::duration<double, std::milli> (time).count ();
+	    };
+	    const double n = std::max (1, stats.frames);
+
+	    sLog.out (
+		"FRAME-PACE: limit ", this->frameRateLimit (), " fps, loop ",
+		n * 1000.0 / millis (this->m_frameEnd - paceWindowStart), " fps | work avg ", millis (stats.work) / n,
+		" max ", millis (stats.workMax), " | sleep asked avg ", millis (stats.asked) / n, " got avg ",
+		millis (stats.slept) / n, " (worst overshoot ", millis (stats.overshootMax), ") | no sleep ",
+		stats.late, " of ", stats.frames, " frames (ms)"
+	    );
+	    paceWindowStart = this->m_frameEnd;
 	}
 
 	if (m_videoDriver->closeRequested ()) {

+ 4 - 0
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -5,6 +5,7 @@
 #include <random>
 
 #include "WallpaperEngine/Application/ApplicationContext.h"
+#include "WallpaperEngine/Application/FramePacer.h"
 #include "WallpaperEngine/Assets/AssetLocator.h"
 
 #include "WallpaperEngine/Render/CWallpaper.h"
@@ -102,6 +103,7 @@ private:
 	std::chrono::steady_clock::time_point nextSwitch;
 	std::chrono::steady_clock::time_point lastUpdate;
 	std::set<std::size_t> failedIndices;
+	bool introPlaying = false;
     };
 
     void initializePlaylists ();
@@ -226,6 +228,8 @@ private:
 #endif
     uint32_t m_nextFrameScreenshot = 0;
     std::chrono::steady_clock::time_point m_pauseStart {};
+    FramePacer m_framePacer;
+    std::chrono::steady_clock::time_point m_frameEnd = std::chrono::steady_clock::now ();
     GLuint m_destinationFramebuffer = 0;
 };
 }

+ 47 - 9
src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp

@@ -7,7 +7,8 @@ namespace WallpaperEngine::Audio::Drivers::Detectors {
 void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, int eol, void* userdata) {
     auto* detector = static_cast<PulseAudioPlayingDetector*> (userdata);
 
-    if (info == nullptr) {
+    if (eol != 0 || info == nullptr) {
+	detector->finishQuery ();
 	return;
     }
 
@@ -23,6 +24,10 @@ void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info,
     }
 }
 
+static void subscriptionCallback (pa_context*, pa_subscription_event_type_t, uint32_t, void* userdata) {
+    static_cast<PulseAudioPlayingDetector*> (userdata)->markDirty ();
+}
+
 PulseAudioPlayingDetector::PulseAudioPlayingDetector (
     Application::ApplicationContext& appContext,
     const Render::Drivers::Detectors::FullScreenDetector& fullscreenDetector
@@ -33,9 +38,22 @@ PulseAudioPlayingDetector::PulseAudioPlayingDetector (
 
     pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr);
 
-    while (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) {
+    pa_context_state_t state;
+
+    while ((state = pa_context_get_state (this->m_context)) != PA_CONTEXT_READY && PA_CONTEXT_IS_GOOD (state)) {
 	pa_mainloop_iterate (this->m_mainloop, 1, nullptr);
     }
+
+    if (state != PA_CONTEXT_READY) {
+	sLog.error ("Automute: cannot reach the sound server, other apps' sound will not be detected");
+	return;
+    }
+
+    pa_context_set_subscribe_callback (this->m_context, subscriptionCallback, this);
+
+    if (pa_operation* op = pa_context_subscribe (this->m_context, PA_SUBSCRIPTION_MASK_SINK_INPUT, nullptr, nullptr)) {
+	pa_operation_unref (op);
+    }
 }
 
 PulseAudioPlayingDetector::~PulseAudioPlayingDetector () {
@@ -51,27 +69,47 @@ PulseAudioPlayingDetector::~PulseAudioPlayingDetector () {
 
 void PulseAudioPlayingDetector::update () {
     if (!this->getApplicationContext ().settings.audio.automute) {
+	this->m_dirty = true;
 	return this->setIsPlaying (false);
     }
     if (this->getFullscreenDetector ().anythingFullscreen ()) {
+	this->m_dirty = true;
 	return this->setIsPlaying (true);
     }
 
-    // the answer is set once the list is complete, the audio thread reads it while the query runs
+    if (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) {
+	return;
+    }
+
+    pa_mainloop_iterate (this->m_mainloop, 0, nullptr);
+
+    if (!this->m_dirty || this->m_querying) {
+	return;
+    }
+
     this->m_found = false;
+    this->m_dirty = false;
 
     pa_operation* op = pa_context_get_sink_input_info_list (this->m_context, sinkInputInfoCallback, this);
     if (op == nullptr) {
+	this->m_dirty = true;
 	return;
     }
 
-    while (pa_operation_get_state (op) == PA_OPERATION_RUNNING) {
-	pa_mainloop_iterate (this->m_mainloop, 1, nullptr);
-    }
-
     pa_operation_unref (op);
-    this->setIsPlaying (this->m_found);
+    this->m_querying = true;
 }
 
 void PulseAudioPlayingDetector::markPlaying () { this->m_found = true; }
-}
+
+void PulseAudioPlayingDetector::markDirty () { this->m_dirty = true; }
+
+void PulseAudioPlayingDetector::finishQuery () {
+    if (!this->m_querying) {
+	return;
+    }
+
+    this->m_querying = false;
+    this->setIsPlaying (this->m_found);
+}
+}

+ 4 - 0
src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h

@@ -15,11 +15,15 @@ public:
 
     void update () override;
     void markPlaying ();
+    void markDirty ();
+    void finishQuery ();
 
 private:
     pa_mainloop* m_mainloop = nullptr;
     pa_mainloop_api* m_mainloopApi = nullptr;
     pa_context* m_context = nullptr;
     bool m_found = false;
+    bool m_dirty = true;
+    bool m_querying = false;
 };
 }

+ 8 - 2
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -16,7 +16,8 @@
 
 using namespace WallpaperEngine::Desktop;
 
-bool WallpaperEngine::Desktop::isGnomeSession () {
+namespace {
+bool desktopListHas (std::string_view name) {
     const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
 
     if (desktops == nullptr) {
@@ -28,7 +29,7 @@ bool WallpaperEngine::Desktop::isGnomeSession () {
     while (!rest.empty ()) {
 	const auto colon = rest.find (':');
 
-	if (rest.substr (0, colon) == "GNOME") {
+	if (rest.substr (0, colon) == name) {
 	    return true;
 	}
 
@@ -41,6 +42,11 @@ bool WallpaperEngine::Desktop::isGnomeSession () {
 
     return false;
 }
+}
+
+bool WallpaperEngine::Desktop::isGnomeSession () { return desktopListHas ("GNOME"); }
+
+bool WallpaperEngine::Desktop::isCosmicSession () { return desktopListHas ("COSMIC"); }
 
 namespace {
 constexpr int HELPER_TIMEOUT_MS = 6000;

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

@@ -9,6 +9,7 @@
 
 namespace WallpaperEngine::Desktop {
 bool isGnomeSession ();
+bool isCosmicSession ();
 
 /**
  * Client of our GNOME Shell extension: it makes our toplevels desktop windows and reports the pointer and window

+ 11 - 1
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -66,6 +66,16 @@ void WaylandMouseInput::update () {
 	return;
     }
 
+    // COSMIC: cosmic-files' desktop surface takes the pointer, the compositor's cursor capture still knows where it is
+    if (this->m_waylandDriver.hasCapturedCursor ()) {
+	if (const auto captured = this->m_waylandDriver.capturedCursorPosition (); captured.has_value ()) {
+	    this->m_globalCursor = captured;
+	    this->m_globalCursorFromX11 = false;
+	}
+
+	return;
+    }
+
 #ifdef ENABLE_KDE_FEATURES
     if (this->m_kdeCursor) {
 	if (const auto kdeCursor = this->m_kdeCursor->position (); kdeCursor.has_value ()) {
@@ -94,7 +104,7 @@ void WaylandMouseInput::update () {
 }
 
 bool WaylandMouseInput::hasGlobalCursor () const {
-    if (this->m_waylandDriver.getGnomeShell () != nullptr) {
+    if (this->m_waylandDriver.getGnomeShell () != nullptr || this->m_waylandDriver.hasCapturedCursor ()) {
 	return true;
     }
 

+ 74 - 1
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -10,6 +10,8 @@
 #define static
 extern "C" {
 #include "color-management-v1-protocol.h"
+#include "ext-image-capture-source-v1-protocol.h"
+#include "ext-image-copy-capture-v1-protocol.h"
 #include "fractional-scale-v1-protocol.h"
 #include "viewporter-protocol.h"
 #include "wlr-layer-shell-unstable-v1-protocol.h"
@@ -213,6 +215,70 @@ WaylandOutputViewport::WaylandOutputViewport (
     wl_output_add_listener (output, &outputListener, this);
 }
 
+namespace {
+void cursorEnter (void* data, ext_image_copy_capture_cursor_session_v1*) {
+    static_cast<WaylandOutputViewport*> (data)->captureCursorInside = true;
+}
+
+void cursorLeave (void* data, ext_image_copy_capture_cursor_session_v1*) {
+    static_cast<WaylandOutputViewport*> (data)->captureCursorInside = false;
+}
+
+void cursorPosition (void* data, ext_image_copy_capture_cursor_session_v1*, int32_t x, int32_t y) {
+    static_cast<WaylandOutputViewport*> (data)->captureCursor = { x, y };
+}
+
+void cursorHotspot (void*, ext_image_copy_capture_cursor_session_v1*, int32_t, int32_t) { }
+
+constexpr ext_image_copy_capture_cursor_session_v1_listener cursorListener
+    = { .enter = cursorEnter, .leave = cursorLeave, .position = cursorPosition, .hotspot = cursorHotspot };
+
+void captureBufferSize (void* data, ext_image_copy_capture_session_v1*, uint32_t width, uint32_t height) {
+    static_cast<WaylandOutputViewport*> (data)->captureSize = { static_cast<int> (width), static_cast<int> (height) };
+}
+
+void captureIgnoredFormat (void*, ext_image_copy_capture_session_v1*, uint32_t) { }
+
+void captureIgnoredDevice (void*, ext_image_copy_capture_session_v1*, wl_array*) { }
+
+void captureIgnoredDmabuf (void*, ext_image_copy_capture_session_v1*, uint32_t, wl_array*) { }
+
+void captureDone (void*, ext_image_copy_capture_session_v1*) { }
+
+void captureStopped (void* data, ext_image_copy_capture_session_v1*) {
+    static_cast<WaylandOutputViewport*> (data)->captureCursorInside = false;
+}
+
+constexpr ext_image_copy_capture_session_v1_listener captureListener = { .buffer_size = captureBufferSize,
+									 .shm_format = captureIgnoredFormat,
+									 .dmabuf_device = captureIgnoredDevice,
+									 .dmabuf_format = captureIgnoredDmabuf,
+									 .done = captureDone,
+									 .stopped = captureStopped };
+}
+
+// cosmic-files draws the desktop on a surface above the wallpaper's, which takes every pointer event; the compositor's
+// cursor capture still says where the pointer is, without anything being copied. The main session only tells the size
+// of the output's buffer, the cursor's position is in those pixels
+void WaylandOutputViewport::setupCursorCapture () {
+    auto* context = this->m_driver->getWaylandContext ();
+
+    if (this->cursorSession != nullptr || context->captureSourceManager == nullptr
+	|| context->copyCaptureManager == nullptr || context->pointer == nullptr || this->output == nullptr) {
+	return;
+    }
+
+    this->captureSource
+	= ext_output_image_capture_source_manager_v1_create_source (context->captureSourceManager, this->output);
+    this->captureSession
+	= ext_image_copy_capture_manager_v1_create_session (context->copyCaptureManager, this->captureSource, 0);
+    ext_image_copy_capture_session_v1_add_listener (this->captureSession, &captureListener, this);
+    this->cursorSession = ext_image_copy_capture_manager_v1_create_pointer_cursor_session (
+	context->copyCaptureManager, this->captureSource, context->pointer
+    );
+    ext_image_copy_capture_cursor_session_v1_add_listener (this->cursorSession, &cursorListener, this);
+}
+
 void WaylandOutputViewport::setupXdgOutput (zxdg_output_manager_v1* manager) {
     this->xdgOutput = zxdg_output_manager_v1_get_xdg_output (manager, this->output);
     zxdg_output_v1_add_listener (this->xdgOutput, &xdgOutputListener, this);
@@ -343,8 +409,15 @@ bool WaylandOutputViewport::isHDR () const { return this->colorSurface != nullpt
 void WaylandOutputViewport::setupLS () {
     surface = wl_compositor_create_surface (m_driver->getWaylandContext ()->compositor);
 
+    const auto& waylandSettings = m_driver->getApp ().getContext ().settings.render.wayland;
+    auto layer = waylandSettings.layer;
+
+    if (waylandSettings.layerAuto && WallpaperEngine::Desktop::isCosmicSession ()) {
+	layer = WallpaperEngine::Application::ApplicationContext::WAYLAND_LAYER_BACKGROUND;
+    }
+
     zwlr_layer_shell_v1_layer wlrLayer;
-    switch (m_driver->getApp ().getContext ().settings.render.wayland.layer) {
+    switch (layer) {
 	case WallpaperEngine::Application::ApplicationContext::WAYLAND_LAYER_BACKGROUND:
 	    wlrLayer = ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND;
 	    break;

+ 11 - 0
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h

@@ -24,6 +24,9 @@ struct wp_color_management_output_v1;
 struct wp_color_management_surface_v1;
 struct wp_fractional_scale_v1;
 struct wp_viewport;
+struct ext_image_capture_source_v1;
+struct ext_image_copy_capture_session_v1;
+struct ext_image_copy_capture_cursor_session_v1;
 struct xdg_surface;
 struct xdg_toplevel;
 #ifdef ENABLE_KDE_FEATURES
@@ -87,6 +90,14 @@ namespace Output {
 	bool hasXdgLogicalPosition = false;
 	zxdg_output_v1* xdgOutput = nullptr;
 
+	ext_image_capture_source_v1* captureSource = nullptr;
+	ext_image_copy_capture_session_v1* captureSession = nullptr;
+	ext_image_copy_capture_cursor_session_v1* cursorSession = nullptr;
+	glm::ivec2 captureSize = {};
+	glm::ivec2 captureCursor = {};
+	bool captureCursorInside = false;
+	void setupCursorCapture ();
+
 	[[nodiscard]] bool hasShellSurface () const { return this->layerSurface || this->xdgToplevel; }
 	void setupLS ();
 	void setupToplevel ();

+ 627 - 0
src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp

@@ -0,0 +1,627 @@
+#include "X11DesktopIcons.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <algorithm>
+#include <cctype>
+#include <csignal>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <set>
+#include <sstream>
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <X11/Xatom.h>
+#include <X11/Xutil.h>
+#include <X11/extensions/Xcomposite.h>
+#include <X11/extensions/Xdamage.h>
+
+using namespace WallpaperEngine::Render::Drivers::Output;
+
+namespace {
+// black: the antialiased edge of an icon or a label blends with it, which reads as a thin shadow on the wallpaper where
+// any other key color leaves a fringe of its own
+constexpr int KEY_TOLERANCE = 2;
+constexpr int OPAQUE_DISTANCE = 48;
+constexpr const char* XFCE_CHANNEL = "xfce4-desktop";
+
+bool runCapture (const std::vector<std::string>& argv, std::string* output = nullptr) {
+    int fds[2];
+
+    if (pipe (fds) != 0) {
+	return false;
+    }
+
+    // everything that allocates happens before the fork, the engine has threads
+    std::vector<char*> args;
+    args.reserve (argv.size () + 1);
+
+    for (const auto& arg : argv) {
+	args.push_back (const_cast<char*> (arg.c_str ()));
+    }
+
+    args.push_back (nullptr);
+    const pid_t pid = fork ();
+
+    if (pid < 0) {
+	close (fds[0]);
+	close (fds[1]);
+	return false;
+    }
+
+    if (pid == 0) {
+	dup2 (fds[1], STDOUT_FILENO);
+	const int null = open ("/dev/null", O_RDWR);
+
+	if (null >= 0) {
+	    dup2 (null, STDIN_FILENO);
+	    dup2 (null, STDERR_FILENO);
+	}
+
+	close (fds[0]);
+	close (fds[1]);
+	execvp (args[0], args.data ());
+	_exit (127);
+    }
+
+    close (fds[1]);
+    std::string text;
+    char buffer[4096];
+    ssize_t count;
+
+    while ((count = read (fds[0], buffer, sizeof (buffer))) > 0) {
+	text.append (buffer, static_cast<size_t> (count));
+    }
+
+    close (fds[0]);
+    int status = 0;
+    waitpid (pid, &status, 0);
+
+    if (output != nullptr) {
+	*output = std::move (text);
+    }
+
+    return WIFEXITED (status) && WEXITSTATUS (status) == 0;
+}
+
+std::string quote (const std::string& text) {
+    std::string out = "'";
+
+    for (const char c : text) {
+	if (c == '\'') {
+	    out += "'\\''";
+	} else {
+	    out += c;
+	}
+    }
+
+    out += "'";
+    return out;
+}
+
+std::vector<std::string> lines (const std::string& text) {
+    std::vector<std::string> out;
+    std::istringstream stream (text);
+    std::string line;
+
+    while (std::getline (stream, line)) {
+	if (!line.empty ()) {
+	    out.push_back (line);
+	}
+    }
+
+    return out;
+}
+
+int number (const std::string& text, size_t from) {
+    return static_cast<int> (std::strtol (text.c_str () + from, nullptr, 10));
+}
+
+std::string restoreFilePath () {
+    const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
+    std::string path = runtime != nullptr && *runtime != '\0' ? runtime : "/tmp";
+    path += "/lwe-xfdesktop-restore." + std::to_string (getuid ()) + ".sh";
+    return path;
+}
+
+/** a zombie that nobody reaped is dead for our purposes */
+bool alive (pid_t pid) {
+    if (pid <= 0) {
+	return false;
+    }
+
+    std::ifstream status ("/proc/" + std::to_string (pid) + "/status");
+    std::string line;
+
+    while (std::getline (status, line)) {
+	if (line.rfind ("State:", 0) == 0) {
+	    return line.find ('Z') == std::string::npos;
+	}
+    }
+
+    return false;
+}
+
+pid_t restoreOwner (const std::string& path) {
+    std::ifstream file (path);
+    std::string first;
+
+    if (!std::getline (file, first) || first.rfind ("# ", 0) != 0) {
+	return 0;
+    }
+
+    return static_cast<pid_t> (number (first, 2));
+}
+
+/** runs the restore file of one engine, once: whoever renames it first is the one to run it (the engine itself on the
+ * way out, the watcher after a crash), and never the file of another engine that started in between */
+void runRestore (const std::string& path, pid_t owner) {
+    const char* script
+	= R"sh(f="$1"; [ "$(sed -n 1p "$f" 2>/dev/null)" = "# $2" ] || exit 0; t="$f.run.$$"; mv "$f" "$t" 2>/dev/null || exit 0; sh "$t"; rm -f "$t")sh";
+    runCapture ({ "sh", "-c", script, "sh", path, std::to_string (owner) });
+}
+
+/** a wallpaper for a desktop that never picked one: xfdesktop's own default can't be named and xfdesktop 4.20 without a
+ * last-image spins at full CPU and leaks memory once its style goes back to an image */
+std::string defaultWallpaper () {
+    for (const char* name : { "xfce-shapes.svg", "xfce-blue.jpg", "xfce-teal.jpg", "xfce-leaves.svg", "xfce-light.svg",
+			      "xfce-x.svg", "xfce-verticals.png" }) {
+	const std::string path = std::string ("/usr/share/backgrounds/xfce/") + name;
+
+	if (access (path.c_str (), R_OK) == 0) {
+	    return path;
+	}
+    }
+
+    return {};
+}
+
+class XfceBackdrop {
+public:
+    bool apply (const std::vector<std::string>& outputNames) {
+	const std::string path = restoreFilePath ();
+
+	if (const pid_t owner = restoreOwner (path); owner != 0) {
+	    if (alive (owner) && owner != getpid ()) {
+		sLog.out ("Another engine already keys xfdesktop's background, sharing it");
+		return true;
+	    }
+
+	    runRestore (path, owner);
+	}
+
+	std::string listing;
+
+	if (!runCapture ({ "xfconf-query", "-c", XFCE_CHANNEL, "-l" }, &listing)) {
+	    return false;
+	}
+
+	std::set<std::string> prefixes;
+	std::set<int> screens { 0 };
+	std::set<int> workspaces { 0 };
+
+	for (const auto& property : lines (listing)) {
+	    const auto workspace = property.find ("/workspace");
+
+	    if (property.rfind ("/backdrop/screen", 0) != 0 || workspace == std::string::npos) {
+		continue;
+	    }
+
+	    prefixes.insert (property.substr (0, property.find ('/', workspace + 1)));
+	    screens.insert (number (property, 16));
+	    workspaces.insert (number (property, workspace + 10));
+	}
+
+	// xfdesktop names a monitor by its index or by its output, depending on version and settings
+	for (const int screen : screens) {
+	    for (const int workspace : workspaces) {
+		for (size_t i = 0; i < std::max<size_t> (outputNames.size (), 1); i++) {
+		    const std::string base = "/backdrop/screen" + std::to_string (screen) + "/monitor";
+		    const std::string suffix = "/workspace" + std::to_string (workspace);
+		    prefixes.insert (base + std::to_string (i) + suffix);
+
+		    if (i < outputNames.size ()) {
+			prefixes.insert (base + outputNames[i] + suffix);
+		    }
+		}
+	    }
+	}
+
+	std::ostringstream restore;
+	restore << "# " << getpid () << "\n";
+	bool changed = false;
+	const std::string fallback = defaultWallpaper ();
+
+	for (const auto& prefix : prefixes) {
+	    if (!fallback.empty ()
+		&& !runCapture ({ "xfconf-query", "-c", XFCE_CHANNEL, "-p", prefix + "/last-image" })) {
+		restore << "xfconf-query -c " << XFCE_CHANNEL << " -p " << quote (prefix + "/last-image")
+			<< " -n -t string -s " << quote (fallback) << "\n";
+	    }
+
+	    for (const char* name : { "image-style", "color-style", "rgba1" }) {
+		const std::string property = prefix + "/" + name;
+		std::string old;
+		const bool existed = runCapture ({ "xfconf-query", "-c", XFCE_CHANNEL, "-p", property }, &old);
+		std::vector<std::string> command { "xfconf-query", "-c", XFCE_CHANNEL, "-p", property };
+		std::string restoreArgs;
+
+		if (std::strcmp (name, "rgba1") == 0) {
+		    auto values = lines (old);
+
+		    if (existed && values.size () >= 4) {
+			values.erase (values.begin (), values.end () - 4);
+			restoreArgs = "-t double -t double -t double -t double";
+
+			for (const auto& value : values) {
+			    restoreArgs += " -s " + quote (value);
+			}
+		    }
+
+		    command.insert (
+			command.end (),
+			{ "-n", "-t", "double", "-t", "double", "-t", "double", "-t", "double", "-s", "0.0", "-s",
+			  "0.0", "-s", "0.0", "-s", "1.0" }
+		    );
+		} else {
+		    const auto values = lines (old);
+
+		    if (existed && !values.empty ()) {
+			restoreArgs = "-s " + quote (values.back ());
+		    }
+
+		    command.insert (command.end (), { "-n", "-t", "int", "-s", "0" });
+		}
+
+		if (!runCapture (command)) {
+		    continue;
+		}
+
+		changed = true;
+
+		if (existed && !restoreArgs.empty ()) {
+		    restore << "xfconf-query -c " << XFCE_CHANNEL << " -p " << quote (property) << " " << restoreArgs
+			    << "\n";
+		    continue;
+		}
+
+		// a property that was not there gets xfdesktop's own default and stays: xfdesktop 4.20 spins at full
+		// CPU and leaks memory after a property it reads was removed, and removing would not make it paint
+		// again anyway
+		if (std::strcmp (name, "image-style") == 0) {
+		    restore << "xfconf-query -c " << XFCE_CHANNEL << " -p " << quote (property) << " -n -t int -s 5\n";
+		} else if (std::strcmp (name, "color-style") == 0) {
+		    restore << "xfconf-query -c " << XFCE_CHANNEL << " -p " << quote (property) << " -n -t int -s 0\n";
+		}
+	    }
+	}
+
+	if (!changed) {
+	    return false;
+	}
+
+	{
+	    std::ofstream file (path, std::ios::trunc);
+	    file << restore.str ();
+	}
+
+	chmod (path.c_str (), 0600);
+	this->m_path = path;
+	this->m_owner = getpid ();
+	this->watch ();
+	return true;
+    }
+
+    void restore () {
+	if (this->m_path.empty () || this->m_owner != getpid ()) {
+	    return;
+	}
+
+	runRestore (this->m_path, this->m_owner);
+	this->m_path.clear ();
+	this->m_owner = 0;
+    }
+
+private:
+    /** a SIGKILLed engine would leave the desktop with the key color, so a shell waits for it and puts the settings
+     * back */
+    void watch () const {
+	const std::string status = "/proc/" + std::to_string (this->m_owner) + "/status";
+	std::string script = "while [ -r " + status + " ] && ! grep -q '^State:.*Z' " + status + "; do sleep 1; done; ";
+	script
+	    += R"sh(f="$1"; [ "$(sed -n 1p "$f" 2>/dev/null)" = "# $2" ] || exit 0; t="$f.run.$$"; mv "$f" "$t" 2>/dev/null || exit 0; sh "$t"; rm -f "$t")sh";
+	const std::string path = this->m_path;
+	const std::string owner = std::to_string (this->m_owner);
+	const pid_t pid = fork ();
+
+	if (pid != 0) {
+	    return;
+	}
+
+	setsid ();
+	const int null = open ("/dev/null", O_RDWR);
+
+	if (null >= 0) {
+	    dup2 (null, STDIN_FILENO);
+	    dup2 (null, STDOUT_FILENO);
+	    dup2 (null, STDERR_FILENO);
+	}
+
+	execl (
+	    "/bin/sh", "sh", "-c", script.c_str (), "sh", path.c_str (), owner.c_str (), static_cast<char*> (nullptr)
+	);
+	_exit (127);
+    }
+
+    std::string m_path;
+    pid_t m_owner = 0;
+};
+
+XfceBackdrop& backdrop () {
+    static XfceBackdrop instance;
+    return instance;
+}
+
+bool classContains (Display* display, Window window, const char* needle) {
+    XClassHint hint {};
+
+    if (!XGetClassHint (display, window, &hint)) {
+	return false;
+    }
+
+    std::string text = std::string (hint.res_class != nullptr ? hint.res_class : "") + " "
+	+ (hint.res_name != nullptr ? hint.res_name : "");
+
+    if (hint.res_class != nullptr) {
+	XFree (hint.res_class);
+    }
+
+    if (hint.res_name != nullptr) {
+	XFree (hint.res_name);
+    }
+
+    std::transform (text.begin (), text.end (), text.begin (), [] (unsigned char c) { return std::tolower (c); });
+    return text.find (needle) != std::string::npos;
+}
+}
+
+X11DesktopIcons::X11DesktopIcons (Display* display, Window root, int fullWidth, int fullHeight) :
+    m_display (display), m_root (root), m_fullWidth (fullWidth), m_fullHeight (fullHeight) { }
+
+X11DesktopIcons::~X11DesktopIcons () {
+    for (auto& tracked : this->m_tracked) {
+	this->untrack (tracked);
+    }
+
+    if (this->m_active) {
+	backdrop ().restore ();
+    }
+}
+
+bool X11DesktopIcons::supports (Display* display, Window window) {
+    return classContains (display, window, "xfdesktop");
+}
+
+bool X11DesktopIcons::start (const std::vector<Window>& windows, const std::vector<std::string>& outputNames) {
+    int compositeBase, compositeError, damageError;
+
+    if (!XCompositeQueryExtension (this->m_display, &compositeBase, &compositeError)
+	|| !XDamageQueryExtension (this->m_display, &this->m_damageEvent, &damageError)) {
+	sLog.out ("Composite or Damage is missing, the desktop's icons stay under the wallpaper");
+	return false;
+    }
+
+    int major = 0, minor = 0;
+    XCompositeQueryVersion (this->m_display, &major, &minor);
+
+    if (major == 0 && minor < 2) {
+	return false;
+    }
+
+    // following first: xfdesktop paints the key color as soon as the setting changes and that damage has to be seen
+    this->follow (windows);
+
+    if (!backdrop ().apply (outputNames)) {
+	sLog.out ("xfdesktop's background could not be set to the key color, its icons stay under the wallpaper");
+	this->follow ({});
+	return false;
+    }
+
+    this->m_active = true;
+    sLog.out ("xfdesktop's icons are drawn over the wallpaper, its background is black while the engine runs");
+    return true;
+}
+
+void X11DesktopIcons::follow (const std::vector<Window>& windows) {
+    std::erase_if (this->m_tracked, [&] (Tracked& tracked) {
+	if (std::find (windows.begin (), windows.end (), tracked.window) != windows.end ()) {
+	    return false;
+	}
+
+	this->untrack (tracked);
+	return true;
+    });
+
+    for (const Window window : windows) {
+	const bool known = std::ranges::any_of (this->m_tracked, [&] (const Tracked& t) { return t.window == window; });
+
+	if (!known) {
+	    this->track (window);
+	}
+    }
+
+    for (auto& tracked : this->m_tracked) {
+	XWindowAttributes attributes;
+
+	if (!XGetWindowAttributes (this->m_display, tracked.window, &attributes)) {
+	    continue;
+	}
+
+	int x = 0, y = 0;
+	Window child;
+	XTranslateCoordinates (this->m_display, tracked.window, this->m_root, 0, 0, &x, &y, &child);
+
+	if (x != tracked.x || y != tracked.y || attributes.width != tracked.width
+	    || attributes.height != tracked.height) {
+	    tracked.x = x;
+	    tracked.y = y;
+	    tracked.width = attributes.width;
+	    tracked.height = attributes.height;
+	    tracked.dirty = true;
+	}
+    }
+}
+
+void X11DesktopIcons::track (Window window) {
+    Tracked tracked;
+    tracked.window = window;
+    XCompositeRedirectWindow (this->m_display, window, CompositeRedirectAutomatic);
+    tracked.damage = XDamageCreate (this->m_display, window, XDamageReportNonEmpty);
+    this->m_tracked.push_back (tracked);
+}
+
+void X11DesktopIcons::untrack (Tracked& tracked) {
+    if (tracked.damage != 0) {
+	XDamageDestroy (this->m_display, tracked.damage);
+	tracked.damage = 0;
+    }
+
+    XCompositeUnredirectWindow (this->m_display, tracked.window, CompositeRedirectAutomatic);
+}
+
+bool X11DesktopIcons::handleEvent (const XEvent& event) {
+    if (event.type != this->m_damageEvent + XDamageNotify) {
+	return false;
+    }
+
+    const auto& damage = reinterpret_cast<const XDamageNotifyEvent&> (event);
+
+    for (auto& tracked : this->m_tracked) {
+	if (tracked.damage == damage.damage) {
+	    tracked.dirty = true;
+	    XDamageSubtract (this->m_display, tracked.damage, None, None);
+	}
+    }
+
+    return true;
+}
+
+void X11DesktopIcons::update () {
+    const auto now = std::chrono::steady_clock::now ();
+
+    for (auto& tracked : this->m_tracked) {
+	if (tracked.dirty && now >= tracked.retryAt) {
+	    tracked.dirty = false;
+	    this->capture (tracked);
+	}
+    }
+}
+
+void X11DesktopIcons::capture (Tracked& tracked) {
+    auto& out = tracked.icons;
+    out.clear ();
+
+    if (tracked.width <= 0 || tracked.height <= 0) {
+	return;
+    }
+
+    const Pixmap pixmap = XCompositeNameWindowPixmap (this->m_display, tracked.window);
+    XImage* image = XGetImage (this->m_display, pixmap, 0, 0, tracked.width, tracked.height, AllPlanes, ZPixmap);
+    XFreePixmap (this->m_display, pixmap);
+
+    if (image == nullptr) {
+	return;
+    }
+
+    // a pixmap has no visual and so no color masks: 24 bit depth in 32 bits, B G R X in memory on a little endian
+    // server
+    if (image->bits_per_pixel != 32 || image->byte_order != LSBFirst) {
+	XDestroyImage (image);
+	return;
+    }
+
+    // the window only counts once it paints the key color: before xfdesktop took the setting up it still shows its own
+    // wallpaper, which would otherwise cover the real one
+    size_t keyed = 0;
+    size_t sampled = 0;
+
+    for (int row = 0; row < tracked.height; row += 4) {
+	const auto* line
+	    = reinterpret_cast<const uint8_t*> (image->data) + static_cast<size_t> (row) * image->bytes_per_line;
+
+	for (int column = 0; column < tracked.width; column += 4) {
+	    const uint8_t* p = line + column * 4;
+	    keyed += std::max ({ p[0], p[1], p[2] }) <= KEY_TOLERANCE;
+	    sampled++;
+	}
+    }
+
+    if (keyed * 2 < sampled) {
+	XDestroyImage (image);
+
+	if (++tracked.attempts < 40) {
+	    tracked.dirty = true;
+	    tracked.retryAt = std::chrono::steady_clock::now () + std::chrono::milliseconds (500);
+	}
+
+	return;
+    }
+
+    tracked.attempts = 0;
+
+    for (int row = 0; row < tracked.height; row++) {
+	const int destRow = tracked.y + row;
+
+	if (destRow < 0 || destRow >= this->m_fullHeight) {
+	    continue;
+	}
+
+	const auto* line
+	    = reinterpret_cast<const uint8_t*> (image->data) + static_cast<size_t> (row) * image->bytes_per_line;
+
+	for (int column = 0; column < tracked.width; column++) {
+	    const int destColumn = tracked.x + column;
+
+	    if (destColumn < 0 || destColumn >= this->m_fullWidth) {
+		continue;
+	    }
+
+	    const uint8_t* p = line + column * 4;
+	    const int distance = std::max ({ p[0], p[1], p[2] });
+
+	    if (distance <= KEY_TOLERANCE) {
+		continue;
+	    }
+
+	    const int alpha = distance >= OPAQUE_DISTANCE ? 255 : distance * 255 / OPAQUE_DISTANCE;
+	    out.push_back (
+		{ static_cast<uint32_t> (destRow) * this->m_fullWidth + destColumn, p[0], p[1], p[2],
+		  static_cast<uint8_t> (alpha) }
+	    );
+	}
+    }
+
+    XDestroyImage (image);
+}
+
+void X11DesktopIcons::composite (char* frame, int width, int height) const {
+    if (width != this->m_fullWidth || height != this->m_fullHeight) {
+	return;
+    }
+
+    auto* pixels = reinterpret_cast<uint8_t*> (frame);
+
+    for (const auto& tracked : this->m_tracked) {
+	for (const auto& icon : tracked.icons) {
+	    uint8_t* d = pixels + static_cast<size_t> (icon.index) * 4;
+	    const int a = icon.a;
+	    d[0] = static_cast<uint8_t> ((d[0] * (255 - a) + icon.b * a) / 255);
+	    d[1] = static_cast<uint8_t> ((d[1] * (255 - a) + icon.g * a) / 255);
+	    d[2] = static_cast<uint8_t> ((d[2] * (255 - a) + icon.r * a) / 255);
+	}
+    }
+}

+ 71 - 0
src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.h

@@ -0,0 +1,71 @@
+#pragma once
+
+#include <chrono>
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include <X11/Xlib.h>
+
+namespace WallpaperEngine::Render::Drivers::Output {
+/**
+ * Keeps the icons of an opaque desktop window (xfdesktop) visible above the wallpaper. The window stays where it is and
+ * keeps handling every click, its background is turned into a key colour, the window's pixels are read through the
+ * Composite extension whenever it is damaged and every pixel that is not the key colour is drawn over the wallpaper
+ * frame before it goes to the screen.
+ */
+class X11DesktopIcons {
+public:
+    X11DesktopIcons (Display* display, Window root, int fullWidth, int fullHeight);
+    ~X11DesktopIcons ();
+
+    X11DesktopIcons (const X11DesktopIcons&) = delete;
+    X11DesktopIcons& operator= (const X11DesktopIcons&) = delete;
+
+    [[nodiscard]] static bool supports (Display* display, Window window);
+
+    bool start (const std::vector<Window>& windows, const std::vector<std::string>& outputNames);
+
+    void follow (const std::vector<Window>& windows);
+
+    bool handleEvent (const XEvent& event);
+
+    void update ();
+
+    void composite (char* frame, int width, int height) const;
+
+    [[nodiscard]] bool active () const { return this->m_active; }
+
+private:
+    struct Icon {
+	uint32_t index;
+	uint8_t b, g, r, a;
+    };
+
+    struct Tracked {
+	Window window = None;
+	int x = 0;
+	int y = 0;
+	int width = 0;
+	int height = 0;
+	unsigned long damage = 0;
+	bool dirty = true;
+	int attempts = 0;
+	std::chrono::steady_clock::time_point retryAt = {};
+	std::vector<Icon> icons;
+    };
+
+    void track (Window window);
+    void untrack (Tracked& tracked);
+    void capture (Tracked& tracked);
+
+    Display* m_display;
+    Window m_root;
+    int m_fullWidth;
+    int m_fullHeight;
+    int m_compositeEvent = 0;
+    int m_damageEvent = 0;
+    bool m_active = false;
+    std::vector<Tracked> m_tracked;
+};
+}

+ 68 - 0
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -67,6 +67,10 @@ void X11Output::free () {
     this->m_viewports.clear ();
 
     this->m_background.reset ();
+#ifdef HAVE_X11_DESKTOP_ICONS
+    this->m_icons.reset ();
+    this->m_iconsTried = false;
+#endif
 
     // XDestroyImage() frees m_imageData itself
     if (this->m_desktopWindow != None) {
@@ -253,6 +257,13 @@ void X11Output::updateRender () const {
 	return;
     }
 
+#ifdef HAVE_X11_DESKTOP_ICONS
+    if (this->m_icons != nullptr) {
+	this->m_icons->update ();
+	this->m_icons->composite (this->m_imageData, this->m_fullWidth, this->m_fullHeight);
+    }
+#endif
+
     XPutImage (
 	this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, this->m_fullHeight
     );
@@ -447,12 +458,57 @@ Window X11Output::topLevelOf (Window window) const {
     return window;
 }
 
+#ifdef HAVE_X11_DESKTOP_ICONS
+void X11Output::updateDesktopIcons (const std::vector<Window>& covering) const {
+    if (this->m_icons != nullptr) {
+	this->m_icons->follow (covering);
+	return;
+    }
+
+    if (this->m_iconsTried) {
+	return;
+    }
+
+    const char* setting = std::getenv ("LWE_DESKTOP_ICONS");
+
+    if (setting != nullptr && std::string_view (setting) == "off") {
+	this->m_iconsTried = true;
+	return;
+    }
+
+    if (!std::ranges::all_of (covering, [this] (Window window) {
+	    return X11DesktopIcons::supports (this->m_display, window);
+	})) {
+	return;
+    }
+
+    this->m_iconsTried = true;
+    std::vector<std::string> names;
+
+    for (const auto* screen : this->m_screens) {
+	names.push_back (screen->name);
+    }
+
+    auto icons
+	= std::make_unique<X11DesktopIcons> (this->m_display, this->m_root, this->m_fullWidth, this->m_fullHeight);
+
+    if (icons->start (covering, names)) {
+	this->m_icons = std::move (icons);
+    }
+}
+#endif
+
 void X11Output::updateDesktopWindow () const {
     bool restacked = false;
 
     while (XPending (this->m_display)) {
 	XEvent event;
 	XNextEvent (this->m_display, &event);
+#ifdef HAVE_X11_DESKTOP_ICONS
+	if (this->m_icons != nullptr && this->m_icons->handleEvent (event)) {
+	    continue;
+	}
+#endif
 	restacked |= event.type == ConfigureNotify || event.type == MapNotify || event.type == UnmapNotify
 	    || event.type == DestroyNotify;
     }
@@ -468,6 +524,11 @@ void X11Output::updateDesktopWindow () const {
     const auto covering = this->findCoveringDesktopWindows (this->stackingOrder ());
 
     if (covering.empty ()) {
+#ifdef HAVE_X11_DESKTOP_ICONS
+	this->m_icons.reset ();
+	this->m_iconsTried = false;
+#endif
+
 	if (this->m_desktopWindowMapped) {
 	    XUnmapWindow (this->m_display, this->m_desktopWindow);
 	    this->m_desktopWindowMapped = false;
@@ -528,4 +589,11 @@ void X11Output::updateDesktopWindow () const {
 	changes.stack_mode = Above;
 	XConfigureWindow (this->m_display, this->m_desktopWindow, CWSibling | CWStackMode, &changes);
     }
+
+#ifdef HAVE_X11_DESKTOP_ICONS
+    // after the stacking above: starting it takes seconds (xfconf-query runs), and a full screen window of ours left on
+    // top of the others meanwhile makes xfwm4's compositor stop painting the windows that were open already
+    XFlush (this->m_display);
+    this->updateDesktopIcons (covering);
+#endif
 }

+ 10 - 0
src/WallpaperEngine/Render/Drivers/Output/X11Output.h

@@ -13,6 +13,9 @@
 #include "Output.h"
 #include "WallpaperEngine/Render/Drivers/VideoDriver.h"
 #include "X11BackgroundWindow.h"
+#ifdef HAVE_X11_DESKTOP_ICONS
+#include "X11DesktopIcons.h"
+#endif
 
 namespace WallpaperEngine::Render::Drivers::Output {
 class X11Output final : public Output {
@@ -39,6 +42,9 @@ private:
     [[nodiscard]] static bool desktopHidesRootWindow ();
 
     void updateDesktopWindow () const;
+#ifdef HAVE_X11_DESKTOP_ICONS
+    void updateDesktopIcons (const std::vector<Window>& covering) const;
+#endif
     [[nodiscard]] std::vector<Window> findCoveringDesktopWindows (const std::vector<Window>& stacking) const;
     [[nodiscard]] std::vector<Window> stackingOrder () const;
     [[nodiscard]] bool isDesktopType (Window window) const;
@@ -58,5 +64,9 @@ private:
     mutable Window m_desktopWindow = None;
     mutable bool m_desktopWindowMapped = false;
     mutable std::chrono::steady_clock::time_point m_nextDesktopCheck = {};
+#ifdef HAVE_X11_DESKTOP_ICONS
+    mutable std::unique_ptr<X11DesktopIcons> m_icons;
+    mutable bool m_iconsTried = false;
+#endif
 };
 }

+ 35 - 0
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -9,6 +9,8 @@
 #define static
 extern "C" {
 #include "color-management-v1-protocol.h"
+#include "ext-image-capture-source-v1-protocol.h"
+#include "ext-image-copy-capture-v1-protocol.h"
 #include "fractional-scale-v1-protocol.h"
 #include "viewporter-protocol.h"
 #include "wlr-layer-shell-unstable-v1-protocol.h"
@@ -201,6 +203,14 @@ handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const cha
 	driver->m_screens.emplace_back (
 	    new WallpaperEngine::Render::Drivers::Output::WaylandOutputViewport (driver, name, registry)
 	);
+    } else if (strcmp (interface, ext_output_image_capture_source_manager_v1_interface.name) == 0) {
+	driver->getWaylandContext ()->captureSourceManager = static_cast<ext_output_image_capture_source_manager_v1*> (
+	    wl_registry_bind (registry, name, &ext_output_image_capture_source_manager_v1_interface, 1)
+	);
+    } else if (strcmp (interface, ext_image_copy_capture_manager_v1_interface.name) == 0) {
+	driver->getWaylandContext ()->copyCaptureManager = static_cast<ext_image_copy_capture_manager_v1*> (
+	    wl_registry_bind (registry, name, &ext_image_copy_capture_manager_v1_interface, 1)
+	);
     } 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));
@@ -544,6 +554,7 @@ void WaylandOpenGLDriver::makeSurfacelessCurrent () {
 WaylandOpenGLDriver::WaylandOpenGLDriver (ApplicationContext& context, WallpaperApplication& app) :
     VideoDriver (app, m_mouseInput), m_output (context, *this), m_requestedExit (false), m_frameCounter (0),
     m_context (context), m_mouseInput (*this) {
+    this->m_cursorCapture = WallpaperEngine::Desktop::isCosmicSession ();
     initWaylandRegistry ();
     initColorManagement ();
     initEGL ();
@@ -830,6 +841,24 @@ void WaylandOpenGLDriver::reapClosedOutputs () {
     }
 }
 
+bool WaylandOpenGLDriver::hasCapturedCursor () const {
+    return std::ranges::any_of (this->m_screens, [] (const auto* screen) { return screen->cursorSession != nullptr; });
+}
+
+std::optional<glm::dvec2> WaylandOpenGLDriver::capturedCursorPosition () const {
+    for (const auto* screen : this->m_screens) {
+	if (screen->cursorSession == nullptr || !screen->captureCursorInside || screen->captureSize.x <= 0
+	    || screen->captureSize.y <= 0 || screen->size.x <= 0 || screen->size.y <= 0) {
+	    continue;
+	}
+
+	const glm::dvec2 fraction = glm::dvec2 (screen->captureCursor) / glm::dvec2 (screen->captureSize);
+	return glm::dvec2 (screen->globalPosition) + fraction * glm::dvec2 (screen->size);
+    }
+
+    return std::nullopt;
+}
+
 void WaylandOpenGLDriver::dispatchEventQueue () {
     if (this->m_gnomeShell) {
 	this->m_gnomeShell->dispatch ();
@@ -847,6 +876,12 @@ void WaylandOpenGLDriver::dispatchEventQueue () {
 	this->setupLateOutputs ();
     }
 
+    if (this->m_cursorCapture) {
+	for (const auto& o : this->m_screens) {
+	    o->setupCursorCapture ();
+	}
+    }
+
     // rendering continues from frame callbacks, so this redraws surfaces that missed their first frame or a dropped
     // callback (and draws the very first frame)
     const auto now = std::chrono::steady_clock::now ();

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

@@ -31,6 +31,8 @@ struct wp_color_manager_v1;
 struct wp_image_description_v1;
 struct wp_viewporter;
 struct wp_fractional_scale_manager_v1;
+struct ext_output_image_capture_source_manager_v1;
+struct ext_image_copy_capture_manager_v1;
 #ifdef ENABLE_KDE_FEATURES
 struct org_kde_plasma_shell;
 #endif
@@ -67,6 +69,8 @@ public:
 	wl_seat* seat = nullptr;
 	wl_pointer* pointer = nullptr;
 	zxdg_output_manager_v1* xdgOutputManager = nullptr;
+	ext_output_image_capture_source_manager_v1* captureSourceManager = nullptr;
+	ext_image_copy_capture_manager_v1* copyCaptureManager = nullptr;
 	wp_color_manager_v1* colorManager = nullptr;
 	wp_viewporter* viewporter = nullptr;
 	wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr;
@@ -110,6 +114,8 @@ public:
     void makeSurfacelessCurrent ();
     [[nodiscard]] bool hasGlobalCursor () const { return this->m_mouseInput.hasGlobalCursor (); }
     [[nodiscard]] Desktop::GnomeShell* getGnomeShell () const { return this->m_gnomeShell.get (); }
+    [[nodiscard]] bool hasCapturedCursor () const;
+    [[nodiscard]] std::optional<glm::dvec2> capturedCursorPosition () const;
     /** runs outside event dispatch */
     void reapClosedOutputs ();
     Output::WaylandOutputViewport* surfaceToViewport (const wl_surface*) const;
@@ -148,6 +154,7 @@ private:
     bool m_waitingLogged = false;
     ApplicationContext& m_context;
     std::unique_ptr<Desktop::GnomeShell> m_gnomeShell;
+    bool m_cursorCapture = false;
     WaylandMouseInput m_mouseInput;
 
     std::chrono::high_resolution_clock::time_point renderStart = std::chrono::high_resolution_clock::now ();

+ 52 - 0
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -3312,6 +3312,7 @@ void CImage::uploadGeometryBuffers (const glm::vec2& size) {
     glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
     glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_DYNAMIC_DRAW);
     this->uploadSceneTexCoords ({ x, y, width, height });
+    this->uploadShapePointMesh (size);
 
     this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
 	? this->m_modelViewProjectionScreen
@@ -3326,6 +3327,57 @@ void CImage::uploadGeometryBuffers (const glm::vec2& size) {
 	    * glm::scale (placement, glm::vec3 (1.0f, -1.0f, 1.0f));
 }
 
+// sub_140260190: a shape whose last effect pass sets point0..3 (the light shafts' perspective gizmo) swaps its square
+// for the quad through those four points, positions (p - 0.5) * size, texcoords = p, triangles (0,1,2) (0,2,3)
+void CImage::uploadShapePointMesh (const glm::vec2& size) {
+    if (!this->getImage ().shape || this->getImage ().effects.empty ()) {
+	return;
+    }
+
+    const auto& effect = this->getImage ().effects.back ();
+
+    if (effect->passOverrides.empty ()) {
+	return;
+    }
+
+    const auto& constants = effect->passOverrides.back ()->constants;
+    glm::vec2 points[4];
+    const char* names[4] = { "point0", "point1", "point2", "point3" };
+
+    for (int i = 0; i < 4; i++) {
+	const auto it = constants.find (names[i]);
+
+	if (it == constants.end () || it->second == nullptr || it->second->value == nullptr) {
+	    return;
+	}
+
+	points[i] = it->second->value->getVec2 ();
+    }
+
+    const int order[6] = { 0, 1, 2, 0, 2, 3 };
+    GLfloat positions[18];
+    GLfloat texcoords[12];
+
+    for (int i = 0; i < 6; i++) {
+	const glm::vec2& point = points[order[i]];
+	positions[i * 3] = (point.x - 0.5f) * size.x;
+	positions[i * 3 + 1] = (point.y - 0.5f) * size.y;
+	positions[i * 3 + 2] = 0.0f;
+	texcoords[i * 2] = point.x;
+	texcoords[i * 2 + 1] = point.y;
+    }
+
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_DYNAMIC_DRAW);
+
+    // the shape's only pass is its first pass and reads m_texcoordDirect, the final pass of a longer chain
+    // m_texcoordFinal
+    for (const GLuint buffer : { this->m_texcoordFinal, this->m_texcoordDirect }) {
+	glBindBuffer (GL_ARRAY_BUFFER, buffer);
+	glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_DYNAMIC_DRAW);
+    }
+}
+
 void CImage::updateGeometryBuffers () {
     const glm::vec2 size = this->resolveGeometrySize ();
     this->m_size = size;

+ 1 - 0
src/WallpaperEngine/Render/Objects/CImage.h

@@ -224,6 +224,7 @@ private:
     [[nodiscard]] glm::vec2 resolveGeometrySize () const;
     void updateScenePosition (const glm::vec2& size);
     void uploadGeometryBuffers (const glm::vec2& size);
+    void uploadShapePointMesh (const glm::vec2& size);
     [[nodiscard]] bool shouldRenderFinalPass (bool isLastPass) const;
     bool configurePassTarget (
 	Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo,

+ 37 - 7
src/WallpaperEngine/Render/RenderContext.cpp

@@ -11,9 +11,13 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
 
+#include <algorithm>
 #include <chrono>
+#include <cmath>
 #include <cstdlib>
+#include <numeric>
 #include <unordered_map>
+#include <vector>
 
 namespace {
 using Clock = std::chrono::steady_clock;
@@ -28,6 +32,7 @@ struct FrameStats {
     Clock::time_point lastFrame {};
     int frames = 0;
     double maxInterval = 0.0;
+    std::vector<float> intervals;
     double scene = 0.0, sceneMax = 0.0;
     double video = 0.0, videoMax = 0.0;
     double swap = 0.0, swapMax = 0.0;
@@ -81,9 +86,10 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     const auto frameStart = Clock::now ();
 
     if (stats.lastFrame != Clock::time_point {}) {
-	stats.maxInterval = std::max (
-	    stats.maxInterval, std::chrono::duration<double, std::milli> (frameStart - stats.lastFrame).count ()
-	);
+	const double interval = std::chrono::duration<double, std::milli> (frameStart - stats.lastFrame).count ();
+
+	stats.maxInterval = std::max (stats.maxInterval, interval);
+	stats.intervals.push_back (static_cast<float> (interval));
     }
 
     stats.lastFrame = frameStart;
@@ -122,14 +128,36 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     }
 
     const double n = stats.frames;
+    double jitter = 0.0, median = 0.0, p99 = 0.0;
+
+    if (stats.intervals.size () > 1) {
+	auto& gaps = stats.intervals;
+	const double mean = std::accumulate (gaps.begin (), gaps.end (), 0.0) / gaps.size ();
+
+	for (const float gap : gaps) {
+	    jitter += (gap - mean) * (gap - mean);
+	}
+
+	jitter = std::sqrt (jitter / gaps.size ());
+
+	const auto medianAt = gaps.begin () + gaps.size () / 2;
+	std::nth_element (gaps.begin (), medianAt, gaps.end ());
+	median = *medianAt;
+
+	const auto p99At = gaps.begin () + (gaps.size () - 1) * 99 / 100;
+	std::nth_element (gaps.begin (), p99At, gaps.end ());
+	p99 = *p99At;
+    }
 
     sLog.out (
-	"FRAME-STATS ", viewport->name, ": ", n * 1000.0 / window, " fps, worst gap ", stats.maxInterval,
-	"ms | scene avg ", stats.scene / n, " max ", stats.sceneMax, " | video avg ", stats.video / n, " max ",
-	stats.videoMax, " | swap avg ", stats.swap / n, " max ", stats.swapMax, " (ms)"
+	"FRAME-STATS ", viewport->name, ": ", n * 1000.0 / window, " fps, gap median ", median, " p99 ", p99, " worst ",
+	stats.maxInterval, " jitter ", jitter, "ms | scene avg ", stats.scene / n, " max ", stats.sceneMax,
+	" | video avg ", stats.video / n, " max ", stats.videoMax, " | swap avg ", stats.swap / n, " max ",
+	stats.swapMax, " (ms)"
     );
 
-    stats = FrameStats { .lastFrame = stats.lastFrame };
+    stats.intervals.clear ();
+    stats = FrameStats { .lastFrame = stats.lastFrame, .intervals = std::move (stats.intervals) };
 }
 
 void RenderContext::drawWallpapers (Drivers::Output::OutputViewport& viewport) {
@@ -355,6 +383,8 @@ void RenderContext::setPause (const bool newState) const {
     for (const auto& wallpaper : this->m_wallpapers | std::views::values) {
 	wallpaper->setPause (newState);
     }
+
+    VideoPlayback::MPV::GLPlayer::setGlobalPause (newState);
 }
 
 Input::InputContext& RenderContext::getInputContext () const { return this->m_driver.getInputContext (); }

+ 68 - 22
src/WallpaperEngine/Render/Volumetrics.cpp

@@ -22,6 +22,7 @@ uniform mat4 u_Volume;
 uniform vec3 u_MeshScale;
 layout (location = 0) in vec3 a_Position;
 out vec4 v_ScreenPos;
+out vec2 v_HashPos;
 
 void main () {
     gl_Position = u_ViewProjection * u_Volume * vec4 (a_Position * u_MeshScale, 1.0);
@@ -29,6 +30,7 @@ void main () {
     gl_Position = vec4 (a_Position.xy, -1.0, 1.0);
 #endif
     v_ScreenPos = gl_Position;
+    v_HashPos = vec2 (gl_Position.x, -gl_Position.y);
 }
 )";
 
@@ -47,6 +49,7 @@ void main () {
 // of _rt_shadowAtlas (g_Texture0), spots through the light's matrix scaled by 0.525 like the cookie, point lights
 // through common_pbr_2.h's CalculateProjectedCoordsPoint (copied below)
 const char* kFrontFragment = R"(
+#extension GL_ARB_gpu_shader5 : enable
 #define mul(x, y) ((y) * (x))
 uniform sampler2D u_Back;
 uniform sampler2D u_SceneDepth;
@@ -74,6 +77,7 @@ uniform mat4 u_ShadowMatrix;
 uniform vec4 u_ShadowTransform;
 uniform vec4 u_PointProjection;
 in vec4 v_ScreenPos;
+in vec2 v_HashPos;
 out vec4 fragColor;
 
 #if SHADOW && POINTLIGHT
@@ -184,10 +188,26 @@ vec4 CalculateProjectedCoordsPoint(vec3 worldPos, vec3 lightOrigin, vec4 project
 }
 #endif
 
+#ifndef GL_ARB_gpu_shader5
+#define fma(a, b, c) ((a) * (b) + (c))
+#endif
+
+// the fma chain fxc and DXVK make of hash12 in WE's volumetricsfront.frag, the jitter depends on every bit of it
 float hash12 (vec2 p) {
+#ifdef GL_ARB_gpu_shader5
+    precise float x = fract (p.x * 43758.5469);
+    precise float y = fract (p.y * 43758.5469);
+    precise float d = x * (y + 19.19);
+    d = fma (y, x + 19.19, d);
+    d = fma (x, x + 19.19, d);
+    precise float a = d + x;
+    precise float b = d + y;
+    return fract (a * (b + a));
+#else
     vec3 p3 = fract (vec3 (p.xyx) * 43758.5453);
     p3 += vec3 (dot (p3, p3.yzx + 19.19));
     return fract ((p3.x + p3.y) * p3.z);
+#endif
 }
 
 float fogAlpha (float alpha, float viewLength, float height) {
@@ -222,17 +242,33 @@ void main () {
     worldStart.xyz /= worldStart.w;
     worldEnd.xyz /= worldEnd.w;
 
+    // the march in the order of operations volumetricsfront.frag has after fxc and DXVK: the ray, a start moved by a
+    // share of its 1/(N+1) step and fma (ray, 1/(N+1), position) per sample. Which taps of the shadow atlas land on
+    // which side of a texel is down to the last bit of the positions, a plain position += ray / (N + 1) flips some
     const float sampleCount = float (SAMPLES);
-    vec3 worldStep = (worldEnd.xyz - worldStart.xyz) / (sampleCount + 1.0);
+    const float stepShare = 1.0 / (sampleCount + 1.0);
+    vec3 ray = worldEnd.xyz - worldStart.xyz;
     float invRadius = 1.0 / u_Radius;
-    float maxLightScale = u_Intensity * length (worldEnd.xyz - worldStart.xyz) * invRadius;
-#if POINTLIGHT
-    maxLightScale *= 0.5;
-#endif
+    float maxLightScale = ((invRadius * length (ray)) * u_Intensity) * u_Density;
+    vec3 position = worldStart.xyz;
 
 #if SHADOW
     // WE's screen UV runs top down, this buffer bottom up
-    worldStart.xyz += worldStep * hash12 (screenDepth.xy * 0.5 + 0.5);
+#if FULLSCREEN
+    // WE rasterizes this triangle top down, v_HashPos holds its vertex values at the pixels where ours has them
+    // precise: otherwise the driver moves the fma into the vertex shader and interpolates its result, which has other
+    // last bits than interpolating first (checked against a replay of live WE: a third of the rows differed)
+#ifdef GL_ARB_gpu_shader5
+    precise float jitterU = fma (v_HashPos.x, 0.5, 0.5);
+    precise float jitterV = fma (v_HashPos.y, -0.5, 0.5);
+    vec2 jitterUV = vec2 (jitterU, jitterV);
+#else
+    vec2 jitterUV = vec2 (fma (v_HashPos.x, 0.5, 0.5), fma (v_HashPos.y, -0.5, 0.5));
+#endif
+#else
+    vec2 jitterUV = screenDepth.xy * 0.5 + 0.5;
+#endif
+    position = fma (ray * stepShare, vec3 (hash12 (jitterUV)), position);
 #endif
 
 #if COOKIE
@@ -242,41 +278,50 @@ void main () {
 #endif
 
     for (int s = 0; s < SAMPLES; ++s) {
-	worldStart.xyz += worldStep;
-	vec3 lightDelta = worldStart.xyz - u_LightOrigin;
-	float sampleValue = pow (clamp (1.0 - length (lightDelta) * invRadius, 0.0, 1.0), u_Exponent);
-#if SHADOW
+	position = fma (ray, vec3 (stepShare), position);
+	vec3 lightDelta = position - u_LightOrigin;
+	float sampleValue = exp2 (log2 (clamp (fma (-length (lightDelta), invRadius, 1.0), 0.0, 1.0)) * u_Exponent);
+#if SHADOW && POINTLIGHT
+	float shadowValue = 1.0;
+
 	if (u_ShadowValid) {
-#if POINTLIGHT
-	    vec4 shadowCoords = CalculateProjectedCoordsPoint (worldStart.xyz, u_LightOrigin, u_PointProjection, u_ShadowTransform);
-#else
-	    vec4 shadowCoords = u_ShadowMatrix * vec4 (worldStart.xyz, 1.0);
+	    vec4 shadowCoords = CalculateProjectedCoordsPoint (position, u_LightOrigin, u_PointProjection, u_ShadowTransform);
+	    shadowValue = texture (u_ShadowAtlas, shadowCoords.xyz);
+	}
+#elif SHADOW
+	if (u_ShadowValid) {
+	    vec4 shadowCoords = u_ShadowMatrix * vec4 (position, 1.0);
 	    shadowCoords.xyz /= shadowCoords.w;
 	    shadowCoords.xy = (shadowCoords.xy * vec2 (0.525, -0.525) + vec2 (0.5)) * u_ShadowTransform.zw + u_ShadowTransform.xy;
-#endif
 	    sampleValue *= texture (u_ShadowAtlas, shadowCoords.xyz);
 	}
 #endif
 #if COOKIE
 	// the cookie is projected through the light's own camera, a little bigger than its frustum
-	vec4 uvs = u_LightViewProjection * vec4 (worldStart.xyz, 1.0);
+	vec4 uvs = u_LightViewProjection * vec4 (position, 1.0);
 	uvs.xyz /= uvs.w;
 	vec3 cookieColor = texture (u_Cookie, uvs.xy * vec2 (0.525, -0.525) + vec2 (0.5)).rgb;
 #elif !POINTLIGHT
 	sampleValue *= smoothstep (u_SpotOuter, u_SpotInner, dot (normalize (lightDelta), u_SpotForward));
 #endif
 #if FOG_DIST || FOG_HEIGHT
-	sampleValue *= fogAlpha (sampleValue, length (u_EyePosition - worldStart.xyz), worldStart.y);
+	sampleValue *= fogAlpha (sampleValue, length (u_EyePosition - position), position.y);
 #endif
 #if COOKIE
-	shadowFactor += sampleValue * cookieColor;
+	shadowFactor = fma (vec3 (sampleValue), cookieColor, shadowFactor);
+#elif SHADOW && POINTLIGHT
+	shadowFactor = fma (shadowValue, sampleValue, shadowFactor);
 #else
 	shadowFactor += sampleValue;
 #endif
     }
 
-    shadowFactor /= sampleCount;
-    fragColor = vec4 (u_Density * maxLightScale * shadowFactor * u_Color * 0.1, 1.0);
+#if POINTLIGHT
+    const float averageShare = 0.5 / sampleCount;
+#else
+    const float averageShare = 1.0 / sampleCount;
+#endif
+    fragColor = vec4 (((maxLightScale * shadowFactor) * averageShare) * u_Color * 0.1, 1.0);
 }
 )";
 
@@ -507,7 +552,7 @@ void Volumetrics::setup () {
     this->upload (this->m_box, vertices, indices);
     this->m_box.winding = outwardWinding (vertices, indices, glm::vec3 (0.0f, 0.0f, 0.5f));
     this->upload (
-	this->m_fullscreen, { { -1.0f, 1.0f, 0.0f }, { -1.0f, -3.0f, 0.0f }, { 3.0f, 1.0f, 0.0f } }, { 0, 1, 2 }
+	this->m_fullscreen, { { -1.0f, -1.0f, 0.0f }, { -1.0f, 3.0f, 0.0f }, { 3.0f, -1.0f, 0.0f } }, { 0, 1, 2 }
     );
 
     // sample counts per quality, lights casting shadows take more and jitter the start (volumetricsfront.frag)
@@ -898,7 +943,8 @@ void Volumetrics::renderLight (
     glUniform3fv (glGetUniformLocation (program, "g_FogHeightColor"), 1, &fog.heightColor[0]);
     glUniform4fv (glGetUniformLocation (program, "g_FogHeightParams"), 1, &fog.heightParamsWorld[0]);
 
-    // from inside the volume a triangle covering the screen (-1,1 / -1,-3 / 3,1) goes through volumetrics_fullscreen
+    // from inside the volume a triangle covering the screen goes through volumetrics_fullscreen (WE's is (-1,1 / -1,-3
+    // / 3,1) top down, this one is its mirror image)
     if (inside) {
 	glDisable (GL_CULL_FACE);
 	glBindVertexArray (this->m_fullscreen.vao);

+ 8 - 0
src/WallpaperEngine/Render/Wallpapers/CVideo.cpp

@@ -102,6 +102,14 @@ void CVideo::setVolume (double volume) { this->m_player->setVolume (volume); }
 
 void CVideo::setSpeed (double speed) { this->m_player->setSpeed (speed); }
 
+void CVideo::setLoop (const bool loop) {
+    if (this->m_player->isLooping () != loop) {
+	this->m_player->setLoop (loop);
+    }
+}
+
+bool CVideo::hasEnded () const { return this->m_player->hasEnded (); }
+
 void CVideo::setSegments (const VideoPlayback::VideoSegments& segments) {
     this->m_player->setSegments (normalizeSegments (segments));
 }

+ 4 - 0
src/WallpaperEngine/Render/Wallpapers/CVideo.h

@@ -28,6 +28,10 @@ public:
 
     void setSpeed (double speed);
 
+    /** a playlist with videosequence plays its videos to the end instead of looping them (wallpaper64 sub_140076ED0) */
+    void setLoop (bool loop);
+    [[nodiscard]] bool hasEnded () const;
+
     void setSegments (const VideoPlayback::VideoSegments& segments);
 
     void seek (double seconds);

+ 438 - 0
src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp

@@ -0,0 +1,438 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include "WallpaperEngine/Application/ApplicationContext.h"
+#include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
+#include "WallpaperEngine/Render/Drivers/Detectors/FullScreenDetector.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <csignal>
+#include <cstdlib>
+#include <fcntl.h>
+#include <filesystem>
+#include <future>
+#include <memory>
+#include <string>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <thread>
+#include <unistd.h>
+#include <vector>
+
+using namespace std::chrono_literals;
+using WallpaperEngine::Application::ApplicationContext;
+using WallpaperEngine::Audio::Drivers::Detectors::PulseAudioPlayingDetector;
+using WallpaperEngine::Render::Drivers::Detectors::FullScreenDetector;
+
+namespace {
+using Clock = std::chrono::steady_clock;
+
+class FakeFullScreen final : public FullScreenDetector {
+public:
+    using FullScreenDetector::FullScreenDetector;
+
+    bool fullscreen = false;
+
+    [[nodiscard]] bool anythingFullscreen () const override { return this->fullscreen; }
+};
+
+// a PipeWire stack of its own in a temp dir with one null sink, never the desktop's server; the tests skip when the
+// programs are missing or it does not come up
+class PrivateSoundServer {
+public:
+    PrivateSoundServer () {
+	char pattern[] = "/tmp/lwe-automute-XXXXXX";
+
+	if (mkdtemp (pattern) == nullptr) {
+	    return;
+	}
+
+	this->m_dir = pattern;
+	this->m_env = {
+	    "HOME=" + this->m_dir,
+	    "PATH=/usr/bin:/usr/sbin:/bin:/sbin",
+	    "XDG_RUNTIME_DIR=" + this->m_dir,
+	    "PULSE_RUNTIME_PATH=" + this->m_dir,
+	    "PIPEWIRE_RUNTIME_DIR=" + this->m_dir,
+	    "XDG_CONFIG_HOME=" + this->m_dir + "/config",
+	    "XDG_STATE_HOME=" + this->m_dir + "/state",
+	    "XDG_DATA_HOME=" + this->m_dir + "/data",
+	    "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/nonexistent",
+	    "ALSA_CONFIG_PATH=/dev/null",
+	};
+
+	for (const char* sub : { "config", "state", "data" }) {
+	    std::filesystem::create_directories (this->m_dir + "/" + sub);
+	}
+
+	for (const char* program : { "pipewire", "wireplumber", "pipewire-pulse" }) {
+	    const pid_t pid = this->spawn ({ program }, -1);
+
+	    if (pid < 0) {
+		return;
+	    }
+
+	    this->m_daemons.push_back (pid);
+	    std::this_thread::sleep_for (300ms);
+	}
+
+	for (int i = 0; i < 100 && !this->m_ready; i++) {
+	    this->m_ready = this->run ({ "pactl", "info" }).second == 0;
+
+	    if (!this->m_ready) {
+		std::this_thread::sleep_for (100ms);
+	    }
+	}
+
+	if (!this->m_ready) {
+	    return;
+	}
+
+	this->run ({ "pactl", "load-module", "module-null-sink", "sink_name=lwe_automute" });
+	this->run ({ "pactl", "set-default-sink", "lwe_automute" });
+    }
+
+    ~PrivateSoundServer () {
+	this->stopPlayer ();
+
+	for (const pid_t pid : this->m_daemons) {
+	    kill (pid, SIGCONT);
+	    kill (pid, SIGTERM);
+	}
+
+	for (const pid_t pid : this->m_daemons) {
+	    waitpid (pid, nullptr, 0);
+	}
+
+	if (!this->m_dir.empty ()) {
+	    std::error_code ec;
+	    std::filesystem::remove_all (this->m_dir, ec);
+	}
+    }
+
+    PrivateSoundServer (const PrivateSoundServer&) = delete;
+    PrivateSoundServer& operator= (const PrivateSoundServer&) = delete;
+
+    [[nodiscard]] bool ready () const { return this->m_ready; }
+    [[nodiscard]] std::string address () const { return "unix:" + this->m_dir + "/native"; }
+    [[nodiscard]] std::string missingSocket () const { return "unix:" + this->m_dir + "/no-such-socket"; }
+
+    void freeze () { kill (this->m_daemons.back (), SIGSTOP); }
+    void thaw () { kill (this->m_daemons.back (), SIGCONT); }
+
+    void startPlayer () {
+	this->stopPlayer ();
+
+	const int zero = open ("/dev/zero", O_RDONLY | O_CLOEXEC);
+	this->m_player = this->spawn (
+	    { "pacat", "--playback", "--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20" },
+	    zero
+	);
+	close (zero);
+    }
+
+    void stopPlayer () {
+	if (this->m_player > 0) {
+	    kill (this->m_player, SIGTERM);
+	    waitpid (this->m_player, nullptr, 0);
+	    this->m_player = -1;
+	}
+    }
+
+    int firstSinkInput () {
+	const auto listing = this->run ({ "pactl", "list", "short", "sink-inputs" }).first;
+
+	return listing.empty () ? -1 : static_cast<int> (std::strtol (listing.c_str (), nullptr, 10));
+    }
+
+    void setMute (int index, bool mute) {
+	this->run ({ "pactl", "set-sink-input-mute", std::to_string (index), mute ? "1" : "0" });
+    }
+
+private:
+    pid_t spawn (const std::vector<std::string>& argv, int input, int output = -1) {
+	std::vector<char*> args;
+	std::vector<char*> env;
+
+	for (const auto& arg : argv) {
+	    args.push_back (const_cast<char*> (arg.c_str ()));
+	}
+
+	for (const auto& entry : this->m_env) {
+	    env.push_back (const_cast<char*> (entry.c_str ()));
+	}
+
+	args.push_back (nullptr);
+	env.push_back (nullptr);
+
+	const pid_t pid = fork ();
+
+	if (pid == 0) {
+	    // Catch2's fatal signal handlers would print the parent's report if a TERM arrives before the exec
+	    for (const int sig : { SIGTERM, SIGINT, SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS }) {
+		signal (sig, SIG_DFL);
+	    }
+
+	    setpgid (0, 0);
+
+	    const int devnull = open ("/dev/null", O_RDWR);
+	    dup2 (input >= 0 ? input : devnull, STDIN_FILENO);
+	    dup2 (output >= 0 ? output : devnull, STDOUT_FILENO);
+	    dup2 (devnull, STDERR_FILENO);
+	    execvpe (args[0], args.data (), env.data ());
+	    _exit (127);
+	}
+
+	return pid;
+    }
+
+    std::pair<std::string, int> run (const std::vector<std::string>& argv) {
+	int fds[2];
+
+	if (pipe (fds) != 0) {
+	    return { "", -1 };
+	}
+
+	const pid_t pid = this->spawn (argv, -1, fds[1]);
+	close (fds[1]);
+
+	std::string out;
+	char buffer[512];
+
+	for (ssize_t got; (got = read (fds[0], buffer, sizeof (buffer))) > 0;) {
+	    out.append (buffer, static_cast<size_t> (got));
+	}
+
+	close (fds[0]);
+
+	int status = 0;
+	waitpid (pid, &status, 0);
+
+	return { out, WIFEXITED (status) ? WEXITSTATUS (status) : -1 };
+    }
+
+    std::string m_dir;
+    std::vector<std::string> m_env;
+    std::vector<pid_t> m_daemons;
+    pid_t m_player = -1;
+    bool m_ready = false;
+};
+
+PrivateSoundServer& server () {
+    static PrivateSoundServer instance;
+
+    return instance;
+}
+
+class EnvOverride {
+public:
+    EnvOverride (const char* name, const std::string& value) : m_name (name) {
+	if (const char* old = getenv (name)) {
+	    this->m_old = old;
+	    this->m_had = true;
+	}
+
+	setenv (name, value.c_str (), 1);
+    }
+
+    ~EnvOverride () {
+	if (this->m_had) {
+	    setenv (this->m_name, this->m_old.c_str (), 1);
+	} else {
+	    unsetenv (this->m_name);
+	}
+    }
+
+    EnvOverride (const EnvOverride&) = delete;
+    EnvOverride& operator= (const EnvOverride&) = delete;
+
+private:
+    const char* m_name;
+    std::string m_old;
+    bool m_had = false;
+};
+
+ApplicationContext makeContext () {
+    static const char* argv[] = { "linux-wallpaperengine" };
+
+    return ApplicationContext (1, const_cast<char**> (argv));
+}
+
+template <typename Predicate>
+bool pumpUntil (PulseAudioPlayingDetector& detector, Predicate&& done, std::chrono::milliseconds timeout = 5s) {
+    const auto deadline = Clock::now () + timeout;
+
+    while (Clock::now () < deadline) {
+	detector.update ();
+
+	if (done ()) {
+	    return true;
+	}
+
+	std::this_thread::sleep_for (10ms);
+    }
+
+    return false;
+}
+}
+
+#define REQUIRE_PRIVATE_SERVER()                                                                                       \
+    if (!server ().ready ()) {                                                                                         \
+	SKIP ("pipewire, wireplumber, pipewire-pulse, pactl and pacat are needed for a private sound server");         \
+    }                                                                                                                  \
+    EnvOverride pulseServer ("PULSE_SERVER", server ().address ());                                                    \
+    server ().stopPlayer ()
+
+TEST_CASE ("automute sees another app's sound start and stop") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    auto context = makeContext ();
+    context.settings.audio.automute = true;
+    FakeFullScreen fullscreen (context);
+    PulseAudioPlayingDetector detector (context, fullscreen);
+
+    REQUIRE_FALSE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }, 500ms));
+
+    server ().startPlayer ();
+    REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }));
+
+    server ().stopPlayer ();
+    REQUIRE (pumpUntil (detector, [&] { return !detector.anythingPlaying (); }));
+}
+
+TEST_CASE ("automute follows a stream being muted and unmuted") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    auto context = makeContext ();
+    context.settings.audio.automute = true;
+    FakeFullScreen fullscreen (context);
+    PulseAudioPlayingDetector detector (context, fullscreen);
+
+    server ().startPlayer ();
+    REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }));
+
+    const int input = server ().firstSinkInput ();
+    REQUIRE (input >= 0);
+
+    server ().setMute (input, true);
+    REQUIRE (pumpUntil (detector, [&] { return !detector.anythingPlaying (); }));
+
+    server ().setMute (input, false);
+    REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }));
+}
+
+TEST_CASE ("automute finds a stream that was already playing when the detector started") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    server ().startPlayer ();
+    for (int i = 0; i < 100 && server ().firstSinkInput () < 0; i++) {
+	std::this_thread::sleep_for (50ms);
+    }
+
+    auto context = makeContext ();
+    context.settings.audio.automute = true;
+    FakeFullScreen fullscreen (context);
+    PulseAudioPlayingDetector detector (context, fullscreen);
+
+    REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }));
+}
+
+TEST_CASE ("automute never makes a frame wait for the sound server") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    auto context = makeContext ();
+    context.settings.audio.automute = true;
+    FakeFullScreen fullscreen (context);
+    PulseAudioPlayingDetector detector (context, fullscreen);
+
+    // a server that stops answering (busy, suspended, stuck): the query goes out and never comes back. The release
+    // timer only keeps a regression from hanging the run, a blocking update() shows up as the worst frame time
+    std::atomic<bool> finished = false;
+    std::thread release ([&] {
+	for (int i = 0; i < 60 && !finished; i++) {
+	    std::this_thread::sleep_for (50ms);
+	}
+
+	server ().thaw ();
+    });
+
+    server ().freeze ();
+    server ().startPlayer ();
+
+    Clock::duration worst = 0ms;
+
+    for (int frame = 0; frame < 100; frame++) {
+	const auto start = Clock::now ();
+	detector.update ();
+	worst = std::max (worst, Clock::now () - start);
+	std::this_thread::sleep_for (5ms);
+    }
+
+    finished = true;
+    release.join ();
+
+    CHECK (worst < 100ms);
+    CHECK_FALSE (detector.anythingPlaying ());
+
+    server ().thaw ();
+    REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }, 10s));
+}
+
+TEST_CASE ("automute without a reachable sound server does not hang and reports silence") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    EnvOverride missing ("PULSE_SERVER", server ().missingSocket ());
+
+    auto context = makeContext ();
+    context.settings.audio.automute = true;
+    FakeFullScreen fullscreen (context);
+    std::unique_ptr<PulseAudioPlayingDetector> detector;
+
+    // a constructor that loops forever is the failure, so it runs on a thread that is left behind when it does
+    auto built = std::make_shared<std::promise<void>> ();
+    auto result = built->get_future ();
+
+    std::thread ([&, built] {
+	detector = std::make_unique<PulseAudioPlayingDetector> (context, fullscreen);
+	built->set_value ();
+    }).detach ();
+
+    if (result.wait_for (5s) != std::future_status::ready) {
+	std::_Exit (1);
+    }
+
+    for (int i = 0; i < 20; i++) {
+	detector->update ();
+    }
+
+    CHECK_FALSE (detector->anythingPlaying ());
+}
+
+TEST_CASE ("automute off reports silence and a fullscreen window counts as playing") {
+    REQUIRE_PRIVATE_SERVER ();
+
+    SECTION ("automute off") {
+	server ().startPlayer ();
+
+	auto context = makeContext ();
+	context.settings.audio.automute = false;
+	FakeFullScreen fullscreen (context);
+	PulseAudioPlayingDetector detector (context, fullscreen);
+
+	REQUIRE_FALSE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }, 700ms));
+    }
+
+    SECTION ("fullscreen window") {
+	auto context = makeContext ();
+	context.settings.audio.automute = true;
+	FakeFullScreen fullscreen (context);
+	fullscreen.fullscreen = true;
+	PulseAudioPlayingDetector detector (context, fullscreen);
+
+	REQUIRE (pumpUntil (detector, [&] { return detector.anythingPlaying (); }));
+
+	fullscreen.fullscreen = false;
+	REQUIRE (pumpUntil (detector, [&] { return !detector.anythingPlaying (); }));
+    }
+}

+ 79 - 0
src/WallpaperEngine/Testing/Cases/FramePacer.cpp

@@ -0,0 +1,79 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include "WallpaperEngine/Application/FramePacer.h"
+
+using WallpaperEngine::Application::FramePacer;
+using namespace std::chrono_literals;
+
+namespace {
+constexpr std::chrono::nanoseconds SECOND = 1000000000ns;
+}
+
+// WE starts its frame counter at 0 and bumps it before dividing, so the first frame already shares the budget by fps -
+// 1
+TEST_CASE ("an idle first frame sleeps its share of the second") {
+    FramePacer pacer;
+
+    CHECK (pacer.beginSleep (0ms, 50) == SECOND / 49);
+}
+
+TEST_CASE ("work time comes off the sleep") {
+    FramePacer pacer;
+
+    CHECK (pacer.beginSleep (5ms, 50) == (SECOND - 5ms) / 49 - 5ms);
+}
+
+TEST_CASE ("a frame over budget does not sleep") {
+    FramePacer pacer;
+
+    CHECK (pacer.beginSleep (30ms, 50) == 0ms);
+}
+
+TEST_CASE ("a sleep that came back short is made up by later frames") {
+    FramePacer pacer;
+    const auto first = pacer.beginSleep (0ms, 50);
+    pacer.endSleep (first - 5ms);
+
+    CHECK (pacer.beginSleep (0ms, 50) > first);
+}
+
+TEST_CASE ("a frame that ran long shortens the sleeps after it") {
+    FramePacer pacer;
+    pacer.endSleep (pacer.beginSleep (0ms, 50));
+    pacer.beginSleep (30ms, 50);
+
+    CHECK (pacer.beginSleep (0ms, 50) < SECOND / 47);
+}
+
+TEST_CASE ("frames on time average 1/fps over a window") {
+    FramePacer pacer;
+    std::chrono::nanoseconds total {};
+
+    for (int i = 0; i < 60; i++) {
+	const auto work = 3ms;
+	const auto pause = pacer.beginSleep (work, 60);
+	pacer.endSleep (pause);
+	total += work + pause;
+    }
+
+    CHECK (total >= 990ms);
+    CHECK (total <= 1020ms);
+}
+
+TEST_CASE ("a long stall starts a new window") {
+    FramePacer pacer;
+    pacer.beginSleep (0ms, 30);
+
+    CHECK (pacer.beginSleep (5s, 30) == 0ms);
+    CHECK (pacer.beginSleep (0ms, 30) < 35ms);
+}
+
+TEST_CASE ("the fixed limiter sleeps 1/fps minus the work of that frame only") {
+    FramePacer pacer;
+
+    CHECK (pacer.beginSleep (0ms, 50, true) == 20ms);
+    pacer.endSleep (15ms);
+    CHECK (pacer.beginSleep (5ms, 50, true) == 15ms);
+    CHECK (pacer.beginSleep (30ms, 50, true) == 0ms);
+    CHECK (pacer.beginSleep (0ms, 50, true) == 20ms);
+}

+ 11 - 2
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -19,6 +19,7 @@ std::unordered_map<std::filesystem::path, GLPlayer*> GLPlayer::s_activePlayers;
 std::unordered_set<GLPlayer*> GLPlayer::s_players;
 double GLPlayer::s_statsMillis = 0.0;
 uint64_t GLPlayer::s_frame = 0;
+bool GLPlayer::s_globalPause = false;
 
 // wallpaper64.exe 2.8.42 sub_1400F3930: the media engine plays while (+96 + 30) >= frame counter, +96 being the
 // counter at the last transfer
@@ -182,17 +183,25 @@ void GLPlayer::clearPaused () {
     this->applyPause ();
 }
 
+void GLPlayer::setGlobalPause (bool paused) {
+    s_globalPause = paused;
+
+    for (GLPlayer* player : s_players) {
+	player->applyPause ();
+    }
+}
+
 void GLPlayer::markUsed () const {
     this->m_lastUsedFrame = s_frame;
 
     // the frame counter only moves while a scene renders, a player paused for going unused can't wait for that
-    if (this->m_enginePaused && !this->m_paused) {
+    if (this->m_enginePaused && !this->m_paused && !s_globalPause) {
 	this->applyPause ();
     }
 }
 
 void GLPlayer::applyPause () const {
-    const bool paused = this->m_paused || this->m_lastUsedFrame + UNUSED_FRAMES_BEFORE_PAUSE < s_frame;
+    const bool paused = this->m_paused || s_globalPause || this->m_lastUsedFrame + UNUSED_FRAMES_BEFORE_PAUSE < s_frame;
 
     if (this->m_handle == nullptr || paused == this->m_enginePaused) {
 	return;

+ 2 - 0
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h

@@ -63,6 +63,7 @@ public:
      * unused for 30 of them is paused until it's drawn again (sub_1400F3930)
      */
     static void advanceFrame ();
+    static void setGlobalPause (bool paused);
 
     int getWidth () const;
     int getHeight () const;
@@ -131,6 +132,7 @@ protected:
     static std::unordered_map<std::filesystem::path, GLPlayer*> s_activePlayers;
     static std::unordered_set<GLPlayer*> s_players;
     static uint64_t s_frame;
+    static bool s_globalPause;
 };
 
 using GLPlayerUniquePtr = std::unique_ptr<GLPlayer>;

+ 42 - 0
tools/check_video_sequence.sh

@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+# Checks the playlist settings "videosequence" (wallpaper64 2.8.42 sub_140076BE0 / sub_140067720): a video of a timer
+# playlist plays once and the playlist moves on when it ends, with the setting off the 60 minute timer keeps the first
+# video, and "beginfirst" + "playintro" (sub_140067A00): only the first video plays to its end, the second stays. Makes two 3 second video wallpapers and a private HOME whose config.json holds the playlist (the real WE
+# config is never touched), renders headlessly and counts how often the video was (re)loaded.
+# Usage: tools/check_video_sequence.sh <engine binary> [assets dir]
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BINARY=$(readlink -f "${1:?engine binary}")
+ASSETS=${2:-/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets}
+command -v ffmpeg > /dev/null || { echo "SKIP: no ffmpeg"; exit 0; }
+work=$(mktemp -d /tmp/lwe-video-sequence.XXXXXX)
+trap 'rm -rf "$work"' EXIT
+
+for name in a b; do
+    mkdir -p "$work/items/$name"
+    colour=red; [ "$name" = b ] && colour=blue
+    ffmpeg -loglevel error -f lavfi -i "color=c=$colour:s=320x180:r=30" -t 3 -pix_fmt yuv420p "$work/items/$name/v.mp4"
+    echo "{\"file\":\"v.mp4\",\"title\":\"$name\",\"type\":\"video\"}" > "$work/items/$name/project.json"
+done
+steam="$work/home/.steam/steam/steamapps/common/wallpaper_engine"
+mkdir -p "$steam"
+ln -s "$ASSETS" "$steam/assets"
+
+loads() {
+    printf '{"steamuser":{"general":{"playlists":[{"name":"seq","items":["%s","%s"],"settings":{"mode":"timer","delay":60,"order":"sequential",%s}}]}}}\n' \
+        "$work/items/a/project.json" "$work/items/b/project.json" "$2" > "$steam/config.json"
+    HOME="$work/home" HEADLESS_RENDER_SIZE=640x360 HEADLESS_RENDER_DELAY=100000 HEADLESS_RENDER_TIMEOUT=16 \
+        "$HERE/headless_render.sh" "$BINARY" "$work/shot.png" --assets-dir "$ASSETS" --fps 30 --silent --playlist seq \
+        > "$work/run-$1.log" 2>&1 < /dev/null || true
+    grep -c 'VO: \[libmpv\]' "$work/run-$1.log" || true
+}
+
+on=$(loads on '"videosequence":true')
+off=$(loads off '"videosequence":false')
+intro=$(loads intro '"videosequence":false,"beginfirst":true,"playintro":true')
+if [ "$on" -ge 3 ] && [ "$off" -eq 1 ] && [ "$intro" -eq 2 ]; then
+    echo "PASS: $on loads in 16 s with videosequence, $off without, $intro with an intro video"
+else
+    echo "FAIL: $on loads with videosequence (want >= 3), $off without (want 1), $intro with playintro (want 2)"
+    exit 1
+fi

+ 14 - 4
tools/linuxvm/RELEASE_TESTING.md

@@ -42,7 +42,7 @@ check (clang-format 22 on `src`) and a build of both CMake variants (`DISABLE_KD
 | mx-xfce | XFCE X11 (MX Linux 25.3, Debian 13 based) | portable + .deb | second monitor, we_manager's .deb self update |
 | popos-cosmic | COSMIC | portable + .deb | layer shell and window states (`zcosmic_toplevel_info`) on cosmic-comp |
 | steamos | Plasma Wayland, read-only root | portable | Steam Deck image on an NVMe disk with Valve SMBIOS, `WEM_LAUNCH` (see below), no dependency install (immutable) |
-| steamdeck | Plasma Wayland, read-only root | portable | the steamos disk as its own golden, but shaped like the hardware (`vm.env`: 1280x800, 4 cores, 16G, Zen 2 CPU model, Valve Jupiter SMBIOS) with a fake battery (`test_power` kernel module, seen by UPower); `deck_check.sh` runs the Steam Deck preset's arguments and follows the battery down and up again |
+| steamdeck | Plasma Wayland, read-only root | portable | the steamos disk as its own golden, but shaped like the hardware (`vm.env`: 1280x800, 4 cores, 16G, Zen 2 CPU model, Valve Jupiter SMBIOS) with a fake battery (`test_power` kernel module, seen by UPower); `deck_check.sh` runs the Steam Deck preset's arguments and follows the battery down and up again Plasma's Battery power profile turns the display off about a minute after login (DPMS off, the VM's screen reads "Display output is not active"), so `PREP` turns the display timeouts off in `powerdevilrc` and restarts powerdevil (a `kde-inhibit` is not enough). `POINTER=0`: the weekday hover check is made for 1920x1080, the VM's screen is 1280x800 (the pointer spots and crops would miss, `steamos` runs it). |
 | bazzite | KDE, immutable | portable + Flatpak | rpm-ostree: dependency install refused, Flatpak |
 
 A new distro joins the matrix once its VM has a profile and a golden snapshot. ChimeraOS is not in it: its image installs and
@@ -92,6 +92,13 @@ Run on every VM of the matrix, each one SKIPs where the guest cannot do it:
 - hotswap cycle (`hotswap_cycle_check`): one engine goes through scene (1120596121), video (1367456719), web (1078208425), scene
   (1111948150), web (834237690), video and scene again; every step must keep the process, log the swap, show a picture that is not
   flat or the empty desktop (`shot-cycle-*.png`), have a web host only on web wallpapers and add no crash lines to the log
+- desktop icons (`desktop_icons_check.sh`, `ICONS=0` in a profile skips it): files on the desktop folder, the session's own icons
+  (Plasma's Folder View, xfdesktop, nemo-desktop, Desktop Icons NG) are located by screenshot (with and without the files),
+  then the engine runs and the same area must still show them. A session without an icon provider SKIPs (GNOME without DING,
+  Hyprland, COSMIC...), on Plasma that is a FAIL. Plasma on Wayland hides Folder View under the engine's bottom layer
+  surface, so the check installs gtk4-layer-shell, PyGObject and pycairo (distro package manager, SKIP where the root is
+  read-only) and starts we_manager's `desktop-icons-overlay.py` after the engine, like we_manager does. The Plasma VMs also
+  run at other resolutions with `desktop_icons_matrix.sh` (fedora-kde at 1280x800 to 3840x2160 and every other Plasma VM)
 - pointer y direction (`pointer_check.sh`, `hover_check.py`): workshop item 3599498791 (a dock and a calendar whose weekday hover zones
   are the engine's cursor hit test) with the VM's pointer on the Monday row and on the Sunday row of the calendar, the enlarged
   label has to be the one under the pointer (it was mirrored on flipped outputs, i.e. KDE Wayland), and the dock icons have to
@@ -121,7 +128,7 @@ All of it lives in `tools/linuxvm/`:
   The `steamdeck` VM was made by copying `steamos`'s golden disk (new port, `qemu-extra`, `vm.env`) and adding
   `/etc/modules-load.d/test_power.conf` + `/etc/modprobe.d/test_power.conf` (AC and USB off, battery discharging) before `golden`.
 - `release_check.sh [--vm name]... [--candidate dir] [--app dir|.deb] [--engine-tarball tgz] [--no-overlay]`: loops over the
-  profiles sequentially, writes `<REPORT_DIR>/summary.md` (default `reports/<date>/`) with screenshots and logs per VM, retries the
+  profiles (one lane; the gate runs 4 lanes, each its own `--vm` list and `REPORT_DIR`), writes `<REPORT_DIR>/summary.md` (default `reports/<date>/`) with screenshots and logs per VM, retries the
   failed checks once, powers the VM off (ssh `systemctl poweroff`, ACPI does not reach a locked KDE session) and resets the
   overlay. `KEEP_VM=1` leaves the VM running, `REPORT_DIR` keeps parallel runs apart (they would share one summary.md).
 - `guest_test.sh` (one PASS/FAIL/SKIP line per check; BEHAVIOR=1 adds hotswap, fullscreen and maximized pause through
@@ -200,8 +207,11 @@ overlays gone.
   of full runs, so a single clean run proves little. A ghost shows as a surplus wallpaper `MetaWindowActor` in the `GROUP` lines of
   the debug extension. The extension hides such orphans (`_hideOrphanActors`), and the golden disks of the GNOME VMs carry the fixed one since
   2026-10-21 (`update_golden_extension.sh`).
-- **Running the matrix in lanes** (2026-10-22): four lanes at once fit in 30 GB (about 5 GB resident per VM), a fifth is fine for harness
-  work. A lane is `release_check.sh --vm <name>` per VM one after the other, each with its own report folder. Under that load a few windows
+- **Running the matrix in lanes** (2026-10-22, rule 2026-10-23): the matrix queue runs 4 VMs at a time, with a shared pool of 5 slots (about 5 GB
+  resident per VM in 30 GB), so harness re-runs grab any free slot instead of a fixed one: when a VM fails, find out whether the
+  harness or the VM is at fault, fix it and re-run that VM at once in a free slot without stopping the queue, never more than 5 VMs
+  at once. `desktop_icons_matrix.sh` does this (`LANES`, `MAXVMS`, flock files in /tmp/lwe-vm-slots shared by every invocation);
+  `release_check.sh` still gets its lanes as separate `--vm` lists. A lane is `release_check.sh --vm <name>` per VM one after the other, each with its own report folder. Under that load a few windows
   turn up later than the 20 s settle in `release_check.sh`: we_manager's autostarted window on a Debian GNOME guest and Steam's sign-in on
   SteamOS/Steam Deck, both are closed once more after the settle. An app that restarts after its own .deb update (MX) can drop the first
   `installPrebuilt()` call, `update_check.sh` asks up to three times.

+ 1 - 1
tools/linuxvm/clean_install_check.sh

@@ -60,7 +60,7 @@ sleep 2
 
 if [[ $app == *.deb ]]; then
     "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
-    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
+    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
 fi
 if [[ $app == *.deb ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
 sshv ". ~/sessenv; export NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-clean.log 2>&1 </dev/null &); for _ in \$(seq 40); do grep -q 'DevTools listening' ~/wem/app-clean.log 2>/dev/null && break; sleep 1; done; sleep 8"

+ 116 - 0
tools/linuxvm/desktop_icons_check.sh

@@ -0,0 +1,116 @@
+#!/bin/bash
+# desktop_icons_check.sh <vm> [screen] - the desktop's icons must stay visible above the engine's wallpaper, on a running VM
+# (release_check.sh runs it for every profile). Screenshots through the VM's display: A the desktop, B the same with a few
+# files on the desktop folder (what the icon provider of the session draws is where B differs from A, the mask), E the engine
+# running without the files, D the engine with them. The icons are visible when D differs from E over the mask about as much
+# as B differs from A. No provider in the session (GNOME without Desktop Icons NG, wlroots compositors, ...) is a SKIP, on
+# Plasma it is a FAIL. Plasma on Wayland hides Folder View under the engine's bottom layer surface, there we_manager's
+# overlay (OVERLAY, default the sibling checkout's script) is installed with what it needs (gtk4-layer-shell, PyGObject,
+# pycairo) and started after the engine, as we_manager does.
+HERE=$(cd "$(dirname "$0")" && pwd)
+vm=$1 screen=${2:-Virtual-1}
+OVERLAY=${OVERLAY:-$HERE/../../../we_manager/src/main/services/desktop-icons-overlay.py}
+WP=${WP:-1111948150}
+sshv() { "$HERE/linuxvm.sh" ssh "$vm" "$@" </dev/null; }
+status=0
+pass() { echo "PASS $vm: $1"; }
+fail() { echo "FAIL $vm: $1"; status=1; }
+skip() { echo "SKIP $vm: $1"; }
+tmp=$(mktemp -d)
+shot() { "$HERE/linuxvm.sh" shot "$vm" "$tmp/$1.png" >/dev/null 2>&1; }
+
+for _ in $(seq 60); do sshv 'bash ~/lwe/sessenv.sh' >/dev/null 2>&1 && break; sleep 5; done
+sshv 'bash ~/lwe/sessenv.sh' >/dev/null 2>&1 || { fail "no desktop session"; exit 1; }
+session=$(sshv '. ~/sessenv; echo "$XDG_CURRENT_DESKTOP $XDG_SESSION_TYPE"')
+kde=0; [[ $session == *KDE*wayland* ]] && kde=1
+desk=$(sshv 'd=$(xdg-user-dir DESKTOP 2>/dev/null); [ -n "$d" ] && [ "$d" != "$HOME" ] || d=$HOME/Desktop; mkdir -p "$d"; echo "$d"')
+
+make_files() {
+    sshv "mkdir -p '$desk/Projects'; touch '$desk/notes.txt' '$desk/data.csv'; find /usr/share/applications \\( -name '*konsole*.desktop' -o -name 'org.gnome.Nautilus.desktop' -o -name 'firefox*.desktop' \\) | head -2 | xargs -I{} cp {} '$desk/'; true"
+}
+remove_files() {
+    sshv "rm -rf '$desk/Projects' '$desk/notes.txt' '$desk/data.csv'; find '$desk' -maxdepth 1 \\( -name '*konsole*.desktop' -o -name 'org.gnome.Nautilus.desktop' -o -name 'firefox*.desktop' \\) -delete; true"
+}
+cleanup() { sshv 'pkill -f "[o]vl.py"; pkill -x linux-wallpaper; true'; remove_files; }
+
+sshv 'pkill -f "[o]vl.py"; pkill -x linux-wallpaper; true'
+remove_files
+sleep 4
+shot A
+make_files
+sleep 8
+shot B
+remove_files
+sleep 4
+shot A2
+
+# icon pixels: where B differs from the empty desktop both times, a notification that came up and stayed is in B and A2
+mask=$(python3 -W ignore - "$tmp" <<'E'
+import sys
+from PIL import Image, ImageChops
+d = sys.argv[1]
+a, a2, b = (Image.open(f'{d}/{n}.png').convert('L') for n in ('A', 'A2', 'B'))
+cut = lambda x: x.point(lambda v: 255 if v > 40 else 0)
+diff = ImageChops.multiply(cut(ImageChops.difference(a, b)), cut(ImageChops.difference(a2, b)))
+diff.save(f'{d}/mask.png')
+print(sum(1 for p in diff.getdata() if p))
+E
+)
+if [ "${mask:-0}" -lt 300 ]; then
+    cleanup
+    if [ $kde = 1 ]; then fail "Plasma's Folder View shows no icons for files on $desk (mask $mask px, screenshots in $tmp)"; else
+        skip "no desktop icon provider in this session ($session): nothing to keep above the wallpaper"
+    fi
+    exit $status
+fi
+pass "the session draws its icons ($mask px differ with files on the desktop)"
+
+sshv ". ~/sessenv; cd ~/lwe; (setsid nohup ./lwe-hints/linux-wallpaperengine ${ENGINE_ARGS:-} --screen-root $screen --assets-dir ~/lwe/assets ~/lwe/wp-$WP >/tmp/di-engine.log 2>&1 &); sleep 20"
+shot E
+
+if [ $kde = 1 ]; then
+    "$HERE/linuxvm.sh" scp "$vm" "$OVERLAY" ovl.py >/dev/null 2>&1 || { fail "overlay script not found: $OVERLAY"; cleanup; exit 1; }
+    libs='bash -c "ls /usr/lib64/libgtk4-layer-shell.so* /usr/lib/libgtk4-layer-shell.so* /usr/lib/x86_64-linux-gnu/libgtk4-layer-shell.so* 2>/dev/null | head -1"'
+    if [ -z "$(sshv "$libs")" ]; then
+        sshv 'if command -v dnf >/dev/null; then sudo dnf install -y gtk4-layer-shell python3-gobject python3-cairo
+              elif command -v pacman >/dev/null; then sudo pacman -Sy --noconfirm --needed gtk4-layer-shell python-gobject python-cairo
+              elif command -v apt-get >/dev/null; then sudo apt-get install -y gir1.2-gtk4layershell-1.0 libgtk4-layer-shell0 python3-gi python3-gi-cairo gir1.2-gtk-4.0
+              elif command -v zypper >/dev/null; then sudo zypper -n install libgtk4-layer-shell0 typelib-1_0-Gtk4LayerShell-1_0 python3-gobject python3-cairo typelib-1_0-Gtk-4_0
+              fi' >"$tmp/install.log" 2>&1
+    fi
+    lib=$(sshv "$libs")
+    if [ -z "$lib" ]; then
+        skip "gtk4-layer-shell can't be installed here ($(tail -1 "$tmp/install.log" | cut -c1-100)), the overlay can't run"
+        cleanup; exit $status
+    fi
+    preload=$(sshv 'bash -c "ls /usr/lib64/libgtk4-layer-shell.so.0 /usr/lib/libgtk4-layer-shell.so.0 /usr/lib/x86_64-linux-gnu/libgtk4-layer-shell.so.0 2>/dev/null | head -1"')
+    [ -n "$preload" ] || preload=$lib
+    make_files
+    sshv ". ~/sessenv; (setsid nohup env LD_PRELOAD=$preload GDK_BACKEND=wayland python3 ~/ovl.py $screen >/tmp/di-overlay.log 2>&1 &); sleep 8"
+    [ "$(sshv 'pgrep -fc "python3 .*[o]vl.py"')" -ge 1 ] && pass "overlay running" || fail "overlay exited: $(sshv 'head -5 /tmp/di-overlay.log')"
+else
+    make_files
+    sleep 8
+fi
+shot D
+
+if python3 -W ignore - "$tmp" <<'E'
+import sys
+from PIL import Image, ImageChops
+d = sys.argv[1]
+im = {n: Image.open(f'{d}/{n}.png').convert('L') for n in 'ABDE'}
+mask = Image.open(f'{d}/mask.png')
+def mean(x, y):
+    diff = ImageChops.difference(x, y)
+    px = [p for p, m in zip(diff.getdata(), mask.getdata()) if m]
+    return sum(px) / len(px)
+provider = mean(im['A'], im['B'])
+kept = mean(im['E'], im['D'])
+print(f'icon area: {provider:.1f} levels without the engine, {kept:.1f} with it')
+sys.exit(0 if kept > provider * 0.4 else 1)
+E
+then pass "icons visible above the wallpaper"; else fail "icons hidden by the wallpaper (screenshots in $tmp)"; fi
+
+cleanup
+echo "     screenshots: $tmp"
+exit $status

+ 89 - 0
tools/linuxvm/desktop_icons_matrix.sh

@@ -0,0 +1,89 @@
+#!/bin/bash
+# desktop_icons_matrix.sh [--lanes N] [--log file] [vm[:WxH]]... - desktop_icons_check.sh over VMs, each from its golden state,
+# LANES (default 4) at a time, VMs powered off afterwards. Without arguments: every profile, fedora-kde also at 1280x800, 2560x1440
+# and 3840x2160. The profile gives what the release gate does to get a session (LOGIN_PASSWORD at a greeter, PREP, a second
+# monitor is not used). Per VM log in <log dir>/<vm>-<size>.log, the merged result in the log file.
+# CAND is a folder with lwe-hints/ (the engine under test) copied over the guest's ~/lwe/lwe-hints, as release_check.sh does.
+# Slots: at most MAXVMS (default 5) VMs run at once over every copy of this script (a flock per slot in /tmp/lwe-vm-slots), the
+# queue itself takes LANES of them. A re-run of a VM that failed because of the harness is just another invocation with that VM
+# (`desktop_icons_matrix.sh --log x.log vm`): it takes any free slot, the fifth or one the queue left behind when it ran dry.
+HERE=$(cd "$(dirname "$0")" && pwd)
+lanes=${LANES:-4} log=$HOME/.claude/release-prep/desktop-icons/matrix.log
+list=()
+while [ $# -gt 0 ]; do
+    case $1 in
+    --lanes) lanes=$2; shift ;;
+    --log) log=$2; shift ;;
+    *) list+=("$1") ;;
+    esac
+    shift
+done
+if [ ${#list[@]} -eq 0 ]; then
+    for f in "$HERE"/profiles/*.sh; do list+=("$(basename "$f" .sh)"); done
+    list+=(fedora-kde:1280x800 fedora-kde:2560x1440 fedora-kde:3840x2160)
+fi
+dir=$(dirname "$log")
+mkdir -p "$dir"
+export HERE dir
+export MAXVMS=${MAXVMS:-5} CAND
+
+take_slot() {
+    local n
+    while :; do
+        for n in $(seq "$MAXVMS"); do
+            exec {SLOT_FD}>"/tmp/lwe-vm-slots/slot$n" 2>/dev/null || continue
+            flock -n "$SLOT_FD" && return 0
+            exec {SLOT_FD}>&-
+        done
+        sleep 10
+    done
+}
+
+one() {
+    local entry=$1 vm size out
+    mkdir -p /tmp/lwe-vm-slots
+    take_slot
+    vm=${entry%%:*}
+    size=1920x1080
+    [[ $entry == *:* ]] && size=${entry#*:}
+    out=$dir/$vm-$size.log
+    {
+        echo "=== $vm $size $(date +%T)"
+        unset SCREEN LOGIN_PASSWORD PREP ICONS
+        # shellcheck disable=SC1090
+        . "$HERE/profiles/$vm.sh" || { echo "FAIL $vm: no profile"; exit 0; }
+        if [ "$ICONS" = 0 ]; then echo "SKIP $vm: ICONS=0 in the profile"; exit 0; fi
+        "$HERE/linuxvm.sh" fresh "$vm" >/dev/null 2>&1
+        LINUXVM_SIZE=$size "$HERE/linuxvm.sh" start "$vm" >/dev/null 2>&1
+        local logged_in=0
+        for _ in $(seq 60); do
+            if [ -n "$LOGIN_PASSWORD" ] && [ $logged_in = 0 ] && "$HERE/linuxvm.sh" ssh "$vm" true </dev/null 2>/dev/null; then
+                sleep 25; "$HERE/linuxvm.sh" type "$vm" "$LOGIN_PASSWORD"; "$HERE/linuxvm.sh" keys "$vm" ret; logged_in=1
+            fi
+            "$HERE/linuxvm.sh" scp "$vm" "$HERE/sessenv.sh" lwe/sessenv.sh 2>/dev/null \
+                && "$HERE/linuxvm.sh" ssh "$vm" "bash ~/lwe/sessenv.sh" </dev/null >/dev/null 2>&1 && break
+            sleep 5
+        done
+        [ -n "$PREP" ] && "$HERE/linuxvm.sh" ssh "$vm" ". ~/sessenv; $PREP" </dev/null
+        if [ -n "$CAND" ]; then
+            "$HERE/linuxvm.sh" ssh "$vm" "rm -rf ~/lwe/lwe-hints.new" </dev/null
+            "$HERE/linuxvm.sh" scp "$vm" "$CAND/lwe-hints" lwe/lwe-hints.new \
+                && "$HERE/linuxvm.sh" ssh "$vm" "rm -rf ~/lwe/lwe-hints && mv ~/lwe/lwe-hints.new ~/lwe/lwe-hints" </dev/null
+        fi
+        sleep 20
+        timeout 900 "$HERE/desktop_icons_check.sh" "$vm" "${SCREEN:-Virtual-1}" 2>&1
+        "$HERE/linuxvm.sh" ssh "$vm" 'sudo systemctl poweroff' </dev/null >/dev/null 2>&1
+        sleep 15
+        "$HERE/linuxvm.sh" kill "$vm" >/dev/null 2>&1
+    } > "$out" 2>&1
+}
+export -f one take_slot
+
+printf '%s\n' "${list[@]}" | xargs -P "$lanes" -I{} bash -c 'one {}'
+: > "$log"
+for entry in "${list[@]}"; do
+    vm=${entry%%:*}; size=1920x1080; [[ $entry == *:* ]] && size=${entry#*:}
+    grep -hv '^     screenshots' "$dir/$vm-$size.log" >> "$log"
+done
+echo DONE >> "$log"
+grep -c '^FAIL' "$log" | sed 's/^/failed: /'

+ 2 - 1
tools/linuxvm/profiles/steamdeck.sh

@@ -4,8 +4,9 @@ SHOT_CMD=host
 FULLSCREEN_CMD='konsole --fullscreen'
 MAXIMIZE_CMD='~/lwe/maximize_kde.sh'
 WEM=app
+POINTER=0
 HIDE=1
-PREP='bash ~/lwe/hide_steam_kde.sh --watch; (setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'
+PREP='bash ~/lwe/hide_steam_kde.sh --watch; for p in AC Battery LowBattery; do for k in TurnOffDisplayWhenIdle DimDisplayWhenIdle; do kwriteconfig6 --file powerdevilrc --group $p --group Display --key $k false; done; done; systemctl --user restart plasma-powerdevil; kscreen-doctor --dpms on; (setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'
 WEM_LAUNCH='systemd-run --user --scope -q'
 EXTRA=deck_extra
 

+ 12 - 3
tools/linuxvm/release_check.sh

@@ -1,8 +1,8 @@
 #!/bin/bash
 # release_check.sh [--vm name]... [--candidate dir] [--app dir|.deb] [--no-overlay] - the release gate of
-# RELEASE_TESTING.md: every VM with a profile, one after the other, each from its golden disk (a throwaway overlay, see
+# RELEASE_TESTING.md: every VM with a profile (a lane runs its VMs one after the other, the gate uses 4 lanes with `--vm`), each from its golden disk (a throwaway overlay, see
 # `linuxvm.sh golden`), with guest_test.sh's checks (wallpapers, hotswap, pause on fullscreen, SIGKILL cleanup), the
-# frame checks, we_manager's install/launch/autostart (wem_check.sh) and update flow (update_check.sh). A failed check
+# frame checks, the desktop icons check (desktop_icons_check.sh, we_manager's overlay on Plasma), we_manager's install/launch/autostart (wem_check.sh) and update flow (update_check.sh). A failed check
 # is retried once. Writes reports/<date>/summary.md plus the screenshots and logs of every VM, exit code 1 when anything
 # failed. VMs are powered off afterwards, the overlay is thrown away (KEEP_VM=1 leaves the VM running to look at it).
 #   --vm name        only this profile (repeatable); default: every file in profiles/
@@ -115,7 +115,7 @@ run_checks() {
 }
 
 for VM in "${vms[@]}"; do
-    unset HIDE POINTER POINTER_DOCK_XY WEM_FLAGS WEM_LAUNCH LOGIN_PASSWORD SCREEN SHOT_CMD FULLSCREEN_CMD MAXIMIZE_CMD MINIMIZE_CMD MULTI MULTI_SHOT_CMD WEM WEM_FLAGS PREP EXTRA SETTLE
+    unset HIDE POINTER POINTER_DOCK_XY WEM_FLAGS WEM_LAUNCH LOGIN_PASSWORD SCREEN SHOT_CMD FULLSCREEN_CMD MAXIMIZE_CMD MINIMIZE_CMD MULTI MULTI_SHOT_CMD WEM WEM_FLAGS PREP EXTRA SETTLE ICONS
     # shellcheck disable=SC1090
     . "$HERE/profiles/$VM.sh" || { echo "no profile for $VM"; continue; }
     export WEM_FLAGS WEM_LAUNCH   # the we_manager scripts add them to its command line (COSMIC)
@@ -181,6 +181,15 @@ for VM in "${vms[@]}"; do
                 fi
                 grep -E '^(PASS|FAIL|SKIP)' "$report/$VM/pointer.txt" >> "$report/$VM/checks.txt"
             fi
+            if [ $fatal = 0 ] && [ "${ICONS:-1}" = 1 ]; then
+                sshv "pkill -f '[l]inux-wallpaperengine' 2>/dev/null; true"; sleep 3
+                "$HERE/desktop_icons_check.sh" "$VM" "$SCREEN" > "$report/$VM/icons.txt" 2>&1
+                if grep -q '^FAIL' "$report/$VM/icons.txt"; then
+                    cp "$report/$VM/icons.txt" "$report/$VM/icons-first.txt"
+                    "$HERE/desktop_icons_check.sh" "$VM" "$SCREEN" > "$report/$VM/icons.txt" 2>&1
+                fi
+                grep -E '^(PASS|FAIL|SKIP)' "$report/$VM/icons.txt" >> "$report/$VM/checks.txt"
+            fi
             if [ $fatal = 0 ] && [ -n "$app" ] && [ "${WEM:-none}" != none ]; then
                 # with the candidate's engine tarball the update check installs it (as a v99 release), we_manager's own
                 # checks then run on it instead of the last published engine

+ 1 - 1
tools/linuxvm/update_check.sh

@@ -54,7 +54,7 @@ pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manag
 sleep 2
 if [[ $app == *.deb ]]; then
     "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
-    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
+    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
 fi
 if [[ $app == *.deb ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
 sshv ". ~/sessenv; export NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-update.log 2>&1 </dev/null &); for _ in \$(seq 40); do grep -q 'DevTools listening' ~/wem/app-update.log 2>/dev/null && break; sleep 1; done; sleep 8"

+ 7 - 5
tools/linuxvm/update_golden_extension.sh

@@ -1,8 +1,9 @@
 #!/bin/bash
-# update_golden_extension.sh <vm>... - puts the repo's GNOME Shell extension.js onto the golden disk of GNOME VMs: boots a fresh
-# overlay, replaces the file, powers off and commits the overlay into golden.qcow2 (the UEFI vars are copied as well).
+# update_golden_extension.sh <vm>... - puts the repo's GNOME Shell extension (extension.js and metadata.json, the version
+# we_manager compares) onto the golden disk of GNOME VMs: boots a fresh overlay, replaces the files, powers off and commits
+# the overlay into golden.qcow2 (the UEFI vars are copied as well).
 HERE=$(cd "$(dirname "$0")" && pwd)
-ext=${LWE_EXTENSION_JS:-$HERE/../../gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js}
+extdir=${LWE_EXTENSION_DIR:-$HERE/../../gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io}
 uuid=linux-wallpaperengine@wallpaperenginelover.github.io
 lv() { "$HERE/linuxvm.sh" "$@"; }
 status=0
@@ -15,8 +16,9 @@ for vm in "$@"; do
     up=0
     for _ in $(seq 60); do lv ssh "$vm" true </dev/null >/dev/null 2>&1 && { up=1; break; }; sleep 5; done
     if [ $up = 0 ]; then echo "$vm: no ssh"; lv kill "$vm" >/dev/null 2>&1; lv fresh "$vm" >/dev/null; status=1; continue; fi
-    lv scp "$vm" "$ext" new-extension.js >/dev/null 2>&1
-    lv ssh "$vm" "d=~/.local/share/gnome-shell/extensions/$uuid; [ -d \$d ] && cp ~/new-extension.js \$d/extension.js && rm ~/new-extension.js && sync && echo copied" </dev/null
+    lv scp "$vm" "$extdir/extension.js" new-extension.js >/dev/null 2>&1
+    lv scp "$vm" "$extdir/metadata.json" new-metadata.json >/dev/null 2>&1
+    lv ssh "$vm" "d=~/.local/share/gnome-shell/extensions/$uuid; [ -d \$d ] && cp ~/new-extension.js \$d/extension.js && cp ~/new-metadata.json \$d/metadata.json && rm ~/new-extension.js ~/new-metadata.json && sync && echo copied" </dev/null
     lv ssh "$vm" 'sudo systemctl poweroff' </dev/null >/dev/null 2>&1
     for _ in $(seq 30); do pgrep -f "qemu-system.*-name $vm " >/dev/null || break; sleep 2; done
     lv stop "$vm" >/dev/null 2>&1; sleep 3

+ 1 - 1
tools/linuxvm/wem_check.sh

@@ -18,7 +18,7 @@ sshv 'mkdir -p ~/wem; pkill -f "[w]em/.*we-manager" 2>/dev/null; pkill -f "[w]e-
 "$HERE/linuxvm.sh" scp "$vm" "$HERE/cdp.py" wem/cdp.py
 if [[ $app == *.deb ]]; then
     "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
-    if sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'; then pass "the .deb installs"; else fail "the .deb did not install: $(sshv 'tail -3 /tmp/wem-deb.log')"; fi
+    if sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'; then pass "the .deb installs"; else fail "the .deb did not install: $(sshv 'tail -3 /tmp/wem-deb.log')"; fi
     start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"
 else
     tar -C "$(dirname "$app")" -cf - "$(basename "$app")" | ssh -i "$HOME/.local/share/linuxvm/id_ed25519" \

+ 3 - 0
tools/wecompare/README.md

@@ -56,6 +56,9 @@ Data locations (all overridable):
   `WE_SPAN_CURSOR` pointer positions (XTest warps, Wine reads the X pointer); grim grabs of the whole layout. It
   writes `wallpaperconfig` and starts WE without `-control` (openWallpaper rewrites the config without the layout),
   and turns `safemode` off: a killed WE leaves `faultyShutdown` set and the next start would run `-nowallpapers`.
+- `we_pause.sh <scene> <outdir> [seconds]` / `ours_pause.py <scene> <outdir>` - a global pause and resume (6 s and 12 s) under live WE
+  (desktop mode, `-control pause`; `-playInWindow` ignores it) and under this engine (mocked UPower battery with
+  `--fps-battery 0`), frame numbers of the videotex kit's `scene_pause` decoded into `frames.txt`
 - `ours_span.sh <scene> <outdir> [count] [interval] [engine args]` - this engine on the same outputs
   (`OURS_SPAN_SCREENS` = the `--screen-span` list, `none` for one `--screen-root` per output), pointer through a wlr
   virtual pointer. `../spancmp.py <we dir> <ours dir> [WxH+X+Y...]` compares the grabs per output.

+ 115 - 0
tools/wecompare/live_trail_probe.py

@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Times the ropetrail history pushes of a running real WE (Wine) from its process memory.
+
+usage: live_trail_probe.py <trail length> [seconds to sample] [pid]
+
+A WE particle system keeps the countdown to the next history push at +588 and the interval (length / segments) at
++592 (u16 segment count at +584, sub_1402308A0). The system is found by scanning for a float at +592 times the
+segment count at +584 equal to the renderer's length, with pointers where a ropetrail object has them, then +588 is read every millisecond: each frame lowers it by that frame's dt, a push resets it to the interval.
+Prints one line per detected frame: time (ms), dt (ms) or PUSH.
+"""
+import re
+import struct
+import subprocess
+import sys
+import time
+
+import numpy as np
+
+length = float(sys.argv[1])
+seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 20.0
+pid = int(sys.argv[3]) if len(sys.argv) > 3 else int(
+    subprocess.check_output(['pgrep', '-x', 'wallpaper64.exe'], text=True).split()[0])
+
+mem = open(f'/proc/{pid}/mem', 'rb', 0)
+
+
+def regions():
+    for line in open(f'/proc/{pid}/maps'):
+        parts = line.split()
+        if 'rw' not in parts[1]:
+            continue
+        a, b = (int(x, 16) for x in parts[0].split('-'))
+        if b - a <= 1 << 30:
+            yield a, b
+
+
+def read(addr, size):
+    mem.seek(addr)
+    return mem.read(size)
+
+
+def plausible(ptr):
+    return 0x10000 < ptr < 0x7FFFFFFFFFFF and ptr % 8 == 0
+
+
+def scan():
+    found = []
+    for a, b in regions():
+        try:
+            data = read(a, b - a)
+        except OSError:
+            continue
+        floats = np.frombuffer(data[: len(data) // 4 * 4], dtype='<f4')
+        with np.errstate(invalid='ignore'):
+            likely = np.nonzero((floats > 0.001) & (floats < 1.0))[0]
+        for i in likely:
+            off = int(i) * 4 - 592
+            if off < 0 or off + 616 > len(data):
+                continue
+            segments = struct.unpack_from('<H', data, off + 584)[0]
+            interval = float(floats[i])
+            timer = struct.unpack_from('<f', data, off + 588)[0]
+            if not (2 <= segments <= 128 and abs(segments * interval - length) < 1e-3
+                    and 0.0 <= timer <= interval + 1e-4):
+                continue
+            pointers = [struct.unpack_from('<Q', data, off + o)[0] for o in (512, 560, 568)]
+            if all(plausible(p) for p in pointers):
+                found.append(a + off)
+    return found
+
+
+def timer_of(addr):
+    data = read(addr + 588, 4)
+    return struct.unpack('<f', data)[0] if len(data) == 4 else None
+
+
+def lock(limit):
+    """A system that is counting: freed ones leave stale copies behind, and a particle system that is destroyed
+    (scene reload, all particles gone) has to be found again"""
+    deadline = time.perf_counter() + limit
+    while time.perf_counter() < deadline:
+        for addr in scan():
+            seen = set()
+            for _ in range(150):
+                seen.add(timer_of(addr))
+                time.sleep(0.002)
+            if len(seen) >= 2 and None not in seen:
+                return addr
+    return None
+
+
+base = lock(40)
+if base is None:
+    sys.exit('no ropetrail system found that keeps counting')
+
+print('system at', hex(base), file=sys.stderr)
+last = None
+start = time.perf_counter()
+while time.perf_counter() - start < seconds:
+    timer = timer_of(base)
+    now = (time.perf_counter() - start) * 1000.0
+    if timer is None or timer < 0 or timer > 10:
+        print(f'{now:.2f} LOST', file=sys.stderr)
+        base = lock(10)
+        last = None
+        if base is None:
+            break
+        continue
+    if last is not None and timer != last:
+        if timer > last:
+            print(f'{now:.2f} PUSH {last:.5f} -> {timer:.5f}')
+        else:
+            print(f'{now:.2f} dt {(last - timer) * 1000:.3f}')
+    last = timer
+    time.sleep(0.0005)

+ 31 - 0
tools/wecompare/wine/ours_pause.py

@@ -0,0 +1,31 @@
+# usage: ours_pause.py <scene dir> <out dir>
+# this engine through the same pause (mocked UPower OnBattery with --fps-battery 0 at 6 s, back at 12 s) as we_pause.sh,
+# on :98 (ours_window.sh), frame numbers in <out dir>/frames.txt
+import os, subprocess, sys, time, signal
+R = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
+scene = sys.argv[1]; out = sys.argv[2]
+os.makedirs(out, exist_ok=True)
+addr = out + '/sysbus.addr'
+try: os.remove(addr)
+except FileNotFoundError: pass
+fs = subprocess.Popen([sys.executable, R + '/tools/desktops/fake_system.py', addr], stdout=open(out + '/fs.log', 'w'), stderr=subprocess.STDOUT)
+for _ in range(100):
+    if os.path.exists(addr) and open(addr).read().strip(): break
+    time.sleep(0.1)
+bus = open(addr).read().strip()
+env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=bus)
+eng = subprocess.Popen(['bash', R + '/tools/wecompare/wine/ours_window.sh', scene, '40', '--fps-battery', '0', '--fps', '30'], env=env,
+                       stdout=open(out + '/engine.log', 'w'), stderr=subprocess.STDOUT)
+time.sleep(float(os.environ.get('LOAD', 8)))
+grab = subprocess.Popen([sys.executable, os.path.expanduser('~/.local/share/we_live/tests/videotex/grab_ours.py'), out + '/frames.txt', '24', ':98', '0', '0', '1920', '1080'])
+import dbus
+def setbat(v):
+    b = dbus.bus.BusConnection(bus)
+    o = dbus.Interface(b.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower'), 'org.freedesktop.DBus.Mock')
+    o.UpdateProperties('org.freedesktop.UPower', {'OnBattery': dbus.Boolean(v)})
+t0 = time.time(); ev = []
+time.sleep(6); setbat(True); ev.append((time.time() - t0, 'pause'))
+time.sleep(6); setbat(False); ev.append((time.time() - t0, 'play'))
+grab.wait()
+open(out + '/events.txt', 'w').write(''.join('%.3f %s\n' % e for e in ev))
+eng.terminate(); fs.terminate()

+ 17 - 0
tools/wecompare/wine/rdscripts/rd_disasm.py

@@ -0,0 +1,17 @@
+import os, renderdoc as rd
+# disassembly of the vertex and fragment shader bound at each event of EIDS (env CAP, EIDS, OUT); OUT gets <stage> sections
+out=open(os.environ['OUT'],'w')
+cap=rd.OpenCaptureFile(); cap.OpenFile(os.environ['CAP'],'',None)
+st,ctl=cap.OpenCapture(rd.ReplayOptions(),None)
+targets=ctl.GetDisassemblyTargets(True)
+out.write('targets %s\n'%targets)
+for eid in [int(x) for x in os.environ['EIDS'].split(',')]:
+    ctl.SetFrameEvent(eid,True)
+    s=ctl.GetPipelineState()
+    for stage in (rd.ShaderStage.Vertex, rd.ShaderStage.Fragment):
+        refl=s.GetShaderReflection(stage)
+        if refl is None: continue
+        out.write('== %d %s\n'%(eid,stage))
+        out.write(ctl.DisassembleShader(s.GetGraphicsPipelineObject(), refl, targets[0]))
+        out.write('\n')
+ctl.Shutdown(); cap.Shutdown(); out.close(); os._exit(0)

+ 115 - 0
tools/wecompare/wine/we_pause.sh

@@ -0,0 +1,115 @@
+#!/bin/bash
+# usage: we_pause.sh <scene dir> <out dir> [seconds]   (WE_SPAN_MONITORS="1920x1080+0+0")
+# live WE 2.8.42 in desktop mode on a private sway display (span_display.sh), a global pause (-control pause at
+# P_AT, default 6 s) and play (PL_AT, default 12 s) while grim grabs decode the frame number blocks of the videotex
+# kit's scene_pause (video texture + a script blinking square) into <out dir>/frames.txt (time, frame mod 128, square).
+# -playInWindow ignores -control pause (no player objects, checked with gdb), desktop mode is needed
+# the rest is we_span.sh
+# live WE 2.8.42 in desktop mode on several monitors (span_display.sh), screen grabs of the whole layout via grim
+#   WE_SPAN_MONITORS="1920x1080+0+0 1280x1024+2120+200"  the outputs (default these two)
+#   WE_SPAN_LAYOUT=0|1|2        wallpaperconfig.layout: per monitor, stretch over all ("fit" in WE's UI), clone
+#   WE_SPAN_GROUP="Monitor0,Monitor1"  a stretch group (profile.groups, layout 1) with the wallpaper on the group
+#   WE_SPAN_CURSOR="x,y x,y"    pointer position in layout pixels before each grab (the last one repeats)
+#   WE_WAIT=<seconds>           wait before the first grab (default 20)
+# WE runs in its own install copy ($WE_SPAN_DIR/we28, config.json rewritten each run) and a Wine prefix whose
+# windows are unmanaged ("Managed"="N"), so sway places WE's desktop windows where WE puts them
+ulimit -c 0
+HERE=$(cd "$(dirname "$0")" && pwd)
+S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
+P=${WE_SPAN_DIR:-$S/span}
+MONITORS=${WE_SPAN_MONITORS:-1920x1080+0+0 1280x1024+2120+200}
+bash "$HERE/span_display.sh" start $MONITORS >/dev/null || exit 1
+eval "$(bash "$HERE/span_display.sh" env)"
+X=$DISPLAY WL=$WAYLAND_DISPLAY WLR=$XDG_RUNTIME_DIR
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-$(command -v wine)}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-$(command -v wineserver)}
+export WINEPREFIX=${WE_PREFIX:-$P/wineprefix} DISPLAY=$X WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$P
+unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$P/run
+mkdir -p $P/run && chmod 700 $P/run
+export PULSE_SERVER=unix:$P/run/no-pulse PIPEWIRE_REMOTE=$P/run/no-pipewire ALSA_CONFIG_PATH=/dev/null
+$WINESERVER -k 2>/dev/null; timeout 3 tail -f /dev/null
+F=$1; [ -d "$F" ] && F=$F/scene.json
+WIN=$(echo "Z:$F" | tr '/' '\\' | tr '\\' '/')
+python3 - "$P/we28/config.json" "$WIN" "${WE_SPAN_LAYOUT:-0}" "$WE_SPAN_GROUP" <<'PY'
+import json, sys
+path, scene, layout, group = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
+config = json.load(open(path))
+# WE keeps the settings under the Windows user's name
+user = config[next(k for k, v in config.items() if isinstance(v, dict) and 'general' in v)]
+general = user['general']
+# a killed WE leaves faultyShutdown=1 in the registry, the next start then runs -nowallpapers when safemode is on
+# (sub_14000A220)
+general['user']['safemode'] = False
+user.pop('wallpaperconfig', None)
+wc = {'layout': layout, 'selectedwallpapers': {}}
+if group:
+    members = group.split(',')
+    wc['profile'] = {'groups': {'group_span': {'monitors': members, 'layout': 1}}}
+    wc['selectedwallpapers']['group_span'] = {'file': scene}
+else:
+    for i in range(8):
+        wc['selectedwallpapers']['Monitor%d' % i] = {'file': scene}
+general['wallpaperconfig'] = wc
+json.dump(config, open(path, 'w'), indent='\t')
+PY
+cd $P/we28
+: > log.txt
+EXE=$S/wedesktop.exe
+if [ ! -f "$EXE" ] || [ "$HERE/wedesktop.c" -nt "$EXE" ]; then
+    x86_64-w64-mingw32-gcc -O2 -municode -mwindows -o "$EXE" "$HERE/wedesktop.c" -luser32 -lgdi32 || exit 1
+fi
+nohup $WINE "$EXE" > $P/wedesktop.log 2>&1 &
+timeout 4 tail -f /dev/null
+# no -control: openWallpaper rewrites wallpaperconfig without the layout, WE loads selectedwallpapers by itself
+nohup $WINE wallpaper64.exe > $P/we_run_last.log 2>&1 &
+timeout ${WE_WAIT:-20} tail -f /dev/null
+mkdir -p "$2"
+# the "Wallpaper UI" pop-up and WE's small helper windows cover the wallpaper
+DISPLAY=$X python3 - <<'PY'
+from Xlib import display
+d = display.Display(); root = d.screen().root
+for w in root.query_tree().children:
+    try:
+        cls = (w.get_wm_class() or ('', ''))[1]
+        g = w.get_geometry()
+    except Exception:
+        continue
+    if cls in ('wallpaperui.exe', 'explorer.exe') or (cls == 'wallpaper64.exe' and max(g.width, g.height) < 200):
+        w.unmap()
+d.sync()
+PY
+DISPLAY=$X xwininfo -root -tree > "$2/windows.txt" 2>&1
+XDG_RUNTIME_DIR=$WLR SWAYSOCK=$(ls $WLR/sway-ipc.*.sock | head -1) swaymsg -t get_tree > "$2/sway_tree.json"
+python3 - "$2" "${3:-24}" "$WL" "$WLR" "$WINE" <<'PY'
+import glob, os, subprocess, sys, time
+import numpy as np
+out, dur, wl, runtime, wine = sys.argv[1], float(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5]
+env = dict(os.environ, WAYLAND_DISPLAY=wl, XDG_RUNTIME_DIR=runtime, SWAYSOCK=glob.glob(runtime + '/sway-ipc.*.sock')[0])
+cenv = dict(os.environ)
+pts = [(20 + b * 88 + 36) * 1920 // 640 for b in range(7)]
+t0 = time.time(); rows = []; ev = []
+sched = [(float(os.environ.get('P_AT', 6)), 'pause'), (float(os.environ.get('PL_AT', 12)), 'play')]
+procs = []
+while time.time() - t0 < dur:
+    t = time.time() - t0
+    if sched and t >= sched[0][0]:
+        _, c = sched.pop(0); ev.append((t, c))
+        procs.append(subprocess.Popen([wine, 'wallpaper64.exe', '-control', c], env=cenv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, cwd=os.getcwd()))
+    p = subprocess.run(['grim', '-t', 'ppm', '-'], env=env, capture_output=True).stdout
+    # header P6\nW H\n255\n
+    parts = p.split(b'\n', 3); w, h = map(int, parts[1].split())
+    a = np.frombuffer(parts[3], np.uint8).reshape(h, w, 3).mean(2)
+    bits = 0
+    for px in pts:
+        v = a[240 - 3:240 + 4, px - 3:px + 4].mean()
+        bits = -1 if (bits < 0 or 60 < v < 190) else bits * 2 + (v >= 190)
+    ind = int(a[240 - 3:240 + 4, 1870 - 3:1870 + 4].mean())
+    rows.append((time.time() - t0, bits, ind, w, h))
+open(out + '/frames.txt', 'w').write(''.join('%.3f %d %d\n' % r[:3] for r in rows))
+open(out + '/events.txt', 'w').write(''.join('%.3f %s\n' % e for e in ev))
+print('size', rows[0][3:], 'grabs', len(rows))
+PY
+cp $P/we28/log.txt "$2/we_log.txt"
+$WINESERVER -k 2>/dev/null