Ver Fonte

Web frames over dmabuf, EGL_PLATFORM crash fix, release test rig, cleanups

Engine
  - Web wallpapers: CEF 146 frames reach the main process as dmabufs (--web-frames auto|shm|dmabuf), imported through EGL on Wayland and on X11
  - X11 driver: drop EGL_PLATFORM before glfwInit. Electron sets it to wayland and we_manager passes it on, the X11/XWayland EGL display then crashed in libwayland-client
  (elementary, web wallpaper as startup background)
  - X11 fullscreen detector: clear the screen list on reset, no null display dereference after a failed reconnect
  - Fix pointer y direction of the cursor hit test and script cursor position on flipped and unflipped outputs
  - DynamicValue: a listener may remove itself while its value propagates (removal is deferred, new test)
  - SDL audio: remove a stream outside the stream list lock
  - Media events: album art only sends mediaThumbnailChanged, metadata sends properties, playback and timeline
  - PulseAudio recorder: keep the context of the stream instead of asking a failed stream (assertion abort), initialize all members
  - Null guards in the dmabuf channel and import, small perf and modernize fixes from clang-tidy, ~25 stale TODO comments removed

Docs
  - README: new 'Identical to Wallpaper Engine' section listing what is a one to one port, trimmed Limitations, Steam Deck row (work in progress)

Release test rig (tools/linuxvm)
  - Run the matrix in parallel lanes, close late windows (WE Manager, Steam) after the settle, wake an idle VM display before screenshots, retry empty installPrebuilt answers,
  hide_steam_kde.sh and a steamdeck profile
  - Results of this run: 25 of 26 VM profiles pass, steamdeck open (its VM display goes blank in the screenshot checks)
UwU há 1 mês atrás
pai
commit
a239861367
100 ficheiros alterados com 2586 adições e 302 exclusões
  1. 21 2
      CMakeLists.txt
  2. 65 46
      README.md
  3. 2 2
      nix/package.nix
  4. 39 2
      src/WallpaperEngine/Application/ApplicationContext.cpp
  5. 6 0
      src/WallpaperEngine/Application/ApplicationContext.h
  6. 30 5
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  7. 0 1
      src/WallpaperEngine/Audio/AudioContext.h
  8. 0 1
      src/WallpaperEngine/Audio/Drivers/AudioDriver.h
  9. 3 3
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  10. 6 2
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  11. 1 1
      src/WallpaperEngine/Data/Builders/VectorBuilder.h
  12. 0 1
      src/WallpaperEngine/Data/Dumpers/StringPrinter.cpp
  13. 34 10
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  14. 8 1
      src/WallpaperEngine/Data/Model/DynamicValue.h
  15. 0 1
      src/WallpaperEngine/Data/Model/Model.h
  16. 0 1
      src/WallpaperEngine/Data/Model/UserSetting.h
  17. 1 2
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  18. 2 0
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  19. 4 0
      src/WallpaperEngine/Desktop/HostWayland.cpp
  20. 4 0
      src/WallpaperEngine/Desktop/HostWayland.h
  21. 1 1
      src/WallpaperEngine/FileSystem/Adapters/Types.h
  22. 1 1
      src/WallpaperEngine/Render/CFBO.h
  23. 12 0
      src/WallpaperEngine/Render/CTexture.cpp
  24. 1 0
      src/WallpaperEngine/Render/CTexture.h
  25. 2 0
      src/WallpaperEngine/Render/CWallpaper.cpp
  26. 38 1
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  27. 1 0
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  28. 54 1
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  29. 4 1
      src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.cpp
  30. 0 1
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  31. 18 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  32. 0 2
      src/WallpaperEngine/Render/Objects/CImage.cpp
  33. 28 8
      src/WallpaperEngine/Render/Objects/CText.cpp
  34. 49 21
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  35. 7 1
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  36. 9 5
      src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp
  37. 4 4
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  38. 2 4
      src/WallpaperEngine/Render/Objects/TextLayout.cpp
  39. 1 1
      src/WallpaperEngine/Render/Objects/TextLayout.h
  40. 9 20
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  41. 9 0
      src/WallpaperEngine/Render/Shaders/Shader.cpp
  42. 2 0
      src/WallpaperEngine/Render/Shaders/Shader.h
  43. 53 65
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  44. 4 0
      src/WallpaperEngine/Render/Shaders/ShaderUnit.h
  45. 78 0
      src/WallpaperEngine/Render/Shaders/SourceMemo.h
  46. 0 1
      src/WallpaperEngine/Render/TextureCache.cpp
  47. 1 0
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  48. 223 16
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  49. 20 0
      src/WallpaperEngine/Render/Wallpapers/CWeb.h
  50. 388 0
      src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.cpp
  51. 46 0
      src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.h
  52. 8 6
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  53. 3 1
      src/WallpaperEngine/Scripting/ScriptEngine.h
  54. 135 0
      src/WallpaperEngine/Testing/Cases/DmabufChannel.cpp
  55. 40 0
      src/WallpaperEngine/Testing/Cases/DynamicValueListeners.cpp
  56. 1 0
      src/WallpaperEngine/Testing/Cases/HandleTable.cpp
  57. 1 1
      src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp
  58. 26 0
      src/WallpaperEngine/Testing/Cases/NumericGuards.cpp
  59. 13 0
      src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp
  60. 1 1
      src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp
  61. 36 33
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  62. 3 0
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h
  63. 27 1
      src/WallpaperEngine/WebBrowser/CEF/BrowserApp.cpp
  64. 54 1
      src/WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.cpp
  65. 10 1
      src/WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.h
  66. 179 0
      src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.cpp
  67. 38 0
      src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.h
  68. 17 0
      src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.cpp
  69. 11 0
      src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h
  70. 1 2
      src/WallpaperEngine/WebBrowser/WebBrowserContext.cpp
  71. 8 0
      tests/desktops/fixtures/webframes/index.html
  72. 1 0
      tests/desktops/fixtures/webframes/project.json
  73. 8 0
      tests/desktops/fixtures/webframes_swapped/index.html
  74. 1 0
      tests/desktops/fixtures/webframes_swapped/project.json
  75. 28 0
      tests/desktops/test_kde.py
  76. 153 0
      tests/desktops/test_web_frames.py
  77. 34 0
      tests/desktops/test_x11_desktop.py
  78. 27 0
      tools/check_video_start.sh
  79. 4 2
      tools/desktops/fullscreen_window.py
  80. 52 0
      tools/fuzz/json.cpp
  81. 43 0
      tools/fuzz/mdl.cpp
  82. 26 0
      tools/fuzz/package.cpp
  83. 27 0
      tools/fuzz/sog.cpp
  84. 20 0
      tools/fuzz/texture.cpp
  85. 26 8
      tools/linuxvm/RELEASE_TESTING.md
  86. 59 3
      tools/linuxvm/check_frame.py
  87. 71 0
      tools/linuxvm/deck_check.sh
  88. 25 1
      tools/linuxvm/guest_test.sh
  89. 30 0
      tools/linuxvm/hide_steam_kde.sh
  90. 2 1
      tools/linuxvm/host_shots.sh
  91. 3 1
      tools/linuxvm/linuxvm.sh
  92. 26 0
      tools/linuxvm/make_reference_frames.sh
  93. 2 2
      tools/linuxvm/pointer_check.sh
  94. 2 0
      tools/linuxvm/profiles/arch-hypr.sh
  95. 1 0
      tools/linuxvm/profiles/arch-xfce.sh
  96. 1 0
      tools/linuxvm/profiles/debian-xfce.sh
  97. 5 2
      tools/linuxvm/profiles/elementary.sh
  98. 1 0
      tools/linuxvm/profiles/endeavouros-xfce.sh
  99. 1 0
      tools/linuxvm/profiles/manjaro-xfce.sh
  100. 4 0
      tools/linuxvm/profiles/mint-cinnamon.sh

+ 21 - 2
CMakeLists.txt

@@ -22,6 +22,19 @@ endif()
 
 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-narrowing")
 
+set(LWE_SANITIZE "" CACHE STRING "Build with sanitizers: address, address;undefined or thread (tools/runtime_analysis.py)")
+if(LWE_SANITIZE)
+    string(REPLACE ";" "," lwe_sanitize_list "${LWE_SANITIZE}")
+    set(lwe_sanitize_flags "-fsanitize=${lwe_sanitize_list} -fno-omit-frame-pointer -g1")
+    if(lwe_sanitize_list MATCHES "undefined|thread")
+        set(lwe_sanitize_flags "${lwe_sanitize_flags} -fno-sanitize=vptr")
+    endif()
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${lwe_sanitize_flags}")
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${lwe_sanitize_flags} -Wno-error=maybe-uninitialized -Wno-error=tsan")
+    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=${lwe_sanitize_list}")
+    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=${lwe_sanitize_list}")
+endif()
+
 find_package(X11)
 find_package(OpenGL REQUIRED)
 find_package(GLEW REQUIRED)
@@ -46,9 +59,9 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 set(KISSFFT_TEST OFF)
 set(KISSFFT_TOOLS OFF)
 
-set(CEF_VERSION "135.0.17+gcbc1c5b+chromium-135.0.7049.52")
+set(CEF_VERSION "146.0.11+g3a0fcf1+chromium-146.0.7680.179")
 # SHA256 of the archives for that version, a CEF_SHA256_<platform> per distribution that is pinned (bump with CEF_VERSION)
-set(CEF_SHA256_linux64_minimal "24ac1980e62be7b1aea2c337d6bd4bc770dccd8b37e47c6db94b397f13ec4dc6")
+set(CEF_SHA256_linux64_minimal "4320d0a18a8d7fbae1e2539030a9315094b34af8a2000999ad8caa7befda7625")
 if(CMAKE_BUILD_TYPE STREQUAL "Debug")
     set(default_cef_dist "standard")
 else()
@@ -618,6 +631,10 @@ set(COMMON_SOURCES
     src/WallpaperEngine/WebBrowser/WebBrowserContext.h
     src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.cpp
     src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h
+    src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.cpp
+    src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.h
+    src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.cpp
+    src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.h
 
     src/WallpaperEngine/Data/Assets/Types.h
     src/WallpaperEngine/Data/Assets/Texture.h
@@ -721,6 +738,8 @@ if(BUILD_TESTING)
 
         ${COMMON_SOURCES}
 
+        src/WallpaperEngine/Testing/Cases/DmabufChannel.cpp
+        src/WallpaperEngine/Testing/Cases/DynamicValueListeners.cpp
         src/WallpaperEngine/Testing/Cases/Example.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.h

+ 65 - 46
README.md

@@ -6,45 +6,78 @@ It started with KDE, but meanwhile supports most desktop environments, on Waylan
 
 The engine itself is a command-line tool driven entirely by flags, see Usage below. For a GUI (Workshop browsing, library, playlists, per-monitor wallpapers, backups) use [WE Manager](https://github.com/WallpaperEngineLover/we_manager), which also downloads and updates the engine for you.
 
-## What's different from upstream
+## Identical to Wallpaper Engine
+
+The goal of this fork is that a wallpaper looks and behaves here like it does in Wallpaper Engine 2.8. Where the engine has
+a counterpart in `wallpaper64.exe` (2.8.0.42), the code is a port of that function and not a guess, and the results were
+compared with the real Wallpaper Engine running under Wine (and on a real Windows VM) on close to 300 Workshop wallpapers.
+These parts follow Wallpaper Engine one to one:
+
+Scene layout and camera:
+
+- Draw order is the `scene.json` array order, groups and locators only nest (a child shows only while every group above it shows), layers under a compose or passthrough layer are drawn into its buffer.
+- Object transforms (parent chain, Euler order, alignment anchors, auto size, crop offset), the quad a layer draws and its half texel inset.
+- Scaling modes (default fill, fit, stretch, center), alignment, zoom and offset, and rendering at each monitor's own pixel size like Wallpaper Engine's per monitor DPI awareness.
+- Camera objects and camera paths, camera shake, camera fade, zoom, the scene camera that scripts can read and set, perspective cameras (3D scenes and perspective layers), fullscreen layers, fog by distance and height.
+- Mouse parallax (formula, smoothing, per layer depth, wallpaper position), including that it only exists in orthographic scenes, and the cursor as Wallpaper Engine hands it to scenes, scripts and shaders (per monitor, unclamped).
+
+Rendering:
+
+- Effects: pass and buffer setup, buffer sizes and sharing, conditions, blend and depth state rules (translucent and additive never write depth, `normal` replaces, alpha only written into layer buffers), the composite buffers of layers, the 6x6 yellow and black checker for textures it cannot load.
+- Shaders: Wallpaper Engine's shader dialect and its `#require` modules, combos and their defaults, constants, material overrides and uniform layout, translated to GLSL, with the texture slot, format and mask component combos it sets.
+- Textures: `.tex` containers and formats (TEXV 4 and 5, TEXI, TEXB 3 and 4 with their conditions, sprite sheets, LUT volumes, video payloads) and how each is uploaded.
+- Post processing: LDR and HDR bloom with Wallpaper Engine's own `util` materials, the combine passes (including its HDR scRGB output), color options, image filters, LUTs, flip, and the camera fade, in its order.
+- Lighting: the old four slot point lights, the LightingV1 modules (point, spot, tube, directional) with cookies and shadow maps, volumetric light, planar reflections and the mip mapped frame buffer.
+- Particles: emitters, initializers, operators and forces of 2.7 and 2.8 (boids, collisions, remap, turbulence, vortex, control point attraction, ...), child systems and their inheritance, control points, prewarm, ropes and trails, sprite sheets, orientation and culling, emitters that read an image layer.
+- Text: sizing (`pointsize * 300 / 72`), HarfBuzz shaping with Wallpaper Engine's font fallback list, MSDF outline, blur and shadow, wrapping and ellipsis, anchors and backgrounds, colour glyphs, blend modes and effects on text.
+- 3D models: skinning and morphs on the GPU, root motion, frustum culling and shadow casting.
+- Puppets (2D characters): `.mdl` parsing, animation layers with their blending and fades, additive layers, bone physics, IK and rope chains, constraint blend rules, bone alpha, morph targets, clipping masks, hit boxes, draw order tracks, and the script bone API.
+- Video wallpapers and video textures: when a texture video plays, pauses and loops, and the `IVideoTexture` object of scripts.
 
-Most of the work since the fork went into making wallpapers look and behave like in Wallpaper Engine 2.8. Where it matters the behavior was taken from the Wallpaper Engine binary itself and checked side by side against the real Wallpaper Engine running under Wine, on close to 200 Workshop wallpapers.
+Sound:
+
+- Sound objects: play modes (single, random, loop) and their timers, gain, spatialization, distance model, and what a volume change starts or stops.
+- The sound mixer: OpenAL Soft 1.21.1 semantics (update size, per update gain ramps, the stop and pause fade, linear resampling) and its HRTF renderer for headphones, bit identical to OpenAL Soft and within 1e-7 of Wallpaper Engine's output.
+- The audio spectrum that visualizers read: the same capture, FFT, band folding and smoothing, and the raw 128 band feed web wallpapers get.
+
+SceneScript and properties:
+
+- Scripts run on V8 with Wallpaper Engine's own `baseclasses.js` and `jsmodules`, so `Vec3`, `WEMath` and friends behave like the originals, and every script API object (layers, effects and materials, animations and animation layers, text, particle instances, model data, camera, `engine`, `input`, `thisScene`) has the members of the real thing in the same order.
+- Script semantics: `init()` timing, `applyUserProperties()` with the same first call and keys, angles in degrees, timers, cursor events with propagation, hit boxes and local positions, `createLayer` and `destroyLayer`, `localStorage` in the same file format and location logic.
+- User properties apply live without a reload, and scripts, animations and bindings on scene settings, object properties and effect constants work like Wallpaper Engine's.
+- Wallpaper files with values of the wrong type are read the way Wallpaper Engine's JSON loader reads them where it ignores them (the default applies), and where it would abort the engine just doesn't crash.
+- Presets and wallpapers that depend on another Workshop item.
+
+Desktop behavior:
+
+- Pause rules: fullscreen, maximized and focused windows pause per monitor by Wallpaper Engine's rules (minimized and other desktop windows do not count), with its defaults.
+- Stretch (span) groups: one wallpaper over the bounding box of several monitors, cursor included, pixel identical to Wallpaper Engine's stretch layout.
+- Web wallpapers run on CEF 146, the version Wallpaper Engine ships, with its property, audio and file API.
+
+Everything not listed here, or listed under Limitations, is either specific to this fork (see below) or not a copy yet.
+
+## What this fork adds
 
 KDE Plasma and Wayland:
 
 - On Plasma the wallpaper is a real desktop surface (`plasma-shell` protocol): not in the taskbar or task switcher, unaffected by Show Desktop.
 - Mouse-reactive wallpapers work on KDE Wayland, the cursor position comes from KWin since the desktop never gets pointer events there.
-- Fullscreen-pause detection through KWin, since it doesn't implement `wlr-foreign-toplevel-management` like wlroots compositors. Still experimental (see Limitations).
-- Unplugging a monitor no longer leaks layer surfaces (that made KWin grow to gigabytes).
+- Fullscreen-pause detection through KWin, since it doesn't implement `wlr-foreign-toplevel-management` like wlroots compositors.
+- Native Wayland output with fractional scaling, GNOME Shell and COSMIC support, wlroots and Hyprland per output pause, and an X11 output that handles several screens and desktops that cover the root window.
 - HDR output (`--hdr`) through the Wayland color management protocol, HDR videos included.
 - Outside Plasma the KDE parts switch themselves off, and there is a build without them (`-DDISABLE_KDE_FEATURES=ON`).
 
-Scenes:
-
-- 3D scenes: perspective camera, models with skinning, morphs and root motion, camera objects and paths, fog.
-- Wallpaper Engine's LightingV1 with shadow maps, legacy point lights, volumetric light, planar reflections, HDR bloom (`--post-processing ultra`), MSAA (`--msaa`) and supersampling (`--ssaa`).
-- Scenes render at the output resolution with Wallpaper Engine's scaling and alignment modes, image filters and color options.
-- Particles: child systems, everything added in Wallpaper Engine 2.7+ (boids, collisions, remap, HSV colors, color lists, ...), exact turbulence/vortex/attraction formulas, prewarm, ropes through the geometry shader like Wallpaper Engine.
-- Text rewritten with HarfBuzz and MSDF: font fallback for missing characters, outlines, blur, drop shadows, wrapping, backgrounds, blend modes, screen anchors. Sizes and positions match Wallpaper Engine.
-- Puppets (animated characters): animation layers with Wallpaper Engine's blending, bone physics, IK and rope chains, blend rules, bone alpha, morphs, clipping masks, animated draw order.
-- Sound objects with Wallpaper Engine's play modes and OpenAL-style spatialization.
-- Presets and other items built on another Workshop item load their base wallpaper, SOG depth-photo wallpapers are drawn natively.
-
-Scripts and audio:
-
-- Scene scripts run on V8 like in Wallpaper Engine, with Wallpaper Engine's own helper classes from its assets and most of the SceneScript API (layer creation and sorting, cursor events, video textures, animations, bones, camera, model data, timers, user shortcuts).
-- Script `localStorage` survives restarts like in Wallpaper Engine (same file format, in `~/.local/state/linux-wallpaperengine/scenestorage`), so a dragged clock or character stays where it was put.
-- The audio spectrum is computed like Wallpaper Engine computes it, so visualizers move the same.
-- Web wallpapers run CEF in a separate, disposable process and get properties, audio data and Wallpaper Engine's JavaScript API.
-
 Control:
 
 - Multi-monitor handling: per-screen backgrounds (`--screen-root`), one wallpaper spanning several monitors (`--screen-span`), several wallpapers side by side on one monitor (`--screen-slot`), per-screen scaling/zoom/alignment/corner color, and Workshop playlists (`--playlist`).
 - Live hotswap of the running wallpaper and its settings via `SIGUSR1`, separately per engine with `--control-file`, no process restart.
-- A global playback speed multiplier (`--speed`), separate from the FPS cap.
-- Video wallpapers can loop just part of the video (`--video-start`/`--video-end`), e.g. only minute 3 to 4 of a 5 minute clip, or several parts one after the other while skipping the rest (`--video-segments "2:00-3:00,4:00-5:00"`).
+- A global playback speed multiplier (`--speed`), separate from the FPS cap; battery and idle pause (`--fps-battery`, `--idle-pause`).
+- Video wallpapers can loop just part of the video (`--video-start`/`--video-end`), or several parts one after the other (`--video-segments "2:00-3:00,4:00-5:00"`).
 - More granular audio: restrict sound to a single screen (`--audio-screen`), a separate ambient volume for non-video backgrounds (`--ambient-volume`), per-object sound volume (`--sound-volume`), and a tunable multiplier on audio-reactive properties (`--audio-sensitivity`, with `--list-audio-objects` to see what's wired up).
-- Layer and effect introspection/toggling (`--list-objects`, `--disable-object`, `--list-effects`, `--disable-effect`, ...) for things the wallpaper author didn't expose as a property.
+- Layer and effect introspection and toggling (`--list-objects`, `--disable-object`, `--list-effects`, `--disable-effect`, ...) for things the wallpaper author didn't expose as a property.
+- Supersampling (`--ssaa`), an expanded canvas for oversize scenes (`--expand-canvas`), `--repair-assets` for wallpapers that only worked in older Wallpaper Engine versions.
+- Web wallpapers in a separate, disposable process with GPU frame transfer through dmabuf (`--web-frames`), SOG depth-photo wallpapers drawn natively.
+- Protections against runaway scripts (time, heap and buffer limits) and limits on every file reader, which Wallpaper Engine does not have.
 
 ## Requirements
 
@@ -149,7 +182,8 @@ fullscreen window and automute.
 | Pop!_OS | COSMIC | Supported | |
 | Bazzite | KDE Plasma (Wayland), image based | Supported | portable build or Flatpak |
 | SteamOS | KDE Plasma (Wayland), read-only root | Supported | system libraries cannot be installed on the read-only root, so that step is not part of the test |
-| elementary OS | Pantheon (Wayland) | Work in progress | Gala has no `wlr-layer-shell`, the X11 session needs `--window-background` |
+| Steam Deck (SteamOS on Deck hardware) | KDE Plasma (Wayland), read-only root | Work in progress | the engine runs in the Deck-shaped VM, but the VM's screen goes blank in the screenshot checks (Steam takes the display there), so the picture checks do not pass yet |
+| elementary OS | Pantheon (Wayland) | Supported | Gala has no `wlr-layer-shell`, the engine draws through XWayland: only X11 windows pause it, and the wallpaper takes the clicks on the desktop |
 | ChimeraOS | gamescope, GNOME | Not supported | not tested: its Mesa cannot draw in a VM, and gamescope's game session has no desktop to put a wallpaper on. The GNOME desktop mode could theoretically work |
 
 Other distributions and desktops that are not listed (Sway, niri, KDE on X11, other Ubuntu flavours, ...) may well work,
@@ -175,6 +209,8 @@ cmake -DCMAKE_BUILD_TYPE='Release' -DDISABLE_KDE_FEATURES=ON ..
 
 On KDE Plasma the engine loads KWin scripts of its own for the cursor position and for the windows that pause it (maximized, fullscreen, and focused with `--pause-on-focus`), per screen like Wallpaper Engine; nothing needs installing.
 
+On a Wayland compositor that offers no layer shell and isn't GNOME (Gala on elementary OS) the engine falls back to XWayland: it draws into a desktop type background window of its own, like `--screen-root` does on an X11 desktop. Wallpapers, scripts and the pointer work as usual, but only X11 windows pause it (such a compositor tells native Wayland clients nothing about its windows) and the wallpaper window takes the clicks that would reach the desktop.
+
 On sway, Hyprland, niri, labwc and other compositors with the wlr foreign toplevel protocol a fullscreen window pauses only the screen it is on (maximized ones too with `--pause-on-maximized`). sway before 1.12 doesn't say which screen a window that opens fullscreen is on, so such a window pauses every screen there.
 
 ## Assets
@@ -241,6 +277,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--layer <layer>` | Wayland only: `wlr-layer-shell` layer (`background`, `bottom`, `top`, `overlay`). Default `bottom`, on KDE `background` can end up under plasmashell's desktop window |
 | `--speed <factor>` | Global playback speed multiplier |
 | `--hwdec <backend>` | mpv hardware decoding for videos: `auto` (default), `no`, `vaapi-copy`, `nvdec-copy`, ... Try `no` if videos crash on NVIDIA |
+| `--web-frames <auto\|shm\|dmabuf>` | how web wallpapers hand their frames over: `dmabuf` shares the browser's GPU buffers (Wayland and X11, much less CPU at high resolutions), `shm` reads every frame back, `auto` (default) picks dmabuf where it works and falls back to shm |
 | `--video-start <time>`, `--video-end <time>` | Video wallpapers only: loop just this part of the video, in seconds, `m:ss` or `h:mm:ss` (either one alone leaves that side at the video's start/end) |
 | `--video-segments <start-end,...>` | Video wallpapers only: play these parts one after the other and skip everything between them, e.g. `"2:00-3:00,4:00-5:00"`; an empty side is the video's start/end (`"4:00-"`) |
 | `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control`, `/tmp/lwe-control-<uid>` without it |
@@ -267,7 +304,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--disable-parallax` | Disable parallax |
 | `--no-fullscreen-pause` | Don't pause while an app is fullscreen |
 | `--pause-on-focus` | Also pause while another application has the focus (Wallpaper Engine's "Other application focused: Pause"; on Wayland only that monitor) |
-| `--pause-on-maximized` | wlroots compositors (sway, Hyprland, niri, labwc...): also pause the monitor a maximized window is on. KDE and GNOME always do, like Wallpaper Engine |
+| `--pause-on-maximized` | wlroots compositors (sway, Hyprland, niri, labwc...): also pause the monitor a maximized window is on. KDE, GNOME and X11 desktops always do, like Wallpaper Engine |
 | `--fps-battery <fps>` | FPS limit while the computer runs on battery (UPower, else `/sys/class/power_supply`), `0` pauses |
 | `--pause-on-battery` | Pause while on battery, same as `--fps-battery 0` |
 | `--idle-pause <minutes>` | Pause after this many minutes without keyboard or mouse input (ext-idle-notify-v1 on Wayland, the X11 screen saver extension, GNOME's idle monitor); anything inhibiting idle, like a playing video, keeps it running |
@@ -381,31 +418,13 @@ Platform and setup:
 - RGB lighting output (iCUE/Chroma `ledsource`) is ignored.
 - Arch has `libnode` only in the AUR, so the Arch release build needs it installed from there.
 
-Puppets (2D animated characters):
-
-- Morph modifiers (morph targets driven by a bone) and clipping masks with record flag 8 are not supported.
-- `layerimage` particle emitters don't follow puppet layers.
-
-3D scenes:
+Text:
 
-- Camera parallax is not applied in 3D scenes.
-
-Images, particles and text:
-
-- `layerimage` particle emitters read the layer right away, not from the GPU a frame later like Wallpaper Engine, and don't support text layers or opacity masks.
-- Particle `spritesheetrefreshsync`, `alphatocoverage` and rope `uvscrolling`/`uvsmoothing` are not supported.
 - Without Segoe UI Emoji installed (see Fonts), emoji come from the Twemoji font in Wallpaper Engine's assets and are drawn as their colour bitmap; Wallpaper Engine itself draws nothing for them without that font.
 
-Sound:
-
-- Spatialized sound objects don't switch to HRTF for headphones like OpenAL on Windows does.
-
 Scripting (SceneScript):
 
-- Not implemented: `setParent`, the effect material calls `getMaterial` and `setMaterialProperty`, blend shape calls, `transformAttachmentToTexture`, and the `resizeScreen` and `mediaStatusChanged` events.
-- A few layer members read `undefined` (`sortorder`, `ledsource`, `colorBlendMode`, most light properties, ...).
 - Property scripts inside a `createLayer` config aren't registered.
-- Particles still update after scripts within a frame, Wallpaper Engine updates them before.
 
 ## Credits
 

+ 2 - 2
nix/package.nix

@@ -94,11 +94,11 @@ let
   );
 
   # the version CMakeLists.txt pins, CMake's DownloadCEF finds the archive already in its folder
-  cefVersion = "135.0.17+gcbc1c5b+chromium-135.0.7049.52";
+  cefVersion = "146.0.11+g3a0fcf1+chromium-146.0.7680.179";
   cefArchive = "cef_binary_${cefVersion}_linux64_minimal.tar.bz2";
   cef = fetchurl {
     url = "https://cef-builds.spotifycdn.com/${lib.replaceStrings [ "+" ] [ "%2B" ] cefArchive}";
-    hash = "sha256-JKwZgOYr57GuosM31r1Lx3DczYs35HxtuUs5fxPsTcY=";
+    hash = "sha256-QyDQoYqNf7rh4lOQMKkxUJSzSviiAAmZrYyqe+/adiU=";
   };
 in
 stdenv.mkDerivation {

+ 39 - 2
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -434,6 +434,28 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.hidden ()
 	.store_into (this->settings.general.webHostShm);
 
+    backgroundGroup.add_argument ("--web-host-frames")
+	.default_value ("shm")
+	.hidden ()
+	.action ([this] (const std::string& value) -> void {
+	    if (value != "shm" && value != "dmabuf") {
+		sLog.exception ("Invalid --web-host-frames value: ", value);
+	    }
+
+	    this->settings.general.webHostFrames = value;
+	});
+
+    backgroundGroup.add_argument ("--web-host-socket")
+	.default_value (-1)
+	.hidden ()
+	.action ([this] (const std::string& value) -> void {
+	    try {
+		this->settings.general.webHostSocket = std::stoi (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid --web-host-socket value: ", value);
+	    }
+	});
+
     backgroundGroup.add_argument ("--web-host-width")
 	.default_value (0)
 	.hidden ()
@@ -1099,6 +1121,21 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.hwdec = value;
 	});
 
+    performanceGroup.add_argument ("--web-frames")
+	.help (
+	    "How web wallpapers hand their frames to the engine: auto (default), shm (the browser reads every frame "
+	    "back "
+	    "to shared memory) or dmabuf (the browser's GPU buffers are shared and copied on the GPU, needs a Wayland "
+	    "session and EGL). auto picks dmabuf where it works and falls back to shm"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    if (value != "auto" && value != "shm" && value != "dmabuf") {
+		sLog.exception ("Invalid --web-frames value: ", value, " (auto, shm or dmabuf)");
+	    }
+
+	    this->settings.render.webFrames = value;
+	});
+
     performanceGroup.add_argument ("--no-fullscreen-pause")
 	.help ("Prevents the background pausing when an app is fullscreen")
 	.flag ()
@@ -1138,8 +1175,8 @@ void ApplicationContext::loadSettingsFromArgv () {
 
     performanceGroup.add_argument ("--pause-on-maximized")
 	.help (
-	    "wlroots compositors: also pause the outputs a maximized window is on (KDE and GNOME always do, like "
-	    "Wallpaper Engine)"
+	    "wlroots compositors: also pause the outputs a maximized window is on (KDE, GNOME and X11 desktops always "
+	    "do, like Wallpaper Engine)"
 	)
 	.flag ()
 	.action ([this] (const std::string& value) -> void { this->settings.render.pauseOnMaximized = true; });

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

@@ -141,6 +141,8 @@ public:
 	    std::vector<SplitScreen> splitScreens;
 	    bool webHost;
 	    std::string webHostShm;
+	    std::string webHostFrames;
+	    int webHostSocket;
 	    uint32_t webHostWidth;
 	    uint32_t webHostHeight;
 	    std::optional<std::filesystem::path> controlFile;
@@ -152,6 +154,7 @@ public:
 	    float playbackSpeed;
 	    WallpaperEngine::VideoPlayback::VideoSegments videoSegments;
 	    std::string hwdec;
+	    std::string webFrames;
 	    bool freezeAnimations;
 	    bool pauseOnFullscreen;
 	    // only fullscreen toplevels that are also activated count (scrollable tiling compositors)
@@ -248,6 +251,8 @@ public:
             .splitScreens = {},
             .webHost = false,
             .webHostShm = "",
+            .webHostFrames = "shm",
+            .webHostSocket = -1,
             .webHostWidth = 0,
             .webHostHeight = 0,
             .controlFile = std::nullopt,
@@ -258,6 +263,7 @@ public:
             .playbackSpeed = 1.0f,
             .videoSegments = {},
             .hwdec = "auto",
+            .webFrames = "auto",
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,

+ 30 - 5
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -8,6 +8,9 @@
 #include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
 #include "WallpaperEngine/Data/Utils/FiniteFloat.h"
+#ifdef ENABLE_WAYLAND
+#include "WallpaperEngine/Desktop/HostWayland.h"
+#endif
 #include "WallpaperEngine/FileSystem/Container.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
@@ -2375,12 +2378,18 @@ void WallpaperApplication::runWebHost () {
     windowInfo.SetAsWindowless (0);
     // frames come when the main process asks, so they line up with what it presents
     windowInfo.external_begin_frame_enabled = true;
+    // dmabuf frames: the browser paints into GPU buffers (OnAcceleratedPaint) the main process imports, instead of
+    // reading them back (OnPaint)
+    const bool dmabufFrames = this->m_context.settings.general.webHostFrames == "dmabuf"
+	&& this->m_context.settings.general.webHostSocket >= 0;
+    windowInfo.shared_texture_enabled = dmabufFrames;
 
     CefBrowserSettings browserSettings;
     // only a ceiling while external begin frames are on, the main process decides when a frame is produced
     browserSettings.windowless_frame_rate = std::max (60, this->m_context.settings.render.maximumFPS);
 
-    const CefRefPtr<CEF::SharedMemoryRenderHandler> renderHandler = new CEF::SharedMemoryRenderHandler (shm);
+    const CefRefPtr<CEF::SharedMemoryRenderHandler> renderHandler
+	= new CEF::SharedMemoryRenderHandler (shm, dmabufFrames ? this->m_context.settings.general.webHostSocket : -1);
     const CefRefPtr<CEF::BrowserClient> client = new CEF::BrowserClient (renderHandler, project.properties);
 
     // the "w" prefix + workshop id host must match what the scheme handler factory expects to resolve
@@ -2689,17 +2698,33 @@ void WallpaperApplication::setupOutput () {
 	);
     }
 
+    std::string sessionType = XDG_SESSION_TYPE;
+
+#ifdef ENABLE_WAYLAND
+    const auto drivers = sVideoFactories.getRegisteredDrivers ();
+
+    if (sessionType == "wayland" && this->m_context.settings.render.mode == ApplicationContext::DESKTOP_BACKGROUND
+	&& getenv ("DISPLAY") != nullptr && std::ranges::find (drivers, "x11") != drivers.end ()
+	&& WallpaperEngine::Desktop::compositorLacksLayerShell ()) {
+	sLog.out ("The compositor has no layer shell, drawing through XWayland into a background window instead");
+	setenv ("LWE_X11_BACKGROUND_WINDOW", "1", 0);
+	setenv ("LWE_XWAYLAND_FALLBACK", "1", 1);
+	unsetenv ("WAYLAND_DISPLAY");
+	setenv ("XDG_SESSION_TYPE", "x11", 1);
+	sessionType = "x11";
+    }
+#endif
+
     sLog.debug ("Checking for window servers: ");
 
     for (const auto& windowServer : sVideoFactories.getRegisteredDrivers ()) {
 	sLog.debug ("\t", windowServer);
     }
 
-    this->m_videoDriver = sVideoFactories.createVideoDriver (
-	this->m_context.settings.render.mode, XDG_SESSION_TYPE, this->m_context, *this
-    );
+    this->m_videoDriver
+	= sVideoFactories.createVideoDriver (this->m_context.settings.render.mode, sessionType, this->m_context, *this);
     this->m_fullScreenDetector
-	= sVideoFactories.createFullscreenDetector (XDG_SESSION_TYPE, this->m_context, *this->m_videoDriver);
+	= sVideoFactories.createFullscreenDetector (sessionType, this->m_context, *this->m_videoDriver);
 }
 
 void WallpaperApplication::setupAudio () {

+ 0 - 1
src/WallpaperEngine/Audio/AudioContext.h

@@ -45,7 +45,6 @@ namespace Audio {
 	void setStreamHrtf (int streamId, const Drivers::StreamHrtf* hrtf) const;
 	[[nodiscard]] const Hrtf::Store* getHrtf () const;
 
-	// TODO: our own format definitions instead of ffmpeg's?
 	[[nodiscard]] AVSampleFormat getFormat () const;
 	[[nodiscard]] int getSampleRate () const;
 	[[nodiscard]] int getChannels () const;

+ 0 - 1
src/WallpaperEngine/Audio/Drivers/AudioDriver.h

@@ -60,7 +60,6 @@ namespace Audio {
 	    // dt is seconds since the previous frame, scaled by the playback speed
 	    virtual void update (float dt);
 
-	    // TODO: our own format definitions instead of ffmpeg's?
 	    [[nodiscard]] virtual AVSampleFormat getFormat () const = 0;
 	    [[nodiscard]] virtual int getSampleRate () const = 0;
 	    [[nodiscard]] virtual int getChannels () const = 0;

+ 3 - 3
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h

@@ -15,10 +15,10 @@ class PlaybackRecorder;
 class PulseAudioPlaybackRecorder final : public PlaybackRecorder {
 public:
     struct PulseAudioData {
-	PulseAudioPlaybackRecorder* owner;
-	pa_stream* captureStream;
+	PulseAudioPlaybackRecorder* owner = nullptr;
+	pa_stream* captureStream = nullptr;
 	std::string monitorName;
-	bool captureLost;
+	bool captureLost = false;
 	pa_context* context = nullptr;
     };
 

+ 6 - 2
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -81,7 +81,6 @@ void SDLAudioDriver::render (float* out, int frames) {
 
     this->m_pending.erase (this->m_pending.begin (), this->m_pending.begin () + static_cast<long> (available));
 
-    // TODO: do we also need to lock while audio is playing, or wait until the stream is unused?
     SDL_UnlockMutex (this->m_streamListMutex);
 }
 
@@ -380,16 +379,21 @@ int SDLAudioDriver::addStream (AudioStream* stream, int volume, float left, floa
     return newStreamId;
 }
 void SDLAudioDriver::removeStream (int streamId) {
+    SDLAudioBuffer* removed = nullptr;
+
     // same lock the audio callback holds while iterating m_streams, else erasing races it and the stream may be deleted
     // in use
     SDL_LockMutex (this->m_streamListMutex);
 
     if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
-	delete it->second;
+	removed = it->second;
 	this->m_streams.erase (it);
     }
 
     SDL_UnlockMutex (this->m_streamListMutex);
+
+    // outside the lock, an AudioStream waits for its reader thread
+    delete removed;
 }
 
 void SDLAudioDriver::setStreamVolume (int streamId, int volume) {

+ 1 - 1
src/WallpaperEngine/Data/Builders/VectorBuilder.h

@@ -37,7 +37,7 @@ class VectorBuilder {
     }
 
 public:
-    // vector size (1-4) of a space-separated string. TODO: doesn't belong here
+    // vector size (1-4) of a space-separated string
     static int preparseSize (const std::string& input) {
 	const auto str = normalizeSeparators (input);
 	const char* p = str.c_str ();

+ 0 - 1
src/WallpaperEngine/Data/Dumpers/StringPrinter.cpp

@@ -32,7 +32,6 @@ void StringPrinter::printWallpaper (const Wallpaper& wallpaper) {
 	this->increaseIndentation ();
 	this->lineEnd ();
 
-	// TODO: implement FBO printing, current output doesn't reflect how it actually works
 	this->m_out << "Objects count: " << scene->objects.size ();
 	this->increaseIndentation ();
 

+ 34 - 10
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -5,8 +5,17 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
+#include <climits>
+
 using namespace WallpaperEngine::Data::Model;
 
+namespace {
+// what the real engine's float to int conversion (cvttss2si) gives for a value an int can't hold
+int toInt (const float value) {
+    return value >= -2147483648.0f && value < 2147483648.0f ? static_cast<int> (value) : INT_MIN;
+}
+}
+
 DynamicValue::DynamicValue (const DynamicValue& other) {
     this->DynamicValue::update (other, UpdateSource::Initialization);
 }
@@ -38,7 +47,6 @@ DynamicValue::DynamicValue (const Model::Color& value) {
 }
 
 DynamicValue::~DynamicValue () {
-    // TODO: properly fix this lifetime handling
     if (this->m_aliveFlag) {
 	*this->m_aliveFlag = false;
     }
@@ -90,8 +98,8 @@ void DynamicValue::update (const float newValue, UpdateSource source) {
     this->m_vec3 = glm::vec3 (newValue);
     this->m_vec2 = glm::vec2 (newValue);
     this->m_float = newValue;
-    this->m_int = static_cast<int> (newValue);
-    this->m_bool = static_cast<int> (newValue) != 0;
+    this->m_int = toInt (newValue);
+    this->m_bool = toInt (newValue) != 0;
     this->m_string = "";
     this->m_type = UnderlyingType::Float;
 
@@ -129,7 +137,7 @@ void DynamicValue::update (const glm::vec2& newValue, UpdateSource source) {
     this->m_vec3 = glm::vec3 (newValue, 0.0f);
     this->m_vec4 = glm::vec4 (newValue, 0.0f, 0.0f);
     this->m_float = newValue.x;
-    this->m_int = static_cast<int> (newValue.x);
+    this->m_int = toInt (newValue.x);
     this->m_bool = newValue.x != 0.0f;
     this->m_string = "";
     this->m_type = UnderlyingType::Vec2;
@@ -142,7 +150,7 @@ void DynamicValue::update (const glm::vec3& newValue, UpdateSource source) {
     this->m_vec3 = newValue;
     this->m_vec4 = glm::vec4 (newValue, 0.0f);
     this->m_float = newValue.x;
-    this->m_int = static_cast<int> (newValue.x);
+    this->m_int = toInt (newValue.x);
     this->m_bool = newValue.x != 0.0f;
     this->m_string = "";
     this->m_type = UnderlyingType::Vec3;
@@ -155,7 +163,7 @@ void DynamicValue::update (const glm::vec4& newValue, UpdateSource source) {
     this->m_vec3 = glm::vec3 (newValue);
     this->m_vec4 = newValue;
     this->m_float = newValue.x;
-    this->m_int = static_cast<int> (newValue.x);
+    this->m_int = toInt (newValue.x);
     this->m_bool = newValue.x != 0.0f;
     this->m_string = "";
     this->m_type = UnderlyingType::Vec4;
@@ -192,7 +200,7 @@ void DynamicValue::update (const Model::Color& newValue, UpdateSource source) {
     this->m_vec3 = glm::vec3 (newValue.r, newValue.g, newValue.b);
     this->m_vec4 = glm::vec4 (newValue.r, newValue.g, newValue.b, newValue.a);
     this->m_float = newValue.r;
-    this->m_int = 255 * newValue.r;
+    this->m_int = toInt (255 * newValue.r);
     this->m_bool = newValue.a != 0.0f;
     this->m_string = "";
     this->m_type = UnderlyingType::Vec4;
@@ -250,13 +258,20 @@ void DynamicValue::update (UpdateSource source) {
 }
 
 std::function<void ()> DynamicValue::listen (const std::function<void (const DynamicValue&, UpdateSource)>& callback) {
-    const auto it = this->m_listeners.insert (this->m_listeners.end (), callback);
+    const auto it = this->m_listeners.insert (this->m_listeners.end (), Listener { callback });
     auto alive = this->m_aliveFlag;
 
     return [this, it, alive] {
 	if (!alive || !*alive) {
 	    return;
 	}
+
+	if (this->m_propagating > 0) {
+	    it->removed = true;
+	    this->m_listenersDirty = true;
+	    return;
+	}
+
 	this->m_listeners.erase (it);
     };
 }
@@ -317,7 +332,16 @@ void DynamicValue::setProperties (std::map<std::string, UserSettingUniquePtr> pr
 }
 
 void DynamicValue::propagate (UpdateSource source) const {
-    for (const auto& callback : this->m_listeners) {
-	callback (*this, source);
+    this->m_propagating++;
+
+    for (auto& listener : this->m_listeners) {
+	if (!listener.removed) {
+	    listener.callback (*this, source);
+	}
+    }
+
+    if (--this->m_propagating == 0 && this->m_listenersDirty) {
+	this->m_listeners.remove_if ([] (const Listener& listener) { return listener.removed; });
+	this->m_listenersDirty = false;
     }
 }

+ 8 - 1
src/WallpaperEngine/Data/Model/DynamicValue.h

@@ -97,7 +97,14 @@ private:
     void propagate (UpdateSource source) const;
 
     std::shared_ptr<bool> m_aliveFlag = std::make_shared<bool> (true);
-    std::list<std::function<void (const DynamicValue&, UpdateSource)>> m_listeners = {};
+    struct Listener {
+	std::function<void (const DynamicValue&, UpdateSource)> callback;
+	bool removed = false;
+    };
+
+    mutable std::list<Listener> m_listeners = {};
+    mutable int m_propagating = 0;
+    mutable bool m_listenersDirty = false;
     std::vector<std::function<void ()>> m_connections = {};
     std::optional<std::string> m_scriptSource = std::nullopt;
     std::shared_ptr<const PropertyAnimation> m_animation;

+ 0 - 1
src/WallpaperEngine/Data/Model/Model.h

@@ -8,7 +8,6 @@
 #include "Types.h"
 
 namespace WallpaperEngine::Data::Model {
-// TODO: FIND A BETTER NAMING SO THIS DOESN'T COLLIDE WITH THE NAMESPACE ITSELF
 struct ModelStruct {
     std::string filename;
     MaterialUniquePtr material;

+ 0 - 1
src/WallpaperEngine/Data/Model/UserSetting.h

@@ -11,6 +11,5 @@ struct UserSetting {
     DynamicValueUniquePtr value;
     PropertySharedPtr property;
     std::optional<ConditionInfo> condition;
-    // TODO: values from scripts without conditions
 };
 }

+ 1 - 2
src/WallpaperEngine/Data/Parsers/MaterialParser.cpp

@@ -70,8 +70,7 @@ MaterialPassUniquePtr MaterialParser::parsePass (const JSON& it, const Project&
     const auto depthwrite = modeName (it, "depthwrite");
 
     return std::make_unique<MaterialPass> (MaterialPass {
-	// TODO: avoid this std::string construction
-	.blending = parseBlendMode (it.optional ("blending", std::string ("normal"))),
+	.blending = parseBlendMode (it.optional<std::string> ("blending", "normal")),
 	// left unknown when missing, which draws like nocull/disabled, 3D models pick their own defaults
 	.cullmode = cullmode.has_value () ? parseCullMode (*cullmode) : CullingMode_Unknown,
 	.depthtest = depthtest.has_value () ? parseDepthtestMode (*depthtest) : DepthtestMode_Unknown,

+ 2 - 0
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -95,6 +95,8 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
 	    result->uncompressedSize
 	);
 
+	result->compressedData.reset ();
+
 	if (bytes < 0) {
 	    sLog.exception ("Cannot decompress texture data, LZ4_decompress_safe returned an error");
 	}

+ 4 - 0
src/WallpaperEngine/Desktop/HostWayland.cpp

@@ -179,3 +179,7 @@ wl_display* WallpaperEngine::Desktop::connectWayland () {
 
     return wl_display_connect (nullptr);
 }
+
+bool WallpaperEngine::Desktop::compositorLacksLayerShell () {
+    return access ("/.flatpak-info", F_OK) != 0 && !isGnomeSession () && !sandboxSocketHasLayerShell ();
+}

+ 4 - 0
src/WallpaperEngine/Desktop/HostWayland.h

@@ -9,4 +9,8 @@ namespace WallpaperEngine::Desktop {
 wl_display* connectWayland ();
 
 bool usesHostWayland ();
+
+// a native Wayland session whose compositor can't put a surface behind the windows (no wlr-layer-shell, not GNOME): the
+// engine then draws through XWayland like on an X11 desktop
+bool compositorLacksLayerShell ();
 }

+ 1 - 1
src/WallpaperEngine/FileSystem/Adapters/Types.h

@@ -89,7 +89,7 @@ inline std::optional<std::string> resolveShortNameAlias (std::vector<std::string
 
 	const std::string nameBasis = shortNameChars (nameStem);
 
-	return shortNameChars (nameExtension).substr (0, 3) != extension || nameBasis.substr (0, basis.size ()) != basis
+	return shortNameChars (nameExtension).substr (0, 3) != extension || !nameBasis.starts_with (basis)
 	    || (nameBasis.size () > basis.size () && basis.size () != 7 - (stem.size () - tilde - 1));
     });
 

+ 1 - 1
src/WallpaperEngine/Render/CFBO.h

@@ -56,7 +56,7 @@ private:
     GLuint m_texture = GL_NONE;
     glm::vec4 m_resolution = {};
     float m_scale = 0;
-    std::string m_name = "";
+    std::string m_name;
     TextureFormat m_format = TextureFormat_UNKNOWN;
     uint32_t m_flags = TextureFlags_NoFlags;
     uint32_t m_mipLevels = 1;

+ 12 - 0
src/WallpaperEngine/Render/CTexture.cpp

@@ -7,6 +7,7 @@
 #include <exception>
 #include <lz4.h>
 #include <mutex>
+#include <ranges>
 #include <thread>
 #include <vector>
 
@@ -83,6 +84,16 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     }
 
     this->uploadImages (upload);
+    this->releaseMipmapData ();
+}
+
+void CTexture::releaseMipmapData () {
+    // the GL texture holds the pixels now; repaints parse the file again and videos or GIFs never get here
+    for (auto& mipmaps : this->m_header->images | std::views::values) {
+	for (auto& mipmap : mipmaps) {
+	    mipmap->uncompressedData.reset ();
+	}
+    }
 }
 
 void CTexture::uploadImages (const UploadFormat& upload) const {
@@ -246,6 +257,7 @@ bool CTexture::repaint (TextureUniquePtr header) {
 
     this->m_header = std::move (header);
     this->uploadImages (this->uploadFormat ());
+    this->releaseMipmapData ();
     return true;
 }
 

+ 1 - 0
src/WallpaperEngine/Render/CTexture.h

@@ -60,6 +60,7 @@ private:
     [[nodiscard]] UploadFormat uploadFormat () const;
     void setupOpenGLParameters (uint32_t textureID) const;
     void uploadImages (const UploadFormat& upload) const;
+    void releaseMipmapData ();
 
     TextureUniquePtr m_header;
     GLuint* m_textureID = nullptr;

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

@@ -556,6 +556,8 @@ void CWallpaper::render (
     if (needsSceneRender) {
 	this->renderFrame (sceneViewport);
 	this->m_lastRenderedFrame = currentFrame;
+	// a video learns its real size inside renderFrame, the UVs from before it would crop the first frame
+	this->updateUVs (sceneViewport, vflip);
     }
 #if !NDEBUG
     glPopDebugGroup ();

+ 38 - 1
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -55,6 +55,10 @@ X11FullScreenDetector::X11FullScreenDetector (Application::ApplicationContext& a
 X11FullScreenDetector::~X11FullScreenDetector () { this->stop (); }
 
 bool X11FullScreenDetector::anythingFullscreen () const {
+    if (this->m_display == nullptr) {
+	return false;
+    }
+
     Window root, parent;
     Window* children = nullptr;
     unsigned int childCount = 0;
@@ -82,7 +86,8 @@ bool X11FullScreenDetector::anythingFullscreen () const {
 	    continue;
 	}
 
-	fullscreen = this->hasFullscreenState (client) || this->coversScreen (client);
+	fullscreen
+	    = this->hasFullscreenState (client) || this->hasMaximizedState (client) || this->coversScreen (client);
     }
 
     XFree (children);
@@ -222,6 +227,32 @@ bool X11FullScreenDetector::hasFullscreenState (Window client) const {
     return fullscreen;
 }
 
+bool X11FullScreenDetector::hasMaximizedState (Window client) const {
+    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
+    const Atom vertAtom = XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
+    const Atom horzAtom = XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool maximized = 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);
+	maximized = std::find (atoms, atoms + count, vertAtom) != atoms + count
+	    && std::find (atoms, atoms + count, horzAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    return maximized;
+}
+
 bool X11FullScreenDetector::coversScreen (Window client) const {
     // window managers without EWMH: the client (not its frame) has an output's geometry
     XWindowAttributes attributes;
@@ -308,6 +339,12 @@ void X11FullScreenDetector::reset () {
 
 void X11FullScreenDetector::initialize () {
     this->m_display = XOpenDisplay (nullptr);
+    this->m_screens.clear ();
+
+    if (this->m_display == nullptr) {
+	sLog.error ("Cannot open the X display, fullscreen detection is off until the next reset");
+	return;
+    }
 
     // recover from X disconnections instead of aborting
 #ifdef HAVE_XSETIOERROREXITHANDLER

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

@@ -25,6 +25,7 @@ namespace Detectors {
 	[[nodiscard]] bool isDesktopWindow (Window window) const;
 	[[nodiscard]] Window clientOf (Window window) const;
 	[[nodiscard]] bool hasFullscreenState (Window client) const;
+	[[nodiscard]] bool hasMaximizedState (Window client) const;
 	[[nodiscard]] bool isHidden (Window client) const;
 	[[nodiscard]] bool onCurrentDesktop (Window client) const;
 	[[nodiscard]] bool coversScreen (Window client) const;

+ 54 - 1
src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp

@@ -12,17 +12,63 @@
 
 #include <GLFW/glfw3native.h>
 
+#include <algorithm>
 #include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <regex>
+#include <sstream>
 #include <unistd.h>
 
 using namespace WallpaperEngine::Render::Drivers;
 
+// whether the wallpaper the engine starts with is a web one (project.json "type": "web")
+static bool isWebProject (const std::filesystem::path& background) {
+    std::error_code error;
+    const auto file = std::filesystem::is_directory (background, error) ? background / "project.json" : background;
+    std::ifstream stream (file);
+    std::ostringstream text;
+
+    text << stream.rdbuf ();
+
+    static const std::regex webType (R"("type"\s*:\s*"web")", std::regex::icase);
+    return std::regex_search (text.str (), webType);
+}
+
+// dmabuf web frames are imported through EGL, which a GLX context has no display for: --web-frames dmabuf asks for an
+// EGL context, and so does auto when the first wallpaper is a web page (the swap, the cursor and everything else go
+// through GLFW either way). Scenes keep GLX, and so does the NVIDIA proprietary driver, where dmabuf is not trusted
+static bool wantsEglContext (const ApplicationContext& context) {
+    const auto& frames = context.settings.render.webFrames;
+
+    if (frames == "dmabuf") {
+	return true;
+    }
+
+    if (frames != "auto" || access ("/proc/driver/nvidia/version", F_OK) == 0) {
+	return false;
+    }
+
+    const auto& general = context.settings.general;
+
+    if (!general.defaultBackground.empty () && isWebProject (general.defaultBackground)) {
+	return true;
+    }
+
+    return std::ranges::any_of (general.screenBackgrounds, [] (const auto& entry) {
+	return isWebProject (entry.second);
+    });
+}
+
 void CustomGLFWErrorHandler (int errorCode, const char* reason) { sLog.error ("GLFW error ", errorCode, ": ", reason); }
 
 GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext& context, WallpaperApplication& app) :
     VideoDriver (app, m_mouseInput), m_mouseInput (*this) {
     glfwSetErrorCallback (CustomGLFWErrorHandler);
 
+    // Electron sets it to wayland for its own session, an X11 EGL display made under it crashes in libwayland-client
+    unsetenv ("EGL_PLATFORM");
+
     if (glfwInit () == GLFW_FALSE) {
 	sLog.exception ("Failed to initialize glfw");
     }
@@ -31,6 +77,10 @@ GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext&
     glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
     glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3);
     glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
+    if (wantsEglContext (context)) {
+	glfwWindowHint (GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
+    }
+
     // drivers only emit KHR_debug output for debug contexts
     glfwWindowHint (GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
     glfwWindowHint (GLFW_VISIBLE, getenv ("LWE_DEBUG_VISIBLE_WINDOW") ? GLFW_TRUE : GLFW_FALSE);
@@ -57,7 +107,10 @@ GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext&
 
     glfwMakeContextCurrent (this->m_window);
 
-    if (const GLenum result = glewInit (); result != GLEW_OK) {
+    // GLEW built for GLX finds no GLX display behind an EGL context, the functions still load
+    glewExperimental = GL_TRUE;
+
+    if (const GLenum result = glewInit (); result != GLEW_OK && result != GLEW_ERROR_NO_GLX_DISPLAY) {
 	sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result));
     }
 

+ 4 - 1
src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.cpp

@@ -72,7 +72,10 @@ X11BackgroundWindow::X11BackgroundWindow (int x, int y, int width, int height) :
 	reinterpret_cast<const unsigned char*> (motif), 5
     );
 
-    XShapeCombineRectangles (display, window, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+    // XWayland only learns the pointer's position over its own windows, so there the window keeps its input
+    if (std::getenv ("LWE_XWAYLAND_FALLBACK") == nullptr) {
+	XShapeCombineRectangles (display, window, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+    }
 
     char name[] = "linux-wallpaperengine";
     XClassHint classHint { name, name };

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

@@ -51,7 +51,6 @@ X11Output::~X11Output () { this->free (); }
 void X11Output::reset () {
     this->free ();
     this->loadScreenInfo ();
-    // TODO: bring back resetting the fullscreen detector here
 }
 
 void X11Output::free () {

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

@@ -774,6 +774,24 @@ void WaylandOpenGLDriver::initGLEW () {
 	    sLog.exception ("Cannot continue...");
 	}
     }
+
+    const auto* renderer = reinterpret_cast<const char*> (glGetString (GL_RENDERER));
+    const auto* version = reinterpret_cast<const char*> (glGetString (GL_VERSION));
+
+    if (renderer != nullptr) {
+	sLog.out ("OpenGL renderer: ", renderer, " (", version != nullptr ? version : "unknown version", ")");
+
+	const std::string name = renderer;
+
+	if (name.find ("llvmpipe") != std::string::npos || name.find ("softpipe") != std::string::npos
+	    || name.find ("swrast") != std::string::npos) {
+	    sLog.error (
+		"Rendering on the CPU (", name,
+		"), expect high CPU use and a low frame rate. The EGL stack "
+		"is not using the GPU driver, check the Mesa/NVIDIA EGL vendor setup"
+	    );
+	}
+    }
 }
 
 WaylandOpenGLDriver::~WaylandOpenGLDriver () {

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

@@ -331,7 +331,6 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 	    size.x = static_cast<float> (scene.getCanvasWidth ());
 	    size.y = static_cast<float> (scene.getCanvasHeight ());
 	}
-	// TODO: a dummy texture of the right size
 	// solid layers are often declared far larger than the scene, nothing samples past the canvas
 	const glm::vec2 placeholderSize = { std::min (size.x, static_cast<float> (scene.getCanvasWidth ())),
 					    std::min (size.y, static_cast<float> (scene.getCanvasHeight ())) };
@@ -2949,7 +2948,6 @@ void CImage::setupPasses () {
 	);
 
 	writesToTarget = this->configurePassTarget (pass, drawTo, asInput, effectInput, inTargetEffectSequence);
-	// TODO: PROPERLY CHECK IF THIS IS ALL THAT'S NEEDED
 	if (!writesToTarget && this->shouldRenderFinalPass (std::next (cur) == end)) {
 	    drawTo = this->getScene ().getFBO ();
 

+ 28 - 8
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -4,6 +4,7 @@
 #include <array>
 #include <cstdio>
 #include <filesystem>
+#include <map>
 #include <sstream>
 #include <strings.h>
 #include <unordered_map>
@@ -135,6 +136,32 @@ std::string installedFamily (const std::vector<std::string>& families) {
 // WE's fallback fonts (off_140484C40, per character by sub_1401AD670): Windows fonts and the assets' Twemoji;
 // Windows fonts count when installed under their family (arial.ttf also via metric clones), CJK through the usual Linux
 // CJK families
+std::shared_ptr<const std::vector<uint8_t>>
+sharedFontData (const WallpaperEngine::Assets::AssetLocator& assets, const std::string& path) {
+    static std::map<std::pair<const void*, std::string>, std::weak_ptr<const std::vector<uint8_t>>> cache;
+
+    for (auto it = cache.begin (); it != cache.end ();) {
+	it = it->second.expired () ? cache.erase (it) : std::next (it);
+    }
+
+    auto& slot = cache[{ &assets, path }];
+
+    if (auto data = slot.lock ()) {
+	return data;
+    }
+
+    auto stream = assets.read (path);
+    stream->seekg (0, std::ios::end);
+    const auto size = stream->tellg ();
+    stream->seekg (0, std::ios::beg);
+    std::vector<uint8_t> data (static_cast<size_t> (size));
+    stream->read (reinterpret_cast<char*> (data.data ()), size);
+
+    auto shared = std::make_shared<const std::vector<uint8_t>> (std::move (data));
+    slot = shared;
+    return shared;
+}
+
 std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::AssetLocator& assets) {
     static std::shared_ptr<const std::vector<uint8_t>> twemoji;
     static bool twemojiRead = false;
@@ -438,14 +465,7 @@ bool CText::loadFont () {
     // wallpapers packed in .pkg don't expose physical paths, so the font is read into memory
     if (!m_loadedFont.empty () && m_loadedFont.rfind ("systemfont_", 0) != 0) {
 	try {
-	    auto stream = getAssetLocator ().read (m_loadedFont);
-	    stream->seekg (0, std::ios::end);
-	    const auto size = stream->tellg ();
-	    stream->seekg (0, std::ios::beg);
-	    std::vector<uint8_t> data (static_cast<size_t> (size));
-	    stream->read (reinterpret_cast<char*> (data.data ()), size);
-
-	    if (m_layout.setPrimaryFont (std::move (data), m_loadedFont)) {
+	    if (m_layout.setPrimaryFont (sharedFontData (getAssetLocator (), m_loadedFont), m_loadedFont)) {
 		return true;
 	    }
 	} catch (const std::exception& e) {

+ 49 - 21
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -22,6 +22,7 @@
 #include "WallpaperEngine/Render/Objects/CImage.h"
 
 #include "WallpaperEngine/Render/Shaders/ShaderCache.h"
+#include "WallpaperEngine/Render/Shaders/SourceMemo.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableFloat.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableInteger.h"
@@ -977,7 +978,7 @@ std::optional<std::reference_wrapper<std::string>> CPass::getTarget () const { r
 
 Render::Shaders::Shader* CPass::getShader () const { return this->m_shader; }
 
-bool CPass::hasGeometryStage () const { return this->m_compiled != nullptr && !this->m_compiled->geometry.empty (); }
+bool CPass::hasGeometryStage () const { return this->m_compiled != nullptr && this->m_compiled->hasGeometry; }
 
 GLuint CPass::getProgramID () const { return this->m_programID; }
 
@@ -1106,7 +1107,6 @@ void CPass::setupShaders () {
 	}
     }
 
-    // TODO: textures passed to the shader shouldn't be in this list
     // the pass's combos, texture format included
     const std::string& shaderName
 	= this->m_override.shaderOverride.has_value () ? this->m_override.shaderOverride.value () : this->m_pass.shader;
@@ -1204,29 +1204,56 @@ void CPass::setupShaders () {
 	}
     }
 
-    std::string vertex = this->m_compiled->vertex;
-    std::string fragment = this->m_compiled->fragment;
+    if (this->m_compiled->released
+	&& sharedPrograms ().find (this->m_compiled->programKey) == sharedPrograms ().end ()) {
+	// the sources went when the program was linked and the program is gone since, translate them again
+	this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures, true);
+	this->m_shader = this->m_compiled->shader.get ();
+    }
 
-    if (shaderName == XRAY_EFFECT_SHADER) {
-	this->m_xrayRevealPatched = patchXrayRevealOverride (fragment);
+    if (!this->m_compiled->released) {
+	std::string vertex = this->m_compiled->vertex;
+	std::string fragment = this->m_compiled->fragment;
 
-	if (!this->m_xrayRevealPatched) {
-	    sLog.error (
-		"Full/disabled xray unavailable: couldn't find the expected reveal blend line in the "
-		"compiled effects/xray shader (spirv-cross output format may have changed)"
-	    );
+	if (shaderName == XRAY_EFFECT_SHADER) {
+	    this->m_xrayRevealPatched = patchXrayRevealOverride (fragment);
+
+	    if (!this->m_xrayRevealPatched) {
+		sLog.error (
+		    "Full/disabled xray unavailable: couldn't find the expected reveal blend line in the "
+		    "compiled effects/xray shader (spirv-cross output format may have changed)"
+		);
+	    }
 	}
-    }
 
-    // passes with the same sources share a program (child particle instances would link hundreds otherwise), uniforms
-    // go up every draw
-    this->m_programKey = vertex + '\0' + fragment + '\0' + this->m_compiled->geometry;
-    if (const auto cached = sharedPrograms ().find (this->m_programKey); cached != sharedPrograms ().end ()) {
+	// passes with the same sources share a program (child particle instances would link hundreds otherwise),
+	// uniforms go up every draw
+	this->m_compiled->programKey = Shaders::sourceDigest ({ vertex, fragment, this->m_compiled->geometry });
+	this->m_programKey = this->m_compiled->programKey;
+
+	if (const auto cached = sharedPrograms ().find (this->m_programKey); cached != sharedPrograms ().end ()) {
+	    this->m_programID = cached->second.program;
+	    cached->second.users++;
+	} else {
+	    this->m_programID = this->linkProgram (vertex, fragment, this->m_compiled->geometry, shaderName);
+	    sharedPrograms ().emplace (this->m_programKey, SharedProgram { this->m_programID, 1 });
+	}
+
+	// nothing reads the translated or the original sources again: a pass sharing this shader finds the program
+	// by its key
+	this->m_compiled->hasGeometry = !this->m_compiled->geometry.empty ();
+	this->m_compiled->xrayRevealPatched = this->m_xrayRevealPatched;
+	std::string ().swap (this->m_compiled->vertex);
+	std::string ().swap (this->m_compiled->fragment);
+	std::string ().swap (this->m_compiled->geometry);
+	this->m_compiled->shader->releaseSources ();
+	this->m_compiled->released = true;
+    } else {
+	this->m_programKey = this->m_compiled->programKey;
+	this->m_xrayRevealPatched = this->m_compiled->xrayRevealPatched;
+	const auto cached = sharedPrograms ().find (this->m_programKey);
 	this->m_programID = cached->second.program;
 	cached->second.users++;
-    } else {
-	this->m_programID = this->linkProgram (vertex, fragment, this->m_compiled->geometry, shaderName);
-	sharedPrograms ().emplace (this->m_programKey, SharedProgram { this->m_programID, 1 });
     }
 
     // bind each g_TextureN sampler to unit N explicitly, the translated GLSL collapses every layout(binding) to 0
@@ -1254,7 +1281,7 @@ std::unordered_map<std::string, std::weak_ptr<CPass::CompiledShader>>& CPass::sh
 }
 
 std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
-    const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures
+    const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures, const bool fresh
 ) {
     // parsing a shader takes a few ms and every child particle instance builds the same one; override constants change
     // the defaults, those passes keep their own
@@ -1279,7 +1306,7 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
 	}
 	key = stream.str ();
 
-	if (const auto it = sharedShaders ().find (key); it != sharedShaders ().end ()) {
+	if (const auto it = sharedShaders ().find (key); !fresh && it != sharedShaders ().end ()) {
 	    if (auto cached = it->second.lock ()) {
 		return cached;
 	    }
@@ -1303,6 +1330,7 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
     compiled->vertex = std::move (sources.vertex);
     compiled->fragment = std::move (sources.fragment);
     compiled->geometry = std::move (sources.geometry);
+    compiled->hasGeometry = !compiled->geometry.empty ();
 
     if (shareable) {
 	std::erase_if (sharedShaders (), [] (const auto& entry) { return entry.second.expired (); });

+ 7 - 1
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -199,10 +199,16 @@ private:
 	std::string vertex;
 	std::string fragment;
 	std::string geometry;
+	/** digest of the sources the program was linked from, set with the first link (they are freed then) */
+	std::string programKey;
+	bool hasGeometry = false;
+	bool xrayRevealPatched = false;
+	bool released = false;
     };
     static std::unordered_map<std::string, std::weak_ptr<CompiledShader>>& sharedShaders ();
     std::shared_ptr<CompiledShader> compileShaderSources (
-	const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures
+	const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures,
+	bool fresh = false
     );
     void setupShaders ();
     bool applyFormatCombos (const TextureMap& passTextures, const TextureMap& overrideTextures);

+ 9 - 5
src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp

@@ -267,7 +267,8 @@ PuppetMeshHeader readPuppetMeshHeader (const std::vector<char>& data) {
     PuppetFileReader reader (data, 0);
     reader.string ();
 
-    const int version = std::atoi (data.data () + strlen ("MDLV"));
+    const std::string tag (data.data (), strnlen (data.data (), std::min<size_t> (data.size (), strlen ("MDLV0021"))));
+    const int version = tag.size () > strlen ("MDLV") ? std::atoi (tag.c_str () + strlen ("MDLV")) : 0;
     PuppetMeshHeader header;
     header.format = reader.next<uint32_t> ();
     const auto materials = reader.next<uint32_t> ();
@@ -527,9 +528,12 @@ std::optional<PuppetMeshFile> WallpaperEngine::Render::Objects::readPuppetMeshFi
 	// WE ignores the size, always three floats per vertex
 	if (bytes >= vertexCount * sizeof (float) * 3 && blob + sizeof (bytes) + bytes <= data.size ()) {
 	    file.auxPositions.resize (vertexCount * 3);
-	    std::memcpy (
-		file.auxPositions.data (), data.data () + blob + sizeof (bytes), vertexCount * sizeof (float) * 3
-	    );
+
+	    if (!file.auxPositions.empty ()) {
+		std::memcpy (
+		    file.auxPositions.data (), data.data () + blob + sizeof (bytes), vertexCount * sizeof (float) * 3
+		);
+	    }
 	} else {
 	    file.warnings.emplace_back (
 		"the auxiliary vertex block is shorter than the mesh, lighting places the bind positions instead"
@@ -567,7 +571,7 @@ std::optional<PuppetMeshFile> WallpaperEngine::Render::Objects::readPuppetMeshFi
 	    );
 
 	    if (w > 0.0f) {
-		file.morphIndices[vertex] = static_cast<uint32_t> (w);
+		file.morphIndices[vertex] = w >= 4294967296.0f ? UINT32_MAX : static_cast<uint32_t> (w);
 	    }
 	}
     }

+ 4 - 4
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -157,8 +157,8 @@ void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, siz
 PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     reader.base ().seekg (static_cast<std::streamoff> (mdlsOffset), std::ios::beg);
 
-    char header[9];
-    reader.next (header, sizeof (header));
+    char header[10] = {};
+    reader.next (header, sizeof (header) - 1);
 
     const uint32_t nextSectionOffset = reader.nextUInt32 ();
     const uint32_t boneCount = reader.nextUInt32 ();
@@ -583,8 +583,8 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 ) {
     reader.base ().seekg (static_cast<std::streamoff> (mdlaOffset), std::ios::beg);
 
-    char header[9];
-    reader.next (header, sizeof (header));
+    char header[10] = {};
+    reader.next (header, sizeof (header) - 1);
     const int version = std::atoi (header + 4);
 
     const uint32_t sectionEnd = reader.nextUInt32 ();

+ 2 - 4
src/WallpaperEngine/Render/Objects/TextLayout.cpp

@@ -338,11 +338,9 @@ void TextLayout::clearFaces () {
     this->resetAtlases ();
 }
 
-bool TextLayout::setPrimaryFont (std::vector<uint8_t> data, const std::string& path) {
+bool TextLayout::setPrimaryFont (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path) {
     this->clearFaces ();
-    return this->addFace (
-	data.empty () ? nullptr : std::make_shared<const std::vector<uint8_t>> (std::move (data)), path
-    );
+    return this->addFace (data != nullptr && !data->empty () ? std::move (data) : nullptr, path);
 }
 
 void TextLayout::setFallbackFonts (std::vector<TextFontSource> fonts) { m_fallbackSources = std::move (fonts); }

+ 1 - 1
src/WallpaperEngine/Render/Objects/TextLayout.h

@@ -73,7 +73,7 @@ public:
     TextLayout (const TextLayout&) = delete;
     TextLayout& operator= (const TextLayout&) = delete;
 
-    bool setPrimaryFont (std::vector<uint8_t> data, const std::string& path);
+    bool setPrimaryFont (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path);
     void setFallbackFonts (std::vector<TextFontSource> fonts);
     [[nodiscard]] bool hasFont () const { return !m_faces.empty (); }
 

+ 9 - 20
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -1,4 +1,5 @@
 #include "GLSLContext.h"
+#include "SourceMemo.h"
 
 #include <algorithm>
 #include <cassert>
@@ -238,29 +239,20 @@ GLSLContext::Sources GLSLContext::toGlsl (
     const std::string& vertex, const std::string& fragment, const std::string& name, const std::string& geometry
 ) {
     // pure function of the sources, and passes get rebuilt often
-    static std::mutex cacheMutex;
-    static std::unordered_map<std::string, Sources> cache;
+    static SourceMemo<Sources> cache (48 * 1024 * 1024);
 
-    std::string cacheKey = vertex;
-    cacheKey += '\0';
-    cacheKey += fragment;
-    cacheKey += '\0';
-    cacheKey += geometry;
+    const std::string cacheKey = sourceDigest ({ vertex, fragment, geometry });
 
-    {
-	std::lock_guard lock (cacheMutex);
-
-	if (const auto cached = cache.find (cacheKey); cached != cache.end ()) {
-	    return cached->second;
-	}
+    if (auto cached = cache.find (cacheKey)) {
+	return *cached;
     }
 
     // glslang/SPIRV-Cross and the options below only change with a rebuild
-    const std::string diskKey = std::string ("glsl " __DATE__ " " __TIME__) + '\0' + cacheKey;
+    const std::string diskKey
+	= std::string ("glsl " __DATE__ " " __TIME__) + '\0' + vertex + '\0' + fragment + '\0' + geometry;
 
     if (auto stored = ShaderCache::get ().loadTranslation (diskKey); stored.has_value ()) {
-	std::lock_guard lock (cacheMutex);
-	cache.emplace (std::move (cacheKey), *stored);
+	cache.insert (cacheKey, *stored, stored->vertex.size () + stored->fragment.size () + stored->geometry.size ());
 	return *stored;
     }
 
@@ -293,10 +285,7 @@ GLSLContext::Sources GLSLContext::toGlsl (
 
     ShaderCache::get ().storeTranslation (diskKey, result);
 
-    {
-	std::lock_guard lock (cacheMutex);
-	cache.emplace (std::move (cacheKey), result);
-    }
+    cache.insert (cacheKey, result, result.vertex.size () + result.fragment.size () + result.geometry.size ());
 
     return result;
 }

+ 9 - 0
src/WallpaperEngine/Render/Shaders/Shader.cpp

@@ -60,6 +60,15 @@ const std::string& Shader::geometry () {
     return this->m_geometry ? this->m_geometry->compile () : none;
 }
 
+void Shader::releaseSources () {
+    this->m_vertex.releaseSources ();
+    this->m_fragment.releaseSources ();
+
+    if (this->m_geometry) {
+	this->m_geometry->releaseSources ();
+    }
+}
+
 const ShaderUnit& Shader::getVertex () const { return this->m_vertex; }
 
 const ShaderUnit& Shader::getFragment () const { return this->m_fragment; }

+ 2 - 0
src/WallpaperEngine/Render/Shaders/Shader.h

@@ -31,6 +31,8 @@ public:
     const std::string& vertex ();
     const std::string& fragment ();
     const std::string& geometry ();
+    /** Once the sources are translated and linked, only the parsed parameters and textures are still read */
+    void releaseSources ();
     [[nodiscard]] const ShaderUnit& getVertex () const;
     [[nodiscard]] const ShaderUnit& getFragment () const;
     [[nodiscard]] const std::map<std::string, int>& getCombos () const;

+ 53 - 65
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -1,4 +1,5 @@
 #include "ShaderUnit.h"
+#include "SourceMemo.h"
 
 #include "WallpaperEngine/Logging/Log.h"
 #include <array>
@@ -77,7 +78,7 @@ struct ShaderRegexTraits : std::regex_traits<char> {
 };
 
 using Regex = std::basic_regex<char, ShaderRegexTraits>;
-constexpr size_t MEMO_LIMIT = 512;
+constexpr size_t MEMO_BYTES = 24 * 1024 * 1024;
 using RegexIterator = std::regex_iterator<std::string::const_iterator, char, ShaderRegexTraits>;
 }
 
@@ -237,32 +238,17 @@ void ShaderUnit::preprocess () {
     this->preprocessVariables ();
 
     // every combo permutation brings the same source again
-    static std::mutex cacheMutex;
-    static std::unordered_map<std::string, std::string> rewritten;
-    std::string input = this->m_preprocessed;
-    bool cached = false;
+    static SourceMemo<std::string> rewritten (MEMO_BYTES);
+    const std::string inputKey = sourceDigest ({ this->m_preprocessed });
 
-    {
-	std::lock_guard lock (cacheMutex);
-
-	if (const auto found = rewritten.find (input); found != rewritten.end ()) {
-	    this->m_preprocessed = found->second;
-	    cached = true;
-	}
-    }
-
-    if (!cached) {
+    if (auto found = rewritten.find (inputKey)) {
+	this->m_preprocessed = std::move (*found);
+    } else {
 	this->preprocessBalanceConditionals ();
 	this->preprocessSwizzledDeclarations ();
 	this->preprocessScalarSwizzles ();
 
-	std::lock_guard lock (cacheMutex);
-
-	if (rewritten.size () >= MEMO_LIMIT) {
-	    rewritten.clear ();
-	}
-
-	rewritten.emplace (std::move (input), this->m_preprocessed);
+	rewritten.insert (inputKey, this->m_preprocessed, this->m_preprocessed.size ());
     }
 
     const std::string from = "gl_FragColor";
@@ -1714,7 +1700,6 @@ void ShaderUnit::parseParameterConfiguration (
 	}
 
 	if (combo != data.end ()) {
-	    // TODO: CLEANUP HOW THIS IS DETERMINED FIRST
 	    const auto textureSlotUsed
 		= this->m_passTextures.contains (index) || this->m_overrideTextures.contains (index);
 	    bool isRequired = false;
@@ -1824,7 +1809,25 @@ const ComboMap& ShaderUnit::getCombos () const { return this->m_combos; }
 
 const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discoveredCombos; }
 
+void ShaderUnit::releaseSources () {
+    // the identifiers asked about after the compile are looked up now
+    for (const char* identifier : { "MORPHING" }) {
+	this->m_referenced.emplace (identifier, this->refersTo (identifier));
+    }
+
+    this->m_released = true;
+    std::string ().swap (this->m_content);
+    std::string ().swap (this->m_preprocessed);
+    std::string ().swap (this->m_final);
+}
+
 bool ShaderUnit::refersTo (const std::string& identifier) const {
+    if (this->m_released) {
+	const auto it = this->m_referenced.find (identifier);
+
+	return it != this->m_referenced.end () && it->second;
+    }
+
     const auto isWordChar = [] (const char c) { return std::isalnum (static_cast<unsigned char> (c)) || c == '_'; };
 
     for (size_t at = this->m_preprocessed.find (identifier); at != std::string::npos;
@@ -1847,6 +1850,10 @@ void ShaderUnit::feedGeometryStage () { this->m_feedsGeometry = true; }
 const ShaderUnit* ShaderUnit::getLinkedUnit () const { return this->m_link; }
 
 const std::string& ShaderUnit::compile () {
+    if (this->m_released) {
+	sLog.exception ("Shader ", this->m_file, " was compiled after its sources were released");
+    }
+
     if (!this->m_final.empty ()) {
 	return this->m_final;
     }
@@ -1858,20 +1865,17 @@ const std::string& ShaderUnit::compile () {
 	R"(\b(?:void|float|int|uint|bool|vec[234]|ivec[234]|uvec[234]|bvec[234]|mat[234](?:x[234])?)\s+log10\s*\()"
     );
     // memoized per source, compile() runs again for every pass a text layer rebuilds
-    static std::mutex cacheMutex;
-    static std::unordered_map<std::string, bool> definesLog10;
-    static std::unordered_map<std::string, std::string> compatCache;
+    static SourceMemo<bool> definesLog10 (1 << 20);
+    static SourceMemo<std::string> compatCache (MEMO_BYTES);
 
+    const std::string contentKey = sourceDigest ({ this->m_content });
     bool hasLog10 = false;
-    {
-	std::lock_guard lock (cacheMutex);
-	auto found = definesLog10.find (this->m_content);
-
-	if (found == definesLog10.end ()) {
-	    found = definesLog10.emplace (this->m_content, std::regex_search (this->m_content, log10Definition)).first;
-	}
 
-	hasLog10 = found->second;
+    if (const auto found = definesLog10.find (contentKey)) {
+	hasLog10 = *found;
+    } else {
+	hasLog10 = std::regex_search (this->m_content, log10Definition);
+	definesLog10.insert (contentKey, hasLog10, contentKey.size ());
     }
 
     if (!hasLog10) {
@@ -1945,36 +1949,28 @@ const std::string& ShaderUnit::compile () {
     }
 
     // these passes only read what's in the key (plus defines for geometry), so permutations share results
-    std::string cacheKey = std::to_string (this->m_type) + (this->m_feedsGeometry ? "g" : "");
+    const std::string type = std::to_string (this->m_type) + (this->m_feedsGeometry ? "g" : "");
+    std::string comboKey;
 
     if (this->m_type == GLSLContext::UnitType_Geometry) {
-	cacheKey += '\x1f';
-	cacheKey += this->m_final;
-
 	for (const auto& [name, value] : this->m_combos) {
-	    cacheKey += '\x1f';
-	    cacheKey += name;
-	    cacheKey += '=';
-	    cacheKey += std::to_string (value);
+	    comboKey += name;
+	    comboKey += '=';
+	    comboKey += std::to_string (value);
+	    comboKey += '\x1f';
 	}
     }
 
-    cacheKey += '\x1f';
-    cacheKey += this->m_preprocessed;
-    cacheKey += '\x1f';
-
-    if (this->m_link != nullptr) {
-	cacheKey += this->m_link->m_preprocessed;
-    }
-
-    {
-	std::lock_guard lock (cacheMutex);
+    const std::string cacheKey = sourceDigest (
+	{ type, this->m_type == GLSLContext::UnitType_Geometry ? std::string_view (this->m_final) : std::string_view (),
+	  comboKey, this->m_preprocessed,
+	  this->m_link != nullptr ? std::string_view (this->m_link->m_preprocessed) : std::string_view () }
+    );
 
-	if (const auto cached = compatCache.find (cacheKey); cached != compatCache.end ()) {
-	    this->m_final += cached->second;
+    if (auto cached = compatCache.find (cacheKey)) {
+	this->m_final += *cached;
 
-	    return this->m_final;
-	}
+	return this->m_final;
     }
 
     const std::string compat = this->applyNonConstantConstCompatibility (this->applyBoolArithmeticCompatibility (
@@ -1993,15 +1989,7 @@ const std::string& ShaderUnit::compile () {
 	))
     ));
 
-    {
-	std::lock_guard lock (cacheMutex);
-
-	if (compatCache.size () >= MEMO_LIMIT) {
-	    compatCache.clear ();
-	}
-
-	compatCache.emplace (std::move (cacheKey), compat);
-    }
+    compatCache.insert (cacheKey, compat, compat.size ());
 
     this->m_final += compat;
 

+ 4 - 0
src/WallpaperEngine/Render/Shaders/ShaderUnit.h

@@ -41,6 +41,8 @@ public:
     [[nodiscard]] const ComboMap& getCombos () const;
     [[nodiscard]] const ComboMap& getDiscoveredCombos () const;
     [[nodiscard]] bool refersTo (const std::string& identifier) const;
+    /** Frees the source texts once the translation is done, only the identifiers refersTo answers for are kept */
+    void releaseSources ();
 
 protected:
     void preprocess ();
@@ -91,6 +93,8 @@ private:
     std::string m_preprocessed;
     bool m_feedsGeometry { false };
     std::string m_final;
+    bool m_released { false };
+    std::map<std::string, bool> m_referenced = {};
     /** The unit owns its parameters, passes and uniforms point at them for as long as the shader lives */
     std::vector<std::unique_ptr<Variables::ShaderVariable>> m_ownedParameters = {};
     std::vector<Variables::ShaderVariable*> m_parameters = {};

+ 78 - 0
src/WallpaperEngine/Render/Shaders/SourceMemo.h

@@ -0,0 +1,78 @@
+#pragma once
+
+#include <cstdint>
+#include <cstdio>
+#include <initializer_list>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include <utility>
+
+namespace WallpaperEngine::Render::Shaders {
+/**
+ * 128 bit digest of a list of sources, so memos don't keep a copy of what they are keyed by; two unrelated 64 bit
+ * hashes and the length make a collision between the sources of one run a non-issue
+ */
+inline std::string sourceDigest (const std::initializer_list<std::string_view> parts) {
+    uint64_t fnv = 0xcbf29ce484222325ull;
+    uint64_t mix = 0x9e3779b97f4a7c15ull;
+    uint64_t length = 0;
+
+    for (const auto part : parts) {
+	for (const char c : part) {
+	    fnv = (fnv ^ static_cast<unsigned char> (c)) * 0x100000001b3ull;
+	    mix = (mix ^ static_cast<unsigned char> (c)) * 0x94d049bb133111ebull;
+	    mix ^= mix >> 29;
+	}
+
+	// part boundaries count: ("ab", "c") is not ("a", "bc")
+	fnv = (fnv ^ 0x1f) * 0x100000001b3ull;
+	mix = (mix ^ 0x1f) * 0x94d049bb133111ebull;
+	length += part.size () + 1;
+    }
+
+    char out[49];
+    snprintf (
+	out, sizeof (out), "%016llx%016llx%016llx", static_cast<unsigned long long> (fnv),
+	static_cast<unsigned long long> (mix), static_cast<unsigned long long> (length)
+    );
+    return out;
+}
+
+/** Digest keyed memo of strings that is emptied once the values it holds pass a byte budget */
+template <typename Value> class SourceMemo {
+public:
+    explicit SourceMemo (const size_t budget) : m_budget (budget) { }
+
+    [[nodiscard]] std::optional<Value> find (const std::string& key) {
+	const std::lock_guard lock (m_mutex);
+
+	if (const auto it = m_entries.find (key); it != m_entries.end ()) {
+	    return it->second;
+	}
+
+	return std::nullopt;
+    }
+
+    void insert (std::string key, Value value, const size_t bytes) {
+	const std::lock_guard lock (m_mutex);
+
+	if (m_bytes + bytes > m_budget) {
+	    m_entries.clear ();
+	    m_bytes = 0;
+	}
+
+	if (m_entries.emplace (std::move (key), std::move (value)).second) {
+	    m_bytes += bytes;
+	}
+    }
+
+private:
+    std::mutex m_mutex;
+    std::unordered_map<std::string, Value> m_entries;
+    size_t m_bytes = 0;
+    size_t m_budget;
+};
+}

+ 0 - 1
src/WallpaperEngine/Render/TextureCache.cpp

@@ -659,7 +659,6 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
 	} catch (AssetLoadException&) { }
     }
 
-    // TODO: fill in with a checkered pattern texture instead?
     throw AssetLoadException ("Cannot find file", filename, std::error_code ());
 }
 

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

@@ -2475,6 +2475,7 @@ std::vector<const Light*> CScene::sortedLightingV1Lights () const {
     });
 
     std::vector<const Light*> lights;
+    lights.reserve (entries.size ());
 
     for (const auto& entry : entries) {
 	lights.push_back (entry.light);

+ 223 - 16
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -11,6 +11,7 @@
 #include "WallpaperEngine/Media/ThumbnailPalette.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 #include "WallpaperEngine/WebBrowser/CEF/TestHookPolicy.h"
+#include "WebDmabufImport.h"
 
 #include <atomic>
 #include <chrono>
@@ -18,8 +19,10 @@
 #include <csignal>
 #include <cstdlib>
 #include <cstring>
+#include <fcntl.h>
 #include <string_view>
 #include <sys/prctl.h>
+#include <sys/socket.h>
 #include <sys/syscall.h>
 #include <sys/wait.h>
 #include <thread>
@@ -32,12 +35,15 @@ using namespace WallpaperEngine::WebBrowser::IPC;
 namespace {
 // closes every fd but stdio so CEF doesn't inherit our Wayland/EGL/X11/audio connections; raw syscalls only, other
 // threads may hold malloc locks
-void closeInheritedFds () {
+void closeInheritedFds (const unsigned int first = 3) {
 #if defined(SYS_close_range)
-    syscall (SYS_close_range, 3u, ~0u, 0u);
+    syscall (SYS_close_range, first, ~0u, 0u);
 #endif
 }
 
+// the descriptor the dmabuf socket has in the host, below it everything but stdio is closed
+constexpr int HOST_SOCKET_FD = 3;
+
 // a page paints its background long before its content, so a flat color doesn't count. Samples a grid
 bool frameHasContent (const uint8_t* pixels, uint32_t width, uint32_t height) {
     constexpr uint32_t columns = 48;
@@ -120,15 +126,73 @@ CWeb::CWeb (
 
     this->m_statsEnabled = std::getenv ("LWE_WEB_STATS") != nullptr;
 
+    this->m_hostBackgroundPath = resolvedBackgroundPath;
+    this->m_frameMode = this->chooseFrameMode ();
     this->spawnHost (resolvedBackgroundPath);
 
     this->m_streamVolume = std::make_unique<Audio::Drivers::PulseProcessVolume> (this->m_hostPid);
     this->setAudioPolicy (false, std::nullopt);
 }
 
+CWeb::FrameMode CWeb::chooseFrameMode () const {
+    const std::string& request = this->getContext ().getApp ().getContext ().settings.render.webFrames;
+
+    if (request == "shm") {
+	return FrameMode::Shm;
+    }
+
+    const bool forced = request == "dmabuf";
+    const char* wayland = std::getenv ("WAYLAND_DISPLAY");
+    const char* x11 = std::getenv ("DISPLAY");
+
+    if (!WebDmabufImport::available ()) {
+	if (forced) {
+	    sLog.error (
+		"--web-frames dmabuf: this OpenGL context cannot import dmabufs (needs EGL), using shared memory"
+	    );
+	}
+
+	return FrameMode::Shm;
+    }
+
+    if ((wayland == nullptr || wayland[0] == '\0') && (x11 == nullptr || x11[0] == '\0')) {
+	// the browser makes shareable buffers on Wayland's dmabuf support or X11's DRI3 only, not headless
+	if (forced) {
+	    sLog.error (
+		"--web-frames dmabuf: no Wayland or X11 session for the browser to render on, using shared memory"
+	    );
+	}
+
+	return FrameMode::Shm;
+    }
+
+    if (!forced) {
+	// auto stays on shared memory where dmabufs are known to be a gamble: the NVIDIA proprietary driver is picky
+	// about modifiers and EGL imports. --web-frames dmabuf tries anyway
+	const auto* vendor = reinterpret_cast<const char*> (glGetString (GL_VENDOR));
+
+	if (vendor != nullptr && std::string_view (vendor).find ("NVIDIA") != std::string_view::npos) {
+	    return FrameMode::Shm;
+	}
+    }
+
+    return FrameMode::Dmabuf;
+}
+
 void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     auto& appContext = this->getContext ().getApp ().getContext ();
     const std::string executable = hostExecutable ();
+    int hostSocket = -1;
+
+    if (this->m_frameMode == FrameMode::Dmabuf) {
+	if (!WallpaperEngine::WebBrowser::IPC::makeDmabufSocketPair (this->m_dmabufSocket, hostSocket)) {
+	    sLog.error ("CWeb: cannot make the dmabuf socket, using shared memory frames");
+	    this->m_frameMode = FrameMode::Shm;
+	    this->m_dmabufSocket = -1;
+	} else if (this->m_dmabufImport == nullptr) {
+	    this->m_dmabufImport = std::make_unique<WebDmabufImport> ();
+	}
+    }
 
     // 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
@@ -173,11 +237,28 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     if (pid < 0) {
 	// sLog.exception() throws before ~CWeb() runs, unlink the shm segment here
 	closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
+
+	if (hostSocket >= 0) {
+	    close (hostSocket);
+	}
+
 	sLog.exception ("CWeb: fork() failed while spawning the web host process");
     }
 
     if (pid == 0) {
-	closeInheritedFds ();
+	if (hostSocket >= 0) {
+	    // the one descriptor the host keeps, at a fixed number; dup2 clears close-on-exec, and when it already sits
+	    // there the flag has to go by hand
+	    if (hostSocket != HOST_SOCKET_FD) {
+		dup2 (hostSocket, HOST_SOCKET_FD);
+	    } else {
+		fcntl (HOST_SOCKET_FD, F_SETFD, 0);
+	    }
+
+	    closeInheritedFds (HOST_SOCKET_FD + 1);
+	} else {
+	    closeInheritedFds ();
+	}
 
 	// kill this child if the parent dies without telling it to quit over shared memory
 	prctl (PR_SET_PDEATHSIG, SIGTERM);
@@ -192,6 +273,13 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 	args.emplace_back ("--web-host-height");
 	args.emplace_back (std::to_string (this->m_shmMaxHeight));
 
+	if (hostSocket >= 0) {
+	    args.emplace_back ("--web-host-frames");
+	    args.emplace_back ("dmabuf");
+	    args.emplace_back ("--web-host-socket");
+	    args.emplace_back (std::to_string (HOST_SOCKET_FD));
+	}
+
 	if (!appContext.settings.general.assets.empty ()) {
 	    args.emplace_back ("--assets-dir");
 	    args.emplace_back (appContext.settings.general.assets.string ());
@@ -221,6 +309,10 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     }
 
     this->m_hostPid = pid;
+
+    if (hostSocket >= 0) {
+	close (hostSocket);
+    }
 }
 
 void CWeb::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
@@ -233,6 +325,7 @@ void CWeb::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
 	= muted || !appContext.settings.audio.enabled ? 0 : ambientVolume.value_or (appContext.state.audio.volume);
 
     this->m_shm->audioMuted.store (volume == 0, std::memory_order_relaxed);
+    this->m_audioVolume = static_cast<float> (volume) / 128.0f;
 
     if (this->m_streamVolume) {
 	this->m_streamVolume->setVolume (static_cast<float> (volume) / 128.0f);
@@ -272,6 +365,11 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glViewport (0, 0, this->getWidth (), this->getHeight ());
 
+    if (this->m_frameMode == FrameMode::Dmabuf) {
+	this->renderDmabufFrame ();
+	return;
+    }
+
     const auto taken = this->m_shm->takeFrame (this->m_frontSlot);
 
     if (!taken.has_value ()) {
@@ -317,23 +415,119 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
     glBindTexture (GL_TEXTURE_2D, 0);
 
     if (!this->m_pageHasContent && frameHasContent (pixels, frameWidth, frameHeight)) {
-	this->m_pageHasContent = true;
+	this->noteFirstContent ();
+    }
+
+    this->m_statsFrames++;
+
+    // ask for the next frame only after taking this one, so what gets painted is always what the next render shows
+    this->requestPageFrame ();
+}
+
+void CWeb::noteFirstContent () {
+    this->m_pageHasContent = true;
+
+    if (this->m_statsEnabled) {
+	sLog.out (
+	    "CWeb host ", this->m_hostPid, ": first page content after ",
+	    std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::steady_clock::now () - this->m_created)
+		.count (),
+	    "ms"
+	);
+    }
+}
+
+void CWeb::renderDmabufFrame () {
+    using namespace std::chrono;
+
+    bool closed = false;
+    auto frame = WallpaperEngine::WebBrowser::IPC::receiveLatestDmabufFrame (
+	this->m_dmabufSocket, this->m_shmMaxWidth, this->m_shmMaxHeight, closed
+    );
+
+    if (!frame.has_value ()) {
+	if (this->m_shm->dmabufRejected.load (std::memory_order_acquire)) {
+	    this->fallBackToShm ("the browser's buffers have a format the engine cannot import");
+	    return;
+	}
+
+	if (this->m_dmabufFrames == 0 && this->m_shm->helperReady.load (std::memory_order_acquire)) {
+	    if (this->m_helperReadyAt == steady_clock::time_point {}) {
+		this->m_helperReadyAt = steady_clock::now ();
+	    } else if (steady_clock::now () - this->m_helperReadyAt > seconds (6)) {
+		this->fallBackToShm ("the browser made no GPU buffer");
+		return;
+	    }
+	}
+
+	this->requestPageFrame ();
+	return;
+    }
+
+    this->m_shm->dmabufTaken.store (frame->sequence, std::memory_order_release);
+
+    if (frame->width != this->m_uploadedTextureWidth || frame->height != this->m_uploadedTextureHeight) {
+	this->find ("_rt_FullFrameBuffer")->resize (frame->width, frame->height);
+	this->m_uploadedTextureWidth = frame->width;
+	this->m_uploadedTextureHeight = frame->height;
+    }
+
+    const bool copied = this->m_dmabufImport->copyTo (*frame, this->getWallpaperFramebuffer ());
+    frame->closeAll ();
+
+    if (!copied) {
+	this->fallBackToShm ("a GPU buffer could not be imported");
+	return;
+    }
+
+    if (++this->m_dmabufFrames == 1) {
+	// the frame slots of the segment are not used in this mode
+	WallpaperEngine::WebBrowser::IPC::setFrameSlotsResident (
+	    this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, false
+	);
 
 	if (this->m_statsEnabled) {
-	    sLog.out (
-		"CWeb host ", this->m_hostPid, ": first page content after ",
-		std::chrono::duration_cast<std::chrono::milliseconds> (
-		    std::chrono::steady_clock::now () - this->m_created
-		)
-		    .count (),
-		"ms"
-	    );
+	    sLog.out ("CWeb host ", this->m_hostPid, ": frames arrive as dmabufs");
 	}
     }
 
+    if (!this->m_pageHasContent
+	&& this->m_dmabufImport->framebufferHasContent (
+	    this->getWallpaperFramebuffer (), frame->width, frame->height
+	)) {
+	this->noteFirstContent ();
+    }
+
     this->m_statsFrames++;
+    this->requestPageFrame ();
+}
 
-    // ask for the next frame only after taking this one, so what gets painted is always what the next render shows
+void CWeb::fallBackToShm (const char* reason) {
+    sLog.out ("CWeb: dmabuf frames do not work here (", reason, "), restarting the web host with shared memory frames");
+
+    this->m_frameMode = FrameMode::Shm;
+    this->stopHost (false);
+    this->m_dmabufImport.reset ();
+
+    if (this->m_dmabufSocket >= 0) {
+	close (this->m_dmabufSocket);
+	this->m_dmabufSocket = -1;
+    }
+
+    auto& shm = *this->m_shm;
+    shm.quitRequested.store (false, std::memory_order_release);
+    shm.helperReady.store (false, std::memory_order_release);
+    shm.helperFailed.store (false, std::memory_order_release);
+    shm.dmabufRejected.store (false, std::memory_order_release);
+    WallpaperEngine::WebBrowser::IPC::setFrameSlotsResident (
+	this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true
+    );
+
+    this->m_helperReadyAt = {};
+    this->m_helperFailureLogged = false;
+    this->spawnHost (this->m_hostBackgroundPath);
+    this->m_streamVolume = std::make_unique<Audio::Drivers::PulseProcessVolume> (this->m_hostPid);
+    this->m_streamVolume->setVolume (this->m_audioVolume);
     this->requestPageFrame ();
 }
 
@@ -492,13 +686,23 @@ CWeb::~CWeb () {
     // waits for a callback that's running right now, so the shared memory can be unmapped safely below
     this->m_spectrumRecorder->removeSpectrumListener (this->m_spectrumListenerId);
 
+    this->stopHost (true);
+
+    if (this->m_dmabufSocket >= 0) {
+	close (this->m_dmabufSocket);
+    }
+
+    closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
+}
+
+void CWeb::stopHost (const bool graceful) {
     this->m_shm->quitRequested.store (true, std::memory_order_release);
 
     // let the host close CEF cleanly before killing it, bounded like the old embedded loop
     bool exited = false;
     const auto shutdownStart = std::chrono::steady_clock::now ();
 
-    for (int i = 0; i < 500; i++) {
+    for (int i = 0; i < (graceful ? 500 : 50); i++) {
 	int status = 0;
 
 	if (waitpid (this->m_hostPid, &status, WNOHANG) == this->m_hostPid) {
@@ -519,12 +723,15 @@ CWeb::~CWeb () {
     }
 
     if (!exited) {
-	sLog.error ("CWeb: web host ", this->m_hostPid, " did not shut down in time, killing it");
+	if (graceful) {
+	    sLog.error ("CWeb: web host ", this->m_hostPid, " did not shut down in time, killing it");
+	}
+
 	kill (this->m_hostPid, SIGKILL);
 	waitpid (this->m_hostPid, nullptr, 0);
     }
 
-    closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
+    this->m_hostPid = -1;
 }
 
 void CWeb::setPropertyOverrides (const std::map<std::string, std::string>& overrides) {

+ 20 - 0
src/WallpaperEngine/Render/Wallpapers/CWeb.h

@@ -23,6 +23,10 @@ namespace WallpaperEngine::Audio::Drivers {
 class PulseProcessVolume;
 }
 
+namespace WallpaperEngine::Render::Wallpapers {
+class WebDmabufImport;
+}
+
 namespace WallpaperEngine::Render::Wallpapers {
 // CEF allows one CefInitialize()/CefShutdown() per process, so a disposable child (runWebHost(), a --web-host re-exec)
 // owns it for one browser and hands frames back through shared memory, like WE's separate webwallpaper.exe
@@ -58,11 +62,27 @@ protected:
     friend class CWallpaper;
 
 private:
+    enum class FrameMode { Shm, Dmabuf };
+
+    [[nodiscard]] FrameMode chooseFrameMode () const;
     void spawnHost (const std::filesystem::path& resolvedBackgroundPath);
+    void stopHost (bool graceful);
+    // the host's browser could not give GPU buffers the engine can use: start it again with shared memory frames
+    void fallBackToShm (const char* reason);
+    void renderDmabufFrame ();
+    void noteFirstContent ();
     void requestPageFrame ();
     // a slot number or size the host wrote that doesn't fit the segment: nothing is read, the next frame is requested
     void rejectFrame ();
 
+    std::filesystem::path m_hostBackgroundPath;
+    FrameMode m_frameMode = FrameMode::Shm;
+    // dmabuf mode: our end of the socket the host's buffers arrive on, and what imports them
+    int m_dmabufSocket = -1;
+    std::unique_ptr<WebDmabufImport> m_dmabufImport;
+    uint64_t m_dmabufFrames = 0;
+    std::chrono::steady_clock::time_point m_helperReadyAt {};
+    float m_audioVolume = 1.0f;
     WallpaperEngine::WebBrowser::IPC::WebHostSharedMemory* m_shm = nullptr;
     std::string m_shmName;
     uint32_t m_shmMaxWidth = 0;

+ 388 - 0
src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.cpp

@@ -0,0 +1,388 @@
+#include "WebDmabufImport.h"
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <cstdlib>
+#include <cstring>
+#include <string_view>
+#include <sys/stat.h>
+
+#include "WallpaperEngine/Logging/Log.h"
+
+using namespace WallpaperEngine::Render::Wallpapers;
+using WallpaperEngine::WebBrowser::IPC::DmabufFrame;
+
+namespace {
+using ImageTargetTexture = void (*) (GLenum target, void* image);
+
+constexpr uint64_t DRM_FORMAT_MOD_INVALID = 0x00ffffffffffffffull;
+// the browser cycles through a handful of buffers, and every imported one pins a frame of GPU memory
+constexpr size_t MAX_ENTRIES = 6;
+
+bool hasExtension (const char* list, std::string_view name) {
+    if (list == nullptr) {
+	return false;
+    }
+
+    const std::string_view all (list);
+
+    for (size_t at = all.find (name); at != std::string_view::npos; at = all.find (name, at + 1)) {
+	const bool startsWord = at == 0 || all[at - 1] == ' ';
+	const bool endsWord = at + name.size () == all.size () || all[at + name.size ()] == ' ';
+
+	if (startsWord && endsWord) {
+	    return true;
+	}
+    }
+
+    return false;
+}
+
+struct Functions {
+    PFNEGLCREATEIMAGEKHRPROC createImage = nullptr;
+    PFNEGLDESTROYIMAGEKHRPROC destroyImage = nullptr;
+    ImageTargetTexture targetTexture = nullptr;
+    bool modifiers = false;
+};
+
+const Functions& functions () {
+    static const Functions loaded = [] {
+	Functions result;
+	const EGLDisplay display = eglGetCurrentDisplay ();
+
+	if (display == EGL_NO_DISPLAY) {
+	    return result;
+	}
+
+	const char* eglExtensions = eglQueryString (display, EGL_EXTENSIONS);
+
+	if (!hasExtension (eglExtensions, "EGL_EXT_image_dma_buf_import")
+	    || !hasExtension (eglExtensions, "EGL_KHR_image_base")) {
+	    return result;
+	}
+
+	result.createImage = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC> (eglGetProcAddress ("eglCreateImageKHR"));
+	result.destroyImage = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC> (eglGetProcAddress ("eglDestroyImageKHR"));
+	result.targetTexture
+	    = reinterpret_cast<ImageTargetTexture> (eglGetProcAddress ("glEGLImageTargetTexture2DOES"));
+	result.modifiers = hasExtension (eglExtensions, "EGL_EXT_image_dma_buf_import_modifiers");
+
+	bool glImport = false;
+	GLint extensionCount = 0;
+	glGetIntegerv (GL_NUM_EXTENSIONS, &extensionCount);
+
+	for (GLint i = 0; i < extensionCount && !glImport; i++) {
+	    const auto* name = reinterpret_cast<const char*> (glGetStringi (GL_EXTENSIONS, static_cast<GLuint> (i)));
+	    glImport = name != nullptr && std::string_view (name) == "GL_OES_EGL_image";
+	}
+
+	if (result.createImage == nullptr || result.destroyImage == nullptr || result.targetTexture == nullptr
+	    || !glImport) {
+	    result = {};
+	}
+
+	return result;
+    }();
+
+    return loaded;
+}
+}
+
+struct WebDmabufImport::Entry {
+    dev_t device = 0;
+    ino_t inode = 0;
+    uint32_t width = 0;
+    uint32_t height = 0;
+    uint32_t fourcc = 0;
+    uint64_t modifier = 0;
+    uint32_t stride = 0;
+    uint64_t offset = 0;
+    EGLImageKHR image = EGL_NO_IMAGE_KHR;
+    GLuint texture = 0;
+};
+
+bool WebDmabufImport::available () {
+    const auto& loaded = functions ();
+
+    return loaded.createImage != nullptr && eglGetCurrentDisplay () != EGL_NO_DISPLAY;
+}
+
+WebDmabufImport::WebDmabufImport () : m_display (eglGetCurrentDisplay ()) {
+    glGenFramebuffers (1, &this->m_readFramebuffer);
+}
+
+WebDmabufImport::~WebDmabufImport () {
+    for (auto& entry : this->m_entries) {
+	glDeleteTextures (1, &entry->texture);
+	functions ().destroyImage (this->m_display, entry->image);
+    }
+
+    glDeleteFramebuffers (1, &this->m_readFramebuffer);
+
+    if (this->m_gridFramebuffer != 0) {
+	glDeleteFramebuffers (1, &this->m_gridFramebuffer);
+	glDeleteTextures (1, &this->m_gridTexture);
+    }
+}
+
+bool WebDmabufImport::framebufferHasContent (const GLuint framebuffer, const uint32_t width, const uint32_t height) {
+    constexpr int columns = 48;
+    constexpr int rows = 27;
+    constexpr int tolerance = 2;
+
+    if (this->m_gridFramebuffer == 0) {
+	GLint previous = 0;
+	glGetIntegerv (GL_TEXTURE_BINDING_2D, &previous);
+	glGenTextures (1, &this->m_gridTexture);
+	glBindTexture (GL_TEXTURE_2D, this->m_gridTexture);
+	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, columns, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glBindTexture (GL_TEXTURE_2D, previous);
+	glGenFramebuffers (1, &this->m_gridFramebuffer);
+	glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_gridFramebuffer);
+	glFramebufferTexture2D (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->m_gridTexture, 0);
+    }
+
+    GLint previousRead = 0;
+    GLint previousDraw = 0;
+    GLboolean colorMask[4];
+    const GLboolean scissor = glIsEnabled (GL_SCISSOR_TEST);
+    glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &previousRead);
+    glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &previousDraw);
+    glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
+
+    glDisable (GL_SCISSOR_TEST);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, framebuffer);
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_gridFramebuffer);
+    glBlitFramebuffer (
+	0, 0, static_cast<GLint> (width), static_cast<GLint> (height), 0, 0, columns, rows, GL_COLOR_BUFFER_BIT,
+	GL_NEAREST
+    );
+
+    uint8_t pixels[columns * rows * 4];
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_gridFramebuffer);
+    glReadPixels (0, 0, columns, rows, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
+
+    glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
+
+    if (scissor) {
+	glEnable (GL_SCISSOR_TEST);
+    }
+
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, static_cast<GLuint> (previousRead));
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, static_cast<GLuint> (previousDraw));
+
+    for (int i = 1; i < columns * rows; i++) {
+	for (int channel = 0; channel < 4; channel++) {
+	    if (std::abs (pixels[i * 4 + channel] - pixels[channel]) > tolerance) {
+		return true;
+	    }
+	}
+    }
+
+    return false;
+}
+
+WebDmabufImport::Entry* WebDmabufImport::find (const DmabufFrame& frame) {
+    struct stat info {};
+
+    if (fstat (frame.fd[0], &info) != 0) {
+	return nullptr;
+    }
+
+    for (auto it = this->m_entries.begin (); it != this->m_entries.end (); ++it) {
+	const Entry& entry = **it;
+
+	if (entry.device == info.st_dev && entry.inode == info.st_ino && entry.width == frame.width
+	    && entry.height == frame.height && entry.fourcc == frame.fourcc && entry.modifier == frame.modifier
+	    && entry.stride == frame.stride[0] && entry.offset == frame.offset[0]) {
+	    // most recently used first
+	    this->m_entries.splice (this->m_entries.begin (), this->m_entries, it);
+	    return this->m_entries.front ().get ();
+	}
+    }
+
+    return nullptr;
+}
+
+WebDmabufImport::Entry* WebDmabufImport::import (const DmabufFrame& frame) {
+    const auto& loaded = functions ();
+    struct stat info {};
+
+    if (loaded.createImage == nullptr || fstat (frame.fd[0], &info) != 0) {
+	return nullptr;
+    }
+
+    constexpr EGLint planeAttributes[4][5] = {
+	{ EGL_DMA_BUF_PLANE0_FD_EXT, EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGL_DMA_BUF_PLANE0_PITCH_EXT,
+	  EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT },
+	{ EGL_DMA_BUF_PLANE1_FD_EXT, EGL_DMA_BUF_PLANE1_OFFSET_EXT, EGL_DMA_BUF_PLANE1_PITCH_EXT,
+	  EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT },
+	{ EGL_DMA_BUF_PLANE2_FD_EXT, EGL_DMA_BUF_PLANE2_OFFSET_EXT, EGL_DMA_BUF_PLANE2_PITCH_EXT,
+	  EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT },
+	{ EGL_DMA_BUF_PLANE3_FD_EXT, EGL_DMA_BUF_PLANE3_OFFSET_EXT, EGL_DMA_BUF_PLANE3_PITCH_EXT,
+	  EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT },
+    };
+
+    EGLint attributes[7 + 4 * 10 + 1];
+    int count = 0;
+    const auto add = [&] (EGLint name, EGLint value) {
+	attributes[count++] = name;
+	attributes[count++] = value;
+    };
+
+    add (EGL_WIDTH, static_cast<EGLint> (frame.width));
+    add (EGL_HEIGHT, static_cast<EGLint> (frame.height));
+    add (EGL_LINUX_DRM_FOURCC_EXT, static_cast<EGLint> (frame.fourcc));
+
+    for (int i = 0; i < frame.planeCount; i++) {
+	add (planeAttributes[i][0], frame.fd[i]);
+	add (planeAttributes[i][1], static_cast<EGLint> (frame.offset[i]));
+	add (planeAttributes[i][2], static_cast<EGLint> (frame.stride[i]));
+
+	if (loaded.modifiers && frame.modifier != DRM_FORMAT_MOD_INVALID) {
+	    add (planeAttributes[i][3], static_cast<EGLint> (frame.modifier & 0xffffffffu));
+	    add (planeAttributes[i][4], static_cast<EGLint> (frame.modifier >> 32));
+	}
+    }
+
+    attributes[count] = EGL_NONE;
+
+    const EGLImageKHR image
+	= loaded.createImage (this->m_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attributes);
+
+    if (image == EGL_NO_IMAGE_KHR) {
+	if (!this->m_errorLogged) {
+	    this->m_errorLogged = true;
+	    sLog.error (
+		"WebDmabufImport: eglCreateImage failed (EGL error 0x", std::hex, eglGetError (), std::dec, ") for a ",
+		frame.width, "x", frame.height, " buffer, fourcc 0x", std::hex, frame.fourcc, ", modifier 0x",
+		frame.modifier, std::dec
+	    );
+	}
+
+	return nullptr;
+    }
+
+    // buffers of another size are a resize behind us, nothing sends those again
+    for (auto it = this->m_entries.begin (); it != this->m_entries.end ();) {
+	if ((*it)->width != frame.width || (*it)->height != frame.height) {
+	    glDeleteTextures (1, &(*it)->texture);
+	    loaded.destroyImage (this->m_display, (*it)->image);
+	    it = this->m_entries.erase (it);
+	} else {
+	    ++it;
+	}
+    }
+
+    auto entry = std::make_unique<Entry> ();
+    entry->device = info.st_dev;
+    entry->inode = info.st_ino;
+    entry->width = frame.width;
+    entry->height = frame.height;
+    entry->fourcc = frame.fourcc;
+    entry->modifier = frame.modifier;
+    entry->stride = frame.stride[0];
+    entry->offset = frame.offset[0];
+    entry->image = image;
+
+    GLint previous = 0;
+    glGetIntegerv (GL_TEXTURE_BINDING_2D, &previous);
+    glGenTextures (1, &entry->texture);
+    glBindTexture (GL_TEXTURE_2D, entry->texture);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+
+    while (glGetError () != GL_NO_ERROR) { }
+
+    loaded.targetTexture (GL_TEXTURE_2D, image);
+    const GLenum error = glGetError ();
+    glBindTexture (GL_TEXTURE_2D, previous);
+
+    if (error != GL_NO_ERROR) {
+	if (!this->m_errorLogged) {
+	    this->m_errorLogged = true;
+	    sLog.error (
+		"WebDmabufImport: the GL driver refused the imported buffer (GL error 0x", std::hex, error, ")"
+	    );
+	}
+
+	glDeleteTextures (1, &entry->texture);
+	loaded.destroyImage (this->m_display, image);
+	return nullptr;
+    }
+
+    this->m_imports++;
+    this->m_entries.push_front (std::move (entry));
+
+    if (this->m_entries.size () > MAX_ENTRIES) {
+	const Entry& oldest = *this->m_entries.back ();
+	glDeleteTextures (1, &oldest.texture);
+	loaded.destroyImage (this->m_display, oldest.image);
+	this->m_entries.pop_back ();
+    }
+
+    return this->m_entries.front ().get ();
+}
+
+bool WebDmabufImport::copyTo (const DmabufFrame& frame, const GLuint framebuffer) {
+    if (frame.planeCount < 1 || frame.fd[0] < 0) {
+	return false;
+    }
+
+    Entry* entry = this->find (frame);
+
+    if (entry == nullptr) {
+	entry = this->import (frame);
+    }
+
+    if (entry == nullptr) {
+	return false;
+    }
+
+    GLint previousRead = 0;
+    GLint previousDraw = 0;
+    GLboolean colorMask[4];
+    const GLboolean scissor = glIsEnabled (GL_SCISSOR_TEST);
+    glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &previousRead);
+    glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &previousDraw);
+    glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
+
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_readFramebuffer);
+    glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, entry->texture, 0);
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, framebuffer);
+    glDisable (GL_SCISSOR_TEST);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+    while (glGetError () != GL_NO_ERROR) { }
+
+    const bool complete = glCheckFramebufferStatus (GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+
+    if (complete) {
+	const GLint width = static_cast<GLint> (frame.width);
+	const GLint height = static_cast<GLint> (frame.height);
+
+	glBlitFramebuffer (0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+    }
+
+    const bool failed = !complete || glGetError () != GL_NO_ERROR;
+
+    glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
+
+    if (scissor) {
+	glEnable (GL_SCISSOR_TEST);
+    }
+
+    glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, static_cast<GLuint> (previousRead));
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, static_cast<GLuint> (previousDraw));
+
+    if (failed && !this->m_errorLogged) {
+	this->m_errorLogged = true;
+	sLog.error ("WebDmabufImport: copying the imported buffer into the frame buffer failed");
+    }
+
+    return !failed;
+}

+ 46 - 0
src/WallpaperEngine/Render/Wallpapers/WebDmabufImport.h

@@ -0,0 +1,46 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <cstdint>
+#include <list>
+#include <memory>
+
+#include "WallpaperEngine/WebBrowser/IPC/DmabufChannel.h"
+
+namespace WallpaperEngine::Render::Wallpapers {
+// main process side of --web-frames dmabuf: imports the web host's GPU buffers through EGL_EXT_image_dma_buf_import
+// and copies them into the wallpaper's frame buffer with the GPU; the pixels never visit the CPU. The host's browser
+// reuses a few buffers, so imported ones are kept by the buffer's identity and dropped when it stops coming
+class WebDmabufImport {
+public:
+    // whether the current GL context sits on an EGL display that can import dmabufs (not GLX, not llvmpipe-less X11)
+    [[nodiscard]] static bool available ();
+
+    WebDmabufImport ();
+    ~WebDmabufImport ();
+
+    // copies frame.width x frame.height into the top left of the framebuffer; false when the buffer cannot be
+    // imported or the GL driver refuses it. The caller closes the frame's descriptors, the import keeps its own
+    [[nodiscard]] bool copyTo (const WallpaperEngine::WebBrowser::IPC::DmabufFrame& frame, GLuint framebuffer);
+
+    // whether the frame holds more than one flat colour, judged on a grid of 48 x 27 samples (a page paints its
+    // background long before its content)
+    [[nodiscard]] bool framebufferHasContent (GLuint framebuffer, uint32_t width, uint32_t height);
+
+    [[nodiscard]] uint64_t importedCount () const { return this->m_imports; }
+
+private:
+    struct Entry;
+
+    Entry* find (const WallpaperEngine::WebBrowser::IPC::DmabufFrame& frame);
+    Entry* import (const WallpaperEngine::WebBrowser::IPC::DmabufFrame& frame);
+
+    std::list<std::unique_ptr<Entry>> m_entries;
+    void* m_display;
+    GLuint m_readFramebuffer = 0;
+    GLuint m_gridFramebuffer = 0;
+    GLuint m_gridTexture = 0;
+    uint64_t m_imports = 0;
+    bool m_errorLogged = false;
+};
+}

+ 8 - 6
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -478,13 +478,12 @@ ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& media
     m_scene (scene), m_mediaSource (mediaSource) {
     this->m_unregisterMediaUpdateCallback
 	= mediaSource.addMetadataListener ([this] (const Media::MediaSource::MediaInfo& info) {
-	      this->notifyMediaUpdate (info);
+	      this->notifyMediaUpdate (info, MediaChange::Metadata);
 	  });
 
     this->m_unregisterAlbumArtUpdateCallback
 	= mediaSource.addAlbumArtListener ([this] (const Media::MediaSource::MediaInfo& info) {
-	      // TODO: SEPARATE THESE INTO THEIR OWN UPDATES SO JS ONLY RECEIVES THE MEANINGFUL UPDATES
-	      this->notifyMediaUpdate (info);
+	      this->notifyMediaUpdate (info, MediaChange::Thumbnail);
 	  });
 
     JS::platform ();
@@ -1277,7 +1276,7 @@ void ScriptEngine::initializeModule (const std::string& key, LoadedModule& modul
 	}
     }
 
-    this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), &module);
+    this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), MediaChange::Metadata, &module);
 }
 
 // the project's properties plus WE's own: sub_14010A520 drops the project's alignment/volume/rate/cameraparallax,
@@ -1814,7 +1813,9 @@ void ScriptEngine::notifyUserPropertiesChanged (const std::vector<std::string>&
     }
 }
 
-void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only) {
+void ScriptEngine::notifyMediaUpdate (
+    const Media::MediaSource::MediaInfo& media, MediaChange change, LoadedModule* only
+) {
     const Scope scope (*this);
     const auto context = this->getContext ();
     auto* isolate = this->m_isolate;
@@ -1878,12 +1879,13 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
 	if (media.available && media.duration != 0.0) {
 	    events.emplace_back ("mediaTimelineChanged", mediaTimelineEvent);
 	}
+    } else if (change == MediaChange::Thumbnail) {
+	events = { { "mediaThumbnailChanged", mediaThumbnailEvent } };
     } else {
 	events = {
 	    { "mediaPropertiesChanged", propertiesEvent },
 	    { "mediaPlaybackChanged", playbackEvent },
 	    { "mediaTimelineChanged", mediaTimelineEvent },
-	    { "mediaThumbnailChanged", mediaThumbnailEvent },
 	};
     }
 

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

@@ -247,7 +247,9 @@ private:
 
     Media::ThumbnailPalette thumbnailPaletteFor (const Media::MediaSource::MediaInfo& media);
     v8::MaybeLocal<v8::Value> callEvent (LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]);
-    void notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only = nullptr);
+    enum class MediaChange { Metadata, Thumbnail };
+    void
+    notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, MediaChange change, LoadedModule* only = nullptr);
     void initializeModule (const std::string& key, LoadedModule& module);
     void bindThisLayer (ScriptableObject& object, LoadedModule* module = nullptr);
     v8::Local<v8::Object> initialUserProperties ();

+ 135 - 0
src/WallpaperEngine/Testing/Cases/DmabufChannel.cpp

@@ -0,0 +1,135 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "WallpaperEngine/WebBrowser/IPC/DmabufChannel.h"
+
+using namespace WallpaperEngine::WebBrowser::IPC;
+
+namespace {
+int makeBuffer (const char value) {
+    const int fd = memfd_create ("dmabuf-test", MFD_CLOEXEC);
+    REQUIRE (fd >= 0);
+    REQUIRE (ftruncate (fd, 16) == 0);
+    REQUIRE (pwrite (fd, &value, 1, 0) == 1);
+    return fd;
+}
+
+char firstByte (const int fd) {
+    char value = 0;
+    REQUIRE (pread (fd, &value, 1, 0) == 1);
+    return value;
+}
+
+DmabufFrame frameOf (const char value, const uint64_t sequence, const uint32_t width = 640) {
+    DmabufFrame frame;
+    frame.width = width;
+    frame.height = 360;
+    frame.fourcc = 0x34325241;
+    frame.modifier = 0x0123456789abcdefull;
+    frame.planeCount = 1;
+    frame.sequence = sequence;
+    frame.stride[0] = width * 4;
+    frame.offset[0] = 64;
+    frame.fd[0] = makeBuffer (value);
+    return frame;
+}
+}
+
+TEST_CASE ("a dmabuf frame arrives with its descriptors and layout", "[web][dmabuf]") {
+    int mainEnd = -1;
+    int hostEnd = -1;
+    REQUIRE (makeDmabufSocketPair (mainEnd, hostEnd));
+
+    bool closed = false;
+    REQUIRE_FALSE (receiveLatestDmabufFrame (mainEnd, 4096, 4096, closed).has_value ());
+    REQUIRE_FALSE (closed);
+
+    DmabufFrame sent = frameOf ('x', 7);
+    REQUIRE (sendDmabufFrame (hostEnd, sent));
+    close (sent.fd[0]);
+
+    auto received = receiveLatestDmabufFrame (mainEnd, 4096, 4096, closed);
+    REQUIRE (received.has_value ());
+    CHECK (received->width == 640);
+    CHECK (received->height == 360);
+    CHECK (received->fourcc == 0x34325241);
+    CHECK (received->modifier == 0x0123456789abcdefull);
+    CHECK (received->planeCount == 1);
+    CHECK (received->sequence == 7);
+    CHECK (received->stride[0] == 2560);
+    CHECK (received->offset[0] == 64);
+    REQUIRE (received->fd[0] >= 0);
+    CHECK (firstByte (received->fd[0]) == 'x');
+    received->closeAll ();
+
+    close (mainEnd);
+    close (hostEnd);
+}
+
+TEST_CASE ("only the newest of several queued dmabuf frames is kept", "[web][dmabuf]") {
+    int mainEnd = -1;
+    int hostEnd = -1;
+    REQUIRE (makeDmabufSocketPair (mainEnd, hostEnd));
+
+    for (int i = 0; i < 3; i++) {
+	DmabufFrame frame = frameOf (static_cast<char> ('a' + i), static_cast<uint64_t> (i + 1));
+	REQUIRE (sendDmabufFrame (hostEnd, frame));
+	close (frame.fd[0]);
+    }
+
+    bool closed = false;
+    auto received = receiveLatestDmabufFrame (mainEnd, 4096, 4096, closed);
+    REQUIRE (received.has_value ());
+    CHECK (received->sequence == 3);
+    CHECK (firstByte (received->fd[0]) == 'c');
+    received->closeAll ();
+
+    CHECK_FALSE (receiveLatestDmabufFrame (mainEnd, 4096, 4096, closed).has_value ());
+
+    close (mainEnd);
+    close (hostEnd);
+}
+
+TEST_CASE ("a dmabuf frame larger than the capacity is dropped and its descriptors closed", "[web][dmabuf]") {
+    int mainEnd = -1;
+    int hostEnd = -1;
+    REQUIRE (makeDmabufSocketPair (mainEnd, hostEnd));
+
+    DmabufFrame frame = frameOf ('z', 1, 2000);
+    REQUIRE (sendDmabufFrame (hostEnd, frame));
+    close (frame.fd[0]);
+
+    bool closed = false;
+    CHECK_FALSE (receiveLatestDmabufFrame (mainEnd, 1000, 1000, closed).has_value ());
+
+    DmabufFrame fitting = frameOf ('y', 2, 500);
+    REQUIRE (sendDmabufFrame (hostEnd, fitting));
+    close (fitting.fd[0]);
+    auto received = receiveLatestDmabufFrame (mainEnd, 1000, 1000, closed);
+    REQUIRE (received.has_value ());
+    CHECK (received->sequence == 2);
+    received->closeAll ();
+
+    close (mainEnd);
+    close (hostEnd);
+}
+
+TEST_CASE ("the receiver notices the host going away and a frame without planes is not sent", "[web][dmabuf]") {
+    int mainEnd = -1;
+    int hostEnd = -1;
+    REQUIRE (makeDmabufSocketPair (mainEnd, hostEnd));
+
+    DmabufFrame empty;
+    CHECK_FALSE (sendDmabufFrame (hostEnd, empty));
+
+    close (hostEnd);
+
+    bool closed = false;
+    CHECK_FALSE (receiveLatestDmabufFrame (mainEnd, 4096, 4096, closed).has_value ());
+    CHECK (closed);
+
+    close (mainEnd);
+}

+ 40 - 0
src/WallpaperEngine/Testing/Cases/DynamicValueListeners.cpp

@@ -0,0 +1,40 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <functional>
+
+#include "WallpaperEngine/Data/Model/DynamicValue.h"
+
+using WallpaperEngine::Data::Model::DynamicValue;
+
+TEST_CASE ("A listener may remove itself while its value propagates") {
+    DynamicValue source (1.0f);
+    std::function<void ()> remove;
+    int first = 0;
+    int second = 0;
+
+    remove = source.listen ([&] (const DynamicValue&, DynamicValue::UpdateSource) {
+	first++;
+	remove ();
+    });
+    source.listen ([&] (const DynamicValue&, DynamicValue::UpdateSource) { second++; });
+
+    source.update (2.0f, DynamicValue::Script);
+    source.update (3.0f, DynamicValue::Script);
+
+    CHECK (first == 1);
+    CHECK (second == 2);
+}
+
+TEST_CASE ("A connected value stops following once it is gone") {
+    DynamicValue source (1.0f);
+
+    {
+	DynamicValue follower (0.0f);
+
+	follower.connect (&source);
+	CHECK (follower.getFloat () == 1.0f);
+    }
+
+    source.update (5.0f, DynamicValue::User);
+    CHECK (source.getFloat () == 5.0f);
+}

+ 1 - 0
src/WallpaperEngine/Testing/Cases/HandleTable.cpp

@@ -49,6 +49,7 @@ TEST_CASE ("A released slot is used again later and the old handle stays stale")
     std::vector<int> values (500);
     std::vector<void*> handles;
 
+    handles.reserve (values.size ());
     for (auto& value : values) {
 	handles.push_back (table.insert (&value));
     }

+ 1 - 1
src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp

@@ -97,7 +97,7 @@ TEST_CASE ("Hyprland socket without the signature, as in a Flatpak") {
 	runtime.instance ("nested", "wayland-1", true);
 	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", "sway").empty ());
 	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", nullptr).empty ());
-	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", "KDE:Hyprland") != "");
+	CHECK (!findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", "KDE:Hyprland").empty ());
     }
 
     SECTION ("only dead sockets") {

+ 26 - 0
src/WallpaperEngine/Testing/Cases/NumericGuards.cpp

@@ -1,10 +1,13 @@
 #include <catch2/catch_test_macros.hpp>
 
+#include <climits>
+#include <limits>
 #include <memory>
 #include <stdexcept>
 #include <string>
 
 #include "WallpaperEngine/Assets/AssetLocator.h"
+#include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 #include "WallpaperEngine/Data/Parsers/WallpaperParser.h"
@@ -82,3 +85,26 @@ TEST_CASE ("A scene is orthographic only with a usable projection, like in WE")
     CHECK_THROWS (sceneWith (R"({ "width": -1920, "height": 1080 })"));
     CHECK_THROWS (sceneWith (R"({ "width": 1920, "height": -1 })"));
 }
+
+TEST_CASE ("A float that no int holds converts like the real engine's, not as undefined behavior") {
+    using Data::Model::DynamicValue;
+    DynamicValue value (0.0f);
+
+    value.update (3.9f, DynamicValue::UpdateSource::User);
+    CHECK (value.getInt () == 3);
+    value.update (-3.9f, DynamicValue::UpdateSource::User);
+    CHECK (value.getInt () == -3);
+
+    // cvttss2si answers INT_MIN for all of these
+    for (const float huge : { 1e30f, -1e30f, std::numeric_limits<float>::infinity (),
+			      -std::numeric_limits<float>::infinity (), std::numeric_limits<float>::quiet_NaN () }) {
+	INFO (huge);
+	value.update (huge, DynamicValue::UpdateSource::User);
+	CHECK (value.getInt () == INT_MIN);
+    }
+
+    value.update (Data::Model::Color { 1.0f, 0.0f, 0.0f, 1.0f }, DynamicValue::UpdateSource::User);
+    CHECK (value.getInt () == 255);
+    value.update (Data::Model::Color { 1e30f, 0.0f, 0.0f, 1.0f }, DynamicValue::UpdateSource::User);
+    CHECK (value.getInt () == INT_MIN);
+}

+ 13 - 0
src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp

@@ -347,6 +347,19 @@ TEST_CASE ("Broken puppet meshes are refused without throwing") {
 	CHECK_NOTHROW (readPuppetMeshFile (cut));
 	CHECK_NOTHROW (findPuppetSkeleton (cut));
     }
+
+    // the version number is read from the tag, which a file shorter than the tag or without its NUL doesn't have
+    for (size_t length = 1; length <= 12; length++) {
+	INFO ("prefix of " << length);
+	const std::vector<char> prefix (good.bytes.begin (), good.bytes.begin () + length);
+
+	CHECK_NOTHROW (readPuppetMeshFile (prefix));
+    }
+
+    const std::string unterminated = "MDLV0023";
+    const std::vector<char> digitsOnly (unterminated.begin (), unterminated.end ());
+    CHECK_NOTHROW (readPuppetMeshFile (digitsOnly));
+    CHECK_FALSE (readPuppetMeshFile (digitsOnly).has_value ());
 }
 
 TEST_CASE ("A header that declares more index bytes than the file holds is refused") {

+ 1 - 1
src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp

@@ -13,7 +13,7 @@ using namespace WallpaperEngine::Scripting;
 namespace {
 // localStorage on a bare isolate with a chosen scene file and screen
 struct Script {
-    explicit Script (std::string scene, std::string screen = "Monitor0") {
+    explicit Script (const std::string& scene, const std::string& screen = "Monitor0") {
 	JS::platform ();
 	allocator.reset (v8::ArrayBuffer::Allocator::NewDefaultAllocator ());
 	v8::Isolate::CreateParams params;

+ 36 - 33
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -222,6 +222,8 @@ void GLPlayer::setLoop (bool loop) {
 static constexpr uint64_t TIME_POS_OBSERVER = 1;
 static constexpr uint64_t FPS_OBSERVER = 2;
 static constexpr uint64_t POSITION_OBSERVER = 3;
+static constexpr uint64_t WIDTH_OBSERVER = 4;
+static constexpr uint64_t HEIGHT_OBSERVER = 5;
 
 // with ab-loop-b unset mpv's own loop restarts the file from 0 instead of going back to A, so an open end is a B
 // past the end of any video
@@ -338,6 +340,28 @@ double GLPlayer::getDuration () const {
     return duration;
 }
 
+void GLPlayer::applyDisplaySize () const {
+    if (this->m_displayWidth <= 0 || this->m_displayHeight <= 0
+	|| (this->m_displayWidth == this->m_width && this->m_displayHeight == this->m_height)) {
+	return;
+    }
+
+    this->m_width = this->m_displayWidth;
+    this->m_height = this->m_displayHeight;
+    this->m_needsRedraw = true;
+    glBindTexture (GL_TEXTURE_2D, this->m_outputTexture);
+    glTexImage2D (
+	GL_TEXTURE_2D, 0, this->m_linearOutput ? GL_RGBA16F : GL_RGBA8, this->m_width, this->m_height, 0, GL_RGBA,
+	this->m_linearOutput ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE, nullptr
+    );
+
+    // stays empty like WE's zero filled one (sub_1400EB570) until a frame is drawn below, a paused texture gets
+    // none
+    if (this->m_doWeOwnFramebuffer) {
+	this->clearTexture ();
+    }
+}
+
 void GLPlayer::render () const {
     // only render while actively playing (m_handle is set by usage-count-driven play())
     if (this->m_handle == nullptr) {
@@ -367,6 +391,15 @@ void GLPlayer::render () const {
 		continue;
 	    }
 
+	    if (event->reply_userdata == WIDTH_OBSERVER || event->reply_userdata == HEIGHT_OBSERVER) {
+		const int64_t value
+		    = property->format == MPV_FORMAT_INT64 ? *static_cast<const int64_t*> (property->data) : 0;
+
+		(event->reply_userdata == WIDTH_OBSERVER ? this->m_displayWidth : this->m_displayHeight) = value;
+		this->applyDisplaySize ();
+		continue;
+	    }
+
 	    if (event->reply_userdata == FPS_OBSERVER) {
 		const double fps
 		    = property->format == MPV_FORMAT_DOUBLE ? *static_cast<const double*> (property->data) : 0.0;
@@ -421,39 +454,6 @@ void GLPlayer::render () const {
 
 	    continue;
 	}
-
-	if (event->event_id != MPV_EVENT_VIDEO_RECONFIG) {
-	    continue;
-	}
-
-	int64_t width, height;
-
-	if (mpv_get_property (this->m_handle, "dwidth", MPV_FORMAT_INT64, &width) < 0) {
-	    continue;
-	}
-
-	if (mpv_get_property (this->m_handle, "dheight", MPV_FORMAT_INT64, &height) < 0) {
-	    continue;
-	}
-
-	if (width < 0 || height < 0) {
-	    continue;
-	}
-
-	this->m_width = width;
-	this->m_height = height;
-	this->m_needsRedraw = true;
-	glBindTexture (GL_TEXTURE_2D, this->m_outputTexture);
-	glTexImage2D (
-	    GL_TEXTURE_2D, 0, this->m_linearOutput ? GL_RGBA16F : GL_RGBA8, this->m_width, this->m_height, 0, GL_RGBA,
-	    this->m_linearOutput ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE, nullptr
-	);
-
-	// stays empty like WE's zero filled one (sub_1400EB570) until a frame is drawn below, a paused texture gets
-	// none
-	if (this->m_doWeOwnFramebuffer) {
-	    this->clearTexture ();
-	}
     }
 
     // mpv only hands out its next frame once the update flags were collected, without this playback stalls
@@ -631,6 +631,9 @@ void GLPlayer::init () {
     mpv_observe_property (this->m_handle, 0, "eof-reached", MPV_FORMAT_FLAG);
     // scripts read the position every frame (IVideoTexture ended callbacks), a synchronous get would stall the same way
     mpv_observe_property (this->m_handle, POSITION_OBSERVER, "time-pos", MPV_FORMAT_DOUBLE);
+    // a synchronous get of these blocked the render thread ~200ms while mpv's core thread set up the decoder
+    mpv_observe_property (this->m_handle, WIDTH_OBSERVER, "dwidth", MPV_FORMAT_INT64);
+    mpv_observe_property (this->m_handle, HEIGHT_OBSERVER, "dheight", MPV_FORMAT_INT64);
 
     const auto& hwdec = this->getContext ().getApp ().getContext ().settings.render.hwdec;
 

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

@@ -91,6 +91,7 @@ private:
     void stop ();
 
 protected:
+    void applyDisplaySize () const;
     bool m_doWeOwnFramebuffer;
     GLuint m_outputTexture;
     GLuint m_fbo = GL_NONE;
@@ -106,6 +107,8 @@ protected:
     mutable bool m_enginePaused = false;
     mutable uint64_t m_lastUsedFrame = 0;
     mutable double m_position = 0.0;
+    mutable int64_t m_displayWidth = 0;
+    mutable int64_t m_displayHeight = 0;
     bool m_loop = true;
     bool m_audio = true;
     bool m_linearOutput = false;

+ 27 - 1
src/WallpaperEngine/WebBrowser/CEF/BrowserApp.cpp

@@ -52,13 +52,39 @@ void BrowserApp::OnBeforeCommandLineProcessing (const CefString& process_type, C
     // Wayland (fallback-x11 hides X when Wayland is there) or a session without Xwayland. The headless platform with
     // ANGLE on EGL renders the same, WebGL on the GPU included
     const char* display = std::getenv ("DISPLAY");
-    if ((display == nullptr || *display == '\0')
+    const bool dmabufFrames = m_application.getContext ().settings.general.webHostFrames == "dmabuf";
+
+    if (dmabufFrames
 	&& (extra == nullptr || std::string_view (extra).find ("--ozone-platform") == std::string_view::npos)) {
+	// headless makes no GPU buffers one can share ("unable to allocate frame"), Wayland's come from the
+	// compositor's dmabuf support and X11's need DRI3 on the server
+	const char* wayland = std::getenv ("WAYLAND_DISPLAY");
+	command_line->AppendSwitchWithValue (
+	    "--ozone-platform", wayland != nullptr && wayland[0] != '\0' ? "wayland" : "x11"
+	);
+	command_line->AppendSwitchWithValue ("--use-gl", "angle");
+	command_line->AppendSwitchWithValue ("--use-angle", "gl-egl");
+    } else if (
+	(display == nullptr || *display == '\0')
+	&& (extra == nullptr || std::string_view (extra).find ("--ozone-platform") == std::string_view::npos)
+    ) {
 	command_line->AppendSwitchWithValue ("--ozone-platform", "headless");
 	command_line->AppendSwitchWithValue ("--use-gl", "angle");
 	command_line->AppendSwitchWithValue ("--use-angle", "gl-egl");
     }
 
+    // Chromium 146's GPU process loses its context on the first decoded video frame under the headless platform
+    // ("Could not find SharedImageBackingFactory ... BGRA_8888", then a restart loop and a page that never paints, seen
+    // with 2681203626's webm), software decoding is fine
+    const bool headlessPlatform
+	= (!dmabufFrames && (display == nullptr || *display == '\0')
+	   && (extra == nullptr || std::string_view (extra).find ("--ozone-platform") == std::string_view::npos))
+	|| (extra != nullptr && std::string_view (extra).find ("--ozone-platform=headless") != std::string_view::npos);
+
+    if (headlessPlatform) {
+	command_line->AppendSwitch ("--disable-accelerated-video-decode");
+    }
+
     // debugging: extra Chromium switches, e.g. swiftshader where the GPU process can't start
     if (extra != nullptr) {
 	std::istringstream stream (extra);

+ 54 - 1
src/WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.cpp

@@ -2,10 +2,13 @@
 #include <algorithm>
 #include <cstring>
 
+#include "WallpaperEngine/WebBrowser/IPC/DmabufChannel.h"
+
 using namespace WallpaperEngine::WebBrowser::CEF;
 using namespace WallpaperEngine::WebBrowser::IPC;
 
-SharedMemoryRenderHandler::SharedMemoryRenderHandler (WebHostSharedMemory* shm) : m_shm (shm) { }
+SharedMemoryRenderHandler::SharedMemoryRenderHandler (WebHostSharedMemory* shm, const int dmabufSocket) :
+    m_shm (shm), m_dmabufSocket (dmabufSocket) { }
 
 void SharedMemoryRenderHandler::GetViewRect (CefRefPtr<CefBrowser> browser, CefRect& rect) {
     const uint32_t width
@@ -39,3 +42,53 @@ void SharedMemoryRenderHandler::OnPaint (
 
     this->m_backSlot = this->m_shm->publishFrame (this->m_backSlot);
 }
+
+void SharedMemoryRenderHandler::OnAcceleratedPaint (
+    CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList& dirtyRects,
+    const CefAcceleratedPaintInfo& info
+) {
+    if (type != PET_VIEW || this->m_dmabufSocket < 0) {
+	return;
+    }
+
+    // DRM_FORMAT_ARGB8888 / DRM_FORMAT_ABGR8888, little endian words: CEF's BGRA is the first, RGBA the second
+    constexpr uint32_t DRM_ARGB8888 = 0x34325241;
+    constexpr uint32_t DRM_ABGR8888 = 0x34324241;
+
+    const uint32_t fourcc = info.format == CEF_COLOR_TYPE_BGRA_8888 ? DRM_ARGB8888
+	: info.format == CEF_COLOR_TYPE_RGBA_8888                   ? DRM_ABGR8888
+								    : 0;
+
+    if (fourcc == 0 || info.plane_count < 1 || info.plane_count > IPC::DmabufFrame::MAX_PLANES) {
+	this->m_shm->dmabufRejected.store (true, std::memory_order_release);
+	return;
+    }
+
+    // three frames in flight at most: a main process that stopped drawing leaves them unread
+    const uint64_t sent = this->m_shm->dmabufSent.load (std::memory_order_relaxed);
+
+    if (sent - this->m_shm->dmabufTaken.load (std::memory_order_acquire) >= 3) {
+	return;
+    }
+
+    IPC::DmabufFrame frame;
+    const auto& visible = info.extra.visible_rect;
+    frame.width = static_cast<uint32_t> (visible.width > 0 ? visible.width : info.extra.coded_size.width);
+    frame.height = static_cast<uint32_t> (visible.height > 0 ? visible.height : info.extra.coded_size.height);
+    frame.fourcc = fourcc;
+    frame.modifier = info.modifier;
+    frame.planeCount = info.plane_count;
+    frame.sequence = sent + 1;
+
+    for (int i = 0; i < info.plane_count; i++) {
+	frame.stride[i] = info.planes[i].stride;
+	frame.offset[i] = info.planes[i].offset;
+	frame.fd[i] = info.planes[i].fd;
+    }
+
+    // the descriptors stay CEF's (the buffer goes back to its pool when this returns), the kernel duplicates them
+    // into the main process
+    if (IPC::sendDmabufFrame (this->m_dmabufSocket, frame)) {
+	this->m_shm->dmabufSent.store (sent + 1, std::memory_order_release);
+    }
+}

+ 10 - 1
src/WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.h

@@ -11,7 +11,10 @@ namespace WallpaperEngine::WebBrowser::CEF {
 // asked for, runWebHost() calls WasResized()
 class SharedMemoryRenderHandler : public CefRenderHandler {
 public:
-    explicit SharedMemoryRenderHandler (WallpaperEngine::WebBrowser::IPC::WebHostSharedMemory* shm);
+    // a socket (>= 0) is the dmabuf mode: the browser then hands over GPU buffers instead of pixels
+    explicit SharedMemoryRenderHandler (
+	WallpaperEngine::WebBrowser::IPC::WebHostSharedMemory* shm, int dmabufSocket = -1
+    );
 
     ~SharedMemoryRenderHandler () override = default;
 
@@ -22,6 +25,11 @@ public:
 	int height
     ) override;
 
+    void OnAcceleratedPaint (
+	CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList& dirtyRects,
+	const CefAcceleratedPaintInfo& info
+    ) override;
+
     [[nodiscard]] uint32_t viewWidth () const { return this->m_viewWidth.load (std::memory_order_relaxed); }
     [[nodiscard]] uint32_t viewHeight () const { return this->m_viewHeight.load (std::memory_order_relaxed); }
 
@@ -29,6 +37,7 @@ public:
 
 private:
     WallpaperEngine::WebBrowser::IPC::WebHostSharedMemory* m_shm;
+    int m_dmabufSocket;
     // slot currently owned by this side, painted into and then swapped with the shared one
     uint32_t m_backSlot = 0;
     std::atomic<uint32_t> m_viewWidth = 0;

+ 179 - 0
src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.cpp

@@ -0,0 +1,179 @@
+#include "DmabufChannel.h"
+
+#include <cerrno>
+#include <cstring>
+#include <sys/socket.h>
+#include <unistd.h>
+
+namespace WallpaperEngine::WebBrowser::IPC {
+namespace {
+    // what travels in the message body, the descriptors ride in the control data
+    struct Wire {
+	uint32_t width;
+	uint32_t height;
+	uint32_t fourcc;
+	uint32_t planeCount;
+	uint64_t modifier;
+	uint64_t sequence;
+	uint32_t stride[DmabufFrame::MAX_PLANES];
+	uint64_t offset[DmabufFrame::MAX_PLANES];
+    };
+}
+
+void DmabufFrame::closeAll () {
+    for (int& descriptor : fd) {
+	if (descriptor >= 0) {
+	    close (descriptor);
+	    descriptor = -1;
+	}
+    }
+
+    planeCount = 0;
+}
+
+bool sendDmabufFrame (const int socket, const DmabufFrame& frame) {
+    if (frame.planeCount < 1 || frame.planeCount > DmabufFrame::MAX_PLANES) {
+	return false;
+    }
+
+    Wire wire {};
+    wire.width = frame.width;
+    wire.height = frame.height;
+    wire.fourcc = frame.fourcc;
+    wire.planeCount = static_cast<uint32_t> (frame.planeCount);
+    wire.modifier = frame.modifier;
+    wire.sequence = frame.sequence;
+
+    for (int i = 0; i < frame.planeCount; i++) {
+	wire.stride[i] = frame.stride[i];
+	wire.offset[i] = frame.offset[i];
+    }
+
+    iovec vector { &wire, sizeof (wire) };
+    alignas (cmsghdr) char control[CMSG_SPACE (sizeof (int) * DmabufFrame::MAX_PLANES)] {};
+    msghdr message {};
+    message.msg_iov = &vector;
+    message.msg_iovlen = 1;
+    message.msg_control = control;
+    message.msg_controllen = CMSG_SPACE (sizeof (int) * frame.planeCount);
+
+    cmsghdr* header = CMSG_FIRSTHDR (&message);
+
+    if (header == nullptr) {
+	return false;
+    }
+
+    header->cmsg_level = SOL_SOCKET;
+    header->cmsg_type = SCM_RIGHTS;
+    header->cmsg_len = CMSG_LEN (sizeof (int) * frame.planeCount);
+    memcpy (CMSG_DATA (header), frame.fd.data (), sizeof (int) * frame.planeCount);
+
+    ssize_t sent;
+
+    do {
+	sent = sendmsg (socket, &message, MSG_DONTWAIT | MSG_NOSIGNAL);
+    } while (sent < 0 && errno == EINTR);
+
+    return sent == static_cast<ssize_t> (sizeof (wire));
+}
+
+std::optional<DmabufFrame>
+receiveLatestDmabufFrame (const int socket, const uint32_t maxWidth, const uint32_t maxHeight, bool& closed) {
+    std::optional<DmabufFrame> latest;
+
+    for (;;) {
+	Wire wire {};
+	iovec vector { &wire, sizeof (wire) };
+	alignas (cmsghdr) char control[CMSG_SPACE (sizeof (int) * DmabufFrame::MAX_PLANES)] {};
+	msghdr message {};
+	message.msg_iov = &vector;
+	message.msg_iovlen = 1;
+	message.msg_control = control;
+	message.msg_controllen = sizeof (control);
+
+	ssize_t received;
+
+	do {
+	    received = recvmsg (socket, &message, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
+	} while (received < 0 && errno == EINTR);
+
+	if (received == 0) {
+	    closed = true;
+	    break;
+	}
+
+	if (received < 0) {
+	    if (errno != EAGAIN && errno != EWOULDBLOCK) {
+		closed = true;
+	    }
+
+	    break;
+	}
+
+	DmabufFrame frame;
+	int count = 0;
+
+	for (cmsghdr* header = CMSG_FIRSTHDR (&message); header != nullptr; header = CMSG_NXTHDR (&message, header)) {
+	    if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS) {
+		continue;
+	    }
+
+	    const int incoming = static_cast<int> ((header->cmsg_len - CMSG_LEN (0)) / sizeof (int));
+	    const int kept = incoming < DmabufFrame::MAX_PLANES ? incoming : DmabufFrame::MAX_PLANES;
+
+	    for (int i = 0; i < incoming; i++) {
+		int descriptor;
+		memcpy (&descriptor, CMSG_DATA (header) + sizeof (int) * i, sizeof (int));
+
+		if (i < kept && count < DmabufFrame::MAX_PLANES) {
+		    frame.fd[count++] = descriptor;
+		} else {
+		    close (descriptor);
+		}
+	    }
+	}
+
+	const bool wellFormed = received == static_cast<ssize_t> (sizeof (wire))
+	    && !(message.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) && wire.planeCount >= 1
+	    && wire.planeCount <= DmabufFrame::MAX_PLANES && static_cast<int> (wire.planeCount) == count
+	    && wire.width >= 1 && wire.height >= 1 && wire.width <= maxWidth && wire.height <= maxHeight;
+
+	if (!wellFormed) {
+	    frame.closeAll ();
+	    continue;
+	}
+
+	frame.width = wire.width;
+	frame.height = wire.height;
+	frame.fourcc = wire.fourcc;
+	frame.modifier = wire.modifier;
+	frame.planeCount = static_cast<int> (wire.planeCount);
+	frame.sequence = wire.sequence;
+
+	for (int i = 0; i < frame.planeCount; i++) {
+	    frame.stride[i] = wire.stride[i];
+	    frame.offset[i] = wire.offset[i];
+	}
+
+	if (latest) {
+	    latest->closeAll ();
+	}
+
+	latest = frame;
+    }
+
+    return latest;
+}
+
+bool makeDmabufSocketPair (int& mainEnd, int& hostEnd) {
+    int ends[2];
+
+    if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, ends) != 0) {
+	return false;
+    }
+
+    mainEnd = ends[0];
+    hostEnd = ends[1];
+    return true;
+}
+}

+ 38 - 0
src/WallpaperEngine/WebBrowser/IPC/DmabufChannel.h

@@ -0,0 +1,38 @@
+#pragma once
+
+#include <array>
+#include <cstdint>
+#include <optional>
+
+namespace WallpaperEngine::WebBrowser::IPC {
+// one painted frame of the web host as dmabuf planes, passed over a unix socket with SCM_RIGHTS; the receiver owns the
+// descriptors and closes them
+struct DmabufFrame {
+    static constexpr int MAX_PLANES = 4;
+
+    uint32_t width = 0;
+    uint32_t height = 0;
+    // DRM fourcc of the buffer
+    uint32_t fourcc = 0;
+    uint64_t modifier = 0;
+    int planeCount = 0;
+    uint64_t sequence = 0;
+    std::array<uint32_t, MAX_PLANES> stride {};
+    std::array<uint64_t, MAX_PLANES> offset {};
+    std::array<int, MAX_PLANES> fd { -1, -1, -1, -1 };
+
+    void closeAll ();
+};
+
+// host side: sends a frame without blocking; false when the socket is full or gone (the frame is dropped, the
+// descriptors stay the caller's)
+bool sendDmabufFrame (int socket, const DmabufFrame& frame);
+
+// main side: drains the socket and keeps the newest frame, older ones are closed. nullopt when nothing arrived;
+// `closed` is set when the host's end is gone. Frames that don't fit maxWidth x maxHeight or lie about their planes
+// are dropped
+std::optional<DmabufFrame> receiveLatestDmabufFrame (int socket, uint32_t maxWidth, uint32_t maxHeight, bool& closed);
+
+// two connected non blocking, close-on-exec sockets; false on failure
+bool makeDmabufSocketPair (int& mainEnd, int& hostEnd);
+}

+ 17 - 0
src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.cpp

@@ -208,6 +208,23 @@ WallpaperEngine::WebBrowser::IPC::attachSharedMemory (const std::string& name, u
     return static_cast<WebHostSharedMemory*> (mapping);
 }
 
+void WallpaperEngine::WebBrowser::IPC::setFrameSlotsResident (
+    const std::string& name, uint32_t width, uint32_t height, bool resident
+) {
+    const std::scoped_lock lock (g_heldMutex);
+    const auto it = g_held.find (name);
+
+    if (it == g_held.end ()) {
+	return;
+    }
+
+    const std::size_t size = resident ? WebHostSharedMemory::totalSize (width, height) : sizeof (WebHostSharedMemory);
+
+    if (ftruncate (it->second, static_cast<off_t> (size)) != 0) {
+	sLog.error ("Cannot resize shared memory segment ", name, " to ", size, " bytes");
+    }
+}
+
 void WallpaperEngine::WebBrowser::IPC::closeSharedMemory (
     WebHostSharedMemory* mem, const std::string& name, uint32_t width, uint32_t height, bool unlinkSegment
 ) {

+ 11 - 0
src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h

@@ -22,6 +22,13 @@ struct WebHostSharedMemory {
     std::atomic<uint32_t> slotWidth[FRAME_SLOTS] {};
     std::atomic<uint32_t> slotHeight[FRAME_SLOTS] {};
 
+    // dmabuf frames (--web-frames dmabuf) travel over a socket instead of the slots above. Host: frames sent so far,
+    // main: the newest one it took; the host stops sending three frames ahead, so a main process that isn't drawing
+    // (paused) doesn't make it pile up buffers. dmabufRejected is the host saying the buffers it got can't be shared
+    std::atomic<uint64_t> dmabufSent { 0 };
+    std::atomic<uint64_t> dmabufTaken { 0 };
+    std::atomic<bool> dmabufRejected { false };
+
     // Main process -> host process: bumped whenever the page should produce its next frame (CEF runs with
     // external begin frames). Doubles as a futex word, see waitForFrameRequest().
     std::atomic<uint32_t> frameRequestSeq { 0 };
@@ -118,6 +125,10 @@ struct WebHostSharedMemory {
 // a zeroed segment for maxWidth*maxHeight BGRA8, outName is what the host attaches to; nullptr on failure
 WebHostSharedMemory* createSharedMemory (std::string& outName, uint32_t maxWidth, uint32_t maxHeight);
 
+// the frame slots stay untouched in dmabuf mode: gives their pages back (the segment keeps its header), and takes
+// them again when the engine goes back to shared memory frames
+void setFrameSlotsResident (const std::string& name, uint32_t maxWidth, uint32_t maxHeight, bool resident);
+
 // removes what dead engines' web hosts left: "lwe-web-<tag>-<n>" segments and "lwe-cef-<tag>-<uuid>" profiles
 // (Desktop::processTag); users hold a shared flock (CEF_PROFILE_LOCK for profiles), unlocked ones are stale unless the
 // tag is a running pid. Each segment is 3 frames, hundreds of MB add up

+ 1 - 2
src/WallpaperEngine/WebBrowser/WebBrowserContext.cpp

@@ -22,7 +22,6 @@
 
 using namespace WallpaperEngine::WebBrowser;
 
-// TODO: random profile folder names, maybe there's a better approach
 namespace uuid {
 static std::random_device rd;
 static std::mt19937 gen (rd ());
@@ -162,7 +161,7 @@ WebBrowserContext::WebBrowserContext (WallpaperEngine::Application::WallpaperApp
 
     // Chromium's own ERROR-level chatter (cancelled requests and the like) is noise here, the page's console is
     // still forwarded by BrowserClient
-    settings.log_severity = LOGSEVERITY_FATAL;
+    settings.log_severity = std::getenv ("LWE_CEF_LOG") != nullptr ? LOGSEVERITY_VERBOSE : LOGSEVERITY_FATAL;
 #if defined(CEF_NO_SANDBOX)
     settings.no_sandbox = true;
 #endif

+ 8 - 0
tests/desktops/fixtures/webframes/index.html

@@ -0,0 +1,8 @@
+<!doctype html><html><body style="margin:0;background:#202020">
+<div style="position:absolute;left:0;top:0;width:25vw;height:25vh;background:#ff0000"></div>
+<div style="position:absolute;right:0;top:0;width:25vw;height:25vh;background:#00ff00"></div>
+<div style="position:absolute;left:0;bottom:0;width:25vw;height:25vh;background:#0000ff"></div>
+<div style="position:absolute;right:0;bottom:0;width:25vw;height:25vh;background:rgba(255,255,255,0.5)"></div>
+<div style="position:absolute;left:30vw;top:30vh;width:40vw;height:40vh;background:linear-gradient(90deg,#000,#fff)"></div>
+<div style="position:absolute;left:40vw;top:10vh;font:bold 8vh sans-serif;color:#ffcc00">TOP LEFT-RIGHT</div>
+</body></html>

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

@@ -0,0 +1 @@
+{"file":"index.html","title":"static","type":"web","general":{"properties":{}}}

+ 8 - 0
tests/desktops/fixtures/webframes_swapped/index.html

@@ -0,0 +1,8 @@
+<!doctype html><html><body style="margin:0;background:#202020">
+<div style="position:absolute;left:0;top:0;width:25vw;height:25vh;background:#0000ff"></div>
+<div style="position:absolute;right:0;top:0;width:25vw;height:25vh;background:#00ff00"></div>
+<div style="position:absolute;left:0;bottom:0;width:25vw;height:25vh;background:#ff0000"></div>
+<div style="position:absolute;right:0;bottom:0;width:25vw;height:25vh;background:rgba(255,255,255,0.5)"></div>
+<div style="position:absolute;left:30vw;top:30vh;width:40vw;height:40vh;background:linear-gradient(90deg,#000,#fff)"></div>
+<div style="position:absolute;left:40vw;top:10vh;font:bold 8vh sans-serif;color:#ffcc00">TOP LEFT-RIGHT</div>
+</body></html>

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

@@ -0,0 +1 @@
+{"file":"index.html","title":"static","type":"web","general":{"properties":{}}}

+ 28 - 0
tests/desktops/test_kde.py

@@ -112,3 +112,31 @@ def test_plasma5(desktop_factory, engine, tmp_path):
             terminate([probe.pid])
         process.terminate()
         process.wait(10)
+
+
+def test_script_ids_stay_unique_after_an_unload(kde, tmp_path):
+    """KWin 6.4 numbers scripts by how many are loaded, after an unload the next one got the id of a live script
+    (KWinScript works around it); this tells whether the KWin of this lab still does that"""
+    scripts = []
+    for name in ("a", "b", "c"):
+        path = tmp_path / f"{name}.js"
+        path.write_text("print('lwe-id-probe');\n")
+        scripts.append(path)
+
+    def call(method, *args):
+        result = kde.run(["gdbus", "call", "--session", "--dest", "org.kde.KWin", "--object-path", "/Scripting",
+                          "--method", f"org.kde.kwin.Scripting.{method}", *args])
+        assert result.returncode == 0, result.stderr
+        return result.stdout.strip()
+
+    def load(path, name):
+        return int(call("loadScript", str(path), name).strip("(), \n"))
+
+    first = load(scripts[0], "lwe-id-a")
+    second = load(scripts[1], "lwe-id-b")
+    call("unloadScript", "lwe-id-a")
+    third = load(scripts[2], "lwe-id-c")
+    for name in ("lwe-id-b", "lwe-id-c"):
+        call("unloadScript", name)
+    if third == second:
+        pytest.xfail(f"this KWin hands the id {second} of a live script to the next one (ids {first}, {second}, {third})")

+ 153 - 0
tests/desktops/test_web_frames.py

@@ -0,0 +1,153 @@
+import os
+import signal
+import time
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from conftest import Unsupported
+
+PAGE = Path(__file__).parent / "fixtures/webframes"
+# the same page with red and blue swapped
+SWAPPED = Path(__file__).parent / "fixtures/webframes_swapped"
+
+# the engine's web host renders on the session's Wayland display and hands its GPU buffers over (--web-frames dmabuf)
+SESSIONS = ["sway", "labwc", "wayfire", "niri", "hyprland", "kde", "gnome"]
+
+RED, GREEN, BLUE = (255, 0, 0), (0, 255, 0), (0, 0, 255)
+BROWSER = "--ignore-gpu-blocklist --disable-dev-shm-usage"
+
+
+def _env(engine, switches=BROWSER):
+    # a container has no setuid chrome-sandbox, and Chromium's close() wrapper needs libcef.so ahead of libc
+    return {
+        "LWE_CEF_NO_SANDBOX": "1",
+        "LWE_WEB_HOST_PRELOAD": str(Path(engine["binary"]).resolve().parent / "libcef.so"),
+        "LWE_WEB_STATS": "1",
+        "LWE_CEF_SWITCHES": switches,
+    }
+
+
+def _page_drawn(path, swapped=False):
+    """the fixture's three coloured corners, as the page paints them on a screen of any size"""
+    image = Image.open(path).convert("RGB")
+    width, height = image.size
+    found = (
+        image.getpixel((width // 10, height // 10)),
+        image.getpixel((width * 9 // 10, height // 10)),
+        image.getpixel((width // 10, height * 9 // 10)),
+    )
+    colours = (BLUE, GREEN, RED) if swapped else (RED, GREEN, BLUE)
+    return all(max(abs(a - b) for a, b in zip(pixel, expected)) <= 3 for pixel, expected in zip(found, colours))
+
+
+def _run(desktop, engine, tmp_path, frames, switches=BROWSER, until=None, timeout=60, extra=()):
+    log = tmp_path / "engine.log"
+    process = desktop.client(
+        [engine["binary"], "--assets-dir", engine["assets"], "--screen-root", desktop.output_names()[0], "--silent",
+         "--fps", "30", "--web-frames", frames, *extra, str(PAGE)],
+        log=log, env=_env(engine, switches),
+    )
+    shot = tmp_path / "shot.png"
+    deadline = time.monotonic() + timeout
+    drawn = False
+    while time.monotonic() < deadline:
+        time.sleep(2)
+        assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+        try:
+            desktop.shot(shot)
+        except Unsupported as error:
+            pytest.skip(str(error))
+        drawn = _page_drawn(shot)
+        if drawn and (until is None or until in log.read_text(errors="replace")):
+            break
+    return process, log, shot, drawn
+
+
+@pytest.mark.parametrize("desktop", SESSIONS, indirect=True)
+def test_dmabuf_frames_draw_the_page(desktop, engine, tmp_path):
+    process, log, shot, drawn = _run(desktop, engine, tmp_path, "dmabuf", until="frames arrive as dmabufs")
+    try:
+        text = log.read_text(errors="replace")
+        assert "frames arrive as dmabufs" in text, f"the host sent no GPU buffer on {desktop.name}:\n{text[-1500:]}"
+        assert "restarting the web host" not in text
+        assert drawn, "the page's colours are not on the screen"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_shared_memory_frames_still_draw_the_page(desktop, engine, tmp_path):
+    process, log, shot, drawn = _run(desktop, engine, tmp_path, "shm")
+    try:
+        assert "frames arrive as dmabufs" not in log.read_text(errors="replace")
+        assert drawn
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_a_browser_without_gpu_buffers_falls_back_to_shared_memory(desktop, engine, tmp_path):
+    """headless Chromium cannot allocate shareable buffers: the host restarts with shared memory frames"""
+    process, log, shot, drawn = _run(
+        desktop, engine, tmp_path, "dmabuf", switches=BROWSER + " --ozone-platform=headless --use-angle=gl-egl",
+        until="restarting the web host", timeout=90,
+    )
+    try:
+        assert "restarting the web host with shared memory frames" in log.read_text(errors="replace")
+        assert drawn, "the page did not show after the fallback"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_dmabuf_frames_follow_an_output_resize(desktop, engine, tmp_path):
+    process, log, shot, drawn = _run(desktop, engine, tmp_path, "dmabuf", until="frames arrive as dmabufs")
+    output = desktop.output_names()[0]
+    try:
+        assert drawn
+        desktop.run(["wlr-randr", "--output", output, "--custom-mode", "1280x720"])
+        deadline = time.monotonic() + 30
+        size = None
+        while time.monotonic() < deadline:
+            time.sleep(2)
+            desktop.shot(shot)
+            size = Image.open(shot).size
+            if size == (1280, 720) and _page_drawn(shot):
+                break
+        assert size == (1280, 720), f"the output is {size}"
+        assert _page_drawn(shot), "the page is not drawn at the new size"
+        assert "restarting the web host" not in log.read_text(errors="replace")
+    finally:
+        desktop.run(["wlr-randr", "--output", output, "--custom-mode", "1920x1080"])
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_dmabuf_frames_survive_a_hotswap_between_web_wallpapers(desktop, engine, tmp_path):
+    control = tmp_path / "control"
+    process, log, shot, drawn = _run(
+        desktop, engine, tmp_path, "dmabuf", until="frames arrive as dmabufs", extra=("--control-file", str(control))
+    )
+    try:
+        assert drawn
+        control.write_text(f"path={SWAPPED}\n")
+        os.kill(process.pid, signal.SIGUSR1)
+        deadline = time.monotonic() + 40
+        swapped = False
+        while time.monotonic() < deadline and not swapped:
+            time.sleep(2)
+            desktop.shot(shot)
+            swapped = _page_drawn(shot, swapped=True)
+        assert swapped, "the second web wallpaper never replaced the first"
+        text = log.read_text(errors="replace")
+        assert text.count("frames arrive as dmabufs") == 2, "the new host did not send GPU buffers"
+        assert "restarting the web host" not in text
+    finally:
+        process.terminate()
+        process.wait(10)

+ 34 - 0
tests/desktops/test_x11_desktop.py

@@ -88,3 +88,37 @@ def test_fullscreen_window_pauses_rendering(desktop, engine, tmp_path):
             os.killpg(probe.pid, 9)
         process.terminate()
         process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", X11_SESSIONS, indirect=True)
+def test_maximized_window_pauses_rendering(desktop, engine, tmp_path):
+    if desktop.name == "herbstluftwm":
+        pytest.skip("herbstluftwm tiles windows and never sets the maximized state")
+    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("maximized-probe", ["python3", str(REPO / "tools/desktops/fullscreen_window.py"), "maximize"],
+                              {"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 maximized 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 maximized window"
+    finally:
+        if probe is not None:
+            os.killpg(probe.pid, 9)
+        process.terminate()
+        process.wait(10)

+ 27 - 0
tools/check_video_start.sh

@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Regression check for the video wallpaper start: reading the video size from mpv synchronously stalled the render thread
+# ~200 ms while it set up the decoder, so the first frame sat there before playback began. Renders a video wallpaper
+# headlessly on the GPU (headless_render.sh) and requires the worst gap between frames in the first LWE_FRAME_STATS window
+# to stay under MAX_GAP_MS (251 ms before the fix, 51 ms after).
+# Usage: tools/check_video_start.sh <engine binary> [assets dir] [workshop content dir]
+# Exit code 0 when the gap is small. Set VIDEO_ID to use another video wallpaper.
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BINARY=${1:?engine binary}
+ASSETS=${2:-/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets}
+CONTENT=${3:-/workspace/SteamLibrary/steamapps/workshop/content/431960}
+VIDEO_ID=${VIDEO_ID:-1367456719}
+MAX_GAP_MS=${MAX_GAP_MS:-120}
+[ -d "$CONTENT/$VIDEO_ID" ] || { echo "SKIP: wallpaper $VIDEO_ID not in $CONTENT"; exit 0; }
+work=$(mktemp -d /tmp/lwe-video-start.XXXXXX)
+trap 'rm -rf "$work"' EXIT
+
+LWE_FRAME_STATS=1 HEADLESS_RENDER_DELAY=150 "$HERE/headless_render.sh" "$BINARY" "$work/shot.png" \
+    --assets-dir "$ASSETS" --fps 60 --silent "$CONTENT/$VIDEO_ID" > "$work/run.log" 2>&1 || { cat "$work/run.log"; exit 1; }
+gap=$(grep -m1 '^FRAME-STATS' "$work/run.log" | sed -n 's/.*worst gap \([0-9.]*\)ms.*/\1/p')
+[ -n "$gap" ] || { echo "FAIL: no FRAME-STATS line"; cat "$work/run.log"; exit 1; }
+if awk -v g="$gap" -v m="$MAX_GAP_MS" 'BEGIN { exit !(g > m) }'; then
+    echo "FAIL: the render thread stalled for ${gap}ms while the video started (limit ${MAX_GAP_MS}ms)"
+    exit 1
+fi
+echo "PASS: worst frame gap while the video started ${gap}ms (limit ${MAX_GAP_MS}ms)"

+ 4 - 2
tools/desktops/fullscreen_window.py

@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
-"""A plain X11 window that asks the window manager for fullscreen and stays until killed (tests/desktops)."""
+"""A plain X11 window that asks the window manager for fullscreen (or, with "maximize", maximized) and stays until killed (tests/desktops)."""
 import signal
 import sys
 
@@ -10,8 +10,10 @@ 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")
+states = ["_NET_WM_STATE_MAXIMIZED_VERT", "_NET_WM_STATE_MAXIMIZED_HORZ"] if sys.argv[1:2] == ["maximize"] \
+    else ["_NET_WM_STATE_FULLSCREEN"]
 window.change_property(d.intern_atom("_NET_WM_STATE"), d.intern_atom("ATOM"), 32,
-                       [d.intern_atom("_NET_WM_STATE_FULLSCREEN")])
+                       [d.intern_atom(name) for name in states])
 window.map()
 d.flush()
 signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))

+ 52 - 0
tools/fuzz/json.cpp

@@ -0,0 +1,52 @@
+#include "WallpaperEngine/Assets/AssetLocator.h"
+#include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Parsers/MaterialParser.h"
+#include "WallpaperEngine/Data/Parsers/ObjectParser.h"
+#include "WallpaperEngine/Data/Parsers/ProjectParser.h"
+#include "WallpaperEngine/Data/Parsers/WallpaperParser.h"
+#include "WallpaperEngine/FileSystem/Container.h"
+
+#include <tuple>
+
+using namespace WallpaperEngine;
+using Data::JSON::JSON;
+
+namespace {
+Assets::AssetLocatorUniquePtr emptyAssets () {
+    return std::make_unique<Assets::AssetLocator> (std::make_unique<FileSystem::Container> ());
+}
+}
+
+// the input is read as every kind of JSON file the loader knows: project, scene, object, material
+extern "C" int LLVMFuzzerTestOneInput (const uint8_t* data, size_t size) {
+    JSON json;
+
+    try {
+	json = JSON::parseAsset (std::string (reinterpret_cast<const char*> (data), size));
+    } catch (const std::exception&) {
+	return 0;
+    }
+
+    Data::Model::Project project {};
+    project.assetLocator = emptyAssets ();
+
+    try {
+	std::ignore = Data::Parsers::ProjectParser::parse (json, emptyAssets ());
+    } catch (const std::exception&) { }
+
+    try {
+	std::ignore = Data::Parsers::ObjectParser::parse (json, project);
+    } catch (const std::exception&) { }
+
+    try {
+	std::ignore = Data::Parsers::WallpaperParser::parse (json, project);
+    } catch (const std::exception&) { }
+
+    try {
+	std::ignore = Data::Parsers::MaterialParser::parse (json, "fuzz.json", project);
+    } catch (const std::exception&) { }
+
+    return 0;
+}

+ 43 - 0
tools/fuzz/mdl.cpp

@@ -0,0 +1,43 @@
+#include "WallpaperEngine/Render/Objects/PuppetClipping.h"
+#include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
+#include "WallpaperEngine/Render/Objects/PuppetRig.h"
+
+#include <tuple>
+#include <vector>
+
+using namespace WallpaperEngine::Render::Objects;
+
+extern "C" int LLVMFuzzerTestOneInput (const uint8_t* bytes, size_t size) {
+    const std::vector<char> data (reinterpret_cast<const char*> (bytes), reinterpret_cast<const char*> (bytes) + size);
+    const auto mesh = readPuppetMeshFile (data);
+
+    try {
+	std::ignore = readMdlvMeshes (data);
+    } catch (const std::exception&) { }
+
+    if (!mesh.has_value ()) {
+	return 0;
+    }
+
+    try {
+	auto clipping = PuppetClipping::read (data, mesh->indexEnd, mesh->version, mesh->indices.size ());
+
+	if (clipping.has_value ()) {
+	    clipping->build (mesh->indices);
+	}
+    } catch (const std::exception&) { }
+
+    if (mesh->skeleton < data.size () && !mesh->blendIndices.empty ()) {
+	try {
+	    PuppetRig rig;
+	    rig.load (data, mesh->sections, mesh->meshCount, "fuzz");
+	    rig.addSceneLayers ({});
+
+	    for (int i = 0; i < 4; i++) {
+		rig.updatePose (glm::mat4 (1.0f));
+	    }
+	} catch (const std::exception&) { }
+    }
+
+    return 0;
+}

+ 26 - 0
tools/fuzz/package.cpp

@@ -0,0 +1,26 @@
+#include "WallpaperEngine/Data/Parsers/PackageParser.h"
+#include "WallpaperEngine/FileSystem/Adapters/Package.h"
+
+#include <iterator>
+#include <sstream>
+
+using namespace WallpaperEngine;
+
+extern "C" int LLVMFuzzerTestOneInput (const uint8_t* data, size_t size) {
+    auto stream = std::make_shared<std::istringstream> (
+	std::string (reinterpret_cast<const char*> (data), size), std::ios::binary
+    );
+
+    try {
+	FileSystem::Adapters::PackageAdapter adapter (Data::Parsers::PackageParser::parse (stream));
+
+	for (const auto& entry : adapter.package->files) {
+	    try {
+		const auto handle = adapter.open (entry->filename);
+		std::string content ((std::istreambuf_iterator<char> (*handle)), std::istreambuf_iterator<char> ());
+	    } catch (const std::exception&) { }
+	}
+    } catch (const std::exception&) { }
+
+    return 0;
+}

+ 27 - 0
tools/fuzz/sog.cpp

@@ -0,0 +1,27 @@
+#include "WallpaperEngine/Splat/SogLoader.h"
+
+#include <cstring>
+#include <string>
+
+using namespace WallpaperEngine::Splat;
+
+// the first two bytes give the length of the meta JSON, whatever follows is what every file of the cloud reads as
+extern "C" int LLVMFuzzerTestOneInput (const uint8_t* data, size_t size) {
+    if (size < 2) {
+	return 0;
+    }
+
+    const size_t metaSize = std::min<size_t> ((data[0] | (data[1] << 8)), size - 2);
+    const std::string meta (reinterpret_cast<const char*> (data) + 2, metaSize);
+    const std::string payload (reinterpret_cast<const char*> (data) + 2 + metaSize, size - 2 - metaSize);
+
+    try {
+	std::ignore = loadSog (meta, [&] (const std::string&) { return payload; });
+    } catch (const std::exception&) { }
+
+    try {
+	std::ignore = decodeWebP (payload);
+    } catch (const std::exception&) { }
+
+    return 0;
+}

+ 20 - 0
tools/fuzz/texture.cpp

@@ -0,0 +1,20 @@
+#include "WallpaperEngine/Data/Parsers/TextureParser.h"
+#include "WallpaperEngine/Data/Utils/BinaryReader.h"
+
+#include <sstream>
+#include <tuple>
+
+using namespace WallpaperEngine::Data;
+
+extern "C" int LLVMFuzzerTestOneInput (const uint8_t* data, size_t size) {
+    auto stream = std::make_shared<std::istringstream> (
+	std::string (reinterpret_cast<const char*> (data), size), std::ios::binary
+    );
+
+    try {
+	Utils::BinaryReader reader (stream);
+	std::ignore = Parsers::TextureParser::parse (reader);
+    } catch (const std::exception&) { }
+
+    return 0;
+}

+ 26 - 8
tools/linuxvm/RELEASE_TESTING.md

@@ -42,6 +42,7 @@ check (clang-format 22 on `src`) and a build of both CMake variants (`DISABLE_KD
 | mx-xfce | XFCE X11 (MX Linux 25.3, Debian 13 based) | portable + .deb | second monitor, we_manager's .deb self update |
 | popos-cosmic | COSMIC | portable + .deb | layer shell and window states (`zcosmic_toplevel_info`) on cosmic-comp |
 | steamos | Plasma Wayland, read-only root | portable | Steam Deck image on an NVMe disk with Valve SMBIOS, `WEM_LAUNCH` (see below), no dependency install (immutable) |
+| steamdeck | Plasma Wayland, read-only root | portable | the steamos disk as its own golden, but shaped like the hardware (`vm.env`: 1280x800, 4 cores, 16G, Zen 2 CPU model, Valve Jupiter SMBIOS) with a fake battery (`test_power` kernel module, seen by UPower); `deck_check.sh` runs the Steam Deck preset's arguments and follows the battery down and up again |
 | bazzite | KDE, immutable | portable + Flatpak | rpm-ostree: dependency install refused, Flatpak |
 
 A new distro joins the matrix once its VM has a profile and a golden snapshot. ChimeraOS is not in it: its image installs and
@@ -67,6 +68,13 @@ in the log), missing frames, black desktop, a leftover process, a log line match
 After a failed first pass the driver repeats only the failed groups in the same boot. A failure that only shows in the retry
 is a state problem of the session, not of the first run.
 
+## Web frames (guest_test.sh, every wallpaper run)
+
+The engine runs with `LWE_WEB_STATS=1`; each web wallpaper reports `web frames arrive as dmabufs` or `through shared memory`, and
+fails when `--web-frames auto` picked dmabuf and fell back to shm ("restarting the web host"). Expected: dmabuf on every
+Wayland desktop and on X11 where a web wallpaper is the startup background, shm for web wallpapers swapped in later on X11
+and on NVIDIA's proprietary driver.
+
 ## Regression checks for known bugs (guest_test.sh, BEHAVIOR=1)
 
 Run on every VM of the matrix, each one SKIPs where the guest cannot do it:
@@ -105,10 +113,13 @@ Run on every VM of the matrix, each one SKIPs where the guest cannot do it:
 All of it lives in `tools/linuxvm/`:
 
 - `profiles/<vm>.sh`: how to reach the session (`SCREEN`, `SHOT_CMD`, `FULLSCREEN_CMD`, `MAXIMIZE_CMD`, `WEM`, `WEM_FLAGS`,
-  `WEM_LAUNCH`, `PREP`, `MULTI`, `POINTER`, `LOGIN_PASSWORD` for greeters without autologin). `WEM_LAUNCH` is the prefix of the
+  `WEM_LAUNCH`, `PREP`, `MULTI`, `POINTER`, `POINTER_DOCK_XY` for a desktop whose own dock covers the pointer spot of the dock check, `LOGIN_PASSWORD` for greeters without autologin). `WEM_LAUNCH` is the prefix of the
   we_manager start line: SteamOS needs `systemd-run --user --scope -q` because a process started from an ssh session dies with it.
 - `linuxvm.sh golden <vm>` / `fresh <vm>`: the VM's disk is frozen as `golden.qcow2` and runs on a throwaway overlay, `fresh`
   throws the overlay away. Every VM of the matrix has one.
+- `<vm>/vm.env` (sourced by `linuxvm.sh start`): `LINUXVM_SIZE`, `LINUXVM_CPUS`, `LINUXVM_MEM` and `LINUXVM_CPU` (the QEMU `-cpu` model) for that VM alone.
+  The `steamdeck` VM was made by copying `steamos`'s golden disk (new port, `qemu-extra`, `vm.env`) and adding
+  `/etc/modules-load.d/test_power.conf` + `/etc/modprobe.d/test_power.conf` (AC and USB off, battery discharging) before `golden`.
 - `release_check.sh [--vm name]... [--candidate dir] [--app dir|.deb] [--engine-tarball tgz] [--no-overlay]`: loops over the
   profiles sequentially, writes `<REPORT_DIR>/summary.md` (default `reports/<date>/`) with screenshots and logs per VM, retries the
   failed checks once, powers the VM off (ssh `systemctl poweroff`, ACPI does not reach a locked KDE session) and resets the
@@ -116,7 +127,7 @@ All of it lives in `tools/linuxvm/`:
 - `guest_test.sh` (one PASS/FAIL/SKIP line per check; BEHAVIOR=1 adds hotswap, fullscreen and maximized pause through
   `pause_check`, SIGKILL cleanup), `run_behavior.sh` (the same by hand), `pointer_check.sh` and `hover_check.py` (the pointer
   checks), `host_shots.sh` (screenshots through the VM's display, and a click on the screen centre so a test window gets the
-  focus), `check_frame.py` (black/flat/unchanged/hotswap differs, Pillow, run with `-I`).
+  focus), `check_frame.py` (black/flat/unchanged/hotswap differs, and `--reference` against `reference/<id>.png`: upside down, mirrored or another crop; Pillow, run with `-I`). `make_reference_frames.sh` renders those references headlessly from the payload (video wallpapers have none). On X11 sessions `guest_test.sh` also runs a `windowbg` group (`--window --window-background` on the output's geometry).
 - `clean_install_check.sh` (a first install of the prebuilt engine through we_manager), `wem_check.sh` (we_manager install,
   launch, stop, kill all, autostart entry), `update_check.sh` (`fake_github.py` serving a newer app .deb, `bump_deb.py`, and the
   candidate engine as a newer release), `deps_check.sh` (the "install build dependencies" button on the VM's package manager,
@@ -132,6 +143,7 @@ All of it lives in `tools/linuxvm/`:
   characters under load). `bootstrap_ssh.sh <vm> <port> <us|de>` sets up ssh in an ISO installed VM: it serves a setup script from
   the host and runs it in a terminal already open in the guest (`FETCH='wget -q'` where curl is missing). `<vm>/qemu-extra` holds
   extra QEMU arguments (SteamOS: NVMe disk and Valve SMBIOS, MX Linux: the ISO as USB disk).
+- `update_golden_extension.sh <vm>...` puts the repo's GNOME Shell extension.js onto the golden disks of GNOME VMs (fresh overlay, replace the file, `qemu-img commit` into `golden.qcow2`).
 - GNOME Shell extension debugging without touching the golden disks: `debug_extension.py <dir>` builds the extension with `LWE_DBG`
   journal lines, `ghost_run.sh <vm> <tag> [extension.js]` runs `release_check.sh` on an overlay that has that extension (needs
   `LWE_CANDIDATE`, `LWE_ENGINE_TARBALL`, `LWE_APP_DEB` or `LWE_APP_DIR`, writes `reports/ghost/<vm>-<tag>/shell-debug.log`),
@@ -181,12 +193,18 @@ overlays gone.
 
 ## Known problems and open items
 
-- **elementary** stays red: the default Wayland session (Gala) has no wlr-layer-shell, the engine cannot start.
+- **elementary** (Gala has no wlr-layer-shell): the engine draws through XWayland there (2026-10-21, 73 checks pass), so only X11 windows pause it,
+  the profile's test window is an XWayland one and there is no maximize check.
 - **Frozen wallpaper on GNOME 46** (Ubuntu, Zorin): Mutter frees a wallpaper window without unmanaging it, and its actor stays in
   the Shell's window group with the last frame (`hot-after` identical to `hot-before`, no engine alive). It turns up in a minority
   of full runs, so a single clean run proves little. A ghost shows as a surplus wallpaper `MetaWindowActor` in the `GROUP` lines of
-  the debug extension. The extension hides such orphans (`_hideOrphanActors`). The golden disks of the GNOME VMs (ubuntu-gnome,
-  zorin-gnome, debian-gnome, fedora-gnome) still carry the old extension: until they are updated, `ghost_run.sh` is the way to run
-  the shipped one.
-- Reference frames per wallpaper for `check_frame.py` (upside down, wrong crop) are still missing; the checks compare with the
-  previous run.
+  the debug extension. The extension hides such orphans (`_hideOrphanActors`), and the golden disks of the GNOME VMs carry the fixed one since
+  2026-10-21 (`update_golden_extension.sh`).
+- **Running the matrix in lanes** (2026-10-22): four lanes at once fit in 30 GB (about 5 GB resident per VM), a fifth is fine for harness
+  work. A lane is `release_check.sh --vm <name>` per VM one after the other, each with its own report folder. Under that load a few windows
+  turn up later than the 20 s settle in `release_check.sh`: we_manager's autostarted window on a Debian GNOME guest and Steam's sign-in on
+  SteamOS/Steam Deck, both are closed once more after the settle. An app that restarts after its own .deb update (MX) can drop the first
+  `installPrebuilt()` call, `update_check.sh` asks up to three times.
+- **Electron's `EGL_PLATFORM=wayland`** reaches the engine when we_manager starts it in a Wayland session. The X11 driver (XWayland
+  fallback on elementary, a web wallpaper as startup background) makes its EGL display under it and crashed in libwayland-client, only
+  through we_manager (a shell start had no such variable). The GLFW driver drops the variable before `glfwInit`.

+ 59 - 3
tools/linuxvm/check_frame.py

@@ -1,17 +1,20 @@
 """check_frame.py [--baseline base.png] shot.png [shot.png ...] - did the wallpaper reach the screen?
 check_frame.py --differ a.png b.png - do two frames differ (hotswap)?
 check_frame.py --similar a.png b.png [max] - are two frames of the same wallpaper alike (a hotswap must look like a fresh start)?
+check_frame.py --reference ref.png shot.png [shot.png ...] - does the shot look like the reference frame of that wallpaper (reference/<id>.png,
+make_reference_frames.sh), not upside down or mirrored, not another crop?
 check_frame.py --crop from,to [--baseline base.png] shot.png - only the part of the width between the two fractions (one
 monitor of a multi monitor screenshot)
 
 Without --baseline a screenshot only fails when it is pure black. With the baseline (the desktop's own screenshot taken
 before the engine started) it must also differ from it along the right edge and the top, where windows, panels and
 desktop icons rarely are, so a desktop that still shows its default background fails. Prints one "PASS|FAIL <file>: <why>"
-line per file, exit code 1 when any failed. Reference frames per wallpaper (upside down, wrong crop) would be the next
-step, see RELEASE_TESTING.md.
+line per file, exit code 1 when any failed. With --reference the middle of the shot is compared cell by cell with the
+reference frame of the wallpaper: enough cells must match (a window or an animation may cover some), and when too few do
+and the flipped reference matches clearly better the shot is reported as upside down or mirrored.
 """
 import sys
-from PIL import Image, ImageChops, ImageStat
+from PIL import Image, ImageChops, ImageOps, ImageStat
 
 
 def strips(image):
@@ -53,6 +56,51 @@ def check(path, baseline):
     return True, f"mean {mean:.0f}, stddev {stddev:.0f}"
 
 
+GRID = (32, 18)
+MIDDLE = (0.08, 0.08, 0.92, 0.86)
+CELL_LIMIT = 36
+MATCH_RATIO = 0.5
+
+
+def cells(image):
+    w, h = image.size
+    middle = image.crop((int(w * MIDDLE[0]), int(h * MIDDLE[1]), int(w * MIDDLE[2]), int(h * MIDDLE[3])))
+    small = middle.resize(GRID, Image.BOX)
+    return list(small.get_flattened_data() if hasattr(small, "get_flattened_data") else small.getdata())
+
+
+def match_ratio(a, b):
+    close = sum(1 for p, q in zip(a, b) if sum(abs(x - y) for x, y in zip(p, q)) / 3 <= CELL_LIMIT)
+    return close / len(a)
+
+
+def fill_crop(reference, size):
+    """the scene fills the screen and crops whichever axis overflows, so the reference is cut to the shot's shape"""
+    w, h = reference.size
+    wanted = size[0] / size[1]
+    if abs(w / h - wanted) < 0.02:
+        return reference
+    if w / h > wanted:
+        width = round(h * wanted)
+        return reference.crop(((w - width) // 2, 0, (w - width) // 2 + width, h))
+    height = round(w / wanted)
+    return reference.crop((0, (h - height) // 2, w, (h - height) // 2 + height))
+
+
+def check_reference(path, reference):
+    image = crop(Image.open(path).convert("RGB"))
+    reference = fill_crop(reference, image.size)
+    shot = cells(image)
+    straight = match_ratio(shot, cells(reference))
+    for name, flipped in (("upside down", ImageOps.flip(reference)), ("mirrored", ImageOps.mirror(reference))):
+        ratio = match_ratio(shot, cells(flipped))
+        if ratio >= 0.6 and ratio >= straight + 0.15:
+            return False, f"{name} ({ratio:.0%} of the cells match the flipped reference, {straight:.0%} the reference)"
+    if straight < MATCH_RATIO:
+        return False, f"does not look like the reference (only {straight:.0%} of the cells match)"
+    return True, f"{straight:.0%} of the cells match the reference"
+
+
 def differ(a, b):
     """Two frames of the same desktop must differ clearly (a hotswap changed the picture)."""
     first, second = Image.open(a).convert("RGB"), Image.open(b).convert("RGB").resize(Image.open(a).size)
@@ -82,6 +130,14 @@ def main():
         args = args[2:]
     if args[:1] == ["--differ"]:
         differ(args[1], args[2])
+    if args[:1] == ["--reference"]:
+        reference = Image.open(args[1]).convert("RGB")
+        failed = False
+        for path in args[2:]:
+            ok, why = check_reference(path, reference)
+            failed |= not ok
+            print(f"{'PASS' if ok else 'FAIL'} {path}: {why}")
+        sys.exit(1 if failed else 0)
     baseline = None
     if args[:1] == ["--baseline"]:
         baseline = Image.open(args[1]).convert("RGB")

+ 71 - 0
tools/linuxvm/deck_check.sh

@@ -0,0 +1,71 @@
+#!/bin/bash
+# deck_check.sh - in the steamdeck VM: the Steam Deck preset's engine arguments run, and the engine follows the fake
+# battery (the test_power kernel module, seen by UPower like a real one) down to battery FPS and back to external power.
+# Env: SCREEN (the --screen-root name). Prints PASS/FAIL lines.
+LWE_DIR=$HOME/lwe
+ENGINE=$LWE_DIR/lwe-hints/linux-wallpaperengine
+WP=$LWE_DIR/wp-3471294034
+OUT=/tmp/lwe-test/deck
+PARAMS=/sys/module/test_power/parameters
+mkdir -p "$OUT"
+
+pass() { echo "PASS $*"; }
+fail() { echo "FAIL $*"; }
+
+power() {
+    sudo -n sh -c "echo $1 > $PARAMS/ac_online; echo $2 > $PARAMS/battery_status"
+}
+
+wait_for() {
+    local pattern=$1 count=$2 n
+    for n in $(seq 30); do
+        [ "$(grep -c "$pattern" "$OUT/engine.log")" -ge "$count" ] && return 0
+        sleep 1
+    done
+    return 1
+}
+
+[ -d $PARAMS ] || sudo -n modprobe test_power
+power off discharging
+for _ in $(seq 10); do
+    [ "$(busctl --system get-property org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower OnBattery)" = "b true" ] && break
+    sleep 1
+done
+if [ "$(busctl --system get-property org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower OnBattery)" = "b true" ]; then
+    pass "deck: UPower reports the fake battery as discharging"
+else
+    fail "deck: UPower does not report the fake battery as discharging"
+    exit 0
+fi
+
+# what we_manager's Steam Deck preset launches with
+args="--fps 30 --no-audio-processing --volumetrics low --shadows low --fps-battery 15 --idle-pause 5"
+(setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" --screen-root "$SCREEN" $args "$WP" > "$OUT/engine.log" 2>&1 < /dev/null &)
+
+if wait_for "Power: running on battery" 1; then
+    pass "deck: preset arguments start the engine, it sees the battery"
+else
+    fail "deck: no 'running on battery' line with the preset arguments ($(tail -n 3 "$OUT/engine.log" | tr '\n' ' '))"
+fi
+
+power on charging
+if wait_for "Power: on external power" 1; then
+    pass "deck: engine notices the charger"
+else
+    fail "deck: engine did not notice the charger"
+fi
+
+power off discharging
+if wait_for "Power: running on battery" 2; then
+    pass "deck: engine notices the charger being unplugged"
+else
+    fail "deck: engine did not notice the battery again"
+fi
+
+if pgrep -f "[l]inux-wallpaperengine.bin.*fps-battery 15" > /dev/null; then
+    pass "deck: engine still running"
+else
+    fail "deck: engine died"
+fi
+pkill -f "[l]inux-wallpaperengine.bin.*fps-battery 15"
+exit 0

+ 25 - 1
tools/linuxvm/guest_test.sh

@@ -10,13 +10,15 @@
 #   WALLPAPERS    ids to run, default: scene with parallax, scene with particles, two web items
 #   SETTLE        seconds to wait for the first frames (default 25), the checks that do not compare frames at a fixed time
 #                 go on as soon as the engine says it draws (a few seconds more, web pages need longer)
-#   ONLY          space separated check groups to run (wallpapers behavior video cycle automute multi), default all
+#   ONLY          space separated check groups to run (wallpapers behavior video cycle automute multi windowbg), default all
 #   MINIMIZE_CMD  minimizes the test window (X11): the engine paused by a fullscreen window must resume once it is hidden
 #   MULTI_SHOT_CMD  screenshot command that captures every monitor (the VM was started with a second output): turns on
 #                 the multi monitor check, the wallpaper must show on both screens
 # resolved: the engine's command line shows the real path (/var/home on Fedora Atomic systems)
 LWE_DIR=$(realpath "${LWE_DIR:-$HOME/lwe}")
 ENGINE=$LWE_DIR/lwe-hints/linux-wallpaperengine
+# says which way a web wallpaper gets its frames
+export LWE_WEB_STATS=1
 OUT=${OUT:-/tmp/lwe-test}
 WALLPAPERS=${WALLPAPERS-"1111948150 1120596121 1078208425 834237690"}
 SETTLE=${SETTLE:-25}
@@ -77,6 +79,12 @@ for id in $WALLPAPERS; do
     total=$((total + 1))
     if engine_pids >/dev/null; then pass "$id: engine running"; else fail "$id: engine exited"; bad_start=$((bad_start + 1)); fi
     if grep -qiE "segmentation|SIGSEGV|terminate called|Aborted|core dumped" "$log"; then fail "$id: crash text in the log"; else pass "$id: no crash text in the log"; fi
+    if grep -qi '"type"[[:space:]]*:[[:space:]]*"web"' "$dir/project.json" 2>/dev/null; then
+        # --web-frames auto picks dmabuf frames on a Wayland session with EGL; a fallback means it did not work there
+        if grep -q "restarting the web host with shared memory frames" "$log"; then fail "$id: dmabuf web frames fell back to shared memory"
+        elif grep -q "frames arrive as dmabufs" "$log"; then pass "$id: web frames arrive as dmabufs"
+        else pass "$id: web frames through shared memory"; fi
+    fi
 
     SHOT_FILE=$OUT/shot-$id.png
     rm -f "$SHOT_FILE"
@@ -295,6 +303,21 @@ hotswap_cycle_check() {
     stop_engine
 }
 
+window_background_check() {
+    local id=1120596121 log=$OUT/engine-windowbg.log geometry
+    [ "${XDG_SESSION_TYPE:-}" = x11 ] && command -v xrandr >/dev/null || return 0
+    [ -d "$LWE_DIR/wp-$id" ] || { echo "SKIP window background: wallpaper $id missing"; return 0; }
+    geometry=$(xrandr | sed -n 's/^[^ ]* connected \(primary \)\?\([0-9]*\)x\([0-9]*\)+\([0-9]*\)+\([0-9]*\).*/\4x\5x\2x\3/p' | head -1)
+    [ -n "$geometry" ] || { echo "SKIP window background: no output geometry from xrandr"; return 0; }
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" --window "$geometry" --window-background "$LWE_DIR/wp-$id" > "$log" 2>&1 < /dev/null &)
+    settle "$log" "$id"
+    if engine_pids >/dev/null; then pass "window background: engine running"; else fail "window background: engine exited"; return 0; fi
+    SHOT_FILE=$OUT/shot-windowbg-$id.png; rm -f "$SHOT_FILE"; take_shot "$SHOT_FILE" "$OUT/windowbg.log"
+    if [ -s "$SHOT_FILE" ]; then pass "window background: screenshot taken"; else fail "window background: no screenshot"; fi
+    if stop_engine; then pass "window background: engine stopped on SIGTERM"; else fail "window background: engine needed SIGKILL"; fi
+}
+
 multi_monitor_check() {
     local id=1111948150 w1 w2
     [ -n "$MULTI_SHOT_CMD" ] || return
@@ -363,6 +386,7 @@ if [ "${BEHAVIOR:-0}" = 1 ]; then
     want cycle && hotswap_cycle_check
     want automute && automute_check
     want multi && multi_monitor_check
+    want windowbg && window_background_check
 fi
 
 touch "$OUT/done"

+ 30 - 0
tools/linuxvm/hide_steam_kde.sh

@@ -0,0 +1,30 @@
+#!/bin/bash
+# hide_steam_kde.sh - freezes Steam and minimizes its windows with a KWin script. On the Steam Deck shaped VM the client starts
+# with -steamdeck, updates itself a few minutes after login and then takes the whole screen (the VM's display reads "not active"),
+# a stopped client stays where it is and its sign-in window no longer covers the wallpaper.
+freeze() {
+    pkill -STOP -f '[u]buntu12_32/steam'
+    pkill -STOP -f '[s]teamwebhelper'
+}
+if [ "$1" = --watch ]; then
+    # Steam is not running yet this early after login: keep stopping what shows up for 15 minutes
+    (setsid nohup bash -c 'for _ in $(seq 900); do pkill -STOP -f "[u]buntu12_32/steam"; pkill -STOP -f "[s]teamwebhelper"; sleep 1; done' >/dev/null 2>&1 &)
+    exit 0
+fi
+freeze
+script=$(mktemp /tmp/lwe-hide-steam-XXXXXX.js)
+echo 'for (const w of workspace.windowList ()) { if (String (w.resourceClass).toLowerCase ().includes ("steam")) { w.minimized = true; } }' > "$script"
+live=$(gdbus introspect --session --dest org.kde.KWin --object-path /Scripting | grep -o 'node Script[0-9]*' | tr -dc '0-9\n')
+names=()
+for attempt in 0 1 2 3; do
+    name=lwe-hide-steam-$attempt
+    id=$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$script" "$name" | tr -dc '0-9')
+    names+=("$name")
+    echo "$live" | grep -qx "$id" || break
+done
+gdbus call --session --dest org.kde.KWin --object-path "/Scripting/Script$id" --method org.kde.kwin.Script.run >/dev/null
+sleep 2
+for name in "${names[@]}"; do
+    gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.unloadScript "$name" >/dev/null
+done
+rm -f "$script"

+ 2 - 1
tools/linuxvm/host_shots.sh

@@ -2,7 +2,7 @@
 # host_shots.sh <vm> <guest out dir> [seconds] - serves the "SHOT_CMD=host" requests of guest_test.sh: whenever the guest
 # creates <file>.png.want, takes a screenshot of the VM's display (the same VNC socket `linuxvm.sh shot` uses) and copies
 # it into the guest as <file>.png, and clicks the screen's centre for every <file>.click (focus for a test window). Runs until the seconds (default 900) are over or the guest's test run has finished
-# (the guest creates <out dir>/done).
+# (the guest creates <out dir>/done). A pointer move comes first, a guest whose screen went idle (Steam Deck VM) shows "Display output is not active" otherwise.
 HERE=$(cd "$(dirname "$0")" && pwd)
 vm=$1 out=$2 limit=${3:-900}
 tmp=$(mktemp -d)
@@ -17,6 +17,7 @@ while [ $SECONDS -lt $end ]; do
     done
     for want in $(echo "$wanted" | grep '\.want$'); do
         name=$(basename "${want%.want}")
+        "$HERE/linuxvm.sh" pointer "$vm" 3 3 >/dev/null 2>&1; "$HERE/linuxvm.sh" pointer "$vm" 5 4 >/dev/null 2>&1; sleep 1
         "$HERE/linuxvm.sh" shot "$vm" "$tmp/$name" && "$HERE/linuxvm.sh" scp "$vm" "$tmp/$name" "${want%.want}" \
             && "$HERE/linuxvm.sh" ssh "$vm" "rm -f $want" </dev/null
     done

+ 3 - 1
tools/linuxvm/linuxvm.sh

@@ -19,6 +19,7 @@
 #   shot <vm> <png>       screenshot through the VNC socket (vncshot.py); pointer/click/keys/type/raw go to qmp.py
 #   golden <vm>           freezes a stopped VM's disk as golden.qcow2 (and its UEFI vars) and puts a throwaway overlay on top
 #   fresh <vm>            throws the overlay away: the next start begins from the golden state again (release_check.sh)
+#   a file <vm>/vm.env sets LINUXVM_SIZE, LINUXVM_CPUS, LINUXVM_MEM and LINUXVM_CPU (QEMU -cpu model) for that VM (steamdeck: 1280x800, 4 cores, 16G, Zen 2)
 #   a file <vm>/qemu-extra holds extra QEMU arguments (SteamOS: NVMe disk, Valve SMBIOS, the recovery image as USB disk)
 #   stop | kill <vm>      ACPI power off | kill QEMU
 # QEMU's virtio-gpu and egl-headless modules are not in the image's qemu-system-x86-core: `fetch` unpacks the Fedora
@@ -123,6 +124,7 @@ create-iso)
 start)
     vm=$2 dir=$(vmdir "$2")
     [ -f "$dir/qemu.pid" ] && kill -0 "$(cat "$dir/qemu.pid")" 2>/dev/null && { echo running; exit 0; }
+    [ -f "$dir/vm.env" ] && . "$dir/vm.env"
     size=${LINUXVM_SIZE:-1920x1080}
     display=(-display egl-headless,rendernode="${LINUXVM_RENDERNODE:-/dev/dri/renderD128}")
     extra=(-vnc unix:"$dir/vnc.sock")
@@ -133,7 +135,7 @@ start)
             -device virtserialport,chardev=vdagent,name=com.redhat.spice.0)
     fi
     QEMU_MODULE_DIR=$LINUXVM/root/usr/lib64/qemu LD_LIBRARY_PATH=$LINUXVM/root/usr/lib64 \
-    qemu-system-x86_64 -name "$vm" -machine q35 -accel kvm -cpu host -smp "${LINUXVM_CPUS:-8}" -m "${LINUXVM_MEM:-8G}" \
+    qemu-system-x86_64 -name "$vm" -machine q35 -accel kvm -cpu "${LINUXVM_CPU:-host}" -smp "${LINUXVM_CPUS:-8}" -m "${LINUXVM_MEM:-8G}" \
         -drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/ovmf/OVMF_CODE.fd \
         -drive if=pflash,format=raw,file="$dir/vars.fd" \
         -drive file="$dir/disk.qcow2",if=virtio,format=qcow2,cache=unsafe,discard=unmap \

+ 26 - 0
tools/linuxvm/make_reference_frames.sh

@@ -0,0 +1,26 @@
+#!/bin/bash
+# make_reference_frames.sh [binary] [payload dir] - renders the test wallpapers of the VM payload headlessly at 1920x1080 and keeps
+# a 192x108 copy of each in reference/<id>.png, what check_frame.py --reference compares the VM screenshots with (upside down,
+# wrong crop). Video wallpapers are left out, their frame depends on the moment of the shot. Needs a GPU render node.
+HERE=$(cd "$(dirname "$0")" && pwd)
+binary=${1:-$HERE/../../build/output/linux-wallpaperengine}
+payload=${2:-$HOME/.local/share/linuxvm/payload}
+tmp=$(mktemp -d)
+trap 'rm -rf "$tmp"' EXIT
+mkdir -p "$HERE/reference"
+for dir in "$payload"/wp-*; do
+    id=${dir##*wp-}
+    type=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1] + '/project.json')).get('type', ''))" "$dir")
+    case $type in
+    video) continue ;;
+    web) export HEADLESS_RENDER_WEB=1 HEADLESS_RENDER_DELAY=700 HEADLESS_RENDER_TIMEOUT=120 ;;
+    *) unset HEADLESS_RENDER_WEB; export HEADLESS_RENDER_DELAY=150 HEADLESS_RENDER_TIMEOUT=60 ;;
+    esac
+    if HEADLESS_RENDER_SIZE=1920x1080 "$HERE/../headless_render.sh" "$binary" "$tmp/$id.png" --assets-dir "$payload/assets" "$dir" > "$tmp/$id.log" 2>&1 \
+        && [ -s "$tmp/$id.png" ]; then
+        python3 -I -c "import sys; from PIL import Image; Image.open(sys.argv[1]).convert('RGB').resize((192, 108), Image.LANCZOS).save(sys.argv[2])" \
+            "$tmp/$id.png" "$HERE/reference/$id.png" && echo "$id ($type): reference written"
+    else
+        echo "$id ($type): render failed, see $tmp/$id.log"; cp "$tmp/$id.log" "/tmp/make_reference_$id.log" 2>/dev/null
+    fi
+done

+ 2 - 2
tools/linuxvm/pointer_check.sh

@@ -15,7 +15,7 @@ sshv 'pkill -f "[l]inux-wallpaperengine.bin"; pkill -x we-manager; true'
 sshv 'pkill -f "[x]fce4-display-settings"; pkill -f "[u]pdate-manager"; pkill -f "[r]elease-upgrader"; pkill -f "[u]pdate-notifier"; pkill -x cachyos-hello; pkill -f "[e]os-welcome|[m]x-welcome|[g]aruda-welcome|[m]anjaro-hello|[m]int-welcome|[z]orin-welcome|[p]op-welcome|[m]intupdate|[m]intUpdate|[m]intreport|[m]intwelcome"; true'
 # SteamOS starts Steam's sign-in window at login
 sshv 'pkill -x steam; pkill -f "[s]teamwebhelper"; true'
-sshv ". ~/sessenv; (setsid ${WEM_LAUNCH:-} nohup ~/lwe/lwe-hints/linux-wallpaperengine --assets-dir ~/lwe/assets $LWE_ARGS_EXTRA --screen-root $screen ~/lwe/wp-3599498791 > /tmp/pointer-check.log 2>&1 < /dev/null &)"
+sshv ". ~/sessenv; (setsid ${WEM_LAUNCH:-} nohup ~/lwe/lwe-hints/linux-wallpaperengine --assets-dir ~/lwe/assets $LWE_ARGS_EXTRA --screen-root $screen ~/lwe/wp-3599498791 > /tmp/pointer-check.log 2>&1 < /dev/null &); sleep 6"
 for _ in $(seq 60); do sshv 'grep -q "drawing at scale" /tmp/pointer-check.log' && break; sleep 2; done
 sleep 30
 # welcome apps start late on some distributions, once more now that the engine runs
@@ -23,7 +23,7 @@ sshv 'pkill -f "[x]fce4-display-settings"; pkill -f "[u]pdate-manager"; pkill -f
 # a welcome window that survives its process name (EndeavourOS): close it by title
 sshv '. ~/sessenv; wmctrl -c "Welcome" 2>/dev/null; wmctrl -c "Plugin loading failure" 2>/dev/null; for w in $(xdotool search --name "^Welcome" 2>/dev/null); do xdotool windowclose $w; done; true'
 if ! sshv 'pgrep -f "[l]inux-wallpaperengine.bin" >/dev/null'; then echo "FAIL weekday hover: the engine did not stay running on 3599498791"; exit 1; fi
-for spot in mon:713,451 sun:714,625 dock:960,1010 top:960,60; do
+for spot in mon:713,451 sun:714,625 dock:${POINTER_DOCK_XY:-960,1010} top:960,60; do
     name=${spot%%:*} xy=${spot#*:}
     sshv '. ~/sessenv; wmctrl -c "Welcome" 2>/dev/null; wmctrl -c "Plugin loading failure" 2>/dev/null; for w in $(xdotool search --name "^Welcome" 2>/dev/null); do xdotool windowclose $w; done; true'
     lv pointer "$vm" "${xy%,*}" "${xy#*,}" >/dev/null 2>&1

+ 2 - 0
tools/linuxvm/profiles/arch-hypr.sh

@@ -1,3 +1,5 @@
+# Hyprland: layer shell, per output pause; maximized windows do not pause here (wlroots rule, needs --pause-on-maximized), so no
+# MAXIMIZE_CMD. The idle inhibitor keeps the session from blanking, sessenv.sh reads the session variables from the user manager
 VM=arch-hypr
 SCREEN=Virtual-1
 SHOT_CMD='grim $SHOT_FILE'

+ 1 - 0
tools/linuxvm/profiles/arch-xfce.sh

@@ -2,6 +2,7 @@ VM=arch-xfce
 SCREEN=Virtual-1
 SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
+MAXIMIZE_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,maximized_vert,maximized_horz; wait"'
 WEM=app
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
 MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'

+ 1 - 0
tools/linuxvm/profiles/debian-xfce.sh

@@ -2,6 +2,7 @@ VM=debian-xfce
 SCREEN=Virtual-1
 SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
+MAXIMIZE_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,maximized_vert,maximized_horz; wait"'
 WEM=deb
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
 MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'

+ 5 - 2
tools/linuxvm/profiles/elementary.sh

@@ -1,6 +1,9 @@
+# Gala has no layer shell: the engine draws through XWayland into a background window and sees only X11 windows, so the test window is an
+# XWayland one (a native Wayland window pauses nothing there) and there is no MAXIMIZE_CMD (Gala keeps a GTK window at its size)
+# Plank covers the bottom 70 px of the screen, the dock check of pointer_check.sh goes on the wallpaper's own dock above it
+POINTER_DOCK_XY=960,980
 VM=elementary
 SCREEN=Virtual-1
 SHOT_CMD=host
-FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
-MAXIMIZE_CMD='python3 ~/lwe/fullscreen_window.py maximize'
+FULLSCREEN_CMD='GDK_BACKEND=x11 python3 ~/lwe/fullscreen_window.py'
 WEM=deb

+ 1 - 0
tools/linuxvm/profiles/endeavouros-xfce.sh

@@ -2,6 +2,7 @@ VM=endeavouros-xfce
 SCREEN=Virtual-1
 SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
+MAXIMIZE_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,maximized_vert,maximized_horz; wait"'
 WEM=app
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
 MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'

+ 1 - 0
tools/linuxvm/profiles/manjaro-xfce.sh

@@ -2,6 +2,7 @@ VM=manjaro-xfce
 SCREEN=Virtual-1
 SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
+MAXIMIZE_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,maximized_vert,maximized_horz; wait"'
 WEM=app
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
 MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'

+ 4 - 0
tools/linuxvm/profiles/mint-cinnamon.sh

@@ -1,7 +1,11 @@
+# Cinnamon on X11 (Muffin): --screen-root draws into a desktop type background window (XDG_CURRENT_DESKTOP X-Cinnamon), the windowbg
+# group of guest_test.sh checks --window-background; the Mint Update Manager and System Reports windows are closed by PREP,
+# fullscreen and maximize go through a GTK window (fullscreen_window.py)
 VM=mint-cinnamon
 SCREEN=Virtual-1
 SHOT_CMD='gnome-screenshot -f $SHOT_FILE'
 FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
+MAXIMIZE_CMD='python3 ~/lwe/fullscreen_window.py maximize'
 WEM=deb
 MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
 MULTI=1

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff