Просмотр исходного кода

better X11 handling, AUR package fixes, Hyprland support features

UwU 1 месяц назад
Родитель
Сommit
a2db23ca22
73 измененных файлов с 3203 добавлено и 241 удалено
  1. 1 1
      .github/workflows/aur.yml
  2. 8 2
      .github/workflows/cmake.yml
  3. 1 0
      .gitignore
  4. 16 4
      CMakeLists.txt
  5. 1 0
      README.md
  6. 1 1
      packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD
  7. 1 1
      packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD
  8. 16 0
      src/WallpaperEngine/Application/ApplicationContext.cpp
  9. 4 0
      src/WallpaperEngine/Application/ApplicationContext.h
  10. 33 11
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  11. 1 12
      src/WallpaperEngine/Audio/AudioStream.cpp
  12. 0 2
      src/WallpaperEngine/Audio/AudioStream.h
  13. 204 0
      src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.cpp
  14. 46 0
      src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.h
  15. 1 1
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  16. 6 18
      src/WallpaperEngine/FileSystem/Adapters/MediaCover.cpp
  17. 10 3
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  18. 30 0
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  19. 5 0
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  20. 25 0
      src/WallpaperEngine/Input/ForwardedButton.cpp
  21. 15 0
      src/WallpaperEngine/Input/ForwardedButton.h
  22. 248 0
      src/WallpaperEngine/Media/CoverDownloader.cpp
  23. 54 0
      src/WallpaperEngine/Media/CoverDownloader.h
  24. 152 0
      src/WallpaperEngine/Media/CoverImage.cpp
  25. 26 0
      src/WallpaperEngine/Media/CoverImage.h
  26. 48 0
      src/WallpaperEngine/Media/MediaSource.cpp
  27. 11 0
      src/WallpaperEngine/Media/MediaSource.h
  28. 6 10
      src/WallpaperEngine/Media/ThumbnailPalette.cpp
  29. 14 35
      src/WallpaperEngine/Render/AlbumTexture.cpp
  30. 2 0
      src/WallpaperEngine/Render/CWallpaper.h
  31. 123 33
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  32. 4 0
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  33. 2 0
      src/WallpaperEngine/Render/Drivers/Output/OutputViewport.h
  34. 51 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  35. 5 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  36. 252 0
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  37. 18 0
      src/WallpaperEngine/Render/Drivers/Output/X11Output.h
  38. 16 3
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  39. 4 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  40. 18 0
      src/WallpaperEngine/Render/Objects/CImage.cpp
  41. 2 0
      src/WallpaperEngine/Render/RenderContext.cpp
  42. 4 0
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  43. 1 0
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  44. 41 43
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  45. 9 1
      src/WallpaperEngine/Render/Wallpapers/CWeb.h
  46. 1 0
      src/WallpaperEngine/Scripting/InputObject.cpp
  47. 39 14
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  48. 7 1
      src/WallpaperEngine/Scripting/ScriptEngine.h
  49. 52 0
      src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp
  50. 256 0
      src/WallpaperEngine/Testing/Cases/MediaCover.cpp
  51. 85 0
      tests/desktops/conftest.py
  52. 53 0
      tests/desktops/test_wallpaper.py
  53. 90 0
      tests/desktops/test_x11_desktop.py
  54. 9 0
      tools/desktop_session.py
  55. 1 0
      tools/desktops/__init__.py
  56. 86 0
      tools/desktops/__main__.py
  57. 43 0
      tools/desktops/fake_system.py
  58. 19 0
      tools/desktops/fullscreen_window.py
  59. 33 0
      tools/desktops/kwin_shot.py
  60. 1 0
      tools/desktops/rootfs-arch.txt
  61. 1 0
      tools/desktops/rootfs-fedora.txt
  62. 165 0
      tools/desktops/runner.py
  63. 595 0
      tools/desktops/session.py
  64. 31 7
      tools/distro_rootfs.sh
  65. 11 3
      tools/glibc_compat/retarget_glibc_versions.py
  66. 22 4
      tools/headless_render.sh
  67. 12 6
      tools/smoke_test_release.sh
  68. 6 3
      tools/wecompare/README.md
  69. 6 4
      tools/wecompare/render_we.py
  70. 33 10
      tools/wecompare/wine/audio_sink.sh
  71. 2 2
      tools/wecompare/wine/we_capture.sh
  72. 2 2
      tools/wecompare/wine/we_cursor.sh
  73. 6 3
      tools/wecompare/wine/we_full.sh

+ 1 - 1
.github/workflows/aur.yml

@@ -19,7 +19,7 @@ jobs:
 
 
       - name: Publish linux-wallpaperengine-kde-git to the AUR
       - name: Publish linux-wallpaperengine-kde-git to the AUR
         if: env.HAS_AUR_KEY == 'true'
         if: env.HAS_AUR_KEY == 'true'
-        uses: KSXGitHub/github-actions-deploy-aur@v4.1.1
+        uses: KSXGitHub/github-actions-deploy-aur@2ac5a4c1d7035885d46b10e3193393be8460b6f1 # v4.1.1
         with:
         with:
           pkgname: linux-wallpaperengine-kde-git
           pkgname: linux-wallpaperengine-kde-git
           pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD
           pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD

+ 8 - 2
.github/workflows/cmake.yml

@@ -164,7 +164,11 @@ jobs:
           mkdir -p /tmp/libnode
           mkdir -p /tmp/libnode
           curl -fsSL "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=libnode" -o /tmp/libnode/PKGBUILD
           curl -fsSL "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=libnode" -o /tmp/libnode/PKGBUILD
           sed -i -e '/--enable-lto/d' -e "/^makedepends=/i options=('!lto')" /tmp/libnode/PKGBUILD
           sed -i -e '/--enable-lto/d' -e "/^makedepends=/i options=('!lto')" /tmp/libnode/PKGBUILD
-          echo "version=$(. /tmp/libnode/PKGBUILD && echo $pkgver-$pkgrel)" >> "$GITHUB_OUTPUT"
+          # parsed, not sourced (that would run AUR code as root); the hash keeps a changed PKGBUILD off old caches
+          pkgver="$(sed -n 's/^pkgver=//p' /tmp/libnode/PKGBUILD | tr -d "'\"")"
+          pkgrel="$(sed -n 's/^pkgrel=//p' /tmp/libnode/PKGBUILD | tr -d "'\"")"
+          [ -n "$pkgver" ] && [ -n "$pkgrel" ] || { echo "no pkgver/pkgrel in the libnode PKGBUILD" >&2; exit 1; }
+          echo "version=$pkgver-$pkgrel-$(sha256sum /tmp/libnode/PKGBUILD | cut -c1-12)" >> "$GITHUB_OUTPUT"
 
 
       - name: Cache libnode package
       - name: Cache libnode package
         if: matrix.distro == 'arch'
         if: matrix.distro == 'arch'
@@ -335,6 +339,8 @@ jobs:
   # the -bin package points at the release's portable tarball, so it is updated after the upload
   # the -bin package points at the release's portable tarball, so it is updated after the upload
   aur:
   aur:
     needs: release
     needs: release
+    # pre-release tags are no valid pkgver
+    if: ${{ !github.event.release.prerelease }}
     runs-on: ubuntu-latest
     runs-on: ubuntu-latest
     env:
     env:
       HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
       HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
@@ -347,7 +353,7 @@ jobs:
 
 
       - name: Publish linux-wallpaperengine-kde-bin to the AUR
       - name: Publish linux-wallpaperengine-kde-bin to the AUR
         if: env.HAS_AUR_KEY == 'true'
         if: env.HAS_AUR_KEY == 'true'
-        uses: KSXGitHub/github-actions-deploy-aur@v4.1.1
+        uses: KSXGitHub/github-actions-deploy-aur@2ac5a4c1d7035885d46b10e3193393be8460b6f1 # v4.1.1
         with:
         with:
           pkgname: linux-wallpaperengine-kde-bin
           pkgname: linux-wallpaperengine-kde-bin
           pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD
           pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD

+ 1 - 0
.gitignore

@@ -2,6 +2,7 @@ cmake-build-*
 .idea
 .idea
 .cache/
 .cache/
 build/
 build/
+build-*/
 .vscode/
 .vscode/
 .zed/
 .zed/
 third_party/
 third_party/

+ 16 - 4
CMakeLists.txt

@@ -45,8 +45,6 @@ find_package(V8 10.2 REQUIRED)
 set(ENABLE_OPT OFF)
 set(ENABLE_OPT OFF)
 set(SPIRV_CROSS_FORCE_PIC ON)
 set(SPIRV_CROSS_FORCE_PIC ON)
 set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 set(CMAKE_POSITION_INDEPENDENT_CODE ON)
-# kissfft's old cmake_minimum_required would otherwise override the options below
-set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
 set(KISSFFT_TEST OFF)
 set(KISSFFT_TEST OFF)
 set(KISSFFT_TOOLS OFF)
 set(KISSFFT_TOOLS OFF)
 
 
@@ -146,8 +144,11 @@ set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
 
 
 add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper)
 add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper)
 add_subdirectory(src/External/glslang-WallpaperEngine glslang)
 add_subdirectory(src/External/glslang-WallpaperEngine glslang)
+# SPIRV-Cross and kissfft want CMake < 3.13, the options set above only stick with CMP0077 NEW
+set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
 add_subdirectory(src/External/SPIRV-Cross-WallpaperEngine spirv-cross)
 add_subdirectory(src/External/SPIRV-Cross-WallpaperEngine spirv-cross)
 add_subdirectory(src/External/kissfft kissfft)
 add_subdirectory(src/External/kissfft kissfft)
+unset(CMAKE_POLICY_DEFAULT_CMP0077)
 # only msdfgen's core is needed (text MSDF glyphs), its own CMake project wants vcpkg/skia/tinyxml for the rest
 # only msdfgen's core is needed (text MSDF glyphs), its own CMake project wants vcpkg/skia/tinyxml for the rest
 file(GLOB MSDFGEN_CORE_SOURCES src/External/msdfgen/core/*.cpp)
 file(GLOB MSDFGEN_CORE_SOURCES src/External/msdfgen/core/*.cpp)
 add_library(msdfgen-core STATIC ${MSDFGEN_CORE_SOURCES})
 add_library(msdfgen-core STATIC ${MSDFGEN_CORE_SOURCES})
@@ -272,7 +273,8 @@ if(X11_SUPPORT_FOUND)
 
 
     set(X11_LIBRARIES
     set(X11_LIBRARIES
         ${X11_LIBRARIES}
         ${X11_LIBRARIES}
-        ${X11_Xrandr_LIB})
+        ${X11_Xrandr_LIB}
+        ${X11_Xext_LIB})
     set(X11_SOURCES
     set(X11_SOURCES
         src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
         src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
         src/WallpaperEngine/Render/Drivers/Output/X11Output.h
         src/WallpaperEngine/Render/Drivers/Output/X11Output.h
@@ -385,6 +387,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h
     src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h
 
 
     src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp
     src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp
+    src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.h
+    src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.cpp
     src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h
     src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.cpp
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.cpp
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h
@@ -401,9 +405,15 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Input/InputContext.cpp
     src/WallpaperEngine/Input/InputContext.cpp
     src/WallpaperEngine/Input/InputContext.h
     src/WallpaperEngine/Input/InputContext.h
     src/WallpaperEngine/Input/MouseInput.h
     src/WallpaperEngine/Input/MouseInput.h
+    src/WallpaperEngine/Input/ForwardedButton.h
+    src/WallpaperEngine/Input/ForwardedButton.cpp
     src/WallpaperEngine/Input/Drivers/GLFWMouseInput.cpp
     src/WallpaperEngine/Input/Drivers/GLFWMouseInput.cpp
     src/WallpaperEngine/Input/Drivers/GLFWMouseInput.h
     src/WallpaperEngine/Input/Drivers/GLFWMouseInput.h
 
 
+    src/WallpaperEngine/Media/CoverDownloader.h
+    src/WallpaperEngine/Media/CoverDownloader.cpp
+    src/WallpaperEngine/Media/CoverImage.h
+    src/WallpaperEngine/Media/CoverImage.cpp
     src/WallpaperEngine/Media/MediaSource.h
     src/WallpaperEngine/Media/MediaSource.h
     src/WallpaperEngine/Media/MediaSource.cpp
     src/WallpaperEngine/Media/MediaSource.cpp
     src/WallpaperEngine/Media/DBusMediaSource.h
     src/WallpaperEngine/Media/DBusMediaSource.h
@@ -672,7 +682,9 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/AudioSensitivity.cpp
         src/WallpaperEngine/Testing/Cases/AudioSensitivity.cpp
         src/WallpaperEngine/Testing/Cases/ThumbnailPalette.cpp
         src/WallpaperEngine/Testing/Cases/ThumbnailPalette.cpp
         src/WallpaperEngine/Testing/Cases/TextInputProperty.cpp
         src/WallpaperEngine/Testing/Cases/TextInputProperty.cpp
-        src/WallpaperEngine/Testing/Cases/TextLayoutRules.cpp)
+        src/WallpaperEngine/Testing/Cases/TextLayoutRules.cpp
+        src/WallpaperEngine/Testing/Cases/MediaCover.cpp
+        src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp)
 endif()
 endif()
 
 
 add_library(
 add_library(

+ 1 - 0
README.md

@@ -211,6 +211,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--disable-effect <id/name>`, `--enable-effect <id/name>` | Turn an effect off, or force a hidden one on, repeatable |
 | `--disable-effect <id/name>`, `--enable-effect <id/name>` | Turn an effect off, or force a hidden one on, repeatable |
 | `--disable-particles` | Disable particles |
 | `--disable-particles` | Disable particles |
 | `--disable-mouse` | Disable mouse interaction |
 | `--disable-mouse` | Disable mouse interaction |
+| `--input-file <path>` | Wayland: file a desktop shell writes the left button to as `{"leftDown": true}`, refreshed while it is held (ignored after 2 seconds). For shells that cover the background and swallow its pointer events |
 | `--disable-parallax` | Disable parallax |
 | `--disable-parallax` | Disable parallax |
 | `--no-fullscreen-pause` | Don't pause while an app is fullscreen |
 | `--no-fullscreen-pause` | Don't pause while an app is fullscreen |
 | `--fullscreen-pause-only-active` | Wayland only: pause only when the fullscreen window is active |
 | `--fullscreen-pause-only-active` | Wayland only: pause only when the fullscreen window is active |

+ 1 - 1
packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD

@@ -1,5 +1,5 @@
 # Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
 # Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
-# pkgver and the checksum are set by .github/workflows/aur.yml on every release
+# pkgver and the checksum are set by the aur job of .github/workflows/cmake.yml on every release
 pkgname=linux-wallpaperengine-kde-bin
 pkgname=linux-wallpaperengine-kde-bin
 _pkgname=linux-wallpaperengine-kde
 _pkgname=linux-wallpaperengine-kde
 pkgver=0.8.0
 pkgver=0.8.0

+ 1 - 1
packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD

@@ -9,7 +9,7 @@ url="https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde"
 license=('GPL-3.0-only')
 license=('GPL-3.0-only')
 # libnode (V8 for scene scripts) is in the AUR
 # libnode (V8 for scene scripts) is in the AUR
 depends=('libnode' 'mpv' 'ffmpeg' 'glew' 'glfw' 'sdl2' 'freeglut' 'glu' 'fftw' 'lz4' 'freetype2' 'harfbuzz' 'gmp'
 depends=('libnode' 'mpv' 'ffmpeg' 'glew' 'glfw' 'sdl2' 'freeglut' 'glu' 'fftw' 'lz4' 'freetype2' 'harfbuzz' 'gmp'
-    'dbus' 'wayland' 'libpulse' 'libglvnd' 'libx11' 'libxrandr' 'libxinerama' 'libxcursor' 'libxi' 'libxxf86vm'
+    'dbus' 'wayland' 'libpulse' 'libglvnd' 'libx11' 'libxext' 'libxrandr' 'libxinerama' 'libxcursor' 'libxi' 'libxxf86vm'
     'nss' 'at-spi2-core' 'libcups' 'libxcomposite' 'libxdamage' 'libxkbcommon' 'pango' 'cairo' 'alsa-lib' 'libdrm'
     'nss' 'at-spi2-core' 'libcups' 'libxcomposite' 'libxdamage' 'libxkbcommon' 'pango' 'cairo' 'alsa-lib' 'libdrm'
     'mesa' 'libxshmfence')
     'mesa' 'libxshmfence')
 makedepends=('git' 'cmake' 'glm' 'wayland-protocols' 'python')
 makedepends=('git' 'cmake' 'glm' 'wayland-protocols' 'python')

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

@@ -1089,6 +1089,15 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.flag ()
 	.flag ()
 	.action ([this] (const std::string& value) -> void { this->settings.general.expandCanvas = true; });
 	.action ([this] (const std::string& value) -> void { this->settings.general.expandCanvas = true; });
 
 
+    configurationGroup.add_argument ("--repair-assets")
+	.help (
+	    "Loads assets of broken wallpapers the way their author meant where Wallpaper Engine itself shows nothing "
+	    "useful, e.g. an image whose material names its texture \"\" (WE draws its missing texture checker, this "
+	    "loads materials/.tex). Off by default to match Wallpaper Engine"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.general.repairAssets = true; });
+
     configurationGroup.add_argument ("--post-processing")
     configurationGroup.add_argument ("--post-processing")
 	.help (
 	.help (
 	    "Wallpaper Engine's post processing quality: \"disabled\" (no bloom), \"enabled\" (default), \"ultra\" or "
 	    "Wallpaper Engine's post processing quality: \"disabled\" (no bloom), \"enabled\" (default), \"ultra\" or "
@@ -1156,6 +1165,13 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.help ("Disables mouse interaction with the backgrounds")
 	.help ("Disables mouse interaction with the backgrounds")
 	.flag ()
 	.flag ()
 	.action ([this] (const std::string& value) -> void { this->settings.mouse.enabled = false; });
 	.action ([this] (const std::string& value) -> void { this->settings.mouse.enabled = false; });
+    configurationGroup.add_argument ("--input-file")
+	.help (
+	    "File a desktop shell writes the left mouse button to, as {\"leftDown\": true} refreshed while the button "
+	    "is held (Wayland). For shells that cover the background surface, which then gets no pointer buttons. "
+	    "A file older than 2 seconds counts as released, so a shell that died cannot leave the button pressed"
+	)
+	.action ([this] (const std::string& value) -> void { this->settings.mouse.inputFile = value; });
     configurationGroup.add_argument ("--disable-parallax")
     configurationGroup.add_argument ("--disable-parallax")
 	.help ("Disables parallax effect for the backgrounds")
 	.help ("Disables parallax effect for the backgrounds")
 	.flag ()
 	.flag ()

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

@@ -119,6 +119,8 @@ public:
 	    bool disableParticles;
 	    bool disableParticles;
 	    /** Grows a scene's render canvas to fit every image layer that extends past it, see --expand-canvas */
 	    /** Grows a scene's render canvas to fit every image layer that extends past it, see --expand-canvas */
 	    bool expandCanvas;
 	    bool expandCanvas;
+	    /** Loads assets the way their author meant where WE's loader drops them, see --repair-assets */
+	    bool repairAssets = false;
 	    bool postProcessingDisabled = false;
 	    bool postProcessingDisabled = false;
 	    /** WE's "ultra" post processing quality: scenes with bloom and hdr render in HDR, see --post-processing */
 	    /** WE's "ultra" post processing quality: scenes with bloom and hdr render in HDR, see --post-processing */
 	    bool ultraPostProcessing = false;
 	    bool ultraPostProcessing = false;
@@ -251,6 +253,8 @@ public:
 	    bool disableparallax;
 	    bool disableparallax;
 	    /** Clamps parallax displacement so an image never slides past its own edges (no black corners) */
 	    /** Clamps parallax displacement so an image never slides past its own edges (no black corners) */
 	    bool clampParallaxToImageSize;
 	    bool clampParallaxToImageSize;
+	    /** where a desktop shell forwards the left button to, see --input-file */
+	    std::filesystem::path inputFile;
 	} mouse;
 	} mouse;
 
 
 	struct {
 	struct {

+ 33 - 11
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -50,7 +50,8 @@
 #include <stb_image_write.h>
 #include <stb_image_write.h>
 #include <thread>
 #include <thread>
 
 
-#define FULLSCREEN_CHECK_WAIT_TIME 250
+// microseconds, for usleep ()
+#define FULLSCREEN_CHECK_WAIT_TIME 250000
 
 
 float g_Time;
 float g_Time;
 float g_TimeLast;
 float g_TimeLast;
@@ -679,6 +680,8 @@ struct HotswapRequest {
     std::optional<std::string> disableParallax;
     std::optional<std::string> disableParallax;
     /** "on"/"off" (also "1"/"0"/"true"/"false"), see --expand-canvas. Baked in at scene build, so it reloads */
     /** "on"/"off" (also "1"/"0"/"true"/"false"), see --expand-canvas. Baked in at scene build, so it reloads */
     std::optional<std::string> expandCanvas;
     std::optional<std::string> expandCanvas;
+    /** "on"/"off", see --repair-assets. Textures are picked at scene build, so it reloads */
+    std::optional<std::string> repairAssets;
     /** hex RGB/RGBA color, e.g. "000000" or "#1a1a1aff" */
     /** hex RGB/RGBA color, e.g. "000000" or "#1a1a1aff" */
     std::optional<std::string> cornerColor;
     std::optional<std::string> cornerColor;
     /** image-filter/image-filter-strength/brightness/contrast/saturation/hue/color-options/flip, see --image-filter */
     /** image-filter/image-filter-strength/brightness/contrast/saturation/hue/color-options/flip, see --image-filter */
@@ -792,6 +795,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.disableParallax = value;
 	    request.disableParallax = value;
 	} else if (key == "expand-canvas") {
 	} else if (key == "expand-canvas") {
 	    request.expandCanvas = value;
 	    request.expandCanvas = value;
+	} else if (key == "repair-assets") {
+	    request.repairAssets = value;
 	} else if (key == "corner-color") {
 	} else if (key == "corner-color") {
 	    request.cornerColor = value;
 	    request.cornerColor = value;
 	} else if (key == "image-filter") {
 	} else if (key == "image-filter") {
@@ -907,11 +912,12 @@ void WallpaperApplication::checkHotswapRequest () {
     if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
     if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
 	&& !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
 	&& !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
 	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
 	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
-	&& !request.expandCanvas.has_value () && !request.cornerColor.has_value () && !request.imageAdjustmentsProvided
-	&& !request.speed.has_value () && !request.videoStart.has_value () && !request.videoEnd.has_value ()
-	&& !request.videoSegments.has_value () && !request.videoSeek.has_value () && !request.audioScreen.has_value ()
-	&& !request.ambientVolume.has_value () && !request.propertiesProvided && !request.audioSensitivityProvided
-	&& !request.soundVolumeProvided && !request.effectsProvided && !request.disableAnimations.has_value ()) {
+	&& !request.expandCanvas.has_value () && !request.repairAssets.has_value () && !request.cornerColor.has_value ()
+	&& !request.imageAdjustmentsProvided && !request.speed.has_value () && !request.videoStart.has_value ()
+	&& !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
+	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
+	&& !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
+	&& !request.disableAnimations.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
 	return;
     }
     }
@@ -1004,7 +1010,7 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applySoundVolumeHotswap (request.soundVolume);
 	this->applySoundVolumeHotswap (request.soundVolume);
     }
     }
 
 
-    bool expandCanvasChanged = false;
+    bool sceneSettingsChanged = false;
 
 
     if (request.expandCanvas.has_value ()) {
     if (request.expandCanvas.has_value ()) {
 	const auto& value = *request.expandCanvas;
 	const auto& value = *request.expandCanvas;
@@ -1013,11 +1019,23 @@ void WallpaperApplication::checkHotswapRequest () {
 	if (!enable && value != "off" && value != "0" && value != "false") {
 	if (!enable && value != "off" && value != "0" && value != "false") {
 	    sLog.error ("Hotswap: ignoring invalid expand-canvas value: ", value);
 	    sLog.error ("Hotswap: ignoring invalid expand-canvas value: ", value);
 	} else {
 	} else {
-	    expandCanvasChanged = this->m_context.settings.general.expandCanvas != enable;
+	    sceneSettingsChanged = this->m_context.settings.general.expandCanvas != enable;
 	    this->m_context.settings.general.expandCanvas = enable;
 	    this->m_context.settings.general.expandCanvas = enable;
 	}
 	}
     }
     }
 
 
+    if (request.repairAssets.has_value ()) {
+	const auto& value = *request.repairAssets;
+	const bool enable = value == "on" || value == "1" || value == "true";
+
+	if (!enable && value != "off" && value != "0" && value != "false") {
+	    sLog.error ("Hotswap: ignoring invalid repair-assets value: ", value);
+	} else {
+	    sceneSettingsChanged |= this->m_context.settings.general.repairAssets != enable;
+	    this->m_context.settings.general.repairAssets = enable;
+	}
+    }
+
     if (request.layersProvided) {
     if (request.layersProvided) {
 	this->m_context.settings.general.disabledObjects = request.disabledObjects;
 	this->m_context.settings.general.disabledObjects = request.disabledObjects;
 	this->m_context.settings.general.enabledObjects = request.enabledObjects;
 	this->m_context.settings.general.enabledObjects = request.enabledObjects;
@@ -1066,15 +1084,16 @@ void WallpaperApplication::checkHotswapRequest () {
     }
     }
 
 
     if (request.propertiesProvided && !request.path.has_value () && !request.layersProvided && !request.effectsProvided
     if (request.propertiesProvided && !request.path.has_value () && !request.layersProvided && !request.effectsProvided
-	&& !request.audioSensitivityProvided && !expandCanvasChanged && this->applyPropertiesLive (changedProperties)) {
+	&& !request.audioSensitivityProvided && !sceneSettingsChanged
+	&& this->applyPropertiesLive (changedProperties)) {
 	return;
 	return;
     }
     }
 
 
     // volume/xray/speed-only requests are pure live setters with nothing to reload. Properties
     // volume/xray/speed-only requests are pure live setters with nothing to reload. Properties
     // and audio sensitivity, like layers, are baked into the scene graph at parse time, so they
     // and audio sensitivity, like layers, are baked into the scene graph at parse time, so they
-    // need the same reload, as does the expanded canvas (it sizes the scene's framebuffers).
+    // need the same reload, as do the expanded canvas (it sizes the scene's framebuffers) and repaired assets.
     if (!request.path.has_value () && !request.layersProvided && !request.effectsProvided && !request.propertiesProvided
     if (!request.path.has_value () && !request.layersProvided && !request.effectsProvided && !request.propertiesProvided
-	&& !request.audioSensitivityProvided && !expandCanvasChanged) {
+	&& !request.audioSensitivityProvided && !sceneSettingsChanged) {
 	return;
 	return;
     }
     }
 
 
@@ -1269,6 +1288,9 @@ void WallpaperApplication::applyVolumeHotswap (int volume) {
 	}
 	}
     }
     }
 
 
+    // web wallpapers derive their volume from the audio policy
+    this->applyAudioPolicy ();
+
     sLog.out ("Hotswap: applied volume ", volume, " live");
     sLog.out ("Hotswap: applied volume ", volume, " live");
 }
 }
 
 

+ 1 - 12
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -285,7 +285,6 @@ void AudioStream::initialize () {
     }
     }
 
 
     this->m_queue->mutex = SDL_CreateMutex ();
     this->m_queue->mutex = SDL_CreateMutex ();
-    this->m_queue->cond = SDL_CreateCond ();
     this->m_queue->wait = SDL_CreateCond ();
     this->m_queue->wait = SDL_CreateCond ();
 
 
     this->m_decodeFrame = av_frame_alloc ();
     this->m_decodeFrame = av_frame_alloc ();
@@ -341,8 +340,6 @@ bool AudioStream::doQueue (AVPacket* pkt) {
     this->m_queue->size += entry.packet->size + sizeof (entry);
     this->m_queue->size += entry.packet->size + sizeof (entry);
     this->m_queue->duration += entry.packet->duration;
     this->m_queue->duration += entry.packet->duration;
 
 
-    SDL_CondSignal (this->m_queue->cond);
-
     return true;
     return true;
 }
 }
 
 
@@ -365,13 +362,7 @@ void AudioStream::queueLoopMarker () {
     }
     }
 }
 }
 
 
-void AudioStream::markReaderFinished () {
-    this->m_readerFinished = true;
-
-    SDL_LockMutex (this->m_queue->mutex);
-    SDL_CondSignal (this->m_queue->cond);
-    SDL_UnlockMutex (this->m_queue->mutex);
-}
+void AudioStream::markReaderFinished () { this->m_readerFinished = true; }
 
 
 AudioStream::Dequeued AudioStream::dequeuePacket () {
 AudioStream::Dequeued AudioStream::dequeuePacket () {
     MyAVPacketList entry {};
     MyAVPacketList entry {};
@@ -465,8 +456,6 @@ AVRational AudioStream::getTimeBase () const {
 
 
 int64_t AudioStream::getQueueDuration () const { return this->m_queue->duration; }
 int64_t AudioStream::getQueueDuration () const { return this->m_queue->duration; }
 
 
-SDL_mutex* AudioStream::getMutex () const { return this->m_queue->mutex; }
-
 void AudioStream::stop () {
 void AudioStream::stop () {
     if (!this->isInitialized ()) {
     if (!this->isInitialized ()) {
 	return;
 	return;

+ 0 - 2
src/WallpaperEngine/Audio/AudioStream.h

@@ -94,7 +94,6 @@ public:
      */
      */
     [[nodiscard]] int64_t getQueueDuration () const;
     [[nodiscard]] int64_t getQueueDuration () const;
     [[nodiscard]] AVRational getTimeBase () const;
     [[nodiscard]] AVRational getTimeBase () const;
-    [[nodiscard]] SDL_mutex* getMutex () const;
 
 
     /**
     /**
      * Reads a frame from the audio stream, resamples it to the driver's settings
      * Reads a frame from the audio stream, resamples it to the driver's settings
@@ -152,7 +151,6 @@ private:
 	int64_t duration = 0;
 	int64_t duration = 0;
 	SDL_mutex* mutex = nullptr;
 	SDL_mutex* mutex = nullptr;
 	SDL_cond* wait = nullptr;
 	SDL_cond* wait = nullptr;
-	SDL_cond* cond = nullptr;
     }* m_queue {};
     }* m_queue {};
 
 
     SDL_Thread* m_audioThread = nullptr;
     SDL_Thread* m_audioThread = nullptr;

+ 204 - 0
src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.cpp

@@ -0,0 +1,204 @@
+#include "PulseProcessVolume.h"
+
+#include <cstdlib>
+#include <fstream>
+#include <sstream>
+#include <string>
+
+using namespace WallpaperEngine::Audio::Drivers;
+
+namespace {
+constexpr auto RETRY_DELAY = std::chrono::seconds (2);
+
+// ppid follows the state after the command name, which can contain spaces and brackets
+pid_t parentOf (pid_t pid) {
+    std::ifstream stat ("/proc/" + std::to_string (pid) + "/stat");
+    std::string line;
+
+    if (!std::getline (stat, line)) {
+	return 0;
+    }
+
+    const auto end = line.rfind (')');
+
+    if (end == std::string::npos) {
+	return 0;
+    }
+
+    char state = 0;
+    long parent = 0;
+    std::istringstream fields (line.substr (end + 1));
+
+    return fields >> state >> parent ? static_cast<pid_t> (parent) : 0;
+}
+} // namespace
+
+PulseProcessVolume::PulseProcessVolume (pid_t root) : m_root (root) {
+    this->m_loop = pa_mainloop_new ();
+    this->connect ();
+}
+
+PulseProcessVolume::~PulseProcessVolume () {
+    this->disconnect ();
+
+    if (this->m_loop) {
+	pa_mainloop_free (this->m_loop);
+    }
+}
+
+void PulseProcessVolume::connect () {
+    this->m_context = pa_context_new (pa_mainloop_get_api (this->m_loop), "wallpaperengine-web-volume");
+
+    pa_context_set_state_callback (this->m_context, onState, this);
+    pa_context_set_subscribe_callback (this->m_context, onEvent, this);
+
+    pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOAUTOSPAWN, nullptr);
+}
+
+void PulseProcessVolume::disconnect () {
+    if (this->m_context == nullptr) {
+	return;
+    }
+
+    pa_context_set_state_callback (this->m_context, nullptr, nullptr);
+    pa_context_set_subscribe_callback (this->m_context, nullptr, nullptr);
+    pa_context_disconnect (this->m_context);
+    pa_context_unref (this->m_context);
+
+    this->m_context = nullptr;
+    this->m_known.clear ();
+}
+
+void PulseProcessVolume::setVolume (float factor) {
+    if (factor == this->m_factor) {
+	return;
+    }
+
+    this->m_factor = factor;
+
+    if (this->m_context == nullptr || pa_context_get_state (this->m_context) != PA_CONTEXT_READY) {
+	// onState() applies it once connected
+	return;
+    }
+
+    pa_operation* operation = pa_context_get_sink_input_info_list (this->m_context, onStream, this);
+
+    if (operation != nullptr) {
+	pa_operation_unref (operation);
+    }
+}
+
+void PulseProcessVolume::update () {
+    for (int i = 0; i < 32 && pa_mainloop_iterate (this->m_loop, 0, nullptr) > 0; i++) { }
+
+    if (this->m_context == nullptr) {
+	return;
+    }
+
+    const auto state = pa_context_get_state (this->m_context);
+    const auto now = std::chrono::steady_clock::now ();
+
+    if ((state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED) && now >= this->m_retryAt) {
+	this->disconnect ();
+	this->connect ();
+	this->m_retryAt = now + RETRY_DELAY;
+    }
+}
+
+bool PulseProcessVolume::descendsFromRoot (pid_t pid) const {
+    for (int depth = 0; depth < 64 && pid > 1; depth++) {
+	if (pid == this->m_root) {
+	    return true;
+	}
+
+	pid = parentOf (pid);
+    }
+
+    return false;
+}
+
+void PulseProcessVolume::adjust (const pa_sink_input_info& info) {
+    auto known = this->m_known.find (info.index);
+
+    if (known == this->m_known.end ()) {
+	bool ours = false;
+
+	if (info.proplist != nullptr) {
+	    if (const char* value = pa_proplist_gets (info.proplist, PA_PROP_APPLICATION_PROCESS_ID)) {
+		char* end = nullptr;
+		const long pid = std::strtol (value, &end, 10);
+
+		ours = *end == '\0' && pid > 0 && this->descendsFromRoot (static_cast<pid_t> (pid));
+	    }
+	}
+
+	known = this->m_known.emplace (info.index, ours).first;
+    }
+
+    if (!known->second) {
+	return;
+    }
+
+    pa_cvolume wanted;
+    pa_cvolume_set (&wanted, info.volume.channels, pa_sw_volume_from_linear (this->m_factor));
+
+    // our own change event comes back here
+    if (pa_cvolume_equal (&wanted, &info.volume)) {
+	return;
+    }
+
+    pa_operation* operation = pa_context_set_sink_input_volume (this->m_context, info.index, &wanted, nullptr, nullptr);
+
+    if (operation != nullptr) {
+	pa_operation_unref (operation);
+    }
+}
+
+void PulseProcessVolume::onState (pa_context* context, void* userdata) {
+    auto* self = static_cast<PulseProcessVolume*> (userdata);
+
+    if (pa_context_get_state (context) != PA_CONTEXT_READY) {
+	return;
+    }
+
+    pa_operation* subscribe = pa_context_subscribe (context, PA_SUBSCRIPTION_MASK_SINK_INPUT, nullptr, nullptr);
+    pa_operation* list = pa_context_get_sink_input_info_list (context, onStream, self);
+
+    if (subscribe != nullptr) {
+	pa_operation_unref (subscribe);
+    }
+
+    if (list != nullptr) {
+	pa_operation_unref (list);
+    }
+}
+
+void PulseProcessVolume::onEvent (
+    pa_context* context, pa_subscription_event_type_t type, uint32_t index, void* userdata
+) {
+    auto* self = static_cast<PulseProcessVolume*> (userdata);
+
+    if ((type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) != PA_SUBSCRIPTION_EVENT_SINK_INPUT) {
+	return;
+    }
+
+    if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
+	self->m_known.erase (index);
+	return;
+    }
+
+    // new streams start corked, so this lands before the first sample
+    pa_operation* operation = pa_context_get_sink_input_info (context, index, onStream, self);
+
+    if (operation != nullptr) {
+	pa_operation_unref (operation);
+    }
+}
+
+void PulseProcessVolume::onStream (pa_context*, const pa_sink_input_info* info, int last, void* userdata) {
+    if (last != 0 || info == nullptr) {
+	return;
+    }
+
+    static_cast<PulseProcessVolume*> (userdata)->adjust (*info);
+}

+ 46 - 0
src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.h

@@ -0,0 +1,46 @@
+#pragma once
+
+#include <chrono>
+#include <cstdint>
+#include <map>
+#include <sys/types.h>
+
+#include <pulse/pulseaudio.h>
+
+namespace WallpaperEngine::Audio::Drivers {
+/**
+ * Sets the volume of the PulseAudio streams of one process tree (matched by application.process.id), which is
+ * how --volume reaches a web wallpaper since CEF can only mute. Never blocks, failed connections are retried.
+ */
+class PulseProcessVolume {
+public:
+    explicit PulseProcessVolume (pid_t root);
+    ~PulseProcessVolume ();
+
+    PulseProcessVolume (const PulseProcessVolume&) = delete;
+    PulseProcessVolume& operator= (const PulseProcessVolume&) = delete;
+
+    /** amplitude factor like SDL's volume / 128 */
+    void setVolume (float factor);
+
+    void update ();
+
+private:
+    void connect ();
+    void disconnect ();
+    [[nodiscard]] bool descendsFromRoot (pid_t pid) const;
+    void adjust (const pa_sink_input_info& info);
+
+    static void onState (pa_context* context, void* userdata);
+    static void onEvent (pa_context* context, pa_subscription_event_type_t type, uint32_t index, void* userdata);
+    static void onStream (pa_context* context, const pa_sink_input_info* info, int last, void* userdata);
+
+    pid_t m_root;
+    float m_factor = 1.0f;
+    pa_mainloop* m_loop = nullptr;
+    pa_context* m_context = nullptr;
+    /** sink input index -> whether it is ours */
+    std::map<uint32_t, bool> m_known;
+    std::chrono::steady_clock::time_point m_retryAt {};
+};
+} // namespace WallpaperEngine::Audio::Drivers

+ 1 - 1
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -202,7 +202,7 @@ void SDLAudioDriver::removeStream (int streamId) {
 
 
 void SDLAudioDriver::setStreamVolume (int streamId, int volume) {
 void SDLAudioDriver::setStreamVolume (int streamId, int volume) {
     // no stream list lock here: every sound calls this each frame, and the audio callback holds that lock
     // no stream list lock here: every sound calls this each frame, and the audio callback holds that lock
-    // while it waits on packets for all streams, which stalled the render thread for up to ~200ms at a time.
+    // while it decodes and mixes all streams, which would make the render thread wait on every callback.
     // The map is only modified by addStream/removeStream on the render thread, the same
     // The map is only modified by addStream/removeStream on the render thread, the same
     // thread calling this, and the callback only reads it, so the lookup is safe and the volume is atomic
     // thread calling this, and the callback only reads it, so the lookup is safe and the volume is atomic
     if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
     if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {

+ 6 - 18
src/WallpaperEngine/FileSystem/Adapters/MediaCover.cpp

@@ -18,31 +18,19 @@ ReadStreamSharedPtr MediaCoverAdapter::open (const std::filesystem::path& path)
 	);
 	);
     }
     }
 
 
-    if (!source.getMediaInfo ().url.has_value ()) {
-	throw std::filesystem::filesystem_error ("Media source does not have a valid URL", path, std::error_code ());
-    }
-
-    std::string album = *source.getMediaInfo ().url;
+    const auto& cover = source.getMediaInfo ().cover;
 
 
-    if (album.starts_with ("file://")) {
-	album = album.substr (7);
-    } else {
-	throw std::filesystem::filesystem_error (
-	    "Only file:// URLs are supported for media covers", album, std::error_code ()
-	);
+    if (!cover.has_value ()) {
+	throw std::filesystem::filesystem_error ("Media source does not have a cover", path, std::error_code ());
     }
     }
 
 
-    std::filesystem::path file = std::filesystem::absolute (album);
-
-    if (std::filesystem::exists (file) == false) {
-	throw std::filesystem::filesystem_error ("Media file does not exist", file, std::error_code ());
-    }
+    const std::filesystem::path& file = *cover;
 
 
     if (std::filesystem::is_regular_file (file) == false) {
     if (std::filesystem::is_regular_file (file) == false) {
-	throw std::filesystem::filesystem_error ("Media file is not a regular file", file, std::error_code ());
+	throw std::filesystem::filesystem_error ("Media cover is not a regular file", file, std::error_code ());
     }
     }
 
 
-    return std::make_shared<std::ifstream> (file);
+    return std::make_shared<std::ifstream> (file, std::ios::binary);
 }
 }
 
 
 bool MediaCoverAdapter::exists (const std::filesystem::path& path) const { return path == ""; }
 bool MediaCoverAdapter::exists (const std::filesystem::path& path) const { return path == ""; }

+ 10 - 3
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -4,6 +4,7 @@
 
 
 #include <cstdio>
 #include <cstdio>
 #include <cstring>
 #include <cstring>
+#include <filesystem>
 #include <fstream>
 #include <fstream>
 #include <sstream>
 #include <sstream>
 #include <unistd.h>
 #include <unistd.h>
@@ -109,10 +110,16 @@ bool KDECursorInput::loadKWinScript () {
 	   << "workspace.cursorPosChanged.connect(lweReportCursorPos);\n"
 	   << "workspace.cursorPosChanged.connect(lweReportCursorPos);\n"
 	   << "lweReportCursorPos();\n";
 	   << "lweReportCursorPos();\n";
 
 
-    // inside a Flatpak only the app's own runtime folder is shared with the host
+    // inside a Flatpak only the app's own runtime folder is shared with the host, FLATPAK_ID alone can be inherited
     std::string scriptDir = runtimeDir;
     std::string scriptDir = runtimeDir;
-    if (const char* flatpakId = std::getenv ("FLATPAK_ID"); flatpakId != nullptr) {
-	scriptDir += std::string ("/app/") + flatpakId;
+    if (const char* flatpakId = std::getenv ("FLATPAK_ID");
+	flatpakId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
+	const std::string appDir = scriptDir + "/app/" + flatpakId;
+	std::error_code error;
+
+	if (std::filesystem::is_directory (appDir, error)) {
+	    scriptDir = appDir;
+	}
     }
     }
 
 
     m_scriptPath = scriptDir + "/linux-wallpaperengine-cursor-" + std::to_string (getpid ()) + ".js";
     m_scriptPath = scriptDir + "/linux-wallpaperengine-cursor-" + std::to_string (getpid ()) + ".js";

+ 30 - 0
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -1,4 +1,5 @@
 #include "WaylandMouseInput.h"
 #include "WaylandMouseInput.h"
+#include "WallpaperEngine/Input/ForwardedButton.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 #include <chrono>
 #include <chrono>
 #include <cstdlib>
 #include <cstdlib>
@@ -31,12 +32,27 @@ WaylandMouseInput::WaylandMouseInput (const WallpaperEngine::Render::Drivers::Wa
 #endif /* ENABLE_KDE_FEATURES */
 #endif /* ENABLE_KDE_FEATURES */
 }
 }
 
 
+void WaylandMouseInput::pollForwardedInput () {
+    const auto now = std::chrono::steady_clock::now ();
+
+    if (now - this->m_lastForwardedPoll < std::chrono::milliseconds (16)) {
+	return;
+    }
+
+    this->m_lastForwardedPoll = now;
+    this->m_forwardedLeftDown
+	= forwardedLeftDown (this->m_waylandDriver.getApp ().getContext ().settings.mouse.inputFile);
+}
+
 void WaylandMouseInput::update () {
 void WaylandMouseInput::update () {
     if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
     if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
 	this->m_pos = { 0, 0 };
 	this->m_pos = { 0, 0 };
+	this->m_forwardedLeftDown = false;
 	return;
 	return;
     }
     }
 
 
+    this->pollForwardedInput ();
+
     if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) {
     if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) {
 	this->m_pos = m_waylandDriver.viewportInFocus->mousePos;
 	this->m_pos = m_waylandDriver.viewportInFocus->mousePos;
 	return;
 	return;
@@ -66,6 +82,16 @@ void WaylandMouseInput::update () {
     }
     }
 }
 }
 
 
+bool WaylandMouseInput::hasGlobalCursor () const {
+#ifdef ENABLE_KDE_FEATURES
+    if (this->m_kdeCursor && this->m_kdeCursor->isInitialized ()) {
+	return true;
+    }
+#endif /* ENABLE_KDE_FEATURES */
+
+    return std::getenv ("HYPRLAND_INSTANCE_SIGNATURE") != nullptr;
+}
+
 bool WaylandMouseInput::matchViewport (const glm::dvec2& globalCursor) {
 bool WaylandMouseInput::matchViewport (const glm::dvec2& globalCursor) {
     for (const auto* viewport : this->m_waylandDriver.m_screens) {
     for (const auto* viewport : this->m_waylandDriver.m_screens) {
 	if (!viewport || viewport->size.x <= 0 || viewport->size.y <= 0) {
 	if (!viewport || viewport->size.x <= 0 || viewport->size.y <= 0) {
@@ -94,6 +120,10 @@ glm::dvec2 WaylandMouseInput::position () const {
 }
 }
 
 
 WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
 WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
+    if (this->m_forwardedLeftDown) {
+	return MouseClickStatus::Clicked;
+    }
+
     const auto* viewport = this->getActiveOutputViewport ();
     const auto* viewport = this->getActiveOutputViewport ();
     if (viewport) {
     if (viewport) {
 	return viewport->leftClick;
 	return viewport->leftClick;

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

@@ -30,6 +30,8 @@ public:
     [[nodiscard]] glm::dvec2 position () const override;
     [[nodiscard]] glm::dvec2 position () const override;
     [[nodiscard]] MouseClickStatus leftClick () const override;
     [[nodiscard]] MouseClickStatus leftClick () const override;
     [[nodiscard]] MouseClickStatus rightClick () const override;
     [[nodiscard]] MouseClickStatus rightClick () const override;
+    /** KWin's cursor script runs or Hyprland answers cursor queries */
+    [[nodiscard]] bool hasGlobalCursor () const;
 
 
 private:
 private:
     [[nodiscard]] const Render::Drivers::Output::WaylandOutputViewport* getActiveOutputViewport () const;
     [[nodiscard]] const Render::Drivers::Output::WaylandOutputViewport* getActiveOutputViewport () const;
@@ -40,11 +42,14 @@ private:
     [[nodiscard]] std::optional<glm::dvec2> queryX11CursorPosition () const;
     [[nodiscard]] std::optional<glm::dvec2> queryX11CursorPosition () const;
 #endif /* ENABLE_X11 */
 #endif /* ENABLE_X11 */
     bool matchViewport (const glm::dvec2& globalCursor);
     bool matchViewport (const glm::dvec2& globalCursor);
+    void pollForwardedInput ();
 
 
     const WallpaperEngine::Render::Drivers::WaylandOpenGLDriver& m_waylandDriver;
     const WallpaperEngine::Render::Drivers::WaylandOpenGLDriver& m_waylandDriver;
 
 
     glm::dvec2 m_pos = {};
     glm::dvec2 m_pos = {};
     std::chrono::steady_clock::time_point m_lastGlobalCursorQuery = {};
     std::chrono::steady_clock::time_point m_lastGlobalCursorQuery = {};
+    std::chrono::steady_clock::time_point m_lastForwardedPoll = {};
+    bool m_forwardedLeftDown = false;
 
 
 #ifdef ENABLE_KDE_FEATURES
 #ifdef ENABLE_KDE_FEATURES
     std::unique_ptr<KDECursorInput> m_kdeCursor;
     std::unique_ptr<KDECursorInput> m_kdeCursor;

+ 25 - 0
src/WallpaperEngine/Input/ForwardedButton.cpp

@@ -0,0 +1,25 @@
+#include "ForwardedButton.h"
+
+#include "WallpaperEngine/Data/JSON.h"
+
+#include <fstream>
+
+bool WallpaperEngine::Input::forwardedLeftDown (
+    const std::filesystem::path& path, std::chrono::seconds maxAge, std::filesystem::file_time_type now
+) {
+    if (path.empty ()) {
+	return false;
+    }
+
+    std::error_code error;
+    const auto modified = std::filesystem::last_write_time (path, error);
+
+    if (error || now - modified > maxAge) {
+	return false;
+    }
+
+    std::ifstream file (path);
+    const auto state = Data::JSON::JSON::parse (file, nullptr, false);
+
+    return state.is_object () && state.value ("leftDown", false);
+}

+ 15 - 0
src/WallpaperEngine/Input/ForwardedButton.h

@@ -0,0 +1,15 @@
+#pragma once
+
+#include <chrono>
+#include <filesystem>
+
+namespace WallpaperEngine::Input {
+/**
+ * The left button a desktop shell forwards through --input-file ({"leftDown": true}, rewritten while held). A file
+ * older than maxAge, missing or half written counts as released.
+ */
+bool forwardedLeftDown (
+    const std::filesystem::path& path, std::chrono::seconds maxAge = std::chrono::seconds (2),
+    std::filesystem::file_time_type now = std::filesystem::file_time_type::clock::now ()
+);
+} // namespace WallpaperEngine::Input

+ 248 - 0
src/WallpaperEngine/Media/CoverDownloader.cpp

@@ -0,0 +1,248 @@
+#include "CoverDownloader.h"
+
+#include "CoverImage.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <fstream>
+
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavformat/avio.h>
+#include <libavutil/dict.h>
+}
+
+using namespace WallpaperEngine::Media;
+
+namespace {
+constexpr auto DOWNLOAD_DEADLINE = std::chrono::seconds (15);
+constexpr size_t MAX_CACHED_COVERS = 64;
+
+std::filesystem::path cacheDirectory () {
+    if (const char* home = std::getenv ("XDG_CACHE_HOME"); home != nullptr && home[0] == '/') {
+	return std::filesystem::path (home) / "linux-wallpaperengine" / "covers";
+    }
+
+    if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] != '\0') {
+	return std::filesystem::path (home) / ".cache" / "linux-wallpaperengine" / "covers";
+    }
+
+    return std::filesystem::temp_directory_path () / "linux-wallpaperengine-covers";
+}
+
+// some FFmpeg builds don't find the CA bundle themselves
+const char* certificateBundle () {
+    for (const char* path :
+	 { "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem" }) {
+	if (std::filesystem::exists (path)) {
+	    return path;
+	}
+    }
+
+    return nullptr;
+}
+
+std::string hashName (const std::string& url) {
+    // FNV-1a
+    uint64_t hash = 0xcbf29ce484222325ULL;
+
+    for (const unsigned char c : url) {
+	hash = (hash ^ c) * 0x100000001b3ULL;
+    }
+
+    char name[17];
+    std::snprintf (name, sizeof (name), "%016llx", static_cast<unsigned long long> (hash));
+
+    return name;
+}
+
+struct Interrupt {
+    const std::atomic<bool>& cancelled;
+    std::chrono::steady_clock::time_point deadline;
+};
+
+int shouldAbort (void* opaque) {
+    const auto* interrupt = static_cast<const Interrupt*> (opaque);
+
+    return interrupt->cancelled || std::chrono::steady_clock::now () > interrupt->deadline;
+}
+} // namespace
+
+CoverDownloader::CoverDownloader () : m_directory (cacheDirectory ()) { }
+
+CoverDownloader::~CoverDownloader () {
+    for (const auto& job : this->m_jobs) {
+	job->cancelled = true;
+    }
+
+    for (const auto& job : this->m_jobs) {
+	if (job->thread.joinable ()) {
+	    job->thread.join ();
+	}
+    }
+}
+
+std::filesystem::path CoverDownloader::cachePath (const std::string& url) const {
+    return this->m_directory / (hashName (url) + ".img");
+}
+
+std::optional<std::filesystem::path> CoverDownloader::request (const std::string& url) {
+    for (const auto& job : this->m_jobs) {
+	if (job->url != url) {
+	    job->cancelled = true;
+	}
+    }
+
+    const auto target = this->cachePath (url);
+    std::error_code error;
+
+    if (std::filesystem::is_regular_file (target, error)) {
+	// prune() keeps the most recently used
+	std::filesystem::last_write_time (target, std::filesystem::file_time_type::clock::now (), error);
+
+	return target;
+    }
+
+    const bool running = std::ranges::any_of (this->m_jobs, [&] (const auto& job) {
+	return job->url == url && !job->cancelled && !job->finished;
+    });
+
+    if (running) {
+	return std::nullopt;
+    }
+
+    auto job = std::make_unique<Job> ();
+    job->url = url;
+    job->target = target;
+    job->thread = std::thread ([job = job.get ()] { run (*job); });
+    this->m_jobs.push_back (std::move (job));
+
+    return std::nullopt;
+}
+
+std::vector<CoverDownloader::Finished> CoverDownloader::collect () {
+    std::vector<Finished> done;
+
+    for (auto it = this->m_jobs.begin (); it != this->m_jobs.end ();) {
+	auto& job = **it;
+
+	if (!job.finished) {
+	    ++it;
+	    continue;
+	}
+
+	job.thread.join ();
+
+	done.push_back ({ job.url, job.succeeded ? std::optional (job.target) : std::nullopt });
+	it = this->m_jobs.erase (it);
+    }
+
+    if (std::ranges::any_of (done, [] (const auto& item) { return item.path.has_value (); })) {
+	this->prune ();
+    }
+
+    return done;
+}
+
+void CoverDownloader::run (Job& job) {
+    // needed by older FFmpeg builds before the first https connection
+    static const int networkReady = avformat_network_init ();
+    (void)networkReady;
+
+    const Interrupt interrupt { job.cancelled, std::chrono::steady_clock::now () + DOWNLOAD_DEADLINE };
+    const AVIOInterruptCB callback { shouldAbort, const_cast<Interrupt*> (&interrupt) };
+
+    AVDictionary* options = nullptr;
+    av_dict_set (&options, "rw_timeout", "8000000", 0);
+    av_dict_set (&options, "user_agent", "linux-wallpaperengine", 0);
+    // keep redirects off file: and other local protocols
+    av_dict_set (&options, "protocol_whitelist", "http,https,tcp,tls,crypto", 0);
+    av_dict_set (&options, "tls_verify", "1", 0);
+
+    if (const char* bundle = certificateBundle ()) {
+	av_dict_set (&options, "ca_file", bundle, 0);
+    }
+
+    AVIOContext* io = nullptr;
+    const int opened = avio_open2 (&io, job.url.c_str (), AVIO_FLAG_READ, &callback, &options);
+    av_dict_free (&options);
+
+    if (opened < 0) {
+	if (!job.cancelled) {
+	    sLog.error ("Cannot download the cover art ", job.url, " (FFmpeg error ", opened, ")");
+	}
+
+	job.finished = true;
+	return;
+    }
+
+    std::vector<uint8_t> bytes;
+    uint8_t chunk[16 * 1024];
+
+    while (true) {
+	const int count = avio_read (io, chunk, sizeof (chunk));
+
+	if (count <= 0) {
+	    break;
+	}
+
+	bytes.insert (bytes.end (), chunk, chunk + count);
+
+	if (bytes.size () > MAX_COVER_BYTES) {
+	    bytes.clear ();
+	    break;
+	}
+    }
+
+    avio_closep (&io);
+
+    if (!job.cancelled && !bytes.empty () && decodeCoverImage (bytes).has_value ()) {
+	std::error_code error;
+	std::filesystem::create_directories (job.target.parent_path (), error);
+
+	// two jobs for one url can overlap
+	static std::atomic<unsigned> counter = 0;
+	auto partial = job.target;
+	partial += "." + std::to_string (counter++) + ".part";
+
+	{
+	    std::ofstream file (partial, std::ios::binary | std::ios::trunc);
+	    file.write (reinterpret_cast<const char*> (bytes.data ()), static_cast<std::streamsize> (bytes.size ()));
+	}
+
+	std::filesystem::rename (partial, job.target, error);
+	job.succeeded = !error;
+
+	if (error) {
+	    std::filesystem::remove (partial, error);
+	}
+    } else if (!job.cancelled) {
+	sLog.error ("The cover art ", job.url, " is not a usable image");
+    }
+
+    job.finished = true;
+}
+
+void CoverDownloader::prune () const {
+    std::error_code error;
+    std::vector<std::pair<std::filesystem::file_time_type, std::filesystem::path>> files;
+
+    for (const auto& entry : std::filesystem::directory_iterator (this->m_directory, error)) {
+	if (entry.is_regular_file (error) && entry.path ().extension () == ".img") {
+	    files.emplace_back (entry.last_write_time (error), entry.path ());
+	}
+    }
+
+    if (files.size () <= MAX_CACHED_COVERS) {
+	return;
+    }
+
+    std::ranges::sort (files);
+
+    for (size_t i = 0; i + MAX_CACHED_COVERS < files.size (); i++) {
+	std::filesystem::remove (files[i].second, error);
+    }
+}

+ 54 - 0
src/WallpaperEngine/Media/CoverDownloader.h

@@ -0,0 +1,54 @@
+#pragma once
+
+#include <atomic>
+#include <filesystem>
+#include <list>
+#include <memory>
+#include <optional>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace WallpaperEngine::Media {
+/**
+ * Downloads http(s) cover art on worker threads into the cache folder, so every cover user gets a local path.
+ * Uses FFmpeg's I/O layer (already linked, brings TLS) instead of libcurl.
+ */
+class CoverDownloader {
+public:
+    struct Finished {
+	std::string url;
+	std::optional<std::filesystem::path> path;
+    };
+
+    CoverDownloader ();
+    ~CoverDownloader ();
+
+    CoverDownloader (const CoverDownloader&) = delete;
+    CoverDownloader& operator= (const CoverDownloader&) = delete;
+
+    /** The cached copy, or nothing while the download (started once) runs. Cancels downloads of other urls */
+    std::optional<std::filesystem::path> request (const std::string& url);
+
+    /** Downloads finished since the last call */
+    std::vector<Finished> collect ();
+
+    [[nodiscard]] std::filesystem::path cachePath (const std::string& url) const;
+
+private:
+    struct Job {
+	std::string url;
+	std::filesystem::path target;
+	std::thread thread;
+	std::atomic<bool> finished = false;
+	std::atomic<bool> cancelled = false;
+	bool succeeded = false;
+    };
+
+    static void run (Job& job);
+    void prune () const;
+
+    std::filesystem::path m_directory;
+    std::list<std::unique_ptr<Job>> m_jobs;
+};
+} // namespace WallpaperEngine::Media

+ 152 - 0
src/WallpaperEngine/Media/CoverImage.cpp

@@ -0,0 +1,152 @@
+#include "CoverImage.h"
+
+#include "WallpaperEngine/Splat/SogLoader.h"
+
+#include <cstring>
+#include <fstream>
+#include <string>
+
+#include "stb_image.h"
+
+using namespace WallpaperEngine::Media;
+
+namespace {
+constexpr int MAX_COVER_SIDE = 4096;
+
+int hexValue (char c) {
+    if (c >= '0' && c <= '9') {
+	return c - '0';
+    }
+
+    if (c >= 'a' && c <= 'f') {
+	return c - 'a' + 10;
+    }
+
+    if (c >= 'A' && c <= 'F') {
+	return c - 'A' + 10;
+    }
+
+    return -1;
+}
+
+bool isWebP (std::span<const uint8_t> bytes) {
+    return bytes.size () >= 12 && std::memcmp (bytes.data (), "RIFF", 4) == 0
+	&& std::memcmp (bytes.data () + 8, "WEBP", 4) == 0;
+}
+} // namespace
+
+std::optional<std::filesystem::path> WallpaperEngine::Media::localCoverPath (std::string_view url) {
+    constexpr std::string_view scheme = "file://";
+
+    if (!url.starts_with (scheme)) {
+	return std::nullopt;
+    }
+
+    url.remove_prefix (scheme.size ());
+
+    if (url.starts_with ("localhost/")) {
+	url.remove_prefix (9);
+    }
+
+    if (!url.starts_with ('/')) {
+	return std::nullopt;
+    }
+
+    std::string path;
+    path.reserve (url.size ());
+
+    for (size_t i = 0; i < url.size (); i++) {
+	char c = url[i];
+
+	if (c == '?' || c == '#') {
+	    break;
+	}
+
+	if (c == '%') {
+	    const int high = i + 2 < url.size () ? hexValue (url[i + 1]) : -1;
+	    const int low = i + 2 < url.size () ? hexValue (url[i + 2]) : -1;
+
+	    if (high < 0 || low < 0) {
+		return std::nullopt;
+	    }
+
+	    c = static_cast<char> (high << 4 | low);
+	    i += 2;
+	}
+
+	if (c == '\0') {
+	    return std::nullopt;
+	}
+
+	path += c;
+    }
+
+    return std::filesystem::path (path);
+}
+
+std::optional<CoverImage> WallpaperEngine::Media::decodeCoverImage (std::span<const uint8_t> bytes) {
+    if (bytes.empty () || bytes.size () > MAX_COVER_BYTES) {
+	return std::nullopt;
+    }
+
+    CoverImage image;
+
+    if (isWebP (bytes)) {
+	try {
+	    auto decoded
+		= Splat::decodeWebP (std::string (reinterpret_cast<const char*> (bytes.data ()), bytes.size ()));
+
+	    image.width = decoded.width;
+	    image.height = decoded.height;
+	    image.rgba = std::move (decoded.rgba);
+	} catch (const std::exception&) {
+	    return std::nullopt;
+	}
+    } else {
+	int channels = 0;
+
+	// check the size before decoding
+	if (!stbi_info_from_memory (
+		bytes.data (), static_cast<int> (bytes.size ()), &image.width, &image.height, &channels
+	    )
+	    || image.width <= 0 || image.height <= 0 || image.width > MAX_COVER_SIDE || image.height > MAX_COVER_SIDE) {
+	    return std::nullopt;
+	}
+
+	auto* pixels = stbi_load_from_memory (
+	    bytes.data (), static_cast<int> (bytes.size ()), &image.width, &image.height, &channels, 4
+	);
+
+	if (pixels == nullptr) {
+	    return std::nullopt;
+	}
+
+	image.rgba.assign (pixels, pixels + static_cast<size_t> (image.width) * image.height * 4);
+	stbi_image_free (pixels);
+    }
+
+    if (image.width <= 0 || image.height <= 0 || image.width > MAX_COVER_SIDE || image.height > MAX_COVER_SIDE
+	|| image.rgba.size () != static_cast<size_t> (image.width) * image.height * 4) {
+	return std::nullopt;
+    }
+
+    return image;
+}
+
+std::optional<CoverImage> WallpaperEngine::Media::loadCoverImage (const std::filesystem::path& path) {
+    std::error_code error;
+    const auto size = std::filesystem::file_size (path, error);
+
+    if (error || size == 0 || size > MAX_COVER_BYTES) {
+	return std::nullopt;
+    }
+
+    std::ifstream file (path, std::ios::binary);
+    std::vector<uint8_t> bytes (size);
+
+    if (!file.read (reinterpret_cast<char*> (bytes.data ()), static_cast<std::streamsize> (size))) {
+	return std::nullopt;
+    }
+
+    return decodeCoverImage (bytes);
+}

+ 26 - 0
src/WallpaperEngine/Media/CoverImage.h

@@ -0,0 +1,26 @@
+#pragma once
+
+#include <cstdint>
+#include <filesystem>
+#include <optional>
+#include <span>
+#include <string_view>
+#include <vector>
+
+namespace WallpaperEngine::Media {
+struct CoverImage {
+    int width = 0;
+    int height = 0;
+    std::vector<uint8_t> rgba;
+};
+
+/** Path of a percent encoded file:// MPRIS art URL, nothing for other schemes or bad escapes */
+std::optional<std::filesystem::path> localCoverPath (std::string_view url);
+
+/** Format is sniffed, browsers write WebP into .jpg files. Refuses sides over 4096 */
+std::optional<CoverImage> decodeCoverImage (std::span<const uint8_t> bytes);
+
+std::optional<CoverImage> loadCoverImage (const std::filesystem::path& path);
+
+constexpr size_t MAX_COVER_BYTES = 16 * 1024 * 1024;
+} // namespace WallpaperEngine::Media

+ 48 - 0
src/WallpaperEngine/Media/MediaSource.cpp

@@ -1,5 +1,8 @@
 #include "MediaSource.h"
 #include "MediaSource.h"
 
 
+#include "CoverDownloader.h"
+#include "CoverImage.h"
+
 #include <ranges>
 #include <ranges>
 
 
 using namespace WallpaperEngine::Media;
 using namespace WallpaperEngine::Media;
@@ -28,6 +31,18 @@ MediaSource::~MediaSource () {
 }
 }
 
 
 void MediaSource::update () {
 void MediaSource::update () {
+    if (this->m_covers) {
+	for (const auto& finished : this->m_covers->collect ()) {
+	    // a download of the previous track can land after the player moved on
+	    if (!finished.path.has_value () || this->m_mediaInfo.url != finished.url) {
+		continue;
+	    }
+
+	    this->m_mediaInfo.cover = finished.path;
+	    this->notifyAlbumArtListeners ();
+	}
+    }
+
     auto now = std::chrono::steady_clock::now ();
     auto now = std::chrono::steady_clock::now ();
 
 
     if (now <= m_nextUpdate) {
     if (now <= m_nextUpdate) {
@@ -78,7 +93,40 @@ void MediaSource::fireMetadataListeners () {
 }
 }
 
 
 void MediaSource::fireAlbumArtListeners () {
 void MediaSource::fireAlbumArtListeners () {
+    this->resolveCover ();
+    this->notifyAlbumArtListeners ();
+}
+
+void MediaSource::notifyAlbumArtListeners () {
     for (auto& listener : m_albumArtListeners | std::views::values) {
     for (auto& listener : m_albumArtListeners | std::views::values) {
 	listener (m_mediaInfo);
 	listener (m_mediaInfo);
     }
     }
+}
+
+void MediaSource::resolveCover () {
+    this->m_mediaInfo.cover.reset ();
+
+    if (!this->m_mediaInfo.url.has_value ()) {
+	return;
+    }
+
+    const auto& url = *this->m_mediaInfo.url;
+
+    if (url.starts_with ("http://") || url.starts_with ("https://")) {
+	if (!this->m_covers) {
+	    this->m_covers = std::make_unique<CoverDownloader> ();
+	}
+
+	// starts the download if not cached, listeners fire again once it lands
+	this->m_mediaInfo.cover = this->m_covers->request (url);
+	return;
+    }
+
+    if (const auto path = localCoverPath (url); path.has_value ()) {
+	std::error_code error;
+
+	if (std::filesystem::is_regular_file (*path, error)) {
+	    this->m_mediaInfo.cover = *path;
+	}
+    }
 }
 }

+ 11 - 0
src/WallpaperEngine/Media/MediaSource.h

@@ -1,6 +1,7 @@
 #pragma once
 #pragma once
 
 
 #include <chrono>
 #include <chrono>
+#include <filesystem>
 #include <functional>
 #include <functional>
 #include <map>
 #include <map>
 #include <memory>
 #include <memory>
@@ -8,6 +9,8 @@
 #include <string>
 #include <string>
 
 
 namespace WallpaperEngine::Media {
 namespace WallpaperEngine::Media {
+class CoverDownloader;
+
 class MediaSource {
 class MediaSource {
 public:
 public:
     enum PlaybackState {
     enum PlaybackState {
@@ -24,7 +27,10 @@ public:
 	/** first of MPRIS's list */
 	/** first of MPRIS's list */
 	std::string albumArtist;
 	std::string albumArtist;
 	std::string genres;
 	std::string genres;
+	/** raw MPRIS art URL */
 	std::optional<std::string> url;
 	std::optional<std::string> url;
+	/** local cover file: the file:// path or the downloaded copy of an http(s) URL */
+	std::optional<std::filesystem::path> cover;
 	double duration;
 	double duration;
 	double position;
 	double position;
 	bool available;
 	bool available;
@@ -61,7 +67,12 @@ protected:
     uint32_t m_albumArtListenerId = 0;
     uint32_t m_albumArtListenerId = 0;
     std::map<uint32_t, std::function<void (MediaInfo&)>> m_albumArtListeners;
     std::map<uint32_t, std::function<void (MediaInfo&)>> m_albumArtListeners;
     MediaInfo m_mediaInfo;
     MediaInfo m_mediaInfo;
+    std::unique_ptr<CoverDownloader> m_covers;
     std::chrono::milliseconds m_updateInterval;
     std::chrono::milliseconds m_updateInterval;
     std::chrono::time_point<std::chrono::steady_clock> m_nextUpdate;
     std::chrono::time_point<std::chrono::steady_clock> m_nextUpdate;
+
+private:
+    void resolveCover ();
+    void notifyAlbumArtListeners ();
 };
 };
 }
 }

+ 6 - 10
src/WallpaperEngine/Media/ThumbnailPalette.cpp

@@ -1,6 +1,6 @@
 #include "ThumbnailPalette.h"
 #include "ThumbnailPalette.h"
 
 
-#include "stb_image.h"
+#include "CoverImage.h"
 
 
 #include <algorithm>
 #include <algorithm>
 #include <array>
 #include <array>
@@ -132,17 +132,13 @@ ThumbnailPalette WallpaperEngine::Media::computeThumbnailPalette (const uint8_t*
 }
 }
 
 
 ThumbnailPalette WallpaperEngine::Media::loadThumbnailPalette (const std::string& path) {
 ThumbnailPalette WallpaperEngine::Media::loadThumbnailPalette (const std::string& path) {
-    int width = 0;
-    int height = 0;
-    int channels = 0;
-    auto* pixels = stbi_load (path.c_str (), &width, &height, &channels, 4);
+    const auto image = loadCoverImage (path);
 
 
-    if (pixels == nullptr) {
+    if (!image.has_value ()) {
 	return {};
 	return {};
     }
     }
 
 
-    const auto palette = computeThumbnailPalette (pixels, static_cast<size_t> (width), static_cast<size_t> (height));
-    stbi_image_free (pixels);
-
-    return palette;
+    return computeThumbnailPalette (
+	image->rgba.data (), static_cast<size_t> (image->width), static_cast<size_t> (image->height)
+    );
 }
 }

+ 14 - 35
src/WallpaperEngine/Render/AlbumTexture.cpp

@@ -2,29 +2,13 @@
 
 
 #include "RenderContext.h"
 #include "RenderContext.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
-#include "WallpaperEngine/Data/Utils/ScopeGuard.h"
+#include "WallpaperEngine/Media/CoverImage.h"
 #include "WallpaperEngine/Media/MediaSource.h"
 #include "WallpaperEngine/Media/MediaSource.h"
-#include "stb_image.h"
 
 
-using namespace WallpaperEngine::Render;
-
-int albumtexture_read (void* user, char* data, int size) {
-    auto* stream = static_cast<ReadStream*> (user);
-
-    stream->read (data, size);
-
-    return stream->gcount ();
-}
-
-void albumtexture_skip (void* user, int n) {
-    auto* stream = static_cast<ReadStream*> (user);
-    stream->seekg (n, std::ios::cur);
-}
-
-int albumtexture_eof (void* user) { return static_cast<ReadStream*> (user)->eof (); }
+#include <iterator>
+#include <span>
 
 
-stbi_io_callbacks album_texture_callbacks
-    = { .read = albumtexture_read, .skip = albumtexture_skip, .eof = albumtexture_eof };
+using namespace WallpaperEngine::Render;
 
 
 AlbumTexture::AlbumTexture (RenderContext& context) : Helpers::ContextAware (context) {
 AlbumTexture::AlbumTexture (RenderContext& context) : Helpers::ContextAware (context) {
     this->m_resolution = glm::vec4 (1.0f, 1.0f, 1.0f, 1.0f);
     this->m_resolution = glm::vec4 (1.0f, 1.0f, 1.0f, 1.0f);
@@ -90,28 +74,23 @@ void AlbumTexture::load () const {
     for (const auto& project : this->getContext ().getApp ().getBackgrounds () | std::views::values) {
     for (const auto& project : this->getContext ().getApp ().getBackgrounds () | std::views::values) {
 	try {
 	try {
 	    auto contents = project->assetLocator->read ("$mediaThumbnail");
 	    auto contents = project->assetLocator->read ("$mediaThumbnail");
+	    const std::string data ((std::istreambuf_iterator<char> (*contents)), std::istreambuf_iterator<char> ());
+	    const auto image
+		= Media::decodeCoverImage (std::span (reinterpret_cast<const uint8_t*> (data.data ()), data.size ()));
 
 
-	    int width, height, channels;
-
-	    auto* dataptr
-		= stbi_load_from_callbacks (&album_texture_callbacks, contents.get (), &width, &height, &channels, 4);
-
-	    if (dataptr == nullptr) {
-		continue;
-	    }
-
-	    ScopeGuard guard ([dataptr] { stbi_image_free (dataptr); });
-
-	    if (width == 0 || height == 0) {
+	    if (!image.has_value ()) {
 		continue;
 		continue;
 	    }
 	    }
 
 
-	    this->m_width = width;
-	    this->m_height = height;
+	    this->m_width = image->width;
+	    this->m_height = image->height;
 	    this->m_resolution = glm::vec4 (this->m_width, this->m_height, this->m_width, this->m_height);
 	    this->m_resolution = glm::vec4 (this->m_width, this->m_height, this->m_width, this->m_height);
 
 
 	    glBindTexture (GL_TEXTURE_2D, this->m_textureID);
 	    glBindTexture (GL_TEXTURE_2D, this->m_textureID);
-	    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, dataptr);
+	    glTexImage2D (
+		GL_TEXTURE_2D, 0, GL_RGBA, image->width, image->height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
+		image->rgba.data ()
+	    );
 	    return;
 	    return;
 	} catch (AssetLoadException&) {
 	} catch (AssetLoadException&) {
 	    // this is expected if the thumbnail is not available
 	    // this is expected if the thumbnail is not available

+ 2 - 0
src/WallpaperEngine/Render/CWallpaper.h

@@ -133,6 +133,8 @@ public:
     [[nodiscard]] virtual int getCanvasHeight () const { return this->getHeight (); }
     [[nodiscard]] virtual int getCanvasHeight () const { return this->getHeight (); }
     /** Scenes render at the output's size with the scaling mode folded into their projection, like WE does */
     /** Scenes render at the output's size with the scaling mode folded into their projection, like WE does */
     [[nodiscard]] virtual bool rendersAtOutputSize () const { return false; }
     [[nodiscard]] virtual bool rendersAtOutputSize () const { return false; }
+    /** Whether the wallpaper uses pointer buttons, otherwise clicks can pass through to the desktop below */
+    [[nodiscard]] virtual bool wantsPointerButtons () const { return false; }
     /** The part of the framebuffer the output shows as ustart, uend, vstart, vend */
     /** The part of the framebuffer the output shows as ustart, uend, vstart, vend */
     [[nodiscard]] glm::vec4 getOutputUVs () const;
     [[nodiscard]] glm::vec4 getOutputUVs () const;
     [[nodiscard]] int getFramebufferWidth () const;
     [[nodiscard]] int getFramebufferWidth () const;

+ 123 - 33
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -1,11 +1,18 @@
 #include "X11FullScreenDetector.h"
 #include "X11FullScreenDetector.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 
+#include <algorithm>
+
+#include <X11/Xatom.h>
 #include <X11/Xlib.h>
 #include <X11/Xlib.h>
 #include <X11/extensions/Xrandr.h>
 #include <X11/extensions/Xrandr.h>
 
 
 #include "WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h"
 #include "WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h"
+
+#define GLFW_EXPOSE_NATIVE_X11
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
+#include <GLFW/glfw3.h>
+#include <GLFW/glfw3native.h>
 
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
 namespace WallpaperEngine::Render::Drivers::Detectors {
 void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
 void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
@@ -48,57 +55,140 @@ X11FullScreenDetector::X11FullScreenDetector (Application::ApplicationContext& a
 X11FullScreenDetector::~X11FullScreenDetector () { this->stop (); }
 X11FullScreenDetector::~X11FullScreenDetector () { this->stop (); }
 
 
 bool X11FullScreenDetector::anythingFullscreen () const {
 bool X11FullScreenDetector::anythingFullscreen () const {
-    bool isFullscreen = false;
-    XWindowAttributes attribs;
-    Window _;
-    Window* children;
-    unsigned int nchildren;
+    Window root, parent;
+    Window* children = nullptr;
+    unsigned int childCount = 0;
 
 
-    if (!XQueryTree (this->m_display, this->m_root, &_, &_, &children, &nchildren)) {
+    if (!XQueryTree (this->m_display, this->m_root, &root, &parent, &children, &childCount)) {
 	return false;
 	return false;
     }
     }
 
 
-    const auto ourWindow = reinterpret_cast<Window> (dynamic_cast<GLFWOpenGLDriver&> (this->m_driver).getWindow ());
-    Window parentWindow;
+    const Window ourWindow = glfwGetX11Window (dynamic_cast<GLFWOpenGLDriver&> (this->m_driver).getWindow ());
+    bool fullscreen = false;
 
 
-    {
-	Window root, *schildren = nullptr;
-	unsigned int num_children;
+    for (unsigned int i = 0; i < childCount && !fullscreen; i++) {
+	XWindowAttributes attributes;
 
 
-	if (!XQueryTree (this->m_display, ourWindow, &root, &parentWindow, &schildren, &num_children)) {
-	    return false;
+	if (!XGetWindowAttributes (this->m_display, children[i], &attributes) || attributes.map_state != IsViewable) {
+	    continue;
 	}
 	}
 
 
-	if (schildren) {
-	    XFree (children);
-	}
-    }
+	// only managed windows count, WM/compositor helpers and our desktop window cover the screen too
+	const Window client = this->clientOf (children[i]);
 
 
-    for (unsigned int i = 0; i < nchildren; i++) {
-	if (!XGetWindowAttributes (this->m_display, children[i], &attribs)) {
+	if (client == None || client == ourWindow || this->isDesktopWindow (client)) {
 	    continue;
 	    continue;
 	}
 	}
 
 
-	if (ourWindow == children[i] || parentWindow == children[i]) {
-	    continue;
-	}
+	fullscreen = this->hasFullscreenState (client) || this->coversScreen (client);
+    }
 
 
-	if (attribs.map_state != IsViewable) {
-	    continue;
-	}
+    XFree (children);
 
 
-	for (const auto& [name, viewport] : this->m_screens) {
-	    if (attribs.x == viewport.x && attribs.y == viewport.y && attribs.width == viewport.z
-		&& attribs.height == viewport.w) {
-		isFullscreen = true;
-		break;
-	    }
+    return fullscreen;
+}
+
+bool X11FullScreenDetector::hasFullscreenState (Window client) const {
+    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
+    const Atom fullscreenAtom = XInternAtom (this->m_display, "_NET_WM_STATE_FULLSCREEN", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool fullscreen = false;
+
+    if (XGetWindowProperty (
+	    this->m_display, client, stateAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32) {
+	const auto* atoms = reinterpret_cast<const Atom*> (data);
+	fullscreen = std::find (atoms, atoms + count, fullscreenAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    return fullscreen;
+}
+
+bool X11FullScreenDetector::coversScreen (Window client) const {
+    // window managers without EWMH: the client (not its frame) has an output's geometry
+    XWindowAttributes attributes;
+    int x = 0, y = 0;
+    Window child;
+
+    if (!XGetWindowAttributes (this->m_display, client, &attributes)
+	|| !XTranslateCoordinates (this->m_display, client, this->m_root, 0, 0, &x, &y, &child)) {
+	return false;
+    }
+
+    return std::ranges::any_of (this->m_screens, [&] (const auto& entry) {
+	const auto& screen = entry.second;
+	return x == screen.x && y == screen.y && attributes.width == screen.z && attributes.height == screen.w;
+    });
+}
+
+Window X11FullScreenDetector::clientOf (Window window) const {
+    // the client inside a WM frame is the window with WM_STATE
+    const Atom wmState = XInternAtom (this->m_display, "WM_STATE", False);
+    Atom type = None;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+
+    XGetWindowProperty (
+	this->m_display, window, wmState, 0, 0, False, AnyPropertyType, &type, &format, &count, &remaining, &data
+    );
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    if (type != None) {
+	return window;
+    }
+
+    Window root, parent, *children = nullptr;
+    unsigned int childCount = 0;
+    Window client = None;
+
+    if (XQueryTree (this->m_display, window, &root, &parent, &children, &childCount)) {
+	for (unsigned int i = 0; i < childCount && client == None; i++) {
+	    client = this->clientOf (children[i]);
 	}
 	}
     }
     }
 
 
-    XFree (children);
+    if (children != nullptr) {
+	XFree (children);
+    }
+
+    return client;
+}
+
+bool X11FullScreenDetector::isDesktopWindow (Window window) const {
+
+    const Atom typeAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE", False);
+    const Atom desktopAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool desktop = false;
+
+    if (XGetWindowProperty (
+	    this->m_display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32) {
+	const auto* atoms = reinterpret_cast<const Atom*> (data);
+	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
 
 
-    return isFullscreen;
+    return desktop;
 }
 }
 
 
 void X11FullScreenDetector::reset () {
 void X11FullScreenDetector::reset () {

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

@@ -22,6 +22,10 @@ namespace Detectors {
 
 
     private:
     private:
 	void initialize ();
 	void initialize ();
+	[[nodiscard]] bool isDesktopWindow (Window window) const;
+	[[nodiscard]] Window clientOf (Window window) const;
+	[[nodiscard]] bool hasFullscreenState (Window client) const;
+	[[nodiscard]] bool coversScreen (Window client) const;
 	void stop ();
 	void stop ();
 
 
 	Display* m_display = nullptr;
 	Display* m_display = nullptr;

+ 2 - 0
src/WallpaperEngine/Render/Drivers/Output/OutputViewport.h

@@ -24,6 +24,8 @@ public:
     virtual void swapOutput () = 0;
     virtual void swapOutput () = 0;
     /** The surface is tagged as PQ with BT.2020 primaries, what gets drawn has to be encoded that way */
     /** The surface is tagged as PQ with BT.2020 primaries, what gets drawn has to be encoded that way */
     [[nodiscard]] virtual bool isHDR () const { return false; }
     [[nodiscard]] virtual bool isHDR () const { return false; }
+    /** whether pointer buttons over the output go to the wallpaper or through to the desktop below */
+    virtual void setWantsPointerButtons (bool wants) { }
     /** The output's reference white and peak in nits while it runs in HDR, zero when unknown */
     /** The output's reference white and peak in nits while it runs in HDR, zero when unknown */
     [[nodiscard]] virtual glm::vec2 getHDRLuminance () const { return glm::vec2 (0.0f); }
     [[nodiscard]] virtual glm::vec2 getHDRLuminance () const { return glm::vec2 (0.0f); }
 };
 };

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

@@ -35,7 +35,8 @@ static void handleLSConfigure (void* data, zwlr_layer_surface_v1* surface, uint3
 static void handleLSClosed (void* data, zwlr_layer_surface_v1* surface) {
 static void handleLSClosed (void* data, zwlr_layer_surface_v1* surface) {
     const auto viewport = static_cast<WaylandOutputViewport*> (data);
     const auto viewport = static_cast<WaylandOutputViewport*> (data);
 
 
-    viewport->getDriver ()->onLayerClose (viewport);
+    viewport->closed = true;
+    viewport->rendering = false;
 }
 }
 
 
 static void geometry (
 static void geometry (
@@ -358,6 +359,11 @@ void WaylandOutputViewport::setupLS () {
     wl_surface_commit (surface);
     wl_surface_commit (surface);
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
 
 
+    // the roundtrip can already deliver closed (river without a layout)
+    if (closed) {
+	return;
+    }
+
     eglWindow = wl_egl_window_create (surface, size.x * scale, size.y * scale);
     eglWindow = wl_egl_window_create (surface, size.x * scale, size.y * scale);
     eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT (
     eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT (
 	m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr
 	m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr
@@ -366,6 +372,10 @@ void WaylandOutputViewport::setupLS () {
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
     wl_display_roundtrip (m_driver->getWaylandContext ()->display);
     wl_display_flush (m_driver->getWaylandContext ()->display);
     wl_display_flush (m_driver->getWaylandContext ()->display);
 
 
+    if (closed) {
+	return;
+    }
+
     static const auto XCURSORSIZE = getenv ("XCURSOR_SIZE") ? std::stoi (getenv ("XCURSOR_SIZE")) : 24;
     static const auto XCURSORSIZE = getenv ("XCURSOR_SIZE") ? std::stoi (getenv ("XCURSOR_SIZE")) : 24;
     cursorTheme
     cursorTheme
 	= wl_cursor_theme_load (getenv ("XCURSOR_THEME"), XCURSORSIZE * scale, m_driver->getWaylandContext ()->shm);
 	= wl_cursor_theme_load (getenv ("XCURSOR_THEME"), XCURSORSIZE * scale, m_driver->getWaylandContext ()->shm);
@@ -408,7 +418,47 @@ void WaylandOutputViewport::makeCurrent () {
     }
     }
 }
 }
 
 
+void WaylandOutputViewport::setWantsPointerButtons (bool wants) {
+    if (this->surface == nullptr || !m_driver->getApp ().getContext ().settings.mouse.enabled) {
+	return;
+    }
+
+    // without a global cursor source, hover and parallax need the pointer on our surface
+    const bool passthrough = !wants && m_driver->hasGlobalCursor ();
+
+    if (passthrough == this->inputPassthrough) {
+	return;
+    }
+
+    this->inputPassthrough = passthrough;
+
+    // applied by the next commit
+    wl_region* region = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor);
+
+    if (!passthrough) {
+	wl_region_add (region, 0, 0, INT32_MAX, INT32_MAX);
+    }
+
+    wl_surface_set_input_region (this->surface, region);
+    wl_region_destroy (region);
+
+    // the release would go to the desktop now
+    this->leftClick = WallpaperEngine::Input::MouseClickStatus::Released;
+    this->rightClick = WallpaperEngine::Input::MouseClickStatus::Released;
+
+    sLog.out (
+	"Output ", this->name,
+	passthrough ? ": the wallpaper does not use clicks, they go to the desktop below"
+		    : ": the wallpaper uses clicks, the pointer stays on it"
+    );
+}
+
 void WaylandOutputViewport::renderFrame () {
 void WaylandOutputViewport::renderFrame () {
+    // the driver frees closed viewports on its next pass
+    if (this->closed) {
+	return;
+    }
+
     this->rendering = true;
     this->rendering = true;
     this->m_driver->getApp ().update (this);
     this->m_driver->getApp ().update (this);
     this->rendering = false;
     this->rendering = false;

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

@@ -45,6 +45,8 @@ namespace Output {
 	int scale = 1;
 	int scale = 1;
 	bool initialized = false;
 	bool initialized = false;
 	bool rendering = false;
 	bool rendering = false;
+	/** layer surface closed or output removed, set during event dispatch and freed by the driver's main loop */
+	bool closed = false;
 
 
 	wl_egl_window* eglWindow = nullptr;
 	wl_egl_window* eglWindow = nullptr;
 	EGLSurface eglSurface = nullptr;
 	EGLSurface eglSurface = nullptr;
@@ -57,6 +59,8 @@ namespace Output {
 	glm::dvec2 mousePos = { 0, 0 };
 	glm::dvec2 mousePos = { 0, 0 };
 	WallpaperEngine::Input::MouseClickStatus leftClick = WallpaperEngine::Input::MouseClickStatus::Released;
 	WallpaperEngine::Input::MouseClickStatus leftClick = WallpaperEngine::Input::MouseClickStatus::Released;
 	WallpaperEngine::Input::MouseClickStatus rightClick = WallpaperEngine::Input::MouseClickStatus::Released;
 	WallpaperEngine::Input::MouseClickStatus rightClick = WallpaperEngine::Input::MouseClickStatus::Released;
+	/** empty input region, clicks go to the desktop below */
+	bool inputPassthrough = false;
 	wl_cursor* pointer = nullptr;
 	wl_cursor* pointer = nullptr;
 	wl_surface* cursorSurface = nullptr;
 	wl_surface* cursorSurface = nullptr;
 	wl_cursor_theme* cursorTheme = nullptr;
 	wl_cursor_theme* cursorTheme = nullptr;
@@ -76,6 +80,7 @@ namespace Output {
 	void applyImageDescription ();
 	void applyImageDescription ();
 	[[nodiscard]] bool isOutputHDR () const { return this->outputHDR; }
 	[[nodiscard]] bool isOutputHDR () const { return this->outputHDR; }
 	[[nodiscard]] bool isHDR () const override;
 	[[nodiscard]] bool isHDR () const override;
+	void setWantsPointerButtons (bool wants) override;
 	[[nodiscard]] glm::vec2 getHDRLuminance () const override { return this->outputLuminance; }
 	[[nodiscard]] glm::vec2 getHDRLuminance () const override { return this->outputLuminance; }
 
 
 	wp_color_management_output_v1* colorOutput = nullptr;
 	wp_color_management_output_v1* colorOutput = nullptr;

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

@@ -2,11 +2,15 @@
 #include "GLFWOutputViewport.h"
 #include "GLFWOutputViewport.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 
+#include <algorithm>
 #include <cstdlib>
 #include <cstdlib>
+#include <unistd.h>
 
 
 #include <X11/Xatom.h>
 #include <X11/Xatom.h>
 #include <X11/Xlib.h>
 #include <X11/Xlib.h>
+#include <X11/Xutil.h>
 #include <X11/extensions/Xrandr.h>
 #include <X11/extensions/Xrandr.h>
+#include <X11/extensions/shape.h>
 
 
 using namespace WallpaperEngine::Render::Drivers::Output;
 using namespace WallpaperEngine::Render::Drivers::Output;
 
 
@@ -59,6 +63,12 @@ void X11Output::free () {
 
 
     // XDestroyImage() already frees m_imageData itself (via its default destroy_image proc, which
     // XDestroyImage() already frees m_imageData itself (via its default destroy_image proc, which
     // calls XFree()/free() on the buffer XCreateImage() was given) - it must not be freed again here
     // calls XFree()/free() on the buffer XCreateImage() was given) - it must not be freed again here
+    if (this->m_desktopWindow != None) {
+	XDestroyWindow (this->m_display, this->m_desktopWindow);
+	this->m_desktopWindow = None;
+	this->m_desktopWindowMapped = false;
+    }
+
     XDestroyImage (this->m_image);
     XDestroyImage (this->m_image);
     this->m_imageData = nullptr;
     this->m_imageData = nullptr;
     XFreeGC (this->m_display, this->m_gc);
     XFreeGC (this->m_display, this->m_gc);
@@ -231,5 +241,247 @@ void X11Output::updateRender () const {
     );
     );
 
 
     XClearWindow (this->m_display, this->m_root);
     XClearWindow (this->m_display, this->m_root);
+    this->updateDesktopWindow ();
+
+    if (this->m_desktopWindowMapped) {
+	XClearWindow (this->m_display, this->m_desktopWindow);
+    }
+
     XFlush (this->m_display);
     XFlush (this->m_display);
 }
 }
+
+std::vector<Window> X11Output::stackingOrder () const {
+    // bottom to top, the root's children without EWMH
+    const Atom stackingAtom = XInternAtom (this->m_display, "_NET_CLIENT_LIST_STACKING", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    std::vector<Window> windows;
+
+    if (XGetWindowProperty (
+	    this->m_display, this->m_root, stackingAtom, 0, 4096, False, XA_WINDOW, &type, &format, &count, &remaining,
+	    &data
+	) == Success
+	&& data != nullptr && format == 32) {
+	const auto* list = reinterpret_cast<const Window*> (data);
+	windows.assign (list, list + count);
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    if (windows.empty ()) {
+	Window rootReturn, parent;
+	Window* children = nullptr;
+	unsigned int childCount = 0;
+
+	if (XQueryTree (this->m_display, this->m_root, &rootReturn, &parent, &children, &childCount)) {
+	    windows.assign (children, children + childCount);
+	}
+
+	if (children != nullptr) {
+	    XFree (children);
+	}
+    }
+
+    return windows;
+}
+
+bool X11Output::isDesktopType (Window window) const {
+    const Atom typeAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE", False);
+    const Atom desktopAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool desktop = false;
+
+    if (XGetWindowProperty (
+	    this->m_display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32) {
+	const auto* atoms = reinterpret_cast<const Atom*> (data);
+	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    return desktop;
+}
+
+Window X11Output::findCoveringDesktopWindow (const std::vector<Window>& stacking) const {
+    for (const Window window : stacking) {
+	if (window == this->m_desktopWindow || !this->isDesktopType (window)) {
+	    continue;
+	}
+
+	XWindowAttributes attributes;
+
+	// 32 bit windows are translucent (nemo-desktop shows the root)
+	if (!XGetWindowAttributes (this->m_display, window, &attributes) || attributes.map_state != IsViewable
+	    || attributes.depth == 32) {
+	    continue;
+	}
+
+	int x = 0, y = 0;
+	Window child;
+	XTranslateCoordinates (this->m_display, window, this->m_root, 0, 0, &x, &y, &child);
+
+	const bool covers = std::ranges::any_of (this->m_screens, [&] (const OutputViewport* screen) {
+	    const auto& area = screen->viewport;
+	    return x <= area.x && y <= area.y && x + attributes.width >= area.x + area.z
+		&& y + attributes.height >= area.y + area.w;
+	});
+
+	if (covers) {
+	    return window;
+	}
+    }
+
+    return None;
+}
+
+void X11Output::createDesktopWindow () const {
+    // override redirect so no WM frame (xfwm4) eats the clicks, updateDesktopWindow () keeps the stacking
+    XSetWindowAttributes attributes {};
+    attributes.background_pixmap = this->m_pixmap;
+    attributes.override_redirect = True;
+
+    this->m_desktopWindow = XCreateWindow (
+	this->m_display, this->m_root, 0, 0, this->m_fullWidth, this->m_fullHeight, 0, CopyFromParent, InputOutput,
+	CopyFromParent, CWBackPixmap | CWOverrideRedirect, &attributes
+    );
+
+    const auto atom = [this] (const char* name) { return XInternAtom (this->m_display, name, False); };
+
+    const Atom desktopType = atom ("_NET_WM_WINDOW_TYPE_DESKTOP");
+    XChangeProperty (
+	this->m_display, this->m_desktopWindow, atom ("_NET_WM_WINDOW_TYPE"), XA_ATOM, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&desktopType), 1
+    );
+
+    const Atom states[]
+	= { atom ("_NET_WM_STATE_STICKY"), atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
+    XChangeProperty (
+	this->m_display, this->m_desktopWindow, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (states), 3
+    );
+
+    const unsigned long allDesktops = 0xFFFFFFFF;
+    XChangeProperty (
+	this->m_display, this->m_desktopWindow, atom ("_NET_WM_DESKTOP"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&allDesktops), 1
+    );
+
+    // 2 keeps compositors (xfwm4) from unredirecting it above every other window
+    const unsigned long keepComposited = 2;
+    XChangeProperty (
+	this->m_display, this->m_desktopWindow, atom ("_NET_WM_BYPASS_COMPOSITOR"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&keepComposited), 1
+    );
+
+    const unsigned long pid = getpid ();
+    XChangeProperty (
+	this->m_display, this->m_desktopWindow, atom ("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&pid), 1
+    );
+
+    char name[] = "linux-wallpaperengine";
+    XClassHint classHint { name, name };
+    XSetClassHint (this->m_display, this->m_desktopWindow, &classHint);
+    XStoreName (this->m_display, this->m_desktopWindow, name);
+
+    // empty input region, clicks reach their desktop window
+    XShapeCombineRectangles (this->m_display, this->m_desktopWindow, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+}
+
+Window X11Output::topLevelOf (Window window) const {
+    Window rootReturn, parent, *children = nullptr;
+    unsigned int count;
+
+    while (XQueryTree (this->m_display, window, &rootReturn, &parent, &children, &count)) {
+	if (children != nullptr) {
+	    XFree (children);
+	    children = nullptr;
+	}
+
+	if (parent == this->m_root || parent == None) {
+	    return window;
+	}
+
+	window = parent;
+    }
+
+    return window;
+}
+
+void X11Output::updateDesktopWindow () const {
+    // root restacks and (un)maps may have moved windows around ours
+    bool restacked = false;
+
+    while (XPending (this->m_display)) {
+	XEvent event;
+	XNextEvent (this->m_display, &event);
+	restacked |= event.type == ConfigureNotify || event.type == MapNotify || event.type == UnmapNotify
+	    || event.type == DestroyNotify;
+    }
+
+    const auto now = std::chrono::steady_clock::now ();
+
+    // desktops can also (re)start their desktop window after us
+    if (now < this->m_nextDesktopCheck && !restacked) {
+	return;
+    }
+
+    this->m_nextDesktopCheck = now + std::chrono::seconds (2);
+
+    const Window covering = this->findCoveringDesktopWindow (this->stackingOrder ());
+
+    if (covering == None) {
+	if (this->m_desktopWindowMapped) {
+	    XUnmapWindow (this->m_display, this->m_desktopWindow);
+	    this->m_desktopWindowMapped = false;
+	    sLog.out ("The desktop window covering the root window is gone, drawing into the root window again");
+	}
+
+	return;
+    }
+
+    if (this->m_desktopWindow == None) {
+	this->createDesktopWindow ();
+	XSelectInput (this->m_display, this->m_root, SubstructureNotifyMask);
+    }
+
+    if (!this->m_desktopWindowMapped) {
+	XMapWindow (this->m_display, this->m_desktopWindow);
+	this->m_desktopWindowMapped = true;
+	sLog.out ("A desktop window covers the root window, drawing into a desktop window of our own above it");
+    }
+
+    // right above their desktop window's top level, below everything else
+    const Window theirs = this->topLevelOf (covering);
+    Window rootReturn, parent, *children = nullptr;
+    unsigned int count = 0;
+    bool inPlace = false;
+
+    if (XQueryTree (this->m_display, this->m_root, &rootReturn, &parent, &children, &count)) {
+	const Window* end = children + count;
+	const Window* their = std::find (children, children + count, theirs);
+	inPlace = their != end && their + 1 != end && *(their + 1) == this->m_desktopWindow;
+    }
+
+    if (children != nullptr) {
+	XFree (children);
+    }
+
+    if (!inPlace) {
+	XWindowChanges changes {};
+	changes.sibling = theirs;
+	changes.stack_mode = Above;
+	XConfigureWindow (this->m_display, this->m_desktopWindow, CWSibling | CWStackMode, &changes);
+    }
+}

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

@@ -1,8 +1,10 @@
 #pragma once
 #pragma once
 
 
+#include <chrono>
 #include <glm/vec4.hpp>
 #include <glm/vec4.hpp>
 #include <map>
 #include <map>
 #include <string>
 #include <string>
+#include <vector>
 
 
 #include <X11/Xlib.h>
 #include <X11/Xlib.h>
 #include <X11/extensions/Xrandr.h>
 #include <X11/extensions/Xrandr.h>
@@ -32,6 +34,18 @@ private:
     void initX11Background ();
     void initX11Background ();
     void free ();
     void free ();
 
 
+    /**
+     * XFCE, MATE and LXQt hide the root behind an opaque desktop window (xfdesktop, caja, pcmanfm-qt). While one is
+     * mapped, frames go into our own window stacked right above it, with an empty input region so clicks still reach
+     * theirs. Translucent ones (nemo-desktop) are left alone.
+     */
+    void updateDesktopWindow () const;
+    [[nodiscard]] Window findCoveringDesktopWindow (const std::vector<Window>& stacking) const;
+    [[nodiscard]] std::vector<Window> stackingOrder () const;
+    [[nodiscard]] bool isDesktopType (Window window) const;
+    [[nodiscard]] Window topLevelOf (Window window) const;
+    void createDesktopWindow () const;
+
     Display* m_display = nullptr;
     Display* m_display = nullptr;
     Pixmap m_pixmap;
     Pixmap m_pixmap;
     Window m_root;
     Window m_root;
@@ -40,5 +54,9 @@ private:
     uint32_t m_imageSize = 0;
     uint32_t m_imageSize = 0;
     XImage* m_image = nullptr;
     XImage* m_image = nullptr;
     std::vector<OutputViewport*> m_screens = {};
     std::vector<OutputViewport*> m_screens = {};
+
+    mutable Window m_desktopWindow = None;
+    mutable bool m_desktopWindowMapped = false;
+    mutable std::chrono::steady_clock::time_point m_nextDesktopCheck = {};
 };
 };
 } // namespace WallpaperEngine::Render::Drivers::Output
 } // namespace WallpaperEngine::Render::Drivers::Output

+ 16 - 3
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -202,7 +202,8 @@ static void handleGlobalRemoved (void* data, struct wl_registry* registry, uint3
 	= std::ranges::find_if (driver->m_screens, [id] (const auto* viewport) { return viewport->waylandName == id; });
 	= std::ranges::find_if (driver->m_screens, [id] (const auto* viewport) { return viewport->waylandName == id; });
 
 
     if (it != driver->m_screens.end ()) {
     if (it != driver->m_screens.end ()) {
-	driver->onLayerClose (*it);
+	(*it)->closed = true;
+	(*it)->rendering = false;
     }
     }
 }
 }
 
 
@@ -548,7 +549,7 @@ void WaylandOpenGLDriver::setupLateOutputs () {
     // KDE often drops and re-adds outputs while it applies the screen layout at login, and monitors can
     // KDE often drops and re-adds outputs while it applies the screen layout at login, and monitors can
     // wake up after we started; the wallpapers stay registered by screen name, only the surface is missing
     // wake up after we started; the wallpapers stay registered by screen name, only the surface is missing
     for (const auto& o : this->m_screens) {
     for (const auto& o : this->m_screens) {
-	if (o->layerSurface || !o->initialized || !isScreenRequested (o->name)) {
+	if (o->layerSurface || o->closed || !o->initialized || !isScreenRequested (o->name)) {
 	    continue;
 	    continue;
 	}
 	}
 
 
@@ -599,7 +600,19 @@ WaylandOpenGLDriver::~WaylandOpenGLDriver () {
     }
     }
 }
 }
 
 
+void WaylandOpenGLDriver::reapClosedOutputs () {
+    std::vector<Output::WaylandOutputViewport*> closed;
+
+    std::ranges::copy_if (this->m_screens, std::back_inserter (closed), [] (const auto* o) { return o->closed; });
+
+    for (auto* viewport : closed) {
+	this->onLayerClose (viewport);
+    }
+}
+
 void WaylandOpenGLDriver::dispatchEventQueue () {
 void WaylandOpenGLDriver::dispatchEventQueue () {
+    this->reapClosedOutputs ();
+
     if (this->m_layerSurfacesReady) {
     if (this->m_layerSurfacesReady) {
 	this->setupLateOutputs ();
 	this->setupLateOutputs ();
     }
     }
@@ -609,7 +622,7 @@ void WaylandOpenGLDriver::dispatchEventQueue () {
     const auto now = std::chrono::steady_clock::now ();
     const auto now = std::chrono::steady_clock::now ();
 
 
     for (const auto& o : this->m_screens) {
     for (const auto& o : this->m_screens) {
-	if (o->layerSurface && now - o->lastSwap > MISSED_FRAME_TIMEOUT) {
+	if (o->layerSurface && !o->closed && now - o->lastSwap > MISSED_FRAME_TIMEOUT) {
 	    o->renderFrame ();
 	    o->renderFrame ();
 	}
 	}
     }
     }

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

@@ -96,6 +96,10 @@ public:
     [[nodiscard]] wp_image_description_v1* getHDRDescription () const;
     [[nodiscard]] wp_image_description_v1* getHDRDescription () const;
 
 
     void onLayerClose (Output::WaylandOutputViewport*);
     void onLayerClose (Output::WaylandOutputViewport*);
+    /** the cursor position is known without a surface of ours under it */
+    [[nodiscard]] bool hasGlobalCursor () const { return this->m_mouseInput.hasGlobalCursor (); }
+    /** frees the viewports the compositor closed, outside of any event dispatch */
+    void reapClosedOutputs ();
     Output::WaylandOutputViewport* surfaceToViewport (const wl_surface*) const;
     Output::WaylandOutputViewport* surfaceToViewport (const wl_surface*) const;
 
 
     Output::WaylandOutputViewport* viewportInFocus = nullptr;
     Output::WaylandOutputViewport* viewportInFocus = nullptr;

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

@@ -669,6 +669,24 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 	sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
 	sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
     }
     }
 
 
+    // WE skips "" texture names (sub_1401556E0), the sampler falls back to "error" (sub_1401515B0): a 6x6 checker
+    // that autosize shrinks the layer to (2282018774). --repair-assets loads materials/.tex instead
+    if (this->m_texture == nullptr && !this->m_image.model->solidlayer
+	&& !image.model->material->passes.front ()->textures.contains (0)) {
+	if (this->getContext ().getApp ().getContext ().settings.general.repairAssets) {
+	    try {
+		this->m_texture = this->getContext ().resolveTexture ("", scene.getScene ().project);
+	    } catch (const Assets::AssetLoadException&) {
+		// nothing shipped under the empty name either
+	    }
+	}
+
+	if (this->m_texture == nullptr) {
+	    sLog.error ("Image ", image.id, " material has no albedo texture, drawing the missing texture");
+	    this->m_texture = scene.getMissingTexture ();
+	}
+    }
+
     const bool placeholderTexture = this->m_texture == nullptr;
     const bool placeholderTexture = this->m_texture == nullptr;
 
 
     if (this->m_texture == nullptr) {
     if (this->m_texture == nullptr) {

+ 2 - 0
src/WallpaperEngine/Render/RenderContext.cpp

@@ -64,6 +64,7 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
 
 
     if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
     if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
 	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
 	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
+	viewport->setWantsPointerButtons (ref->second->wantsPointerButtons ());
 	ref->second->render (
 	ref->second->render (
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	);
 	);
@@ -98,6 +99,7 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
 
 
     if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
     if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
 	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
 	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
+	viewport->setWantsPointerButtons (ref->second->wantsPointerButtons ());
 	ref->second->render (
 	ref->second->render (
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	);
 	);

+ 4 - 0
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -3411,6 +3411,10 @@ ModelData::Error CScene::checkModelDataMaterial (const std::string& material, ui
     return result;
     return result;
 }
 }
 
 
+bool CScene::wantsPointerButtons () const {
+    return this->m_scriptEngine != nullptr && this->m_scriptEngine->wantsPointerButtons ();
+}
+
 void CScene::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
 void CScene::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
     const std::optional<int> volume = muted ? std::optional<int> (0) : ambientVolume;
     const std::optional<int> volume = muted ? std::optional<int> (0) : ambientVolume;
 
 

+ 1 - 0
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -269,6 +269,7 @@ public:
     [[nodiscard]] int getObjectIndex (const CObject* object) const;
     [[nodiscard]] int getObjectIndex (const CObject* object) const;
 
 
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
+    [[nodiscard]] bool wantsPointerButtons () const override;
 
 
     /** Script play()/stop() request for a Sound object, remembered because scripts can ask before the CSound exists */
     /** Script play()/stop() request for a Sound object, remembered because scripts can ask before the CSound exists */
     void setSoundPlaying (int id, bool playing);
     void setSoundPlaying (int id, bool playing);

+ 41 - 43
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -3,6 +3,7 @@
 // https://github.com/andmcgregor/cefgui
 // https://github.com/andmcgregor/cefgui
 #include "CWeb.h"
 #include "CWeb.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Audio/Drivers/PulseProcessVolume.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Project.h"
@@ -11,7 +12,6 @@
 #include "WallpaperEngine/Render/RenderContext.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 
 
 #include <atomic>
 #include <atomic>
-#include <cctype>
 #include <chrono>
 #include <chrono>
 #include <cmath>
 #include <cmath>
 #include <csignal>
 #include <csignal>
@@ -128,32 +128,46 @@ CWeb::CWeb (
     this->m_statsEnabled = std::getenv ("LWE_WEB_STATS") != nullptr;
     this->m_statsEnabled = std::getenv ("LWE_WEB_STATS") != nullptr;
 
 
     this->spawnHost (resolvedBackgroundPath);
     this->spawnHost (resolvedBackgroundPath);
+
+    this->m_streamVolume = std::make_unique<Audio::Drivers::PulseProcessVolume> (this->m_hostPid);
+    // --volume until the application applies the real policy
+    this->setAudioPolicy (false, std::nullopt);
 }
 }
 
 
 void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     auto& appContext = this->getContext ().getApp ().getContext ();
     auto& appContext = this->getContext ().getApp ().getContext ();
     const std::string executable = hostExecutable ();
     const std::string executable = hostExecutable ();
 
 
+    // stream restore would hand our "Chromium" volume to the user's browser, so the host's stream opts out
     // tests only (HEADLESS_RENDER_WEB=1): LD_PRELOAD for the host alone, libcef.so before libc for its close() wrapper
     // tests only (HEADLESS_RENDER_WEB=1): LD_PRELOAD for the host alone, libcef.so before libc for its close() wrapper
+    const char* preload = std::getenv ("LWE_WEB_HOST_PRELOAD");
     std::vector<std::string> environment;
     std::vector<std::string> environment;
-    std::vector<char*> envp;
 
 
-    if (const char* preload = std::getenv ("LWE_WEB_HOST_PRELOAD"); preload != nullptr && preload[0] != '\0') {
-	for (char** entry = environ; *entry != nullptr; entry++) {
-	    if (!std::string_view (*entry).starts_with ("LD_PRELOAD=")) {
-		environment.emplace_back (*entry);
-	    }
+    for (char** entry = environ; *entry != nullptr; entry++) {
+	const std::string_view variable (*entry);
+
+	if (!variable.starts_with ("PULSE_PROP_state.restore-props=")
+	    && !variable.starts_with ("PULSE_PROP_module-stream-restore.id=")
+	    && !(preload != nullptr && preload[0] != '\0' && variable.starts_with ("LD_PRELOAD="))) {
+	    environment.emplace_back (*entry);
 	}
 	}
+    }
+
+    environment.emplace_back ("PULSE_PROP_state.restore-props=false");
+    environment.emplace_back ("PULSE_PROP_module-stream-restore.id=lwe-web");
 
 
+    if (preload != nullptr && preload[0] != '\0') {
 	environment.emplace_back (std::string ("LD_PRELOAD=") + preload);
 	environment.emplace_back (std::string ("LD_PRELOAD=") + preload);
+    }
 
 
-	for (auto& entry : environment) {
-	    envp.push_back (entry.data ());
-	}
+    std::vector<char*> envp;
 
 
-	envp.push_back (nullptr);
+    for (auto& entry : environment) {
+	envp.push_back (entry.data ());
     }
     }
 
 
+    envp.push_back (nullptr);
+
     const pid_t pid = fork ();
     const pid_t pid = fork ();
 
 
     if (pid < 0) {
     if (pid < 0) {
@@ -204,13 +218,9 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 
 
 	argv.push_back (nullptr);
 	argv.push_back (nullptr);
 
 
-	if (envp.empty ()) {
-	    execv (executable.c_str (), argv.data ());
-	} else {
-	    execve (executable.c_str (), argv.data (), envp.data ());
-	}
+	execve (executable.c_str (), argv.data (), envp.data ());
 
 
-	// only reached if execv() itself failed
+	// only reached if execve() itself failed
 	_exit (127);
 	_exit (127);
     }
     }
 
 
@@ -222,9 +232,16 @@ void CWeb::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
 	return;
 	return;
     }
     }
 
 
-    const bool shouldMute = muted || (ambientVolume.has_value () && *ambientVolume == 0);
+    const auto& appContext = this->getContext ().getApp ().getContext ();
+    // like scene sounds, the ambient volume replaces --volume
+    const int volume
+	= muted || !appContext.settings.audio.enabled ? 0 : ambientVolume.value_or (appContext.state.audio.volume);
 
 
-    this->m_shm->audioMuted.store (shouldMute, std::memory_order_relaxed);
+    this->m_shm->audioMuted.store (volume == 0, std::memory_order_relaxed);
+
+    if (this->m_streamVolume) {
+	this->m_streamVolume->setVolume (static_cast<float> (volume) / 128.0f);
+    }
 }
 }
 
 
 void CWeb::setSize (const int width, const int height) {
 void CWeb::setSize (const int width, const int height) {
@@ -257,6 +274,7 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
 
 
     this->updateMouse (viewport);
     this->updateMouse (viewport);
     this->updateMedia ();
     this->updateMedia ();
+    this->m_streamVolume->update ();
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glViewport (0, 0, this->getWidth (), this->getHeight ());
     glViewport (0, 0, this->getWidth (), this->getHeight ());
 
 
@@ -383,27 +401,6 @@ void copyText (char* target, std::size_t capacity, const std::string& text) {
     std::memcpy (target, text.data (), length);
     std::memcpy (target, text.data (), length);
     target[length] = '\0';
     target[length] = '\0';
 }
 }
-
-// MPRIS art URLs are percent encoded file:// URLs, the way they appear on the bus
-std::string coverPathFromUrl (const std::optional<std::string>& url) {
-    if (!url.has_value () || !url->starts_with ("file://")) {
-	return "";
-    }
-
-    std::string path;
-
-    for (std::size_t i = 7; i < url->size (); i++) {
-	if ((*url)[i] == '%' && i + 2 < url->size () && std::isxdigit ((*url)[i + 1])
-	    && std::isxdigit ((*url)[i + 2])) {
-	    path += static_cast<char> (std::stoi (url->substr (i + 1, 2), nullptr, 16));
-	    i += 2;
-	} else {
-	    path += (*url)[i];
-	}
-    }
-
-    return path;
-}
 } // namespace
 } // namespace
 
 
 void CWeb::updateMedia () {
 void CWeb::updateMedia () {
@@ -411,13 +408,14 @@ void CWeb::updateMedia () {
     const auto& last = this->m_lastMedia;
     const auto& last = this->m_lastMedia;
 
 
     if (this->m_mediaPublished && info.title == last.title && info.artist == last.artist && info.album == last.album
     if (this->m_mediaPublished && info.title == last.title && info.artist == last.artist && info.album == last.album
-	&& info.url == last.url && info.playbackState == last.playbackState && info.available == last.available
+	&& info.cover == last.cover && info.playbackState == last.playbackState && info.available == last.available
 	&& info.duration == last.duration && info.position == last.position) {
 	&& info.duration == last.duration && info.position == last.position) {
 	return;
 	return;
     }
     }
 
 
-    const bool coverChanged = !this->m_mediaPublished || info.url != last.url;
-    const std::string coverPath = coverPathFromUrl (info.url);
+    // a downloaded cover arrives as a change of its own
+    const bool coverChanged = !this->m_mediaPublished || info.cover != last.cover;
+    const std::string coverPath = info.cover.has_value () ? info.cover->string () : "";
     Media::ThumbnailPalette palette;
     Media::ThumbnailPalette palette;
 
 
     if (coverChanged) {
     if (coverChanged) {

+ 9 - 1
src/WallpaperEngine/Render/Wallpapers/CWeb.h

@@ -19,6 +19,10 @@
 
 
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 
 
+namespace WallpaperEngine::Audio::Drivers {
+class PulseProcessVolume;
+}
+
 namespace WallpaperEngine::Render::Wallpapers {
 namespace WallpaperEngine::Render::Wallpapers {
 // Web wallpapers are rendered by CEF, which this never embeds directly (CEF only supports one
 // Web wallpapers are rendered by CEF, which this never embeds directly (CEF only supports one
 // CefInitialize()/CefShutdown() pair per process, so switching a running process between hosting
 // CefInitialize()/CefShutdown() pair per process, so switching a running process between hosting
@@ -41,9 +45,12 @@ public:
 
 
     void setSize (int width, int height);
     void setSize (int width, int height);
 
 
-    /** ambientVolume==0 (or muted) mutes the host's CEF browser; CEF exposes no analog volume control */
+    /** CEF can only mute: silence mutes the browser, other volumes go to the host's PulseAudio streams */
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
 
 
+    /** any page may listen to clicks */
+    [[nodiscard]] bool wantsPointerButtons () const override { return true; }
+
     /** The host passes changes to the page's applyUserProperties */
     /** The host passes changes to the page's applyUserProperties */
     void setPropertyOverrides (const std::map<std::string, std::string>& overrides);
     void setPropertyOverrides (const std::map<std::string, std::string>& overrides);
     /** Painted something not flat, the host failed, or it took too long */
     /** Painted something not flat, the host failed, or it took too long */
@@ -87,6 +94,7 @@ private:
     uint32_t m_statsRenders = 0;
     uint32_t m_statsRenders = 0;
     uint32_t m_statsFrames = 0;
     uint32_t m_statsFrames = 0;
     pid_t m_hostPid = -1;
     pid_t m_hostPid = -1;
+    std::unique_ptr<Audio::Drivers::PulseProcessVolume> m_streamVolume;
     // registered with the audio recorder so spectra are pushed to the host as soon as they're computed instead of
     // registered with the audio recorder so spectra are pushed to the host as soon as they're computed instead of
     // being sampled once per rendered frame
     // being sampled once per rendered frame
     int m_spectrumListenerId = 0;
     int m_spectrumListenerId = 0;

+ 1 - 0
src/WallpaperEngine/Scripting/InputObject.cpp

@@ -28,6 +28,7 @@ void get_cursor_screen_position (const v8::FunctionCallbackInfo<v8::Value>& info
 }
 }
 
 
 void get_cursor_left_down (const v8::FunctionCallbackInfo<v8::Value>& info) {
 void get_cursor_left_down (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    ScriptEngine::from (info.GetIsolate ()).noteButtonStateRead ();
     info.GetReturnValue ().Set (sceneOf (info).isCursorLeftDown ());
     info.GetReturnValue ().Set (sceneOf (info).isCursorLeftDown ());
 }
 }
 
 

+ 39 - 14
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -1191,6 +1191,39 @@ bool ScriptEngine::hasCursorHandlers (const ScriptableObject& object) {
     return false;
     return false;
 }
 }
 
 
+bool ScriptEngine::wantsPointerButtons () {
+    if (this->m_buttonStateRead) {
+	return true;
+    }
+
+    const Scope scope (*this);
+    const auto context = this->getContext ();
+
+    for (auto& module : this->m_scriptModules | std::views::values) {
+	if (!module.initialized || module.module.IsEmpty ()) {
+	    continue;
+	}
+
+	if (module.buttonHandlers < 0) {
+	    const v8::TryCatch tryCatch (this->m_isolate);
+
+	    module.buttonHandlers = 0;
+
+	    for (const char* handler : { "cursorDown", "cursorUp", "cursorClick" }) {
+		if (JS::get (context, module.module.Get (this->m_isolate), handler)->IsFunction ()) {
+		    module.buttonHandlers = 1;
+		}
+	    }
+	}
+
+	if (module.buttonHandlers > 0) {
+	    return true;
+	}
+    }
+
+    return false;
+}
+
 void ScriptEngine::dispatchCursorEvent (
 void ScriptEngine::dispatchCursorEvent (
     const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition,
     const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition,
     const std::optional<std::string>& hitBox
     const std::optional<std::string>& hitBox
@@ -1543,25 +1576,17 @@ void ScriptEngine::tick () {
 }
 }
 
 
 Media::ThumbnailPalette ScriptEngine::thumbnailPaletteFor (const Media::MediaSource::MediaInfo& media) {
 Media::ThumbnailPalette ScriptEngine::thumbnailPaletteFor (const Media::MediaSource::MediaInfo& media) {
-    if (!media.url.has_value ()) {
+    if (!media.cover.has_value ()) {
 	return {};
 	return {};
     }
     }
 
 
     // every module gets the event, decode the cover once per file
     // every module gets the event, decode the cover once per file
-    if (this->m_paletteUrl == *media.url) {
-	return this->m_palette;
-    }
-
-    this->m_paletteUrl = *media.url;
-    this->m_palette = {};
-
-    std::string path = *media.url;
-
-    if (!path.starts_with ("file://")) {
+    if (this->m_palettePath == *media.cover) {
 	return this->m_palette;
 	return this->m_palette;
     }
     }
 
 
-    this->m_palette = Media::loadThumbnailPalette (path.substr (7));
+    this->m_palettePath = *media.cover;
+    this->m_palette = Media::loadThumbnailPalette (media.cover->string ());
 
 
     return this->m_palette;
     return this->m_palette;
 }
 }
@@ -1667,7 +1692,7 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
 
 
     const v8::Local<v8::Object> mediaThumbnailEvent = v8::Object::New (isolate);
     const v8::Local<v8::Object> mediaThumbnailEvent = v8::Object::New (isolate);
 
 
-    JS::set (context, mediaThumbnailEvent, "hasThumbnail", v8::Boolean::New (isolate, media.url.has_value ()));
+    JS::set (context, mediaThumbnailEvent, "hasThumbnail", v8::Boolean::New (isolate, media.cover.has_value ()));
     JS::set (context, mediaThumbnailEvent, "primaryColor", color (palette.primary));
     JS::set (context, mediaThumbnailEvent, "primaryColor", color (palette.primary));
     JS::set (context, mediaThumbnailEvent, "secondaryColor", color (palette.secondary));
     JS::set (context, mediaThumbnailEvent, "secondaryColor", color (palette.secondary));
     JS::set (context, mediaThumbnailEvent, "tertiaryColor", color (palette.tertiary));
     JS::set (context, mediaThumbnailEvent, "tertiaryColor", color (palette.tertiary));
@@ -1686,7 +1711,7 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
 	if (media.available && !media.title.empty ()) {
 	if (media.available && !media.title.empty ()) {
 	    events.emplace_back ("mediaPropertiesChanged", propertiesEvent);
 	    events.emplace_back ("mediaPropertiesChanged", propertiesEvent);
 	}
 	}
-	if (media.available && media.url.has_value ()) {
+	if (media.available && media.cover.has_value ()) {
 	    events.emplace_back ("mediaThumbnailChanged", mediaThumbnailEvent);
 	    events.emplace_back ("mediaThumbnailChanged", mediaThumbnailEvent);
 	}
 	}
 	if (media.available && media.duration != 0.0) {
 	if (media.available && media.duration != 0.0) {

+ 7 - 1
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -8,6 +8,7 @@
 #include "SceneObject.h"
 #include "SceneObject.h"
 
 
 #include <chrono>
 #include <chrono>
+#include <filesystem>
 #include <functional>
 #include <functional>
 #include <future>
 #include <future>
 #include <map>
 #include <map>
@@ -86,6 +87,7 @@ public:
 	std::string propertyName;
 	std::string propertyName;
 	// -1 until checked, then whether the module exports any cursor* handler
 	// -1 until checked, then whether the module exports any cursor* handler
 	int cursorHandlers = -1;
 	int cursorHandlers = -1;
+	int buttonHandlers = -1;
 	// owning object was destroyed, waiting for the retire pass in tick()
 	// owning object was destroyed, waiting for the retire pass in tick()
 	bool dropped = false;
 	bool dropped = false;
 	// registration order, which is scene order, what update() calls follow
 	// registration order, which is scene order, what update() calls follow
@@ -214,6 +216,9 @@ public:
 
 
     /** Whether any running script on the object exports a cursor handler (cursorEnter, cursorClick, ...) */
     /** Whether any running script on the object exports a cursor handler (cursorEnter, cursorClick, ...) */
     [[nodiscard]] bool hasCursorHandlers (const ScriptableObject& object);
     [[nodiscard]] bool hasCursorHandlers (const ScriptableObject& object);
+    /** a script exports cursorDown/cursorUp/cursorClick or has read input.cursorLeftDown */
+    [[nodiscard]] bool wantsPointerButtons ();
+    void noteButtonStateRead () { this->m_buttonStateRead = true; }
     /**
     /**
      * Calls handler (cursorEnter/Leave/Move/Down/Up/Click) on the object's scripts with button (always 0),
      * Calls handler (cursorEnter/Leave/Move/Down/Up/Click) on the object's scripts with button (always 0),
      * worldPosition, localPosition and hitBox (sub_18164E4D0)
      * worldPosition, localPosition and hitBox (sub_18164E4D0)
@@ -333,7 +338,8 @@ private:
     Media::MediaSource& m_mediaSource;
     Media::MediaSource& m_mediaSource;
     std::function<void ()> m_unregisterMediaUpdateCallback;
     std::function<void ()> m_unregisterMediaUpdateCallback;
     std::function<void ()> m_unregisterAlbumArtUpdateCallback;
     std::function<void ()> m_unregisterAlbumArtUpdateCallback;
-    std::string m_paletteUrl;
+    std::filesystem::path m_palettePath;
+    bool m_buttonStateRead = false;
     Media::ThumbnailPalette m_palette;
     Media::ThumbnailPalette m_palette;
 
 
     JSObjectAdapters m_adapters;
     JSObjectAdapters m_adapters;

+ 52 - 0
src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp

@@ -0,0 +1,52 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <string>
+
+#include "WallpaperEngine/Input/ForwardedButton.h"
+
+using WallpaperEngine::Input::forwardedLeftDown;
+using namespace std::chrono_literals;
+
+namespace {
+std::filesystem::path write (const std::string& name, const std::string& content) {
+    const auto path = std::filesystem::temp_directory_path () / name;
+    std::ofstream (path) << content;
+    return path;
+}
+} // namespace
+
+TEST_CASE ("The button a desktop shell forwards is read from its file") {
+    const auto path = write ("lwe-forwarded-button-test", R"({"leftDown": true})");
+
+    CHECK (forwardedLeftDown (path));
+
+    write ("lwe-forwarded-button-test", R"({"leftDown": false})");
+    CHECK_FALSE (forwardedLeftDown (path));
+
+    write ("lwe-forwarded-button-test", R"({"somethingElse": true})");
+    CHECK_FALSE (forwardedLeftDown (path));
+
+    std::filesystem::remove (path);
+}
+
+TEST_CASE ("A forwarded button counts as released when nothing says otherwise") {
+    const auto path = write ("lwe-forwarded-button-stale", R"({"leftDown": true})");
+    const auto written = std::filesystem::last_write_time (path);
+
+    CHECK (forwardedLeftDown (path, 2s, written + 1s));
+    CHECK_FALSE (forwardedLeftDown (path, 2s, written + 3s));
+
+    write ("lwe-forwarded-button-stale", R"({"leftDown": tr)");
+    CHECK_FALSE (forwardedLeftDown (path));
+
+    write ("lwe-forwarded-button-stale", "[true]");
+    CHECK_FALSE (forwardedLeftDown (path));
+
+    std::filesystem::remove (path);
+
+    CHECK_FALSE (forwardedLeftDown (path));
+    CHECK_FALSE (forwardedLeftDown ({}));
+}

+ 256 - 0
src/WallpaperEngine/Testing/Cases/MediaCover.cpp

@@ -0,0 +1,256 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include <atomic>
+#include <chrono>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <optional>
+#include <span>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "WallpaperEngine/Media/CoverDownloader.h"
+#include "WallpaperEngine/Media/CoverImage.h"
+
+using namespace WallpaperEngine::Media;
+
+namespace {
+// 4x2, red with the bottom right pixel blue
+const std::vector<uint8_t> PNG_COVER = {
+    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+    0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x08, 0x06, 0x00, 0x00, 0x00, 0x7f, 0xa8, 0x7d,
+    0x63, 0x00, 0x00, 0x00, 0x17, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xfc, 0xcf, 0xc0, 0xf0,
+    0x9f, 0x01, 0x09, 0x30, 0x21, 0x73, 0x18, 0x19, 0xfe, 0x33, 0x00, 0x00, 0x41, 0x29, 0x03, 0x02,
+    0xb6, 0x2f, 0x64, 0xee, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
+};
+
+const std::vector<uint8_t> WEBP_COVER = {
+    0x52, 0x49, 0x46, 0x46, 0x20, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50,
+    0x38, 0x4c, 0x13, 0x00, 0x00, 0x00, 0x2f, 0x03, 0x40, 0x00, 0x00, 0x0f, 0x10, 0xf3,
+    0xbf, 0xff, 0xf3, 0x1f, 0x0e, 0x7e, 0xf0, 0x10, 0xd1, 0xff, 0x08, 0x00,
+};
+
+void expectRedWithBlueCorner (const std::optional<CoverImage>& image) {
+    REQUIRE (image.has_value ());
+    REQUIRE (image->width == 4);
+    REQUIRE (image->height == 2);
+    CHECK (image->rgba[0] == 255);
+    CHECK (image->rgba[1] == 0);
+    CHECK (image->rgba[2] == 0);
+    const size_t corner = (1 * 4 + 3) * 4;
+    CHECK (image->rgba[corner] == 0);
+    CHECK (image->rgba[corner + 2] == 255);
+}
+
+// answers every request on localhost with one canned response chosen by the path
+class CoverServer {
+public:
+    CoverServer () {
+	this->m_socket = socket (AF_INET, SOCK_STREAM, 0);
+
+	sockaddr_in address {};
+	address.sin_family = AF_INET;
+	address.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+	REQUIRE (bind (this->m_socket, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0);
+	REQUIRE (listen (this->m_socket, 8) == 0);
+
+	socklen_t length = sizeof (address);
+	getsockname (this->m_socket, reinterpret_cast<sockaddr*> (&address), &length);
+	this->m_port = ntohs (address.sin_port);
+
+	this->m_thread = std::thread ([this] { this->serve (); });
+    }
+
+    ~CoverServer () {
+	this->m_stop = true;
+	shutdown (this->m_socket, SHUT_RDWR);
+	close (this->m_socket);
+	this->m_thread.join ();
+    }
+
+    [[nodiscard]] std::string url (const std::string& path) const {
+	return "http://127.0.0.1:" + std::to_string (this->m_port) + path;
+    }
+
+    std::atomic<int> requests = 0;
+
+private:
+    void serve () {
+	while (!this->m_stop) {
+	    const int client = accept (this->m_socket, nullptr, nullptr);
+
+	    if (client < 0) {
+		return;
+	    }
+
+	    std::string request;
+	    char chunk[1024];
+
+	    while (request.find ("\r\n\r\n") == std::string::npos) {
+		const auto count = recv (client, chunk, sizeof (chunk), 0);
+
+		if (count <= 0) {
+		    break;
+		}
+
+		request.append (chunk, static_cast<size_t> (count));
+	    }
+
+	    this->requests++;
+	    const auto path = request.substr (
+		request.find (' ') + 1, request.find (' ', request.find (' ') + 1) - request.find (' ') - 1
+	    );
+	    std::string header = "HTTP/1.1 200 OK\r\n";
+	    std::string body;
+
+	    if (path == "/cover.png") {
+		body.assign (PNG_COVER.begin (), PNG_COVER.end ());
+	    } else if (path == "/cover.webp") {
+		body.assign (WEBP_COVER.begin (), WEBP_COVER.end ());
+	    } else if (path == "/redirect") {
+		header = "HTTP/1.1 302 Found\r\nLocation: /cover.png\r\n";
+	    } else if (path == "/page.html") {
+		body = "<html><body>not an image</body></html>";
+	    } else {
+		header = "HTTP/1.1 404 Not Found\r\n";
+		body = "missing";
+	    }
+
+	    const std::string response
+		= header + "Content-Length: " + std::to_string (body.size ()) + "\r\nConnection: close\r\n\r\n" + body;
+	    send (client, response.data (), response.size (), MSG_NOSIGNAL);
+	    close (client);
+	}
+    }
+
+    int m_socket = -1;
+    uint16_t m_port = 0;
+    std::atomic<bool> m_stop = false;
+    std::thread m_thread;
+};
+
+std::optional<CoverDownloader::Finished> waitFor (CoverDownloader& downloader, const std::string& url) {
+    const auto deadline = std::chrono::steady_clock::now () + std::chrono::seconds (10);
+
+    while (std::chrono::steady_clock::now () < deadline) {
+	for (auto& finished : downloader.collect ()) {
+	    if (finished.url == url) {
+		return finished;
+	    }
+	}
+
+	std::this_thread::sleep_for (std::chrono::milliseconds (10));
+    }
+
+    return std::nullopt;
+}
+} // namespace
+
+TEST_CASE ("Cover URLs are percent decoded and only file:// ones are local paths") {
+    CHECK (localCoverPath ("file:///home/user/My%20Music/cover.jpg") == "/home/user/My Music/cover.jpg");
+    CHECK (localCoverPath ("file://localhost/tmp/a.png") == "/tmp/a.png");
+    CHECK (localCoverPath ("file:///tmp/caf%C3%A9.png") == "/tmp/caf\xC3\xA9.png");
+    CHECK (localCoverPath ("file:///tmp/a.png?x=1#y") == "/tmp/a.png");
+
+    CHECK_FALSE (localCoverPath ("https://i.scdn.co/image/abc").has_value ());
+    CHECK_FALSE (localCoverPath ("file://relative/path.png").has_value ());
+    CHECK_FALSE (localCoverPath ("file:///tmp/a%zz.png").has_value ());
+    CHECK_FALSE (localCoverPath ("file:///tmp/a%2").has_value ());
+    CHECK_FALSE (localCoverPath ("file:///tmp/a%00b.png").has_value ());
+    CHECK_FALSE (localCoverPath ("").has_value ());
+}
+
+TEST_CASE ("Covers decode by their bytes, not their extension") {
+    expectRedWithBlueCorner (decodeCoverImage (PNG_COVER));
+    expectRedWithBlueCorner (decodeCoverImage (WEBP_COVER));
+
+    const auto directory = std::filesystem::temp_directory_path () / "lwe-cover-test";
+    std::filesystem::create_directories (directory);
+    const auto file = directory / "cover.jpg";
+
+    {
+	std::ofstream out (file, std::ios::binary);
+	out.write (
+	    reinterpret_cast<const char*> (WEBP_COVER.data ()), static_cast<std::streamsize> (WEBP_COVER.size ())
+	);
+    }
+
+    expectRedWithBlueCorner (loadCoverImage (file));
+    std::filesystem::remove_all (directory);
+
+    CHECK_FALSE (loadCoverImage (directory / "missing.png").has_value ());
+}
+
+TEST_CASE ("Anything that is not a usable image is refused") {
+    CHECK_FALSE (decodeCoverImage ({}).has_value ());
+
+    const std::string html = "<html>nope</html>";
+    CHECK_FALSE (
+	decodeCoverImage (std::span (reinterpret_cast<const uint8_t*> (html.data ()), html.size ())).has_value ()
+    );
+
+    auto truncated = WEBP_COVER;
+    truncated.resize (20);
+    CHECK_FALSE (decodeCoverImage (truncated).has_value ());
+}
+
+TEST_CASE ("Cover art is downloaded in the background and kept in the cache") {
+    const auto cache = std::filesystem::temp_directory_path () / "lwe-cover-cache-test";
+    std::filesystem::remove_all (cache);
+    setenv ("XDG_CACHE_HOME", cache.c_str (), 1);
+
+    CoverServer server;
+    CoverDownloader downloader;
+
+    SECTION ("an image arrives, and a second request is answered from the cache") {
+	const auto url = server.url ("/cover.png");
+
+	CHECK_FALSE (downloader.request (url).has_value ());
+
+	const auto finished = waitFor (downloader, url);
+	REQUIRE (finished.has_value ());
+	REQUIRE (finished->path.has_value ());
+	expectRedWithBlueCorner (loadCoverImage (*finished->path));
+
+	CHECK (downloader.request (url) == finished->path);
+	CHECK (server.requests == 1);
+    }
+
+    SECTION ("a redirect is followed and a WebP stays decodable") {
+	const auto redirected = server.url ("/redirect");
+	CHECK_FALSE (downloader.request (redirected).has_value ());
+	const auto first = waitFor (downloader, redirected);
+	REQUIRE (first.has_value ());
+	REQUIRE (first->path.has_value ());
+	expectRedWithBlueCorner (loadCoverImage (*first->path));
+
+	const auto webp = server.url ("/cover.webp");
+	CHECK_FALSE (downloader.request (webp).has_value ());
+	const auto second = waitFor (downloader, webp);
+	REQUIRE (second.has_value ());
+	REQUIRE (second->path.has_value ());
+	expectRedWithBlueCorner (loadCoverImage (*second->path));
+    }
+
+    SECTION ("an error page and a missing file leave nothing behind") {
+	for (const auto* path : { "/page.html", "/nothing-here" }) {
+	    const auto url = server.url (path);
+
+	    CHECK_FALSE (downloader.request (url).has_value ());
+
+	    const auto finished = waitFor (downloader, url);
+	    REQUIRE (finished.has_value ());
+	    CHECK_FALSE (finished->path.has_value ());
+	    CHECK_FALSE (std::filesystem::exists (downloader.cachePath (url)));
+	}
+    }
+
+    std::filesystem::remove_all (cache);
+}

+ 85 - 0
tests/desktops/conftest.py

@@ -0,0 +1,85 @@
+"""Integration tests that run the engine inside real desktop sessions, each one headless and private to the test.
+
+Needs the engine binary (LWE_BINARY, default build/output/linux-wallpaperengine), Wallpaper Engine's assets
+(LWE_ASSETS_DIR) and a scene wallpaper (LWE_TEST_WALLPAPER, a workshop item folder). A session whose programs are not
+installed here is skipped. Tests only ever talk to the sessions they start: never to the desktop of the machine they
+run on.
+"""
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(REPO / "tools"))
+
+from desktops.session import KINDS, Session, Unsupported  # noqa: E402
+
+STEAM_ROOTS = (
+    Path("/workspace/SteamLibrary"),
+    Path.home() / ".local/share/Steam",
+    Path.home() / ".steam/steam",
+)
+
+
+def _first_existing(paths):
+    return next((path for path in paths if path.exists()), None)
+
+
+@pytest.fixture(scope="session")
+def engine():
+    binary = Path(os.environ.get("LWE_BINARY", REPO / "build/output/linux-wallpaperengine"))
+    assets = os.environ.get("LWE_ASSETS_DIR") or _first_existing(
+        [root / "steamapps/common/wallpaper_engine/assets" for root in STEAM_ROOTS]
+    )
+    wallpaper = os.environ.get("LWE_TEST_WALLPAPER") or _first_existing(
+        [root / "steamapps/workshop/content/431960/1846362380" for root in STEAM_ROOTS]
+    )
+    missing = [what for what, value in (("the engine binary", binary if binary.exists() else None),
+                                        ("the assets", assets), ("a test wallpaper", wallpaper)) if not value]
+    if missing:
+        pytest.skip(f"missing {', '.join(missing)}, see tests/desktops/conftest.py")
+    return {"binary": str(binary), "assets": str(assets), "wallpaper": str(wallpaper)}
+
+
+@pytest.fixture(scope="session")
+def desktop_factory(tmp_path_factory):
+    """one session at a time, shared by the tests of that session: a full desktop is several hundred MB"""
+    started = {}
+    available = Session.available()
+
+    def get(name):
+        if available.get(name) is None:
+            pytest.skip(f"{name} is not installed here and has no rootfs, run: python3 tools/desktop_session.py setup")
+        for other in [key for key in started if key != name]:
+            started.pop(other).stop()
+        if name not in started:
+            session = Session.of(name)
+            try:
+                session.start()
+            except Exception as error:
+                pytest.fail(f"{name} did not start: {error}")
+            started[name] = session
+        return started[name]
+
+    yield get
+    for session in started.values():
+        session.stop()
+
+
+@pytest.fixture
+def desktop(request, desktop_factory):
+    return desktop_factory(request.param)
+
+
+def changed_fraction(before, after, threshold=24):
+    """share of the pixels that differ by more than the threshold in any channel"""
+    import numpy
+    from PIL import Image
+
+    a = numpy.asarray(Image.open(before).convert("RGB"), dtype=numpy.int16)
+    b = numpy.asarray(Image.open(after).convert("RGB"), dtype=numpy.int16)
+    if a.shape != b.shape:
+        return 1.0
+    return float((numpy.abs(a - b).max(axis=2) > threshold).mean())

+ 53 - 0
tests/desktops/test_wallpaper.py

@@ -0,0 +1,53 @@
+import time
+
+import pytest
+
+from conftest import KINDS, Unsupported, changed_fraction
+
+# what is known not to work yet, each reason is a thing to fix: the test starts passing and strict xfail says so
+KNOWN_GAPS = {
+    "gnome": "Mutter has no layer-shell, the Wayland driver cannot create a background surface",
+}
+
+# what the lab cannot show, not the engine
+LAB_LIMITS = {
+    "river": "river 0.4 closes every layer surface unless a window manager client runs, and none is packaged",
+}
+
+
+def _param(name):
+    if name in LAB_LIMITS:
+        return pytest.param(name, marks=pytest.mark.skip(reason=LAB_LIMITS[name]))
+    if name in KNOWN_GAPS:
+        return pytest.param(name, marks=pytest.mark.xfail(reason=KNOWN_GAPS[name], strict=True))
+    return name
+
+
+WALLPAPER_SESSIONS = [_param(name) for name in KINDS]
+
+
+@pytest.mark.parametrize("desktop", WALLPAPER_SESSIONS, indirect=True)
+def test_engine_draws_the_wallpaper(desktop, engine, tmp_path):
+    before = tmp_path / "before.png"
+    try:
+        desktop.shot(before)
+    except Unsupported as error:
+        pytest.skip(str(error))
+
+    outputs = desktop.output_names()
+    assert outputs, f"{desktop.name} lists no output"
+    process = desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root", outputs[0],
+                              "--silent", "--fps", "30", engine["wallpaper"]], log=tmp_path / "engine.log")
+    try:
+        deadline = time.monotonic() + 45
+        fraction = 0.0
+        while time.monotonic() < deadline and fraction < 0.03:
+            time.sleep(3)
+            assert process.poll() is None, f"the engine exited with {process.returncode}:\n{(tmp_path / 'engine.log').read_text()[-1500:]}"
+            after = tmp_path / "after.png"
+            desktop.shot(after)
+            fraction = changed_fraction(before, after)
+        assert fraction >= 0.03, f"{fraction:.0%} of {desktop.name}'s screen changed after the engine started"
+    finally:
+        process.terminate()
+        process.wait(10)

+ 90 - 0
tests/desktops/test_x11_desktop.py

@@ -0,0 +1,90 @@
+"""What an X11 desktop needs from the engine besides the picture: its own desktop menu keeps working on top of the
+wallpaper, and a fullscreen window pauses rendering."""
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from conftest import REPO, KINDS, changed_fraction
+from desktops.session import X11
+
+X11_SESSIONS = [name for name, kind in KINDS.items() if issubclass(kind, X11)]
+# the desktops that draw a desktop window with a context menu of their own
+DESKTOP_MENUS = ["xfce", "mate", "lxqt", "cinnamon"]
+
+
+def _engine(desktop, engine, log):
+    return desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                           desktop.output_names()[0], "--silent", "--fps", "30", engine["wallpaper"]],
+                          log=log, env={"LWE_FRAME_STATS": "1"})
+
+
+def _x(desktop, *argv):
+    return desktop.run(list(argv), {"DISPLAY": f":{desktop.display}"})
+
+
+def _frame_lines(log):
+    return Path(log).read_text(errors="replace").count("FRAME-STATS")
+
+
+def _menu_opens(desktop, tmp_path, tag):
+    """right click on empty desktop, whether a menu showed up next to the pointer"""
+    width, height = desktop.size
+    x, y = width * 3 // 4, height * 3 // 4
+    _x(desktop, "xdotool", "mousemove", str(x), str(y))
+    time.sleep(1)
+    desktop.shot(tmp_path / f"{tag}-before.png")
+    _x(desktop, "xdotool", "click", "3")
+    time.sleep(2)
+    desktop.shot(tmp_path / f"{tag}-after.png")
+    _x(desktop, "xdotool", "key", "Escape")
+    time.sleep(1)
+    # the wallpaper itself barely moves in a few seconds, a menu is a few percent of the screen
+    return changed_fraction(tmp_path / f"{tag}-before.png", tmp_path / f"{tag}-after.png") > 0.01
+
+
+@pytest.mark.parametrize("desktop", DESKTOP_MENUS, indirect=True)
+def test_desktop_menu_opens_over_the_wallpaper(desktop, engine, tmp_path):
+    if not _menu_opens(desktop, tmp_path, "bare"):
+        pytest.skip(f"{desktop.name} opens no desktop menu in this session even without the engine")
+    process = _engine(desktop, engine, tmp_path / "engine.log")
+    try:
+        time.sleep(8)
+        assert _menu_opens(desktop, tmp_path, "engine"), \
+            f"the desktop menu of {desktop.name} no longer opens with the wallpaper running"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", X11_SESSIONS, indirect=True)
+def test_fullscreen_window_pauses_rendering(desktop, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(desktop, engine, log)
+    probe = None
+    try:
+        time.sleep(8)
+        before = _frame_lines(log)
+        time.sleep(5)
+        assert _frame_lines(log) > before, f"the engine does not render on {desktop.name}"
+
+        probe = desktop.spawn("fullscreen-probe", ["python3", str(REPO / "tools/desktops/fullscreen_window.py")],
+                              {"DISPLAY": f":{desktop.display}"})
+        time.sleep(4)
+        paused = _frame_lines(log)
+        time.sleep(5)
+        assert _frame_lines(log) == paused, f"{desktop.name}: still rendering under a fullscreen window"
+
+        os.killpg(probe.pid, 15)
+        probe.wait(10)
+        probe = None
+        time.sleep(4)
+        resumed = _frame_lines(log)
+        time.sleep(5)
+        assert _frame_lines(log) > resumed, f"{desktop.name}: rendering did not resume after the fullscreen window"
+    finally:
+        if probe is not None:
+            os.killpg(probe.pid, 9)
+        process.terminate()
+        process.wait(10)

+ 9 - 0
tools/desktop_session.py

@@ -0,0 +1,9 @@
+#!/usr/bin/env python3
+"""python3 tools/desktop_session.py <list|setup|start|env|tool|shot|stop|status> ..., see tools/desktops/session.py"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from desktops.__main__ import main  # noqa: E402
+
+main()

+ 1 - 0
tools/desktops/__init__.py

@@ -0,0 +1 @@
+"""Headless desktop sessions for the integration tests: see session.py and the tools list in CLAUDE.md."""

+ 86 - 0
tools/desktops/__main__.py

@@ -0,0 +1,86 @@
+import argparse
+import os
+import subprocess
+import sys
+
+from .runner import REPO, ROOTFS, Userland
+from .session import KINDS, Session, Unsupported
+
+FEDORA_PACKAGES = REPO / "tools/desktops/rootfs-fedora.txt"
+ARCH_PACKAGES = REPO / "tools/desktops/rootfs-arch.txt"
+
+
+def setup(which):
+    """the rootfs a session runs in where its programs are not installed natively"""
+    script = str(REPO / "tools/distro_rootfs.sh")
+    image, packages, install = {
+        "fedora": ("fedora:44", FEDORA_PACKAGES, ["dnf", "install", "-y", "--setopt=install_weak_deps=False"]),
+        "arch": ("archlinux:latest", ARCH_PACKAGES, ["pacman", "-Syu", "--noconfirm", "--needed", "--disable-sandbox"]),
+    }[which]
+    root = ROOTFS[which]
+    if not root.is_dir():
+        subprocess.run([script, "fetch", image, str(root)], check=True)
+    if which == "arch":
+        # proot has no free space to report
+        subprocess.run(["sed", "-i", "s/^CheckSpace/#CheckSpace/", str(root / "etc/pacman.conf")], check=True)
+    names = packages.read_text().split()
+    subprocess.run([script, "run", str(root), *install, *names], check=True)
+    # the session bus ignores uids without a passwd entry
+    uid, gid = os.getuid(), os.getgid()
+    subprocess.run([script, "run", str(root), "sh", "-c",
+                    f"getent group {gid} >/dev/null || groupadd -g {gid} lwe; "
+                    f"getent passwd {uid} >/dev/null || useradd -u {uid} -g {gid} -M -d /tmp -s /bin/bash lwe"], check=True)
+
+def main():
+    parser = argparse.ArgumentParser(prog="desktop_session.py", description="Headless desktop sessions for tests")
+    sub = parser.add_subparsers(dest="command", required=True)
+    sub.add_parser("list", help="the sessions and where each would run")
+    sub.add_parser("setup", help="create the rootfs for sessions that are not installed natively").add_argument(
+        "which", choices=("fedora", "arch"))
+    start = sub.add_parser("start", help="start a session")
+    start.add_argument("name", choices=sorted(KINDS))
+    start.add_argument("--size", default="1920x1080")
+    start.add_argument("--outputs", type=int, default=1)
+    for name, text in (("env", "shell exports for a program under test"), ("stop", "stop a session or all"),
+                       ("status", "whether a session runs")):
+        sub.add_parser(name, help=text).add_argument("name", nargs="?" if name == "stop" else None, default="all")
+    tool = sub.add_parser("tool", help="run a program in a session's userland: swaymsg, hyprctl, wmctrl, grim")
+    tool.add_argument("name")
+    tool.add_argument("argv", nargs=argparse.REMAINDER)
+    shot = sub.add_parser("shot", help="screenshot of a session")
+    shot.add_argument("name")
+    shot.add_argument("path")
+    args = parser.parse_args()
+
+    if args.command == "list":
+        for name, userland in Session.available().items():
+            print(f"{name:14} {userland or 'not available (run setup)'}")
+    elif args.command == "setup":
+        setup(args.which)
+    elif args.command == "start":
+        width, height = (int(part) for part in args.size.split("x"))
+        session = Session.of(args.name, size=(width, height), outputs=args.outputs).start()
+        print(f"{args.name} is up in {session.userland.name}, use: eval \"$(python3 tools/desktop_session.py env {args.name})\"")
+    elif args.command == "stop":
+        for name in (KINDS if args.name in ("all", None) else [args.name]):
+            Session.of(name).stop()
+    elif args.command == "status":
+        print("running" if Session.of(args.name).is_running() else "stopped")
+    elif args.command == "env":
+        print(Session.load(args.name).shell_exports(), end="")
+    elif args.command == "tool":
+        session = Session.load(args.name)
+        result = session.run(args.argv)
+        sys.stdout.write(result.stdout)
+        sys.stderr.write(result.stderr)
+        sys.exit(result.returncode)
+    elif args.command == "shot":
+        try:
+            Session.load(args.name).shot(args.path)
+        except Unsupported as error:
+            sys.exit(f"{error}")
+
+
+
+if __name__ == "__main__":
+    main()

+ 43 - 0
tools/desktops/fake_system.py

@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""A private D-Bus system bus with stand-ins for the services a desktop expects from systemd and friends.
+Usage: fake_system.py <address-file>   (stays in the foreground, writes the bus address first)"""
+import os
+import signal
+import sys
+
+import dbus
+import dbusmock
+
+
+class Lab(dbusmock.DBusTestCase):
+    pass
+
+
+def custom(name, path, interface, properties):
+    Lab.spawn_server(name, path, interface, system_bus=True)
+    obj = dbus.Interface(Lab.get_dbus(True).get_object(name, path), dbusmock.MOCK_IFACE)
+    obj.AddProperties(interface, dbus.Dictionary(properties, signature="sv"))
+    return obj
+
+
+def main():
+    Lab.start_system_bus()
+    address = os.environ["DBUS_SYSTEM_BUS_ADDRESS"]
+    for template in ("logind", "upower", "networkmanager", "polkitd", "timedated", "power_profiles_daemon"):
+        Lab.spawn_server_template(template, {}, stdout=open(os.devnull, "w"))
+    custom(
+        "org.freedesktop.locale1", "/org/freedesktop/locale1", "org.freedesktop.locale1",
+        {"X11Layout": "us", "X11Model": "pc105", "X11Variant": "", "X11Options": "", "VConsoleKeymap": "us",
+         "Locale": dbus.Array(["LANG=C.UTF-8"], signature="s")},
+    )
+    custom(
+        "org.freedesktop.hostname1", "/org/freedesktop/hostname1", "org.freedesktop.hostname1",
+        {"Hostname": "lwe-test", "StaticHostname": "lwe-test", "PrettyHostname": "", "IconName": "computer"},
+    )
+    with open(sys.argv[1], "w") as out:
+        out.write(address + "\n")
+    signal.pause()
+
+
+signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
+main()

+ 19 - 0
tools/desktops/fullscreen_window.py

@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+"""A plain X11 window that asks the window manager for fullscreen and stays until killed (tests/desktops)."""
+import signal
+import sys
+
+from Xlib import X, display
+
+d = display.Display()
+screen = d.screen()
+window = screen.root.create_window(0, 0, 640, 480, 0, screen.root_depth, X.InputOutput, X.CopyFromParent,
+                                   background_pixel=screen.black_pixel)
+window.set_wm_name("lwe-fullscreen-probe")
+window.change_property(d.intern_atom("_NET_WM_STATE"), d.intern_atom("ATOM"), 32,
+                       [d.intern_atom("_NET_WM_STATE_FULLSCREEN")])
+window.map()
+d.flush()
+signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
+while True:
+    d.next_event()

+ 33 - 0
tools/desktops/kwin_shot.py

@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+"""Screenshot of a KWin session over org.kde.KWin.ScreenShot2 (kwin started with KWIN_SCREENSHOT_NO_PERMISSION_CHECKS=1)."""
+import os
+import sys
+import threading
+
+import dbus
+from PIL import Image
+
+bus = dbus.SessionBus()
+iface = dbus.Interface(bus.get_object("org.kde.KWin", "/org/kde/KWin/ScreenShot2"), "org.kde.KWin.ScreenShot2")
+read_end, write_end = os.pipe()
+chunks = []
+
+
+def drain():
+    while True:
+        block = os.read(read_end, 1 << 20)
+        if not block:
+            return
+        chunks.append(block)
+
+
+reader = threading.Thread(target=drain)
+reader.start()
+meta = iface.CaptureWorkspace({"native-resolution": True, "include-cursor": False}, dbus.types.UnixFd(write_end))
+os.close(write_end)
+reader.join()
+data = b"".join(chunks)
+width, height, stride = int(meta["width"]), int(meta["height"]), int(meta["stride"])
+image = Image.frombuffer("RGBA", (width, height), data, "raw", "BGRA", stride, 1)
+image.convert("RGB").save(sys.argv[1])
+print(width, height, len(data), dict((str(k), str(v)) for k, v in meta.items() if k not in ("width", "height", "stride")))

+ 1 - 0
tools/desktops/rootfs-arch.txt

@@ -0,0 +1 @@
+hyprland niri sway labwc grim foot wlr-randr wev waybar playerctl mesa xorg-xwayland libinput

+ 1 - 0
tools/desktops/rootfs-fedora.txt

@@ -0,0 +1 @@
+sway swaybg swayidle labwc grim slurp wlr-randr wev foot wl-clipboard wtype wlrctl waybar playerctl python3-dbus python3-gobject wayfire river niri gnome-shell mutter gnome-session gnome-session-wayland-session gnome-settings-daemon nautilus gnome-terminal dconf gnome-screenshot xdg-desktop-portal-gnome gnome-extensions-app gnome-shell-extension-appindicator kscreen spectacle xdg-desktop-portal-kde kde-cli-tools qt6-qttools plasma-workspace-x11 kwin-x11 xfce4-session xfwm4 xfdesktop xfce4-panel xfce4-settings xfconf xfce4-terminal Thunar cinnamon cinnamon-session cinnamon-settings-daemon muffin nemo cinnamon-screensaver cinnamon-control-center mate-session-manager marco mate-panel mate-settings-daemon caja mate-terminal lxqt-session lxqt-panel lxqt-config pcmanfm-qt openbox qterminal lxqt-globalkeys lxqt-notificationd lxqt-qtplugin lxqt-themes lxqt-policykit budgie-desktop budgie-desktop-view budgie-session budgie-control-center cosmic-comp cosmic-session cosmic-panel cosmic-bg cosmic-settings-daemon cosmic-settings cosmic-applets cosmic-launcher cosmic-workspaces cosmic-osd cosmic-notifications cosmic-idle cosmic-randr cosmic-screenshot cosmic-term cosmic-files cosmic-app-library i3 bspwm awesome icewm picom feh herbstluftwm fluxbox sxhkd ImageMagick scrot python3-pyatspi at-spi2-core python3-dogtail xclip wmctrl xinput python3-pytest python3-pytest-timeout python3-pytest-xdist xorg-x11-server-Xephyr xdg-desktop-portal xdg-desktop-portal-gtk xdg-desktop-portal-wlr xorg-x11-server-Xorg xorg-x11-drv-dummy python3-dbusmock ibus pipewire-gstreamer xorg-x11-server-Xvfb mesa-dri-drivers mesa-vulkan-drivers dbus-daemon dbus-x11 python3-pillow python3-numpy xprop xwininfo xdpyinfo xrandr xset xev xkill xwd xauth xorg-x11-server-Xwayland kwin plasma-workspace libxcrypt-compat

+ 165 - 0
tools/desktops/runner.py

@@ -0,0 +1,165 @@
+"""Where a session's programs run: natively when they are installed, in a distribution rootfs under proot otherwise.
+
+Sessions never inherit the caller's environment, a sandbox shares its host's display, audio and D-Bus sockets and a
+test must never reach them.
+"""
+import os
+import shutil
+import signal
+import subprocess
+import time
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[2]
+BASE = Path(os.environ.get("LWE_DESKTOPS_DIR", "/tmp/lwe-d"))
+ROOTFS_DIR = Path(os.environ.get("LWE_ROOTFS_DIR", Path.home() / ".local/share/distro-rootfs"))
+ROOTFS = {
+    "fedora": Path(os.environ.get("LWE_FEDORA_ROOTFS", ROOTFS_DIR / "fedora-44-sys")),
+    "arch": Path(os.environ.get("LWE_ARCH_ROOTFS", ROOTFS_DIR / "arch-compositors")),
+}
+BIN_DIRS = ("usr/bin", "usr/sbin", "usr/libexec", "bin", "sbin")
+SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
+
+
+def proot_binary():
+    return os.environ.get("PROOT") or shutil.which("proot") or str(Path.home() / ".local/share/arch-proot/proot")
+
+
+class Userland:
+    """native, or the programs of the fedora or arch rootfs"""
+
+    def __init__(self, name):
+        self.name = name
+
+    def __repr__(self):
+        return f"Userland({self.name})"
+
+    def has(self, program):
+        if self.name == "native":
+            return shutil.which(program) is not None
+        root = ROOTFS[self.name]
+        return any((root / directory / program).exists() for directory in BIN_DIRS)
+
+    def exists(self, path):
+        """an absolute path inside the userland"""
+        root = Path("/") if self.name == "native" else ROOTFS[self.name]
+        return (root / path.lstrip("/")).exists()
+
+    def path(self, program):
+        if self.name == "native":
+            return shutil.which(program) or next(
+                (str(Path("/") / d / program) for d in BIN_DIRS if (Path("/") / d / program).exists()), None
+            )
+        root = ROOTFS[self.name]
+        return next((f"/{d}/{program}" for d in BIN_DIRS if (root / d / program).exists()), None)
+
+    @staticmethod
+    def pick(*programs, prefer=("native", "fedora", "arch")):
+        """the first userland that has all of the programs"""
+        for name in prefer:
+            userland = Userland(name)
+            if (name == "native" or ROOTFS[name].is_dir()) and all(userland.has(p) for p in programs):
+                return userland
+        raise RuntimeError(
+            f"none of {', '.join(programs)} is installed here and no rootfs has it, "
+            f"run: python3 tools/desktop_session.py setup"
+        )
+
+    def command(self, argv, env):
+        assignments = [f"{key}={value}" for key, value in env.items()]
+        if self.name == "native":
+            home = env.get("HOME", "/tmp")
+            argv = [_without_file_capabilities(argv[0]), *argv[1:]]
+            command = ["env", "-i", f"PATH={os.environ.get('PATH', SYSTEM_PATH)}", f"HOME={home}", "LANG=C.UTF-8", *assignments, *argv]
+            # a read-only shared /tmp/.X11-unix stops compositors from starting Xwayland
+            if not os.access("/tmp/.X11-unix", os.W_OK):
+                sockets = BASE / "x11-unix"
+                sockets.mkdir(parents=True, exist_ok=True, mode=0o1777)
+                command = [proot_binary(), "-b", f"{sockets}:/tmp/.X11-unix", *command]
+            return command
+        return [str(REPO / "tools/distro_rootfs.sh"), "run", str(ROOTFS[self.name]), "-u", "env", *assignments, *argv]
+
+    def process_env(self):
+        env = dict(os.environ)
+        if self.name != "native":
+            env["BINDS"] = f"-b {BASE}:{BASE} -b {REPO}:{REPO}"
+            env["PROOT"] = proot_binary()
+        return env
+
+    def spawn(self, argv, env, log):
+        """starts a program in a session of its own, so that its whole tree can be taken down"""
+        with open(log, "ab") as out:
+            return subprocess.Popen(
+                self.command(argv, env), stdout=out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
+                env=self.process_env(), start_new_session=True,
+            )
+
+    def run(self, argv, env, timeout=60, check=False):
+        return subprocess.run(
+            self.command(argv, env), capture_output=True, text=True, timeout=timeout, check=check,
+            stdin=subprocess.DEVNULL, env=self.process_env(),
+        )
+
+
+def _without_file_capabilities(program):
+    """no_new_privs (Docker) refuses to exec files with capabilities (Fedora's sway/kwin_wayland), a copy has none"""
+    path = shutil.which(program) or program
+    if not os.path.isabs(path):
+        return program
+    try:
+        os.getxattr(path, "security.capability")
+    except OSError:
+        return program
+    with open("/proc/self/status") as status:
+        if "NoNewPrivs:\t1" not in status.read():
+            return program
+    copy = BASE / "nocap" / os.path.basename(path)
+    if not copy.exists() or copy.stat().st_mtime < os.stat(path).st_mtime:
+        copy.parent.mkdir(parents=True, exist_ok=True)
+        shutil.copyfile(path, copy)
+        copy.chmod(0o755)
+    return str(copy)
+
+
+def wait_for(what, check, timeout=30.0, interval=0.2):
+    deadline = time.monotonic() + timeout
+    while time.monotonic() < deadline:
+        value = check()
+        if value:
+            return value
+        time.sleep(interval)
+    raise TimeoutError(f"timed out after {timeout:.0f}s waiting for {what}")
+
+
+def terminate(pids, grace=3.0):
+    """SIGTERM to the process groups, SIGKILL for what is left after the grace time"""
+    for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, 1.0)):
+        for pid in pids:
+            try:
+                os.killpg(pid, sig)
+            except (ProcessLookupError, PermissionError):
+                pass
+        deadline = time.monotonic() + wait
+        while time.monotonic() < deadline and any(_alive(pid) for pid in pids):
+            time.sleep(0.1)
+
+
+def _alive(pid):
+    try:
+        with open(f"/proc/{pid}/stat") as stat:
+            return stat.read().rsplit(")", 1)[1].split()[0] != "Z"
+    except (FileNotFoundError, ProcessLookupError):
+        return False
+
+
+def kill_with_runtime_dir(run_dir):
+    """what changed its session id (daemons started through D-Bus activation) is found by its runtime dir"""
+    needle = f"XDG_RUNTIME_DIR={run_dir}".encode() + b"\0"
+    for entry in Path("/proc").iterdir():
+        if not entry.name.isdigit() or int(entry.name) == os.getpid():
+            continue
+        try:
+            if needle in (entry / "environ").read_bytes():
+                os.kill(int(entry.name), signal.SIGKILL)
+        except (OSError, ProcessLookupError):
+            pass

+ 595 - 0
tools/desktops/session.py

@@ -0,0 +1,595 @@
+"""Headless sessions of every desktop environment and compositor, private to the caller.
+
+Each Session owns a directory under BASE: a runtime dir with the Wayland socket, the session bus and the compositor's
+own sockets, a home, the logs and state.json. Programs of the session run in its userland (see runner.py), the
+programs under test (the engine, we_manager) run on the caller's side with client_env().
+"""
+import glob
+import json
+import os
+import re
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+from .runner import BASE, REPO, Userland, kill_with_runtime_dir, terminate, wait_for
+
+KDE_VARIABLES = ("DISPLAY", "DESKTOP_SESSION", "XDG_SESSION_DESKTOP", "KDE_FULL_SESSION")
+
+
+class Unsupported(Exception):
+    pass
+
+
+class Session:
+    name = ""
+    # short, Hyprland's IPC socket path has to fit in 108 bytes
+    short = ""
+    needs = ()
+    sysbus = False
+    desktop = ""
+
+    def __init__(self, size=(1920, 1080), outputs=1):
+        self.size = tuple(size)
+        self.outputs = outputs
+        self.dir = BASE / self.short
+        self.run_dir = self.dir / "run"
+        self.home = self.dir / "home"
+        self.userland = None
+        self.pids = []
+        self.session_env = {}
+        # more variables of the session (a compositor's IPC socket), and facts about it that are not variables
+        self.extra = {}
+        self.info = {}
+
+    # ----- lookup
+
+    @classmethod
+    def of(cls, name, **options):
+        try:
+            return KINDS[name](**options)
+        except KeyError:
+            raise SystemExit(f"unknown session {name}, one of: {', '.join(KINDS)}")
+
+    @classmethod
+    def load(cls, name):
+        session = cls.of(name)
+        state = json.loads((session.dir / "state.json").read_text())
+        session.userland = Userland(state["userland"])
+        session.pids = state["pids"]
+        session.session_env = state["session_env"]
+        session.extra = state["extra"]
+        session.info = state["info"]
+        session.size = tuple(state["size"])
+        session.outputs = state["outputs"]
+        return session
+
+    @classmethod
+    def available(cls):
+        """userland name or None per session name, whether it can be started here"""
+        result = {}
+        for name, kind in KINDS.items():
+            try:
+                result[name] = Userland.pick(*kind.needs).name
+            except RuntimeError:
+                result[name] = None
+        return result
+
+    def is_running(self):
+        state = self.dir / "state.json"
+        if not state.exists():
+            return False
+        pids = json.loads(state.read_text())["pids"]
+        return bool(pids) and os.path.exists(f"/proc/{pids[0]}")
+
+    # ----- lifecycle
+
+    def start(self):
+        if self.is_running():
+            return self
+        self.stop()
+        shutil.rmtree(self.dir, ignore_errors=True)
+        self.run_dir.mkdir(parents=True, mode=0o700)
+        self.home.mkdir(parents=True)
+        self.userland = Userland.pick(*self.needs)
+        try:
+            self._start_bus()
+            if self.sysbus:
+                self._start_system_bus()
+            self._launch()
+        except BaseException:
+            self.stop()
+            raise
+        self._save()
+        return self
+
+    def stop(self):
+        if self.dir.exists() and (self.dir / "state.json").exists():
+            self.pids = json.loads((self.dir / "state.json").read_text())["pids"]
+        terminate(list(reversed(self.pids)))
+        if self.dir.exists():
+            kill_with_runtime_dir(self.run_dir)
+        self.pids = []
+        state = self.dir / "state.json"
+        if state.exists():
+            state.unlink()
+
+    def _save(self):
+        (self.dir / "state.json").write_text(json.dumps({
+            "userland": self.userland.name, "pids": self.pids, "session_env": self.session_env, "extra": self.extra, "info": self.info,
+            "size": self.size, "outputs": self.outputs,
+        }))
+        (self.dir / "env").write_text(self.shell_exports())
+
+    # ----- environments
+
+    def env(self):
+        """for the programs that run in the session's userland"""
+        env = {
+            "XDG_RUNTIME_DIR": str(self.run_dir),
+            "DBUS_SESSION_BUS_ADDRESS": f"unix:path={self.run_dir}/bus",
+            "HOME": str(self.home),
+            "XDG_CONFIG_HOME": str(self.home / ".config"),
+            "XDG_DATA_HOME": str(self.home / ".local/share"),
+            "XDG_CACHE_HOME": str(self.home / ".cache"),
+            "XDG_STATE_HOME": str(self.home / ".local/state"),
+        }
+        address = self.run_dir / "system-bus-address"
+        if address.exists():
+            env["DBUS_SYSTEM_BUS_ADDRESS"] = address.read_text().strip()
+        env.update(self.session_env)
+        env.update(self.extra)
+        return env
+
+    def client_env(self):
+        """for programs under test, started on the caller's side: only what finds this session"""
+        env = {
+            key: value for key, value in self.env().items()
+            if key in ("XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP",
+                       "WAYLAND_DISPLAY", "DISPLAY", "KDE_FULL_SESSION", "KDE_SESSION_VERSION")
+        }
+        env.update(self.extra)
+        # never the desktop's audio server, a sandbox sees it
+        env["PULSE_SERVER"] = "unix:/nonexistent"
+        env["PIPEWIRE_REMOTE"] = "/nonexistent"
+        return env
+
+    def shell_exports(self):
+        env = self.client_env()
+        lines = [f"export {key}={value}" for key, value in env.items()]
+        unset = [key for key in KDE_VARIABLES if key not in env]
+        return "\n".join(lines + [f"unset {' '.join(unset)}"]) + "\n"
+
+    # ----- running programs
+
+    def spawn(self, name, argv, env=None, userland=None):
+        """a long running program of the session, logged to <dir>/<name>.log"""
+        userland = userland or self.userland
+        process = userland.spawn(argv, {**self.env(), **(env or {})}, self.dir / f"{name}.log")
+        self.pids.append(process.pid)
+        return process
+
+    def run(self, argv, env=None, timeout=60):
+        """a short program in the session's userland, its CompletedProcess"""
+        return self.userland.run(argv, {**self.env(), **(env or {})}, timeout=timeout)
+
+    def client(self, argv, log=None, env=None):
+        """a program under test on the caller's side, in the session's environment"""
+        base = {"PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8"}
+        out = open(log or self.dir / "client.log", "ab")
+        return subprocess.Popen(
+            argv, env={**base, **self.client_env(), **(env or {})}, stdout=out, stderr=subprocess.STDOUT,
+            stdin=subprocess.DEVNULL, start_new_session=True,
+        )
+
+    def shot(self, path):
+        """screenshot to path, taken in the session's userland"""
+        scratch = self.dir / "shot.png"
+        scratch.unlink(missing_ok=True)
+        self._shot(scratch)
+        shutil.copyfile(scratch, path)
+
+    def _shot(self, path):
+        raise Unsupported(f"no screenshot method for {self.name} yet")
+
+    def output_names(self):
+        """the outputs a program can be told to use with --screen-root"""
+        if "WAYLAND_DISPLAY" in self.session_env:
+            # the socket is reachable from the caller's side too, and not every userland has wayland-info (Arch's)
+            userland = Userland("native") if Userland("native").has("wayland-info") else self.userland
+            out = userland.run(["wayland-info"], self.env()).stdout
+            names = []
+            for block in re.split(r"(?=^interface: )", out, flags=re.M):
+                if block.startswith("interface: 'wl_output'"):
+                    names += [name.strip() for name in re.findall(r"^\s+name: (.+)$", block, re.M)]
+            return names
+        return self._x_outputs()
+
+    def _x_outputs(self):
+        return []
+
+    def windows(self):
+        return []
+
+    # ----- buses
+
+    def _start_bus(self):
+        self.spawn("dbus", ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address=unix:path={self.run_dir}/bus"])
+        wait_for("the session bus", (self.run_dir / "bus").exists, 15)
+
+    def _start_system_bus(self):
+        """stand-ins for the systemd services Cinnamon and GNOME need at startup"""
+        self.spawn("sysbus", ["python3", str(REPO / "tools/desktops/fake_system.py"), str(self.run_dir / "system-bus-address")])
+        wait_for("the fake system bus", lambda: (self.run_dir / "system-bus-address").exists(), 30)
+
+    def _bus_name(self, name):
+        reply = self.run(["dbus-send", "--session", "--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus",
+                          "org.freedesktop.DBus.NameHasOwner", f"string:{name}"])
+        return "boolean true" in reply.stdout
+
+    def _launch(self):
+        raise NotImplementedError
+
+    # ----- shared helpers
+
+    def _socket(self, pattern):
+        for path in sorted(glob.glob(str(self.run_dir / pattern))):
+            if not path.endswith(".lock"):
+                return path
+        return None
+
+    def wait_socket(self, pattern, timeout=40):
+        return wait_for(f"{pattern} in {self.run_dir}", lambda: self._socket(pattern), timeout)
+
+
+class Wlroots(Session):
+    """sway, labwc, wayfire and river on wlroots' headless backend"""
+
+    program = ""
+
+    def _wlroots_env(self):
+        env = {
+            "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_HEADLESS_OUTPUTS": str(self.outputs),
+            # nothing here may reach the desktop's session or take its GPU
+            "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent",
+        }
+        for key in ("WLR_RENDER_DRM_DEVICE", "WLR_RENDERER"):
+            if key in os.environ:
+                env[key] = os.environ[key]
+        return env
+
+    def _config(self):
+        return []
+
+    def _launch(self):
+        argv = [self.program, *self._config()]
+        self.spawn(self.program, argv, self._wlroots_env())
+        socket = self.wait_socket("wayland-[0-9]*")
+        self.session_env.update({
+            "WAYLAND_DISPLAY": os.path.basename(socket), "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop,
+        })
+        self._ready()
+
+    def _ready(self):
+        # wlroots' headless outputs start at 1280x720
+        width, height = self.size
+        for index in range(1, self.outputs + 1):
+            self.run(["wlr-randr", "--output", f"HEADLESS-{index}", "--custom-mode", f"{width}x{height}"],
+                     {"WAYLAND_DISPLAY": self.session_env["WAYLAND_DISPLAY"]})
+
+    def _shot(self, path):
+        result = self.run(["grim", str(path)])
+        if result.returncode != 0:
+            raise RuntimeError(f"grim failed: {result.stderr.strip()}")
+
+
+class Sway(Wlroots):
+    name, short, program, desktop = "sway", "s", "sway", "sway"
+    needs = ("sway", "swaymsg", "grim")
+
+    def _config(self):
+        width, height = self.size
+        (self.dir / "sway.conf").write_text(
+            f"output * resolution {width}x{height}\nxwayland disable\ndefault_border none\nswaybg_command -\n"
+        )
+        return ["-c", str(self.dir / "sway.conf")]
+
+    def _ready(self):
+        self.extra["SWAYSOCK"] = wait_for("sway's IPC socket", lambda: self._socket("sway-ipc.*.sock"), 30)
+
+
+class Labwc(Wlroots):
+    name, short, program, desktop = "labwc", "l", "labwc", "labwc"
+    needs = ("labwc", "wlr-randr", "grim")
+
+    def _config(self):
+        config = self.dir / "config"
+        config.mkdir()
+        # the compositors that run as a window of this one fill its output
+        (config / "rc.xml").write_text(
+            '<?xml version="1.0"?>\n<labwc_config>\n  <windowRules>\n'
+            + "".join(
+                f'    <windowRule identifier="{app}"><action name="ToggleFullscreen"/></windowRule>\n'
+                for app in ("Hyprland", "niri", "cosmic-comp")
+            )
+            + "  </windowRules>\n</labwc_config>\n"
+        )
+        return ["-C", str(config)]
+
+
+class Wayfire(Wlroots):
+    name, short, program, desktop = "wayfire", "w", "wayfire", "wayfire"
+    needs = ("wayfire", "wlr-randr", "grim")
+
+
+class River(Wlroots):
+    name, short, program, desktop = "river", "r", "river", "river"
+    needs = ("river", "wlr-randr", "grim")
+
+    def _config(self):
+        init = self.dir / "init"
+        init.write_text("#!/bin/sh\n")
+        init.chmod(0o755)
+        return ["-c", str(init)]
+
+
+class Nested(Session):
+    """Hyprland, niri and COSMIC have no headless backend (they would take the GPU through DRM), they run as a window
+    of a headless labwc"""
+
+    program = ""
+
+    def _launch(self):
+        if Labwc().is_running():
+            parent = Session.load("labwc")
+        else:
+            parent = Labwc(self.size, 1).start()
+            parent.info["implicit"] = True
+            parent._save()
+        socket = f"{parent.run_dir}/{parent.session_env['WAYLAND_DISPLAY']}"
+        argv, env = self._command()
+        self.spawn(self.program, argv, {"WAYLAND_DISPLAY": socket, "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent", **env})
+        self.session_env.update({"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop})
+        self._wait()
+
+    def _command(self):
+        return [self.program], {}
+
+    def _wait(self):
+        self.session_env["WAYLAND_DISPLAY"] = os.path.basename(self.wait_socket("wayland-[0-9]*"))
+
+    def stop(self):
+        super().stop()
+        # the labwc they run in goes with the last of them, unless it was started on its own
+        labwc = Labwc()
+        if labwc.is_running() and Session.load("labwc").info.get("implicit") and not any(
+            kind().is_running() for kind in (Hyprland, Niri, Cosmic)
+        ):
+            labwc.stop()
+
+    def _shot(self, path):
+        result = self.run(["grim", str(path)])
+        if result.returncode != 0:
+            raise RuntimeError(f"grim failed: {result.stderr.strip()}")
+
+
+class Hyprland(Nested):
+    name, short, program, desktop = "hyprland", "h", "Hyprland", "Hyprland"
+    needs = ("Hyprland", "hyprctl", "grim")
+
+    def _command(self):
+        width, height = self.size
+        lines = [f"monitor = HEADLESS-{i}, {width}x{height}@60, {width * (i - 1)}x0, 1" for i in range(1, self.outputs + 1)]
+        (self.dir / "hyprland.conf").write_text("\n".join(lines + ["misc { disable_hyprland_logo = true }", "debug { disable_logs = false }"]) + "\n")
+        return [self.program, "--config", str(self.dir / "hyprland.conf")], {}
+
+    def _wait(self):
+        super()._wait()
+        signature = wait_for("Hyprland's IPC socket", lambda: self._socket("hypr/*/.socket.sock"), 30)
+        self.extra["HYPRLAND_INSTANCE_SIGNATURE"] = os.path.basename(os.path.dirname(signature))
+        for _ in range(self.outputs):
+            self.run(["hyprctl", "output", "create", "headless"], self.extra)
+
+
+class Niri(Nested):
+    name, short, program, desktop = "niri", "n", "niri", "niri"
+    needs = ("niri", "grim")
+
+    def _command(self):
+        (self.dir / "niri.kdl").write_text("")
+        return [self.program, "--config", str(self.dir / "niri.kdl")], {}
+
+    def _wait(self):
+        super()._wait()
+        self.extra["NIRI_SOCKET"] = wait_for("niri's IPC socket", lambda: self._socket("niri.*.sock"), 30)
+
+
+class Cosmic(Nested):
+    name, short, program, desktop = "cosmic", "c", "cosmic-comp", "COSMIC"
+    needs = ("cosmic-comp", "grim")
+
+
+class Kde(Session):
+    """KWin's virtual backend, plasmashell paints nothing on it yet"""
+
+    name, short, desktop = "kde", "k", "KDE"
+    needs = ("kwin_wayland", "kscreen-doctor")
+    sysbus = True
+
+    def _launch(self):
+        width, height = self.size
+        env = {
+            "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": "6",
+            "QT_QPA_PLATFORM": "wayland", "KWIN_SCREENSHOT_NO_PERMISSION_CHECKS": "1",
+        }
+        self.session_env.update(env)
+        self.spawn("kwin", ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height),
+                            "--socket", "lwe-kde", "--no-lockscreen", "--xwayland"], env)
+        self.session_env["WAYLAND_DISPLAY"] = "lwe-kde"
+        self.wait_socket("lwe-kde")
+        wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
+
+    def _shot(self, path):
+        result = self.run(["python3", str(REPO / "tools/desktops/kwin_shot.py"), str(path)])
+        if result.returncode != 0:
+            raise RuntimeError(f"kwin_shot failed: {result.stderr.strip()}")
+
+
+class Gnome(Session):
+    """GNOME Shell as a headless Wayland display server"""
+
+    name, short, desktop = "gnome", "g", "GNOME"
+    needs = ("gnome-shell",)
+    sysbus = True
+
+    def _launch(self):
+        width, height = self.size
+        env = {"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "GNOME", "XDG_SESSION_DESKTOP": "gnome",
+               "GNOME_SHELL_SESSION_MODE": "user"}
+        self.session_env.update(env)
+        self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--virtual-monitor", f"{width}x{height}",
+                             "--wayland-display", "lwe-gnome"], env)
+        self.session_env["WAYLAND_DISPLAY"] = "lwe-gnome"
+        self.wait_socket("lwe-gnome")
+        # mutter picks the first free X display and says which, it can be the number of the desktop's own display
+        log = self.dir / "shell.log"
+        found = wait_for("Xwayland", lambda: re.search(r"public X11 display :(\d+)", log.read_text()) if log.exists() else None, 30)
+        self.info["xwayland_display"] = found.group(1)
+
+    def _shot(self, path):
+        raise Unsupported("GNOME Shell only hands out screenshots to its own tools, capturing needs ScreenCast over PipeWire")
+
+
+class X11(Session):
+    """a desktop environment or window manager on an X server of its own"""
+
+    server = "xvfb"
+    components = ()
+    command = ()
+    env_extra = {}
+    desktop_window = ""
+    ready_timeout = 90
+    # the panels and the desktop need a moment after their windows exist before they have painted
+    settle = 0
+
+    @property
+    def display(self):
+        return int(self.info["display"])
+
+    def _launch(self):
+        self.info["display"] = str(self._free_display())
+        self._start_server()
+        env = {"DISPLAY": f":{self.display}", "XDG_SESSION_TYPE": "x11", "XDG_CURRENT_DESKTOP": self.desktop or "X-Generic", **self.env_extra}
+        self.session_env.update(env)
+        if self.command:
+            self.spawn("session", list(self.command), env)
+        else:
+            for index, argv in enumerate(self.components):
+                self.spawn(f"component{index}", list(argv), env)
+                if index == 0:
+                    wait_for("the window manager", self._wm_name, 30)
+        wait_for("the window manager", self._wm_name, self.ready_timeout)
+        if self.desktop_window:
+            wait_for("the desktop window", lambda: re.search(self.desktop_window, self._wmctrl("-lx")), self.ready_timeout)
+        time.sleep(self.settle)
+
+    def _free_display(self):
+        taken = set()
+        host = os.environ.get("DISPLAY", "")
+        if host.startswith(":"):
+            taken.add(int(host[1:].split(".")[0] or 0))
+        unix = Path("/proc/net/unix").read_text()
+        for number in range(100, 200):
+            lock = f"/tmp/.X{number}-lock"
+            rootfs_locks = [root / f"tmp/.X{number}-lock" for root in (Path(p) for p in self._rootfs_paths())]
+            if (number in taken or Path(lock).exists() or f"/tmp/.X11-unix/X{number}" in unix
+                    or any(path.exists() for path in rootfs_locks)):
+                continue
+            return number
+        raise RuntimeError("no free X display")
+
+    def _rootfs_paths(self):
+        from .runner import ROOTFS
+        return [path for path in ROOTFS.values() if path.is_dir()]
+
+    def _start_server(self):
+        display = f":{self.display}"
+        width, height = self.size
+        # the real server, /usr/bin/Xorg is a wrapper that only lets console users start it
+        xorg = next((p for p in ("/usr/libexec/Xorg", "/usr/lib/xorg/Xorg") if self.userland.exists(p)), None) \
+            if self.server == "xorg" else None
+        if xorg:
+            (self.dir / "xorg.conf").write_text(
+                'Section "Device"\n    Identifier "dummy"\n    Driver "dummy"\n    VideoRam 256000\nEndSection\n'
+                'Section "Monitor"\n    Identifier "mon"\n    HorizSync 5-1000\n    VertRefresh 5-200\n'
+                f'    Modeline "{width}x{height}_60" 173.00 {width} {width + 128} {width + 328} {width + 656} {height} {height + 3} {height + 8} {height + 40} -hsync +vsync\n'
+                'EndSection\nSection "Screen"\n    Identifier "screen0"\n    Device "dummy"\n    Monitor "mon"\n    DefaultDepth 24\n'
+                f'    SubSection "Display"\n        Depth 24\n        Modes "{width}x{height}_60"\n        Virtual {width} {height}\n    EndSubSection\nEndSection\n'
+                'Section "ServerFlags"\n    Option "DontVTSwitch" "true"\n    Option "AutoAddDevices" "false"\n'
+                '    Option "AutoEnableDevices" "false"\n    Option "AutoAddGPU" "false"\nEndSection\n'
+            )
+            # a real refresh rate: muffin and mutter turn Xvfb's mode down
+            self.spawn("xserver", [xorg, display, "-config", str(self.dir / "xorg.conf"), "-configdir", "/nonexistent", "-noreset",
+                                   "-nolisten", "tcp", "-ac", "+extension", "GLX", "-logfile", str(self.dir / "Xorg.log")])
+        else:
+            self.spawn("xserver", ["Xvfb", display, "-screen", "0", f"{width}x{height}x24", "-ac", "+extension", "GLX", "+render", "-noreset"])
+        wait_for("the X server", lambda: self._x(["xprop", "-root"]).returncode == 0, 30)
+
+    def _x(self, argv):
+        return self.run(argv, {"DISPLAY": f":{self.display}"})
+
+    def _wmctrl(self, flag):
+        return self._x(["wmctrl", flag]).stdout
+
+    def _wm_name(self):
+        out = self._wmctrl("-m")
+        match = re.search(r"^Name: (.+)$", out, re.M)
+        return match.group(1) if match else None
+
+    def windows(self):
+        """(window id, class, title) of the managed windows"""
+        windows = []
+        for line in self._wmctrl("-lx").splitlines():
+            parts = line.split(None, 4)
+            if len(parts) >= 3:
+                windows.append((parts[0], parts[2], parts[4] if len(parts) > 4 else ""))
+        return windows
+
+    def _x_outputs(self):
+        return re.findall(r"^(\S+) connected", self._x(["xrandr", "--query"]).stdout, re.M)
+
+    def _shot(self, path):
+        result = self._x(["import", "-window", "root", str(path)])
+        if result.returncode != 0:
+            raise RuntimeError(f"import failed: {result.stderr.strip()}")
+
+
+def x11(name, short, desktop="", server="xvfb", needs=(), sysbus=False, **attrs):
+    return type(name.capitalize(), (X11,), {"name": name, "short": short, "desktop": desktop, "server": server,
+                                             "needs": needs, "sysbus": sysbus, **attrs})
+
+
+Xfce = x11("xfce", "x1", "XFCE", "xorg", ("xfce4-session", "xfwm4", "xfdesktop", "wmctrl", "import"), True,
+           command=("xfce4-session",), desktop_window="xfdesktop", settle=4)
+Cinnamon = x11("cinnamon", "x2", "X-Cinnamon", "xorg", ("cinnamon-session", "cinnamon", "nemo-desktop", "wmctrl", "import"), True,
+               command=("cinnamon-session",), desktop_window="nemo-desktop",
+               env_extra={"GDK_BACKEND": "x11", "LIBGL_ALWAYS_SOFTWARE": "1"}, settle=12)
+Mate = x11("mate", "x3", "MATE", "xorg", ("mate-session", "marco", "caja", "wmctrl", "import"), True,
+           command=("mate-session",), desktop_window="Caja", settle=4)
+Lxqt = x11("lxqt", "x4", "LXQt", "xorg", ("openbox", "pcmanfm-qt", "lxqt-panel", "wmctrl", "import"), False,
+           components=(("openbox",), ("pcmanfm-qt", "--desktop", "--profile=lxqt"), ("lxqt-panel",)),
+           desktop_window="pcmanfm", env_extra={"QT_QPA_PLATFORM": "xcb"}, settle=3)
+WINDOW_MANAGERS = {
+    "i3": ("i3", "-c", "/etc/i3/config"), "openbox": ("openbox",), "bspwm": ("bspwm",), "awesome": ("awesome",),
+    "icewm": ("icewm",), "fluxbox": ("fluxbox",), "herbstluftwm": ("herbstluftwm",),
+}
+WM_CLASSES = [
+    x11(name, f"w{index}", "", "xvfb", (argv[0], "wmctrl", "import"), False, components=(argv,))
+    for index, (name, argv) in enumerate(WINDOW_MANAGERS.items())
+]
+
+KINDS = {
+    kind.name: kind
+    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, Gnome, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
+}

+ 31 - 7
tools/distro_rootfs.sh

@@ -4,7 +4,7 @@
 #
 #
 # Usage:
 # Usage:
 #   tools/distro_rootfs.sh fetch <image[:tag]> <dir>     e.g. debian:12, fedora:44, opensuse/tumbleweed, ghcr.io/...
 #   tools/distro_rootfs.sh fetch <image[:tag]> <dir>     e.g. debian:12, fedora:44, opensuse/tumbleweed, ghcr.io/...
-#   tools/distro_rootfs.sh run <dir> [-u] <cmd...>       -u runs as uid 1000 instead of fake root
+#   tools/distro_rootfs.sh run <dir> [-u] <cmd...>       -u runs as the calling user instead of fake root
 #
 #
 # PROOT points at the proot binary (default: proot from PATH, a static build works best), BINDS adds "-b src:dst" pairs.
 # PROOT points at the proot binary (default: proot from PATH, a static build works best), BINDS adds "-b src:dst" pairs.
 # Whiteout files of later layers are applied, other OCI features (hardlinks across layers etc.) are not.
 # Whiteout files of later layers are applied, other OCI features (hardlinks across layers etc.) are not.
@@ -12,6 +12,16 @@ set -euo pipefail
 
 
 PROOT="${PROOT:-proot}"
 PROOT="${PROOT:-proot}"
 
 
+# whether no component of $2 below $1 is a symlink
+plain_path() {
+    local root="$1" path="$2"
+    while [ "$path" != "$root" ] && [ "$path" != . ] && [ "$path" != / ]; do
+        [ -L "$path" ] && return 1
+        path="$(dirname "$path")"
+    done
+    return 0
+}
+
 fetch() {
 fetch() {
     local image="$1" dir="$2" repo tag token manifest digest registry=registry-1.docker.io
     local image="$1" dir="$2" repo tag token manifest digest registry=registry-1.docker.io
     repo="${image%%:*}"
     repo="${image%%:*}"
@@ -41,18 +51,32 @@ fetch() {
     for layer in $(jq -r '.layers[].digest' <<<"$manifest"); do
     for layer in $(jq -r '.layers[].digest' <<<"$manifest"); do
         echo "layer $layer" >&2
         echo "layer $layer" >&2
         curl -fsSL -H "Authorization: Bearer $token" "https://$registry/v2/$repo/blobs/$layer" -o "$dir/.layer"
         curl -fsSL -H "Authorization: Bearer $token" "https://$registry/v2/$repo/blobs/$layer" -o "$dir/.layer"
+        if [[ "$layer" == sha256:* ]] && [ "$(sha256sum "$dir/.layer" | cut -d' ' -f1)" != "${layer#sha256:}" ]; then
+            echo "layer $layer: digest mismatch, the download is corrupt" >&2
+            exit 1
+        fi
         # whiteouts: .wh.name deletes name from the lower layers, .wh..wh..opq empties the directory
         # whiteouts: .wh.name deletes name from the lower layers, .wh..wh..opq empties the directory
         local wh
         local wh
         while IFS= read -r wh; do
         while IFS= read -r wh; do
-            local base="${wh##*/}" parent
+            wh="${wh#./}"
+            case "/$wh/" in */../*) continue ;; esac
+            local base="${wh##*/}" parent target="$dir"
             parent="$(dirname "$wh")"
             parent="$(dirname "$wh")"
+            if [ "$parent" != . ]; then target="$dir/$parent"; fi
+            # a symlink (var/run -> /run) would point rm at the host's files
+            if ! plain_path "$dir" "$target"; then
+                echo "skipping whiteout $wh, its directory goes through a symlink" >&2
+                continue
+            fi
             if [ "$base" = ".wh..wh..opq" ]; then
             if [ "$base" = ".wh..wh..opq" ]; then
-                find "$dir/$parent" -mindepth 1 -delete 2>/dev/null || true
+                find "$target" -mindepth 1 ! -path "$dir/.layer" -delete 2>/dev/null || true
             else
             else
-                rm -rf "${dir:?}/$parent/${base#.wh.}"
+                rm -rf "${target:?}/${base#.wh.}"
             fi
             fi
-        done < <(tar -tf "$dir/.layer" 2>/dev/null | grep '\.wh\.' || true)
-        tar -xf "$dir/.layer" -C "$dir" --exclude='*.wh.*' --no-same-owner 2>/dev/null || true
+        done < <(tar -tf "$dir/.layer" 2>/dev/null | grep -E '(^|/)\.wh\.' || true)
+        # mknod fails without root, hide that noise
+        tar -xf "$dir/.layer" -C "$dir" --exclude='*.wh.*' --no-same-owner 2>&1 |
+            { grep -v -e 'Cannot mknod' -e 'Exiting with failure status' || true; } >&2 || true
         rm -f "$dir/.layer"
         rm -f "$dir/.layer"
     done
     done
     chmod -R u+w "$dir"
     chmod -R u+w "$dir"
@@ -64,7 +88,7 @@ run() {
     local dir="$1" user=(-0) home=/root
     local dir="$1" user=(-0) home=/root
     shift
     shift
     if [ "${1:-}" = -u ]; then
     if [ "${1:-}" = -u ]; then
-        user=(-i 1000:1000)
+        user=(-i "$(id -u):$(id -g)")
         home=/tmp
         home=/tmp
         shift
         shift
     fi
     fi

+ 11 - 3
tools/glibc_compat/retarget_glibc_versions.py

@@ -30,7 +30,10 @@ def elf_hash(name):
 
 
 
 
 def version_tuple(name):
 def version_tuple(name):
-    return tuple(int(p) for p in name[len("GLIBC_"):].split("."))
+    parts = name[len("GLIBC_"):].split(".")
+    if not all(p.isdigit() for p in parts):
+        return None
+    return tuple(int(p) for p in parts)
 
 
 
 
 def cstr(data, offset):
 def cstr(data, offset):
@@ -69,8 +72,11 @@ def retarget(path, floor, provided):
             name = cstr(data, strtab + vna_name)
             name = cstr(data, strtab + vna_name)
             if name == BASE_VERSION:
             if name == BASE_VERSION:
                 base_name = vna_name
                 base_name = vna_name
-            elif name.startswith(b"GLIBC_") and version_tuple(name.decode()) > floor:
-                newer[vna_other] = (aux, name.decode())
+            elif name.startswith(b"GLIBC_"):
+                # GLIBC_PRIVATE and GLIBC_ABI_* tags have no version to compare
+                version = version_tuple(name.decode())
+                if version is not None and version > floor:
+                    newer[vna_other] = (aux, name.decode())
             aux += vna_next
             aux += vna_next
         offset += vn_next
         offset += vn_next
 
 
@@ -105,6 +111,8 @@ def main():
     if len(sys.argv) < 4:
     if len(sys.argv) < 4:
         raise SystemExit(__doc__)
         raise SystemExit(__doc__)
     floor = version_tuple("GLIBC_" + sys.argv[1])
     floor = version_tuple("GLIBC_" + sys.argv[1])
+    if floor is None:
+        raise SystemExit(__doc__)
     provided = set(sys.argv[2].split(","))
     provided = set(sys.argv[2].split(","))
     for path in sys.argv[3:]:
     for path in sys.argv[3:]:
         retarget(path, floor, provided)
         retarget(path, floor, provided)

+ 22 - 4
tools/headless_render.sh

@@ -82,10 +82,28 @@ fi
 # HEADLESS_RENDER_PULSE_SERVER: private audio server to play into (tools/wecompare/wine/audio_sink.sh), never the desktop's
 # HEADLESS_RENDER_PULSE_SERVER: private audio server to play into (tools/wecompare/wine/audio_sink.sh), never the desktop's
 PULSE=unix:/nonexistent-pulse
 PULSE=unix:/nonexistent-pulse
 if [ -n "${HEADLESS_RENDER_PULSE_SERVER:-}" ]; then
 if [ -n "${HEADLESS_RENDER_PULSE_SERVER:-}" ]; then
-    case "$HEADLESS_RENDER_PULSE_SERVER" in
-        *"/run/user/"*) echo "HEADLESS_RENDER_PULSE_SERVER must not be the desktop's audio server" >&2; exit 1 ;;
-    esac
-    PULSE=$HEADLESS_RENDER_PULSE_SERVER
+    # a local socket that is not the desktop's server, also through symlinks or bind mounts
+    PULSE_SOCKET="${HEADLESS_RENDER_PULSE_SERVER#unix:}"
+    if [[ "$PULSE_SOCKET" != /* || "$PULSE_SOCKET" == *[[:space:]]* ]]; then
+        echo "HEADLESS_RENDER_PULSE_SERVER must be a unix socket path, got $HEADLESS_RENDER_PULSE_SERVER" >&2
+        exit 1
+    fi
+    DESKTOP_PULSE=("${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/pulse/native" "/run/user/$(id -u)/pulse/native")
+    if [[ "${PULSE_SERVER:-}" == unix:/* ]]; then DESKTOP_PULSE+=("${PULSE_SERVER#unix:}"); fi
+    if [[ "${PULSE_SERVER:-}" == /* ]]; then DESKTOP_PULSE+=("$PULSE_SERVER"); fi
+    if [[ "$(realpath -m "$PULSE_SOCKET")" == /run/user/* ]]; then
+        echo "HEADLESS_RENDER_PULSE_SERVER must not be the desktop's audio server" >&2
+        exit 1
+    fi
+    if [ -S "$PULSE_SOCKET" ]; then
+        for candidate in "${DESKTOP_PULSE[@]}"; do
+            if [ -S "$candidate" ] && [ "$(stat -Lc %d:%i "$candidate")" = "$(stat -Lc %d:%i "$PULSE_SOCKET")" ]; then
+                echo "HEADLESS_RENDER_PULSE_SERVER must not be the desktop's audio server" >&2
+                exit 1
+            fi
+        done
+    fi
+    PULSE=unix:$PULSE_SOCKET
 fi
 fi
 ISOLATE=(-u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u KDE_FULL_SESSION -u KDE_SESSION_VERSION
 ISOLATE=(-u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u KDE_FULL_SESSION -u KDE_SESSION_VERSION
     -u DESKTOP_SESSION -u XDG_CURRENT_DESKTOP -u XDG_SESSION_DESKTOP XDG_RUNTIME_DIR="$RUNTIME_DIR"
     -u DESKTOP_SESSION -u XDG_CURRENT_DESKTOP -u XDG_SESSION_DESKTOP XDG_RUNTIME_DIR="$RUNTIME_DIR"

+ 12 - 6
tools/smoke_test_release.sh

@@ -57,15 +57,18 @@ install_desktop_runtime() {
 # packages providing the given sonames, through each package manager's file index
 # packages providing the given sonames, through each package manager's file index
 install_sonames() {
 install_sonames() {
     . /etc/os-release
     . /etc/os-release
-    local pkgs=() so
+    local pkgs=() so pkg
     case " $ID ${ID_LIKE:-} " in
     case " $ID ${ID_LIKE:-} " in
         *" debian "* | *" ubuntu "*)
         *" debian "* | *" ubuntu "*)
             apt-get install -y -qq --no-install-recommends apt-file >/dev/null
             apt-get install -y -qq --no-install-recommends apt-file >/dev/null
             apt-file update >/dev/null
             apt-file update >/dev/null
             for so in "$@"; do
             for so in "$@"; do
-                pkgs+=($(apt-file search -x "/${so//./\\.}\$" | cut -d: -f1 | grep -v -- '-dbg' | head -1))
+                pkg="$(apt-file search -x "/${so//./\\.}\$" | cut -d: -f1 | grep -v -- '-dbg' | head -1 || true)"
+                if [ -n "$pkg" ]; then pkgs+=("$pkg"); else echo "   no package provides $so" >&2; fi
             done
             done
-            apt-get install -y -qq --no-install-recommends "${pkgs[@]}" >/dev/null
+            if [ "${#pkgs[@]}" -gt 0 ]; then
+                apt-get install -y -qq --no-install-recommends "${pkgs[@]}" >/dev/null
+            fi
             ;;
             ;;
         *" fedora "*)
         *" fedora "*)
             dnf -y -q install "${@/%/()(64bit)}" >/dev/null
             dnf -y -q install "${@/%/()(64bit)}" >/dev/null
@@ -77,9 +80,12 @@ install_sonames() {
             pacman -Fy >/dev/null
             pacman -Fy >/dev/null
             for so in "$@"; do
             for so in "$@"; do
                 [[ "$so" == libnode.so.* ]] && continue
                 [[ "$so" == libnode.so.* ]] && continue
-                pkgs+=($(pacman -Fq "/usr/lib/$so" | head -1 | cut -d/ -f2))
+                pkg="$(pacman -Fq "/usr/lib/$so" | head -1 | cut -d/ -f2 || true)"
+                if [ -n "$pkg" ]; then pkgs+=("$pkg"); else echo "   no package provides $so" >&2; fi
             done
             done
-            [ "${#pkgs[@]}" -gt 0 ] && pacman -S --noconfirm --needed "${pkgs[@]}" >/dev/null
+            if [ "${#pkgs[@]}" -gt 0 ]; then
+                pacman -S --noconfirm --needed "${pkgs[@]}" >/dev/null
+            fi
             ;;
             ;;
         *" suse "* | *" opensuse "*)
         *" suse "* | *" opensuse "*)
             zypper -n -q install "${@/%/()(64bit)}" >/dev/null
             zypper -n -q install "${@/%/()(64bit)}" >/dev/null
@@ -122,7 +128,7 @@ lazy="$(grep -E 'undefined symbol' <<<"$out" | grep -vE '/(linux-wallpaperengine
     sed -E 's/^\s*undefined symbol: (\S+).*\/([^/)]+)\)$/\2: \1/' | sort -u || true)"
     sed -E 's/^\s*undefined symbol: (\S+).*\/([^/)]+)\)$/\2: \1/' | sort -u || true)"
 if [ -n "$missing$ours" ]; then
 if [ -n "$missing$ours" ]; then
     echo "-- missing"
     echo "-- missing"
-    sed 's/^/   /' <<<"$missing$ours" | head -30
+    printf '%s\n' "$missing" "$ours" | sed -e '/^$/d' -e 's/^/   /' | head -30
     failed=1
     failed=1
 fi
 fi
 if [ -n "$lazy" ]; then
 if [ -n "$lazy" ]; then

+ 6 - 3
tools/wecompare/README.md

@@ -38,7 +38,7 @@ Data locations (all overridable):
 - `we_cursor.sh <scene> <outdir> "x,y x,y" [settle]` - warps the pointer before each grab (parallax, cursor).
 - `we_cursor.sh <scene> <outdir> "x,y x,y" [settle]` - warps the pointer before each grab (parallax, cursor).
 - `we_capture.sh <scene> [secs]` - RenderDoc capture of one WE frame (inspect with `tools/rdc_dump.py` on :98,
 - `we_capture.sh <scene> [secs]` - RenderDoc capture of one WE frame (inspect with `tools/rdc_dump.py` on :98,
   `rdscripts/` has the replay scripts).
   `rdscripts/` has the replay scripts).
-- `audio_sink.sh start|stop|env|record <wav> <secs>` - a private PulseAudio with one null sink (never the desktop's
+- `audio_sink.sh start|stop|env|record <wav> <secs>` - a private PulseAudio (or, where pulseaudio isn't installed, a private PipeWire + pipewire-pulse + WirePlumber) with one null sink (never the desktop's
   server) and a recorder on its monitor. `WE_AUDIO_REC=<wav> we_full.sh ...` plays live WE into it, and
   server) and a recorder on its monitor. `WE_AUDIO_REC=<wav> we_full.sh ...` plays live WE into it, and
   `HEADLESS_RENDER_PULSE_SERVER` does the same for `tools/headless_render.sh`; `../wavstat.py` prints levels. Align
   `HEADLESS_RENDER_PULSE_SERVER` does the same for `tools/headless_render.sh`; `../wavstat.py` prints levels. Align
   recordings by onset, not wall clock.
   recordings by onset, not wall clock.
@@ -63,8 +63,11 @@ targets by feature from `FEATURES.md`.
     ln -s <wallpaper_engine>/distribution/bin bin; ln -s <wallpaper_engine>/assets assets
     ln -s <wallpaper_engine>/distribution/bin bin; ln -s <wallpaper_engine>/assets assets
     ln -s <wallpaper_engine>/distribution/plugins plugins
     ln -s <wallpaper_engine>/distribution/plugins plugins
     bash wine/we_display.sh
     bash wine/we_display.sh
-    WINEPREFIX=$WE_LIVE_DIR/wineprefix DISPLAY=:98 wine64 wineboot --init
-    WINEPREFIX=$WE_LIVE_DIR/wineprefix dxvk-setup install -s -y
+    WINEPREFIX=$WE_LIVE_DIR/wineprefix DISPLAY=:98 wine wineboot --init
+    # DXVK dlls into the prefix (Debian: `dxvk-setup install -s -y`); copy, never symlink, WE_WINED3D=1 needs wined3d
+    for d in d3d11 dxgi; do
+        cp /usr/lib64/wine-wow64/wine/x86_64-windows/dxvk-$d.dll $WE_LIVE_DIR/wineprefix/drive_c/windows/system32/$d.dll
+    done
 
 
 For RenderDoc: `mkdir -p $WE_LIVE_DIR/vklayer; cp wine/renderdoc_capture.json $WE_LIVE_DIR/vklayer/;
 For RenderDoc: `mkdir -p $WE_LIVE_DIR/vklayer; cp wine/renderdoc_capture.json $WE_LIVE_DIR/vklayer/;
 cp wine/rd_trigger.py $WE_LIVE_DIR/`, and `cp wine/qrenderdoc_analytics.json ~/.local/share/qrenderdoc/analytics.json`
 cp wine/rd_trigger.py $WE_LIVE_DIR/`, and `cp wine/qrenderdoc_analytics.json ~/.local/share/qrenderdoc/analytics.json`

+ 6 - 4
tools/wecompare/render_we.py

@@ -11,7 +11,7 @@ seconds apart (env overrides). -control openWallpaper sent to a running instance
 Wine (it only brings the UI window back), hence one instance per item.
 Wine (it only brings the UI window back), hence one instance per item.
 Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
 Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
 """
 """
-import os, subprocess, sys, time
+import os, shutil, subprocess, sys, time
 import resource
 import resource
 import numpy as np
 import numpy as np
 import mss
 import mss
@@ -34,7 +34,9 @@ RETRIES = int(os.environ.get('RETRIES', 3))
 env = {k: v for k, v in os.environ.items() if k not in ('WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'DBUS_SESSION_BUS_ADDRESS')}
 env = {k: v for k, v in os.environ.items() if k not in ('WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'DBUS_SESSION_BUS_ADDRESS')}
 env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=S + '/wineprefix', DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
 env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=S + '/wineprefix', DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
            PULSE_SERVER=f'unix:{S}/run/no-pulse', PIPEWIRE_REMOTE=f'{S}/run/no-pipewire', ALSA_CONFIG_PATH=S + '/run/asound-null.conf')
            PULSE_SERVER=f'unix:{S}/run/no-pulse', PIPEWIRE_REMOTE=f'{S}/run/no-pipewire', ALSA_CONFIG_PATH=S + '/run/asound-null.conf')
-WINE = '/usr/lib/wine/wine64'
+# Debian keeps the 64-bit loader out of PATH, Fedora's wine is the wow64 build
+WINE = '/usr/lib/wine/wine64' if os.path.exists('/usr/lib/wine/wine64') else shutil.which('wine')
+WINESERVER = '/usr/lib/wine/wineserver' if os.path.exists('/usr/lib/wine/wineserver') else shutil.which('wineserver')
 we_proc = None
 we_proc = None
 log = None
 log = None
 
 
@@ -91,7 +93,7 @@ def hide_ui():
 
 
 def start_we(first):
 def start_we(first):
     global we_proc, log
     global we_proc, log
-    subprocess.run(['/usr/lib/wine/wineserver', '-k'], env=env, stderr=subprocess.DEVNULL)
+    subprocess.run([WINESERVER, '-k'], env=env, stderr=subprocess.DEVNULL)
     time.sleep(1)
     time.sleep(1)
     log = open(S + '/we_run_last.log', 'w')
     log = open(S + '/we_run_last.log', 'w')
     we_proc = subprocess.Popen([WINE, 'wallpaper64.exe', '-control', 'openWallpaper', '-file', winpath(first),
     we_proc = subprocess.Popen([WINE, 'wallpaper64.exe', '-control', 'openWallpaper', '-file', winpath(first),
@@ -168,7 +170,7 @@ def main():
             except OSError:
             except OSError:
                 pass
                 pass
             print(f'we {id_} {FRAMES} frames{"" if ok else " (still flat)"} {time.time() - t0:.1f}s', flush=True)
             print(f'we {id_} {FRAMES} frames{"" if ok else " (still flat)"} {time.time() - t0:.1f}s', flush=True)
-    subprocess.run(['/usr/lib/wine/wineserver', '-k'], env=env, stderr=subprocess.DEVNULL)
+    subprocess.run([WINESERVER, '-k'], env=env, stderr=subprocess.DEVNULL)
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':

+ 33 - 10
tools/wecompare/wine/audio_sink.sh

@@ -17,22 +17,45 @@ running() { [ -S "$SOCK" ] && PULSE_SERVER=unix:$SOCK PULSE_COOKIE=$R/cookie pac
 case "$1" in
 case "$1" in
 start)
 start)
     running && exit 0
     running && exit 0
-    mkdir -p "$R"
-    cat > "$R/default.pa" <<EOF
+    mkdir -p "$R" && chmod 700 "$R"
+    if command -v pulseaudio >/dev/null; then
+        cat > "$R/default.pa" <<EOF
 load-module module-native-protocol-unix socket=$SOCK auth-anonymous=1
 load-module module-native-protocol-unix socket=$SOCK auth-anonymous=1
 load-module module-null-sink sink_name=lwe_null rate=48000 channels=2 format=float32le sink_properties=device.description=lwe_null
 load-module module-null-sink sink_name=lwe_null rate=48000 channels=2 format=float32le sink_properties=device.description=lwe_null
 set-default-sink lwe_null
 set-default-sink lwe_null
 set-default-source lwe_null.monitor
 set-default-source lwe_null.monitor
 EOF
 EOF
-    # own runtime/state dirs and no autospawn, so it never finds the host's server
-    env -u DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=$R PULSE_RUNTIME_PATH=$R PULSE_STATE_PATH=$R \
-        PULSE_CONFIG_PATH=$R PULSE_COOKIE=$R/cookie \
-        nohup pulseaudio -n --daemonize=no --exit-idle-time=-1 --use-pid-file=no --disallow-module-loading \
-        --log-target=file:$R/log -F "$R/default.pa" > /dev/null 2>&1 &
-    for i in $(seq 50); do running && exit 0; sleep 0.1; done
-    echo "pulseaudio did not come up, see $R/log" >&2; exit 1 ;;
+        # own runtime/state dirs and no autospawn, so it never finds the host's server
+        env -u DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=$R PULSE_RUNTIME_PATH=$R PULSE_STATE_PATH=$R \
+            PULSE_CONFIG_PATH=$R PULSE_COOKIE=$R/cookie \
+            nohup pulseaudio -n --daemonize=no --exit-idle-time=-1 --use-pid-file=no --disallow-module-loading \
+            --log-target=file:$R/log -F "$R/default.pa" > /dev/null 2>&1 &
+        for i in $(seq 50); do running && exit 0; sleep 0.1; done
+    else
+        # no pulseaudio (Fedora): a private PipeWire with config/state under $R, never the user's restore state
+        mkdir -p "$R/config" "$R/state" "$R/data"
+        for prog in pipewire wireplumber pipewire-pulse; do
+            env -u DBUS_SESSION_BUS_ADDRESS -u PIPEWIRE_REMOTE -u PULSE_SERVER -u WAYLAND_DISPLAY -u DISPLAY \
+                XDG_RUNTIME_DIR=$R PULSE_RUNTIME_PATH=$R XDG_CONFIG_HOME=$R/config XDG_STATE_HOME=$R/state \
+                XDG_DATA_HOME=$R/data setsid nohup $prog > "$R/$prog.log" 2>&1 &
+            sleep 0.3
+        done
+        for i in $(seq 50); do
+            if running; then
+                export PULSE_SERVER=unix:$SOCK
+                pactl load-module module-null-sink sink_name=lwe_null rate=48000 channels=2 format=float32le \
+                    sink_properties=device.description=lwe_null > /dev/null \
+                    && pactl set-default-sink lwe_null && pactl set-default-source lwe_null.monitor && exit 0
+                break
+            fi
+            sleep 0.1
+        done
+    fi
+    echo "audio server did not come up, see $R" >&2; exit 1 ;;
 stop)
 stop)
-    pkill -f "pulseaudio -n .*$R/default.pa" ;;
+    for pid in $(pgrep -x pulseaudio) $(pgrep -x pipewire) $(pgrep -x wireplumber) $(pgrep -x pipewire-pulse); do
+        tr '\0' '\n' 2>/dev/null < /proc/$pid/environ | grep -qx "XDG_RUNTIME_DIR=$R" && kill $pid
+    done ;;
 env)
 env)
     env_lines ;;
     env_lines ;;
 record)
 record)

+ 2 - 2
tools/wecompare/wine/we_capture.sh

@@ -7,8 +7,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }
 pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
-WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
-WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=:98 WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=:98 WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run

+ 2 - 2
tools/wecompare/wine/we_cursor.sh

@@ -7,8 +7,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=:98
 D=:98
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
-WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
-WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run

+ 6 - 3
tools/wecompare/wine/we_full.sh

@@ -7,8 +7,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=${WE_DISPLAY:-:98}
 D=${WE_DISPLAY:-:98}
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
-WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
-WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
@@ -59,4 +59,7 @@ with mss.MSS(display=sys.argv[4]) as m:
         time.sleep(float(sys.argv[3]))
         time.sleep(float(sys.argv[3]))
 PY
 PY
 $WINESERVER -k 2>/dev/null
 $WINESERVER -k 2>/dev/null
-[ -n "$REC" ] && { pkill -INT -P $REC timeout; wait $REC; }
+if [ -n "$REC" ]; then
+    pkill -INT -P $REC timeout
+    wait $REC || true
+fi