Explorar o código

tons of optimizations

UwU hai 1 mes
pai
achega
b74f0432eb
Modificáronse 77 ficheiros con 7386 adicións e 980 borrados
  1. 22 2
      CMakeLists.txt
  2. 14 2
      README.md
  3. 131 0
      protocols/ext-idle-notify-v1.xml
  4. 164 1
      src/WallpaperEngine/Application/ApplicationContext.cpp
  5. 32 0
      src/WallpaperEngine/Application/ApplicationContext.h
  6. 431 169
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  7. 42 10
      src/WallpaperEngine/Application/WallpaperApplication.h
  8. 13 2
      src/WallpaperEngine/Data/JSON.cpp
  9. 541 0
      src/WallpaperEngine/Desktop/PowerMonitor.cpp
  10. 44 0
      src/WallpaperEngine/Desktop/PowerMonitor.h
  11. 30 5
      src/WallpaperEngine/Render/AlbumTexture.cpp
  12. 4 0
      src/WallpaperEngine/Render/AlbumTexture.h
  13. 53 1
      src/WallpaperEngine/Render/CWallpaper.cpp
  14. 23 0
      src/WallpaperEngine/Render/CWallpaper.h
  15. 6 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  16. 6 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  17. 6 43
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  18. 103 39
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  19. 8 3
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  20. 5 1
      src/WallpaperEngine/Render/GifAnimation.cpp
  21. 23 0
      src/WallpaperEngine/Render/ImageDecoder.cpp
  22. 5 0
      src/WallpaperEngine/Render/ImageDecoder.h
  23. 23 489
      src/WallpaperEngine/Render/Objects/CImage.cpp
  24. 22 81
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  25. 563 0
      src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp
  26. 143 0
      src/WallpaperEngine/Render/Objects/PuppetMeshFile.h
  27. 18 4
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  28. 2 1
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  29. 152 41
      src/WallpaperEngine/Render/RenderContext.cpp
  30. 18 1
      src/WallpaperEngine/Render/RenderContext.h
  31. 73 0
      src/WallpaperEngine/Render/SplitLayout.cpp
  32. 19 0
      src/WallpaperEngine/Render/SplitLayout.h
  33. 1 1
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  34. 2 0
      src/WallpaperEngine/Render/Wallpapers/CSplat.h
  35. 6 7
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  36. 1 0
      src/WallpaperEngine/Render/Wallpapers/CWeb.h
  37. 12 19
      src/WallpaperEngine/Scripting/LocalStorageObject.cpp
  38. 18 9
      src/WallpaperEngine/Scripting/LocalStorageObject.h
  39. 8 1
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  40. 153 0
      src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
  41. 84 0
      src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp
  42. 397 0
      src/WallpaperEngine/Testing/Cases/EncodedImages.cpp
  43. 77 0
      src/WallpaperEngine/Testing/Cases/PowerSupply.cpp
  44. 398 0
      src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp
  45. 182 0
      src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp
  46. 71 0
      src/WallpaperEngine/Testing/Cases/SplitLayout.cpp
  47. 140 0
      src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
  48. 12 0
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  49. 1 5
      src/WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.cpp
  50. 15 0
      src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h
  51. 36 1
      tests/desktops/test_gnome.py
  52. 44 0
      tests/desktops/test_river.py
  53. 182 0
      tests/desktops/test_split.py
  54. 1 3
      tests/desktops/test_wallpaper.py
  55. 16 11
      tools/desktops/__main__.py
  56. 191 0
      tools/desktops/river-layer-shell-v1.xml
  57. 1911 0
      tools/desktops/river-window-management-v1.xml
  58. 74 0
      tools/desktops/river_min_wm.c
  59. 1 0
      tools/desktops/rootfs-fedora-gnome.txt
  60. 102 16
      tools/desktops/session.py
  61. 7 2
      tools/desktops/wlr_virtual_pointer.c
  62. 3 0
      tools/headless_render.sh
  63. 105 0
      tools/linuxvm/fake_github.py
  64. 8 3
      tools/linuxvm/linuxvm.sh
  65. 3 2
      tools/package_release.sh
  66. 49 3
      tools/wecompare/README.md
  67. 14 2
      tools/wecompare/render_we.py
  68. 131 0
      tools/wecompare/wine/proton.sh
  69. 36 0
      tools/wecompare/wine/proton_run.py
  70. 54 0
      tools/wecompare/wine/proton_valve.sh
  71. 2 0
      tools/wecompare/wine/sharedvideo/run.sh
  72. 89 0
      tools/wecompare/wine/steam_manifest_links.py
  73. 2 0
      tools/wecompare/wine/we_capture.sh
  74. 2 0
      tools/wecompare/wine/we_cursor.sh
  75. 2 0
      tools/wecompare/wine/we_full.sh
  76. 2 0
      tools/wecompare/wine/we_resize.sh
  77. 2 0
      tools/wecompare/wine/we_span.sh

+ 22 - 2
CMakeLists.txt

@@ -186,6 +186,10 @@ if(WAYLAND_SUPPORT_FOUND)
         COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/fractional-scale-v1.xml ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.h)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c
         COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/fractional-scale-v1.xml ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.h
+        COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/ext-idle-notify-v1.xml ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.h)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.c
+        COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/ext-idle-notify-v1.xml ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.c)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h
         COMMAND ${WaylandScanner} client-header ${WAYLAND_PROTOCOLS_DIR}/stable/viewporter/viewporter.xml ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.c
@@ -237,7 +241,9 @@ if(WAYLAND_SUPPORT_FOUND)
         ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c
         ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.h
         ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.c
-        ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h)
+        ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h
+        ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.c
+        ${WAYLAND_OUTPUT_DIR}/ext-idle-notify-v1-protocol.h)
 
     if(NOT DISABLE_KDE_FEATURES)
         pkg_check_modules(DBUS dbus-1)
@@ -446,6 +452,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Desktop/KWinScript.cpp
     src/WallpaperEngine/Desktop/SessionBus.h
     src/WallpaperEngine/Desktop/SessionBus.cpp
+    src/WallpaperEngine/Desktop/PowerMonitor.h
+    src/WallpaperEngine/Desktop/PowerMonitor.cpp
     src/WallpaperEngine/Desktop/HyprlandIPC.h
     src/WallpaperEngine/Desktop/HyprlandIPC.cpp
     src/WallpaperEngine/Media/ThumbnailPalette.h
@@ -496,6 +504,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Drivers/VideoDriver.cpp
     src/WallpaperEngine/Render/RenderContext.h
     src/WallpaperEngine/Render/RenderContext.cpp
+    src/WallpaperEngine/Render/SplitLayout.h
+    src/WallpaperEngine/Render/SplitLayout.cpp
     src/WallpaperEngine/Render/TextureCache.h
     src/WallpaperEngine/Render/TextureCache.cpp
     src/WallpaperEngine/Render/ImageDecoder.h
@@ -541,6 +551,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CImage.cpp
     src/WallpaperEngine/Render/Objects/PuppetClipping.h
     src/WallpaperEngine/Render/Objects/PuppetClipping.cpp
+    src/WallpaperEngine/Render/Objects/PuppetMeshFile.h
+    src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp
     src/WallpaperEngine/Render/Objects/PuppetIK.h
     src/WallpaperEngine/Render/Objects/PuppetIK.cpp
     src/WallpaperEngine/Render/Objects/PuppetPhysics.h
@@ -722,7 +734,15 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp
         src/WallpaperEngine/Testing/Cases/LocalStorage.cpp
         src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp
-        src/WallpaperEngine/Testing/Cases/WebHostFiles.cpp)
+        src/WallpaperEngine/Testing/Cases/WebHostFiles.cpp
+        src/WallpaperEngine/Testing/Cases/PowerSupply.cpp
+        src/WallpaperEngine/Testing/Cases/EncodedImages.cpp
+        src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp
+        src/WallpaperEngine/Testing/Cases/PuppetMeshFile.cpp
+        src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp
+        src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
+        src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
+        src/WallpaperEngine/Testing/Cases/SplitLayout.cpp)
 endif()
 
 add_library(

+ 14 - 2
README.md

@@ -39,7 +39,7 @@ Scripts and audio:
 
 Control:
 
-- Multi-monitor handling: per-screen backgrounds (`--screen-root`), one wallpaper spanning several monitors (`--screen-span`), per-screen scaling/zoom/alignment/corner color, and Workshop playlists (`--playlist`).
+- 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"`).
@@ -177,7 +177,9 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--window <XxYxWxH>` | Run in windowed mode with custom size/position |
 | `--screen-root <screen>` | Set as background for a specific screen |
 | `--screen-span <screen-1>,<screen-2>,...` | Stretch a single wallpaper across multiple screens |
-| `--bg <id/path>` | Assign a background to a screen (used after `--screen-root`/`--screen-span`) |
+| `--screen-slot <screen>` | Add a slot to a screen, once per wallpaper, so several share it side by side (stacked on a portrait screen); the following `--bg`, `--scaling`, etc. apply to that slot, called `<screen>#<n>` |
+| `--split-layout aspect\|equal\|center` | How the previous `--screen-slot`'s screen is shared: sized from each wallpaper's aspect ratio (default), equal slots, or the wallpapers' own shapes centered with bars around them |
+| `--bg <id/path>` | Assign a background to a screen (used after `--screen-root`/`--screen-span`/`--screen-slot`) |
 | `--playlist <file>` | Cycle through a Wallpaper Engine playlist from `config.json` |
 | `--scaling <mode>` | `stretch`, `fit`, `fill`, `center`, `free`, or `default` |
 | `--zoom <factor>` | Manual zoom on top of `--scaling`, e.g. `1.5` in, `0.5` out |
@@ -222,6 +224,9 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--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 |
+| `--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 |
 | `--fullscreen-pause-only-active` | Wayland only: pause only when the fullscreen window is active |
 | `--fullscreen-pause-ignore-appid <val>` | Wayland only: ignore fullscreen windows whose app_id contains `<val>`, repeatable |
 | `--audio-screen <screen>` | Only this screen's background produces audio |
@@ -257,6 +262,13 @@ One wallpaper across multiple monitors:
 linux-wallpaperengine --scaling fill --screen-span HDMI-A-1,DP-2,DP-3 --bg 1845706469
 ```
 
+Three wallpapers on one monitor, e.g. two portrait ones around a landscape one (the first slot plays audio unless
+`--audio-screen DP-1#2` picks another; a control file with `screen=DP-1#2` hotswaps just that slot):
+```bash
+linux-wallpaperengine --screen-slot DP-1 --bg 3663326998 --screen-slot DP-1 --bg 1846362380 --scaling fit \
+  --screen-slot DP-1 --bg 3486109050 --split-layout aspect
+```
+
 Windowed:
 ```bash
 linux-wallpaperengine --window 0x0x1280x720 1845706469

+ 131 - 0
protocols/ext-idle-notify-v1.xml

@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="ext_idle_notify_v1">
+  <copyright>
+    Copyright © 2015 Martin Gräßlin
+    Copyright © 2022 Simon Ser
+
+    Permission is hereby granted, free of charge, to any person obtaining a
+    copy of this software and associated documentation files (the "Software"),
+    to deal in the Software without restriction, including without limitation
+    the rights to use, copy, modify, merge, publish, distribute, sublicense,
+    and/or sell copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice (including the next
+    paragraph) shall be included in all copies or substantial portions of the
+    Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+    DEALINGS IN THE SOFTWARE.
+  </copyright>
+
+  <interface name="ext_idle_notifier_v1" version="2">
+    <description summary="idle notification manager">
+      This interface allows clients to monitor user idle status.
+
+      After binding to this global, clients can create ext_idle_notification_v1
+      objects to get notified when the user is idle for a given amount of time.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the manager">
+        Destroy the manager object. All objects created via this interface
+        remain valid.
+      </description>
+    </request>
+
+    <request name="get_idle_notification">
+      <description summary="create a notification object">
+        Create a new idle notification object.
+
+        The notification object has a minimum timeout duration and is tied to a
+        seat. The client will be notified if the seat is inactive for at least
+        the provided timeout. See ext_idle_notification_v1 for more details.
+
+        A zero timeout is valid and means the client wants to be notified as
+        soon as possible when the seat is inactive.
+      </description>
+      <arg name="id" type="new_id" interface="ext_idle_notification_v1"/>
+      <arg name="timeout" type="uint" summary="minimum idle timeout in msec"/>
+      <arg name="seat" type="object" interface="wl_seat"/>
+    </request>
+
+    <!-- Version 2 additions -->
+
+    <request name="get_input_idle_notification" since="2">
+      <description summary="create a notification object">
+        Create a new idle notification object to track input from the
+        user, such as keyboard and mouse movement. Because this object is
+        meant to track user input alone, it ignores idle inhibitors.
+
+        The notification object has a minimum timeout duration and is tied to a
+        seat. The client will be notified if the seat is inactive for at least
+        the provided timeout. See ext_idle_notification_v1 for more details.
+
+        A zero timeout is valid and means the client wants to be notified as
+        soon as possible when the seat is inactive.
+      </description>
+      <arg name="id" type="new_id" interface="ext_idle_notification_v1"/>
+      <arg name="timeout" type="uint" summary="minimum idle timeout in msec"/>
+      <arg name="seat" type="object" interface="wl_seat"/>
+    </request>
+    
+  </interface>
+
+  <interface name="ext_idle_notification_v1" version="2">
+    <description summary="idle notification">
+      This interface is used by the compositor to send idle notification events
+      to clients.
+
+      Initially the notification object is not idle. The notification object
+      becomes idle when no user activity has happened for at least the timeout
+      duration, starting from the creation of the notification object. User
+      activity may include input events or a presence sensor, but is
+      compositor-specific.
+
+      How this notification responds to idle inhibitors depends on how
+      it was constructed. If constructed from the
+      get_idle_notification request, then if an idle inhibitor is
+      active (e.g. another client has created a zwp_idle_inhibitor_v1
+      on a visible surface), the compositor must not make the
+      notification object idle. However, if constructed from the
+      get_input_idle_notification request, then idle inhibitors are
+      ignored, and only input from the user, e.g. from a keyboard or
+      mouse, counts as activity.
+
+      When the notification object becomes idle, an idled event is sent. When
+      user activity starts again, the notification object stops being idle,
+      a resumed event is sent and the timeout is restarted.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the notification object">
+        Destroy the notification object.
+      </description>
+    </request>
+
+    <event name="idled">
+      <description summary="notification object is idle">
+        This event is sent when the notification object becomes idle.
+
+        It's a compositor protocol error to send this event twice without a
+        resumed event in-between.
+      </description>
+    </event>
+
+    <event name="resumed">
+      <description summary="notification object is no longer idle">
+        This event is sent when the notification object stops being idle.
+
+        It's a compositor protocol error to send this event twice without an
+        idled event in-between. It's a compositor protocol error to send this
+        event prior to any idled event.
+      </description>
+    </event>
+  </interface>
+</protocol>

+ 164 - 1
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -14,6 +14,7 @@
 #include <functional>
 #include <iostream>
 #include <optional>
+#include <ranges>
 #include <sstream>
 #include <stdexcept>
 #include <string_view>
@@ -280,6 +281,50 @@ bool matchesObjectToken (const std::string& token, int id, const std::string& na
 }
 } // namespace
 
+const ApplicationContext::SplitScreen* ApplicationContext::findSplitScreen (const std::string& screenOrSlot) const {
+    const auto screen = screenOrSlot.substr (0, screenOrSlot.rfind ('#'));
+
+    for (const auto& split : this->settings.general.splitScreens) {
+	if (split.screen == screen) {
+	    return &split;
+	}
+    }
+
+    return nullptr;
+}
+
+bool ApplicationContext::isScreenRequested (const std::string& name) const {
+    if (this->settings.general.screenBackgrounds.contains (name) || this->findSplitScreen (name) != nullptr) {
+	return true;
+    }
+
+    return std::ranges::any_of (this->settings.general.spanGroups, [&name] (const auto& spanGroup) {
+	return std::ranges::find (spanGroup.screens, name) != spanGroup.screens.end ();
+    });
+}
+
+std::vector<std::string> ApplicationContext::describeRequestedScreens () const {
+    std::vector<std::string> lines;
+
+    for (const auto& screen : this->settings.general.screenBackgrounds | std::views::keys) {
+	if (screen.find ('#') == std::string::npos) {
+	    lines.push_back (screen);
+	}
+    }
+
+    for (const auto& split : this->settings.general.splitScreens) {
+	lines.push_back (split.screen + " (split into " + std::to_string (split.slots.size ()) + ")");
+    }
+
+    for (const auto& spanGroup : this->settings.general.spanGroups) {
+	for (const auto& screen : spanGroup.screens) {
+	    lines.push_back (screen + " (span group)");
+	}
+    }
+
+    return lines;
+}
+
 std::optional<bool> ApplicationContext::resolveObjectVisibility (int id, const std::string& name) const {
     for (const auto& token : this->settings.general.disabledObjects) {
 	if (matchesObjectToken (token, id, name)) {
@@ -454,6 +499,9 @@ void ApplicationContext::loadSettingsFromArgv () {
 		    sLog.exception ("--screen-root: screen '", value, "' already belongs to a span group");
 		}
 	    }
+	    if (this->findSplitScreen (value) != nullptr) {
+		sLog.exception ("--screen-root: screen '", value, "' is already split with --screen-slot");
+	    }
 	    if (this->settings.render.mode == EXPLICIT_WINDOW) {
 		sLog.exception ("Cannot run in both background and window mode");
 	    }
@@ -495,6 +543,9 @@ void ApplicationContext::loadSettingsFromArgv () {
 			sLog.exception ("--screen-span: screen '", screen, "' already belongs to another span group");
 		    }
 		}
+		if (this->findSplitScreen (screen) != nullptr) {
+		    sLog.exception ("--screen-span: screen '", screen, "' is already split with --screen-slot");
+		}
 		group.screens.push_back (screen);
 	    }
 
@@ -511,8 +562,72 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.general.screenBackgrounds[lastScreen] = "";
 	})
 	.append ();
+    backgroundGroup.add_argument ("--screen-slot")
+	.help (
+	    "Adds a slot to the given screen, so several wallpapers share it side by side (top to bottom on a portrait "
+	    "screen). Repeat it once per wallpaper; the following --bg, --playlist, --scaling, --clamp, --zoom, etc. "
+	    "apply to the slot just added. The slot is called <screen>#<n> (counting from 1) for --audio-screen and "
+	    "the control file's screen= line"
+	)
+	.action ([this, &lastScreen] (const std::string& value) -> void {
+	    if (this->settings.render.mode == EXPLICIT_WINDOW) {
+		sLog.exception ("Cannot run in both background and window mode");
+	    }
+	    if (value.empty () || value.find ('#') != std::string::npos || value.starts_with ("span:")) {
+		sLog.exception ("--screen-slot: invalid screen name '", value, "'");
+	    }
+	    if (this->settings.general.screenBackgrounds.contains (value)) {
+		sLog.exception ("--screen-slot: screen '", value, "' is already configured with --screen-root");
+	    }
+	    for (const auto& group : this->settings.general.spanGroups) {
+		if (std::find (group.screens.begin (), group.screens.end (), value) != group.screens.end ()) {
+		    sLog.exception ("--screen-slot: screen '", value, "' already belongs to a span group");
+		}
+	    }
+
+	    this->settings.render.mode = DESKTOP_BACKGROUND;
+
+	    auto& splits = this->settings.general.splitScreens;
+	    auto split = std::find_if (splits.begin (), splits.end (), [&value] (const SplitScreen& existing) {
+		return existing.screen == value;
+	    });
+
+	    if (split == splits.end ()) {
+		split = splits.insert (splits.end (), SplitScreen { .screen = value });
+	    }
+
+	    lastScreen = value + "#" + std::to_string (split->slots.size () + 1);
+	    split->slots.push_back (lastScreen);
+	    this->settings.general.screenBackgrounds[lastScreen] = "";
+	    this->settings.general.screenScalings[lastScreen] = this->settings.render.window.scalingMode;
+	    this->settings.general.screenClamps[lastScreen] = this->settings.render.window.clamp;
+	})
+	.append ();
+    backgroundGroup.add_argument ("--split-layout")
+	.help (
+	    "How the slots of the previous --screen-slot's screen share it: aspect (default, sized from each "
+	    "wallpaper's aspect ratio and stretched to fill the screen), equal (same size slots) or center (each "
+	    "wallpaper's own aspect ratio, centered, with bars around them when they don't fill the screen)"
+	)
+	.choices ("aspect", "equal", "center")
+	.action ([this, &lastScreen] (const std::string& value) -> void {
+	    const auto hash = lastScreen.rfind ('#');
+	    auto& splits = this->settings.general.splitScreens;
+	    const auto split = std::find_if (splits.begin (), splits.end (), [&] (const SplitScreen& existing) {
+		return hash != std::string::npos && existing.screen == lastScreen.substr (0, hash);
+	    });
+
+	    if (split == splits.end ()) {
+		sLog.exception ("--split-layout has to follow a --screen-slot");
+	    }
+
+	    split->layout = value == "equal" ? SplitScreen::LAYOUT_EQUAL
+		: value == "center"          ? SplitScreen::LAYOUT_CENTER
+					     : SplitScreen::LAYOUT_ASPECT;
+	})
+	.append ();
     backgroundGroup.add_argument ("-b", "--bg")
-	.help ("After --screen-root or --screen-span, specifies the background to use")
+	.help ("After --screen-root, --screen-span or --screen-slot, specifies the background to use")
 	.action ([this, &lastScreen] (const std::string& value) -> void {
 	    this->settings.general.screenBackgrounds[lastScreen] = translateBackground (value);
 	    this->settings.general.defaultBackground = translateBackground (value);
@@ -904,6 +1019,54 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.default_value (60)
 	.store_into (this->settings.render.maximumFPS);
 
+    performanceGroup.add_argument ("--fps-battery")
+	.help (
+	    "FPS limit while the computer runs on battery (UPower, else /sys/class/power_supply), 0 pauses. Control "
+	    "file: fps-battery=<fps|off>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    int fps;
+
+	    try {
+		fps = std::stoi (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid --fps-battery value: ", value);
+	    }
+
+	    if (fps < 0) {
+		sLog.exception ("--fps-battery can't be negative");
+	    }
+
+	    this->settings.render.batteryFPS = fps;
+	});
+
+    performanceGroup.add_argument ("--pause-on-battery")
+	.help ("Pauses the background while the computer runs on battery, same as --fps-battery 0")
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.render.batteryFPS = 0; });
+
+    performanceGroup.add_argument ("--idle-pause")
+	.help (
+	    "Pauses the background after this many minutes without keyboard or mouse input (0 = never). Uses "
+	    "ext-idle-notify-v1 on Wayland, the X11 screen saver extension or GNOME's idle monitor; inhibitors such as "
+	    "a playing video keep it running. Control file: idle-pause=<minutes>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    int minutes;
+
+	    try {
+		minutes = std::stoi (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid --idle-pause value: ", value);
+	    }
+
+	    if (minutes < 0) {
+		sLog.exception ("--idle-pause can't be negative");
+	    }
+
+	    this->settings.render.idlePauseMinutes = minutes;
+	});
+
     performanceGroup.add_argument ("--speed")
 	.help (
 	    "Global playback speed multiplier for animations, particles and effects (e.g. 0.5 for half speed, "

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

@@ -96,6 +96,27 @@ public:
 	WallpaperEngine::Data::Model::ImageAdjustments imageAdjustments = {};
     };
 
+    /** see --screen-slot */
+    struct SplitScreen {
+	enum Layout {
+	    /** sized by aspect ratio, stretched to fill */
+	    LAYOUT_ASPECT = 0,
+	    LAYOUT_EQUAL = 1,
+	    /** own aspect ratio at full height, centered with bars */
+	    LAYOUT_CENTER = 2,
+	};
+
+	std::string screen;
+	/** "<screen>#<n>" keys, left to right (top to bottom on portrait) */
+	std::vector<std::string> slots;
+	Layout layout = LAYOUT_ASPECT;
+    };
+
+    [[nodiscard]] const SplitScreen* findSplitScreen (const std::string& screenOrSlot) const;
+    /** --screen-root screen, split screen or span member */
+    [[nodiscard]] bool isScreenRequested (const std::string& name) const;
+    [[nodiscard]] std::vector<std::string> describeRequestedScreens () const;
+
     struct {
 	struct {
 	    bool onlyListProperties;
@@ -150,11 +171,14 @@ public:
 	    std::map<std::string, glm::vec4> screenCornerColors;
 	    /** Image filter, color options and flip for different screens, see --image-filter */
 	    std::map<std::string, WallpaperEngine::Data::Model::ImageAdjustments> screenImageAdjustments;
+	    /** Per screen/slot/span overrides of render.videoSegments */
+	    std::map<std::string, WallpaperEngine::VideoPlayback::VideoSegments> screenVideoSegments;
 	    std::map<std::string, PlaylistDefinition> screenPlaylists;
 	    /** Playlist used in window mode */
 	    std::optional<PlaylistDefinition> defaultPlaylist;
 	    /** Span groups: multiple monitors sharing one stretched wallpaper */
 	    std::vector<SpanGroup> spanGroups;
+	    std::vector<SplitScreen> splitScreens;
 	    // hidden: disposable CEF host for one Web wallpaper, needs webHostShm/Width/Height
 	    bool webHost;
 	    std::string webHostShm;
@@ -183,6 +207,10 @@ public:
 	    bool pauseOnMaximized;
 	    // app_id substrings ignored for fullscreen pause ("firefox" matches org.mozilla.firefox)
 	    std::vector<std::string> fullscreenPauseIgnoreAppIds;
+	    /** 0 pauses, nullopt keeps maximumFPS, see --fps-battery */
+	    std::optional<int> batteryFPS;
+	    /** minutes, 0 = never, see --idle-pause */
+	    int idlePauseMinutes;
 	    /** Wayland-only: PQ output on monitors in HDR mode and HDR video, see --hdr */
 	    bool hdr;
 	    struct {
@@ -272,9 +300,11 @@ public:
             .screenAlignments = {},
             .screenCornerColors = {},
             .screenImageAdjustments = {},
+            .screenVideoSegments = {},
             .screenPlaylists = {},
             .defaultPlaylist = std::nullopt,
             .spanGroups = {},
+            .splitScreens = {},
             .webHost = false,
             .webHostShm = "",
             .webHostWidth = 0,
@@ -293,6 +323,8 @@ public:
             .pauseOnFocus = false,
             .pauseOnMaximized = false,
             .fullscreenPauseIgnoreAppIds = {},
+            .batteryFPS = std::nullopt,
+            .idlePauseMinutes = 0,
             .hdr = false,
             .debug = {
                 .baseOnly = false,

+ 431 - 169
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -45,11 +45,13 @@
 #include <ctime>
 #include <fstream>
 #include <numeric>
+#include <ranges>
 #include <string_view>
 #include <unistd.h>
 #define STB_IMAGE_WRITE_IMPLEMENTATION
 #include <stb_image_write.h>
 #include <thread>
+#include <utility>
 
 // microseconds, for usleep ()
 #define FULLSCREEN_CHECK_WAIT_TIME 250000
@@ -648,6 +650,8 @@ namespace {
 /** Everything a control-file request can carry; any field left unset means "don't touch this" */
 struct HotswapRequest {
     std::optional<std::string> path;
+    /** limits the request to this screen or slot */
+    std::optional<std::string> screen;
     // a layers=1 line makes disabledObjects/enabledObjects a full replacement
     bool layersProvided = false;
     std::vector<std::string> disabledObjects;
@@ -663,6 +667,10 @@ struct HotswapRequest {
     std::optional<int> volume;
     /** frame rate limit, see --fps */
     std::optional<int> fps;
+    /** see --fps-battery */
+    std::optional<std::string> batteryFps;
+    /** see --idle-pause */
+    std::optional<std::string> idlePause;
     std::optional<std::string> xray;
     /** "stretch"/"fit"/"fill"/"center"/"default" */
     std::optional<std::string> scaling;
@@ -750,6 +758,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 
 	if (key == "path") {
 	    request.path = value;
+	} else if (key == "screen") {
+	    request.screen = value.empty () ? std::nullopt : std::optional<std::string> (value);
 	} else if (key == "layers") {
 	    request.layersProvided = true;
 	} else if (key == "disable-object") {
@@ -780,6 +790,10 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    } catch (const std::exception&) {
 		sLog.error ("Hotswap: ignoring invalid fps value: ", value);
 	    }
+	} else if (key == "fps-battery") {
+	    request.batteryFps = value;
+	} else if (key == "idle-pause") {
+	    request.idlePause = value;
 	} else if (key == "xray") {
 	    request.xray = value;
 	} else if (key == "scaling") {
@@ -911,8 +925,19 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 
     const auto request = parseHotswapRequest (file);
+    HotswapTarget target;
+
+    if (request.screen.has_value ()) {
+	target = this->resolveHotswapScreen (*request.screen);
+
+	if (!target.has_value ()) {
+	    sLog.error ("Hotswap: no screen or slot called ", *request.screen);
+	    return;
+	}
+    }
 
     if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
+	&& !request.fps.has_value () && !request.batteryFps.has_value () && !request.idlePause.has_value ()
 	&& !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
 	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
 	&& !request.expandCanvas.has_value () && !request.repairAssets.has_value () && !request.cornerColor.has_value ()
@@ -938,13 +963,24 @@ void WallpaperApplication::checkHotswapRequest () {
 	general.audioSensitivity.clear ();
 	general.soundVolume.clear ();
 
-	// Wallpaper Engine keeps these per wallpaper too
-	this->m_context.settings.render.window.imageAdjustments = {};
-	this->m_context.settings.render.videoSegments.clear ();
-	general.screenImageAdjustments.clear ();
+	// per wallpaper like WE; an empty entry keeps the global parts off the new one
+	if (target.has_value ()) {
+	    if (auto* spanGroup = this->findSpanGroup (*target); spanGroup != nullptr) {
+		spanGroup->imageAdjustments = {};
+	    } else {
+		general.screenImageAdjustments.erase (*target);
+	    }
+
+	    general.screenVideoSegments[*target] = {};
+	} else {
+	    this->m_context.settings.render.window.imageAdjustments = {};
+	    this->m_context.settings.render.videoSegments.clear ();
+	    general.screenImageAdjustments.clear ();
+	    general.screenVideoSegments.clear ();
 
-	for (auto& spanGroup : general.spanGroups) {
-	    spanGroup.imageAdjustments = {};
+	    for (auto& spanGroup : general.spanGroups) {
+		spanGroup.imageAdjustments = {};
+	    }
 	}
     }
 
@@ -956,24 +992,32 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applyFpsHotswap (*request.fps);
     }
 
+    if (request.batteryFps.has_value ()) {
+	this->applyBatteryFpsHotswap (*request.batteryFps);
+    }
+
+    if (request.idlePause.has_value ()) {
+	this->applyIdlePauseHotswap (*request.idlePause);
+    }
+
     if (request.xray.has_value ()) {
 	this->applyXrayHotswap (*request.xray);
     }
 
     if (request.scaling.has_value ()) {
-	this->applyScalingHotswap (*request.scaling);
+	this->applyScalingHotswap (target, *request.scaling);
     }
 
     if (request.zoom.has_value ()) {
-	this->applyZoomHotswap (*request.zoom);
+	this->applyZoomHotswap (target, *request.zoom);
     }
 
     if (request.offset.has_value ()) {
-	this->applyOffsetHotswap (*request.offset);
+	this->applyOffsetHotswap (target, *request.offset);
     }
 
     if (request.alignment.has_value ()) {
-	this->applyAlignmentHotswap (*request.alignment);
+	this->applyAlignmentHotswap (target, *request.alignment);
     }
 
     if (request.disableParallax.has_value ()) {
@@ -981,11 +1025,11 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 
     if (request.cornerColor.has_value ()) {
-	this->applyCornerColorHotswap (*request.cornerColor);
+	this->applyCornerColorHotswap (target, *request.cornerColor);
     }
 
     if (request.imageAdjustmentsProvided) {
-	this->applyImageAdjustmentsHotswap (request.imageAdjustments);
+	this->applyImageAdjustmentsHotswap (target, request.imageAdjustments);
     }
 
     if (request.speed.has_value ()) {
@@ -993,11 +1037,11 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 
     if (request.videoStart.has_value () || request.videoEnd.has_value () || request.videoSegments.has_value ()) {
-	this->applyVideoSegmentsHotswap (request.videoStart, request.videoEnd, request.videoSegments);
+	this->applyVideoSegmentsHotswap (target, request.videoStart, request.videoEnd, request.videoSegments);
     }
 
     if (request.videoSeek.has_value ()) {
-	this->applyVideoSeekHotswap (*request.videoSeek);
+	this->applyVideoSeekHotswap (target, *request.videoSeek);
     }
 
     if (request.hwdec.has_value ()) {
@@ -1129,6 +1173,10 @@ void WallpaperApplication::checkHotswapRequest () {
 
     // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
     for (auto& [screen, background] : this->m_backgrounds) {
+	if (!this->hotswapReaches (target, screen)) {
+	    continue;
+	}
+
 	const std::string targetPath = request.path.value_or (this->resolveScreenBackgroundPath (screen));
 
 	try {
@@ -1175,11 +1223,77 @@ void WallpaperApplication::checkHotswapRequest () {
 
     this->applyAudioPolicy ();
 
-    if (request.path.has_value ()) {
+    if (request.path.has_value () && !request.screen.has_value ()) {
 	this->m_context.settings.general.defaultBackground = *request.path;
     }
 }
 
+std::optional<std::string> WallpaperApplication::resolveHotswapScreen (const std::string& name) const {
+    if (this->m_backgrounds.contains (name)) {
+	return name;
+    }
+
+    for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
+	if (std::ranges::find (spanGroup.screens, name) != spanGroup.screens.end ()) {
+	    return "span:" + spanGroup.screens.front ();
+	}
+    }
+
+    return std::nullopt;
+}
+
+bool WallpaperApplication::hotswapReaches (const HotswapTarget& target, const std::string& screen) const {
+    if (!target.has_value () || *target == screen) {
+	return true;
+    }
+
+    const auto* spanGroup = this->findSpanGroup (*target);
+
+    return spanGroup != nullptr && std::ranges::find (spanGroup->screens, screen) != spanGroup->screens.end ();
+}
+
+template <typename T, typename Update>
+void WallpaperApplication::updateScreenSetting (
+    const HotswapTarget& target, std::map<std::string, T>& screens, T& window,
+    T ApplicationContext::SpanGroup::* spanField, Update update
+) {
+    if (target.has_value ()) {
+	if (auto* spanGroup = this->findSpanGroup (*target); spanGroup != nullptr) {
+	    spanGroup->*spanField = update (spanGroup->*spanField);
+	} else {
+	    auto& value = screens[*target];
+	    value = update (value);
+	}
+
+	return;
+    }
+
+    window = update (window);
+
+    for (auto& value : screens | std::views::values) {
+	value = update (value);
+    }
+
+    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
+	spanGroup.*spanField = update (spanGroup.*spanField);
+    }
+}
+
+template <typename Apply>
+void WallpaperApplication::forEachTargetWallpaper (const HotswapTarget& target, Apply apply) const {
+    if (!this->m_renderContext) {
+	return;
+    }
+
+    std::set<WallpaperEngine::Render::CWallpaper*> done;
+
+    for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
+	if (this->hotswapReaches (target, screen) && done.insert (wallpaper.get ()).second) {
+	    apply (screen, *wallpaper);
+	}
+    }
+}
+
 std::string WallpaperApplication::storageScreen (const std::string& screen) const {
     // WE: nothing in a window, "Monitor<index>" on the desktop (sub_14012E710); output names survive reordering
     const auto mode = this->m_context.settings.render.mode;
@@ -1261,7 +1375,8 @@ WallpaperApplication::resolveScreenImageAdjustments (const std::string& screen,
 
 glm::ivec2 WallpaperApplication::resolveScreenRenderSize (const std::string& screen) const {
     const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
-    const auto it = viewports.find (screen);
+    const auto* split = this->m_context.findSplitScreen (screen);
+    const auto it = viewports.find (split != nullptr ? split->screen : screen);
 
     if (it != viewports.end ()) {
 	return { it->second->viewport.z, it->second->viewport.w };
@@ -1303,6 +1418,116 @@ void WallpaperApplication::applyFpsHotswap (int fps) {
     sLog.out ("Hotswap: applied fps limit ", fps, " live");
 }
 
+void WallpaperApplication::applyBatteryFpsHotswap (const std::string& value) {
+    auto& batteryFPS = this->m_context.settings.render.batteryFPS;
+
+    if (value == "off" || value == "none" || value.empty ()) {
+	batteryFPS = std::nullopt;
+    } else if (value == "pause") {
+	batteryFPS = 0;
+    } else {
+	try {
+	    batteryFPS = std::max (0, std::stoi (value));
+	} catch (const std::exception&) {
+	    sLog.error ("Hotswap: ignoring invalid fps-battery value: ", value);
+	    return;
+	}
+    }
+
+    this->updatePowerMonitor ();
+
+    sLog.out ("Hotswap: applied fps-battery ", batteryFPS.has_value () ? std::to_string (*batteryFPS) : "off", " live");
+}
+
+void WallpaperApplication::applyIdlePauseHotswap (const std::string& value) {
+    int minutes = 0;
+
+    if (value != "off" && value != "none" && !value.empty ()) {
+	try {
+	    minutes = std::max (0, std::stoi (value));
+	} catch (const std::exception&) {
+	    sLog.error ("Hotswap: ignoring invalid idle-pause value: ", value);
+	    return;
+	}
+    }
+
+    this->m_context.settings.render.idlePauseMinutes = minutes;
+    this->updatePowerMonitor ();
+
+    sLog.out ("Hotswap: applied idle-pause ", minutes, " live");
+}
+
+void WallpaperApplication::updatePowerMonitor () {
+    const auto& render = this->m_context.settings.render;
+
+    if (!render.batteryFPS.has_value () && render.idlePauseMinutes <= 0) {
+	this->m_powerMonitor.reset ();
+	return;
+    }
+
+    if (!this->m_powerMonitor) {
+	this->m_powerMonitor = std::make_unique<WallpaperEngine::Desktop::PowerMonitor> ();
+	sLog.out ("Power: ", this->m_powerMonitor->onBattery () ? "running on battery" : "on external power");
+    }
+
+    this->m_powerMonitor->setIdleTimeout (render.idlePauseMinutes);
+}
+
+int WallpaperApplication::frameRateLimit () const {
+    const auto& render = this->m_context.settings.render;
+
+    if (render.batteryFPS.value_or (0) > 0 && this->m_powerMonitor && this->m_powerMonitor->onBattery ()) {
+	return std::min (*render.batteryFPS, render.maximumFPS);
+    }
+
+    return render.maximumFPS;
+}
+
+uint32_t WallpaperApplication::pauseReasons () const {
+    const auto& render = this->m_context.settings.render;
+    uint32_t reasons = 0;
+
+    if (this->m_fullScreenDetector->anythingFullscreen ()) {
+	reasons |= PauseWindows;
+    }
+
+    if (this->m_powerMonitor) {
+	if (render.batteryFPS == 0 && this->m_powerMonitor->onBattery ()) {
+	    reasons |= PauseBattery;
+	}
+
+	if (render.idlePauseMinutes > 0 && this->m_powerMonitor->idle ()) {
+	    reasons |= PauseIdle;
+	}
+    }
+
+    return reasons;
+}
+
+void WallpaperApplication::logPauseReasons (uint32_t reasons) {
+    if (reasons == this->m_pauseReasons) {
+	return;
+    }
+
+    this->m_pauseReasons = reasons;
+
+    if (reasons == 0) {
+	sLog.out ("Resumed");
+	return;
+    }
+
+    std::string names;
+
+    for (const auto& [bit, name] : { std::pair { PauseWindows, "windows" }, std::pair { PauseBattery, "battery" },
+				     std::pair { PauseIdle, "idle" } }) {
+	if (reasons & bit) {
+	    names += names.empty () ? name : std::string (", ") + name;
+	}
+    }
+
+    sLog.out ("Paused: ", names);
+}
+
 void WallpaperApplication::applyXrayHotswap (const std::string& value) {
     auto& mode = this->m_context.state.xray.mode;
 
@@ -1324,7 +1549,7 @@ void WallpaperApplication::applyXrayHotswap (const std::string& value) {
     sLog.out ("Hotswap: xray ", name, " live");
 }
 
-void WallpaperApplication::applyScalingHotswap (const std::string& value) {
+void WallpaperApplication::applyScalingHotswap (const HotswapTarget& target, const std::string& value) {
     const auto mode = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
 
     if (!mode.has_value ()) {
@@ -1332,26 +1557,18 @@ void WallpaperApplication::applyScalingHotswap (const std::string& value) {
 	return;
     }
 
-    this->m_context.settings.render.window.scalingMode = *mode;
-
-    for (auto& [screen, scaling] : this->m_context.settings.general.screenScalings) {
-	scaling = *mode;
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.scaling = *mode;
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setScalingMode (*mode);
-	}
-    }
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenScalings, this->m_context.settings.render.window.scalingMode,
+	&ApplicationContext::SpanGroup::scaling, [&] (const auto&) { return *mode; }
+    );
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	wallpaper.setScalingMode (*mode);
+    });
 
     sLog.out ("Hotswap: applied scaling mode ", value, " live");
 }
 
-void WallpaperApplication::applyZoomHotswap (const std::string& value) {
+void WallpaperApplication::applyZoomHotswap (const HotswapTarget& target, const std::string& value) {
     float zoom;
 
     try {
@@ -1361,26 +1578,18 @@ void WallpaperApplication::applyZoomHotswap (const std::string& value) {
 	return;
     }
 
-    this->m_context.settings.render.window.zoom = zoom;
-
-    for (auto& [screen, screenZoom] : this->m_context.settings.general.screenZooms) {
-	screenZoom = zoom;
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.zoom = zoom;
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setZoom (zoom);
-	}
-    }
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenZooms, this->m_context.settings.render.window.zoom,
+	&ApplicationContext::SpanGroup::zoom, [&] (const auto&) { return zoom; }
+    );
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	wallpaper.setZoom (zoom);
+    });
 
     sLog.out ("Hotswap: applied zoom ", zoom, " live");
 }
 
-void WallpaperApplication::applyOffsetHotswap (const std::string& value) {
+void WallpaperApplication::applyOffsetHotswap (const HotswapTarget& target, const std::string& value) {
     const auto comma = value.find (',');
 
     if (comma == std::string::npos) {
@@ -1398,26 +1607,18 @@ void WallpaperApplication::applyOffsetHotswap (const std::string& value) {
 	return;
     }
 
-    this->m_context.settings.render.window.offset = offset;
-
-    for (auto& [screen, screenOffset] : this->m_context.settings.general.screenOffsets) {
-	screenOffset = offset;
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.offset = offset;
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setOffset (offset.x, offset.y);
-	}
-    }
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenOffsets, this->m_context.settings.render.window.offset,
+	&ApplicationContext::SpanGroup::offset, [&] (const auto&) { return offset; }
+    );
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	wallpaper.setOffset (offset.x, offset.y);
+    });
 
     sLog.out ("Hotswap: applied offset ", offset.x, ",", offset.y, " live");
 }
 
-void WallpaperApplication::applyAlignmentHotswap (const std::string& value) {
+void WallpaperApplication::applyAlignmentHotswap (const HotswapTarget& target, const std::string& value) {
     // "position,x,y,zoom" in WE's units (0-100, zoom 0-200)
     std::array<float, 4> values {};
     std::stringstream stream (value);
@@ -1444,21 +1645,13 @@ void WallpaperApplication::applyAlignmentHotswap (const std::string& value) {
 	.zoom = std::clamp (values[3], 0.0f, 200.0f) / 100.0f,
     };
 
-    this->m_context.settings.render.window.alignment = alignment;
-
-    for (auto& [screen, screenAlignment] : this->m_context.settings.general.screenAlignments) {
-	screenAlignment = alignment;
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.alignment = alignment;
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setAlignment (alignment);
-	}
-    }
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenAlignments, this->m_context.settings.render.window.alignment,
+	&ApplicationContext::SpanGroup::alignment, [&] (const auto&) { return alignment; }
+    );
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	wallpaper.setAlignment (alignment);
+    });
 
     sLog.out ("Hotswap: applied alignment ", value, " live");
 }
@@ -1482,7 +1675,7 @@ void WallpaperApplication::applyParallaxHotswap (const std::string& value) {
     sLog.out ("Hotswap: parallax ", newState ? "force-disabled" : "enabled", " live");
 }
 
-void WallpaperApplication::applyCornerColorHotswap (const std::string& value) {
+void WallpaperApplication::applyCornerColorHotswap (const HotswapTarget& target, const std::string& value) {
     const auto color = WallpaperEngine::Render::CFBO::parseColor (value);
 
     if (!color.has_value ()) {
@@ -1490,45 +1683,30 @@ void WallpaperApplication::applyCornerColorHotswap (const std::string& value) {
 	return;
     }
 
-    this->m_context.settings.render.window.cornerColor = *color;
-
-    for (auto& [screen, screenColor] : this->m_context.settings.general.screenCornerColors) {
-	screenColor = *color;
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.cornerColor = *color;
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setCornerColor (*color);
-	}
-    }
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenCornerColors, this->m_context.settings.render.window.cornerColor,
+	&ApplicationContext::SpanGroup::cornerColor, [&] (const auto&) { return *color; }
+    );
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	wallpaper.setCornerColor (*color);
+    });
 
     sLog.out ("Hotswap: applied corner color ", value, " live");
 }
 
-void WallpaperApplication::applyImageAdjustmentsHotswap (const ImageAdjustments& request) {
-    auto& window = this->m_context.settings.render.window.imageAdjustments;
-
-    window = request.over (window);
-
-    for (auto& [screen, adjustments] : this->m_context.settings.general.screenImageAdjustments) {
-	adjustments = request.over (adjustments);
-    }
-
-    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	spanGroup.imageAdjustments = request.over (spanGroup.imageAdjustments);
-    }
-
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    wallpaper->setImageAdjustments (
-		this->resolveScreenImageAdjustments (screen, wallpaper->getWallpaperData ().project)
+void WallpaperApplication::applyImageAdjustmentsHotswap (const HotswapTarget& target, const ImageAdjustments& request) {
+    this->updateScreenSetting (
+	target, this->m_context.settings.general.screenImageAdjustments,
+	this->m_context.settings.render.window.imageAdjustments, &ApplicationContext::SpanGroup::imageAdjustments,
+	[&] (const ImageAdjustments& adjustments) { return request.over (adjustments); }
+    );
+    this->forEachTargetWallpaper (
+	target, [&] (const std::string& screen, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	    wallpaper.setImageAdjustments (
+		this->resolveScreenImageAdjustments (screen, wallpaper.getWallpaperData ().project)
 	    );
 	}
-    }
+    );
 
     sLog.out ("Hotswap: applied image filter and color options live");
 }
@@ -1563,11 +1741,14 @@ void WallpaperApplication::applySpeedHotswap (const std::string& value) {
 }
 
 void WallpaperApplication::applyVideoSegmentsHotswap (
-    const std::optional<std::string>& start, const std::optional<std::string>& end,
+    const HotswapTarget& target, const std::optional<std::string>& start, const std::optional<std::string>& end,
     const std::optional<std::string>& segments
 ) {
     using WallpaperEngine::Render::Wallpapers::CVideo;
-    auto& current = this->m_context.settings.render.videoSegments;
+    auto& general = this->m_context.settings.general;
+    WallpaperEngine::VideoPlayback::VideoSegments current = target.has_value ()
+	? this->resolveScreenVideoSegments (*target)
+	: this->m_context.settings.render.videoSegments;
     const auto clears = [] (const std::string& value) { return value.empty () || value == "none"; };
 
     if (segments.has_value ()) {
@@ -1612,14 +1793,19 @@ void WallpaperApplication::applyVideoSegmentsHotswap (
 
     current = CVideo::normalizeSegments (current);
 
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    if (wallpaper->is<CVideo> ()) {
-		wallpaper->as<CVideo> ()->setSegments (current);
-	    }
-	}
+    if (target.has_value ()) {
+	general.screenVideoSegments[*target] = current;
+    } else {
+	this->m_context.settings.render.videoSegments = current;
+	general.screenVideoSegments.clear ();
     }
 
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	if (wallpaper.is<CVideo> ()) {
+	    wallpaper.as<CVideo> ()->setSegments (current);
+	}
+    });
+
     std::string description = current.empty () ? "whole video" : "";
 
     for (const auto& segment : current) {
@@ -1630,7 +1816,15 @@ void WallpaperApplication::applyVideoSegmentsHotswap (
     sLog.out ("Hotswap: applied video parts ", description, " live");
 }
 
-void WallpaperApplication::applyVideoSeekHotswap (const std::string& value) {
+WallpaperEngine::VideoPlayback::VideoSegments
+WallpaperApplication::resolveScreenVideoSegments (const std::string& screen) const {
+    const auto& screens = this->m_context.settings.general.screenVideoSegments;
+    const auto it = screens.find (screen);
+
+    return it != screens.end () ? it->second : this->m_context.settings.render.videoSegments;
+}
+
+void WallpaperApplication::applyVideoSeekHotswap (const HotswapTarget& target, const std::string& value) {
     const auto seconds = WallpaperEngine::Render::Wallpapers::CVideo::parseTime (value);
 
     if (!seconds.has_value ()) {
@@ -1638,13 +1832,11 @@ void WallpaperApplication::applyVideoSeekHotswap (const std::string& value) {
 	return;
     }
 
-    if (this->m_renderContext) {
-	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
-		wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->seek (*seconds);
-	    }
+    this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
+	if (wallpaper.is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
+	    wallpaper.as<WallpaperEngine::Render::Wallpapers::CVideo> ()->seek (*seconds);
 	}
-    }
+    });
 }
 
 void WallpaperApplication::applyHwdecHotswap (const std::string& value) {
@@ -1699,7 +1891,16 @@ void WallpaperApplication::applyAudioPolicy () {
     std::map<WallpaperEngine::Render::CWallpaper*, bool> wantMuted;
 
     for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	const bool screenMuted = audioScreen.has_value () && screen != *audioScreen;
+	bool screenMuted = audioScreen.has_value () && screen != *audioScreen;
+
+	// only one slot plays audio: --audio-screen's, else the first
+	if (const auto* split = this->m_context.findSplitScreen (screen); split != nullptr) {
+	    const bool named
+		= audioScreen.has_value () && std::ranges::find (split->slots, *audioScreen) != split->slots.end ();
+	    const std::string& audible = named ? *audioScreen : split->slots.front ();
+
+	    screenMuted = screen != audible || (audioScreen.has_value () && !named && *audioScreen != split->screen);
+	}
 	auto [it, inserted] = wantMuted.try_emplace (wallpaper.get (), screenMuted);
 
 	if (!inserted) {
@@ -2246,6 +2447,8 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	int vpWidth;
 	int vpHeight;
 	int xoffset;
+	/** rows from the top */
+	int yoffset;
 	float ustart, uend, vstart, vend;
     };
 
@@ -2255,53 +2458,76 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
     for (const auto& [screen, viewport] : this->m_renderContext->getOutput ().getViewports ()) {
 	viewport->makeCurrent ();
 
-	const auto wallpaperIt = wallpapers.find (screen);
-	if (wallpaperIt == wallpapers.end ()) {
-	    sLog.error ("Cannot find wallpaper for screen ", screen);
-	    continue;
+	const int screenWidth = viewport->viewport.z - viewport->viewport.x;
+	// wallpapers on this screen, rects from the top left
+	std::vector<std::pair<std::string, glm::ivec4>> parts;
+
+	if (const auto* split = this->m_context.findSplitScreen (screen); split != nullptr) {
+	    const auto& output = viewport->viewport;
+
+	    for (const auto& slot : split->slots) {
+		const auto rect = this->m_renderContext->getSlotRect (slot);
+
+		if (!rect.has_value ()) {
+		    continue;
+		}
+
+		const int top = vflip ? output.y + output.w - (rect->y + rect->w) : rect->y - output.y;
+		parts.emplace_back (slot, glm::ivec4 (rect->x - output.x, top, rect->z, rect->w));
+	    }
+	} else {
+	    parts.emplace_back (screen, glm::ivec4 (0, 0, screenWidth, viewport->viewport.w - viewport->viewport.y));
 	}
 
-	const auto& wallpaper = wallpaperIt->second;
-	const int vpWidth = viewport->viewport.z - viewport->viewport.x;
-	const int vpHeight = viewport->viewport.w - viewport->viewport.y;
+	for (const auto& [part, area] : parts) {
+	    const auto wallpaperIt = wallpapers.find (part);
+	    if (wallpaperIt == wallpapers.end ()) {
+		sLog.error ("Cannot find wallpaper for screen ", part);
+		continue;
+	    }
 
-	// read the wallpaper's FBO directly, more reliable than the default framebuffer on some drivers
-	// (NVIDIA/Wayland)
-	glBindFramebuffer (GL_FRAMEBUFFER, wallpaper->renderAdjustedFramebuffer ());
+	    const auto& wallpaper = wallpaperIt->second;
+	    const int vpWidth = area.z;
+	    const int vpHeight = area.w;
 
-	glFinish ();
+	    // the default framebuffer is unreliable on some drivers (NVIDIA/Wayland)
+	    glBindFramebuffer (GL_FRAMEBUFFER, wallpaper->renderAdjustedFramebuffer ());
 
-	// errors left over from rendering (e.g. a uniform type mismatch) would otherwise fail the readback below
-	while (glGetError () != GL_NO_ERROR) { }
+	    glFinish ();
 
-	const int readWidth = wallpaper->getFramebufferWidth ();
-	const int readHeight = wallpaper->getFramebufferHeight ();
-	const auto bufferSize = readWidth * readHeight * 3;
-	auto* buffer = new uint8_t[bufferSize];
+	    // clear leftover render errors so they don't fail the readback
+	    while (glGetError () != GL_NO_ERROR) { }
 
-	glPixelStorei (GL_PACK_ALIGNMENT, 1);
-	if (GLEW_VERSION_4_5) {
-	    glReadnPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer);
-	} else {
-	    glReadPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, buffer);
-	}
+	    const int readWidth = wallpaper->getFramebufferWidth ();
+	    const int readHeight = wallpaper->getFramebufferHeight ();
+	    const auto bufferSize = readWidth * readHeight * 3;
+	    auto* buffer = new uint8_t[bufferSize];
 
-	glBindFramebuffer (GL_FRAMEBUFFER, 0);
+	    glPixelStorei (GL_PACK_ALIGNMENT, 1);
+	    if (GLEW_VERSION_4_5) {
+		glReadnPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer);
+	    } else {
+		glReadPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, buffer);
+	    }
 
-	if (const GLenum error = glGetError (); error != GL_NO_ERROR) {
-	    sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error);
-	    delete[] buffer;
-	    continue;
-	}
+	    glBindFramebuffer (GL_FRAMEBUFFER, 0);
 
-	const glm::vec4 uvs = wallpaper->getOutputUVs ();
+	    if (const GLenum error = glGetError (); error != GL_NO_ERROR) {
+		sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error);
+		delete[] buffer;
+		continue;
+	    }
 
-	captures.push_back (
-	    { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset, uvs.x, uvs.y, uvs.z, uvs.w }
-	);
+	    const glm::vec4 uvs = wallpaper->getOutputUVs ();
+
+	    captures.push_back (
+		{ buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset + area.x, area.y, uvs.x, uvs.y,
+		  uvs.z, uvs.w }
+	    );
+	}
 
 	if (viewport->single) {
-	    currentXOffset += vpWidth;
+	    currentXOffset += screenWidth;
 	}
     }
 
@@ -2349,7 +2575,7 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 		    const int count = samplesX * samplesY;
 		    const int xfinal = x + capture.xoffset;
 		    // FBOs aren't flipped like the default framebuffer
-		    const int yfinal = vflip ? y : (capture.vpHeight - y - 1);
+		    const int yfinal = capture.yoffset + (vflip ? y : (capture.vpHeight - y - 1));
 
 		    if (yfinal >= 0 && yfinal < height && xfinal >= 0 && xfinal < width) {
 			for (int channel = 0; channel < 3; channel++) {
@@ -2442,6 +2668,10 @@ void WallpaperApplication::ensureAudioCapture (const Project& project) {
     this->m_audioCapturing = true;
 }
 
+ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const std::string& screen) {
+    return const_cast<ApplicationContext::SpanGroup*> (std::as_const (*this).findSpanGroup (screen));
+}
+
 const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const std::string& screen) const {
     if (!screen.starts_with ("span:")) {
 	return nullptr;
@@ -2480,6 +2710,13 @@ void WallpaperApplication::installWallpaper (
 	wallpaper->setAlignment (this->resolveScreenAlignment (screen));
 	wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
 	wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
+
+	if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
+	    wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSegments (
+		this->resolveScreenVideoSegments (screen)
+	    );
+	}
+
 	this->m_renderContext->setWallpaper (screen, std::move (wallpaper), holdPrevious);
 	return;
     }
@@ -2518,6 +2755,12 @@ void WallpaperApplication::installWallpaper (
     wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
     wallpaper->setSpanInfo ({ .screens = spanGroup->screens, .totalBounds = { low, high - low } });
 
+    if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
+	wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSegments (
+	    this->resolveScreenVideoSegments (screen)
+	);
+    }
+
     for (const auto& name : spanGroup->screens) {
 	this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious);
     }
@@ -2559,6 +2802,7 @@ void WallpaperApplication::setup () {
     this->setupAudio ();
     this->prepareOutputs ();
     this->setupOpenGLDebugging ();
+    this->updatePowerMonitor ();
 
     if (this->m_context.settings.general.dumpStructure) {
 	auto prettyPrinter = Data::Dumpers::StringPrinter ();
@@ -2592,9 +2836,18 @@ void WallpaperApplication::render () {
     if (this->m_isPaused) {
 	usleep (FULLSCREEN_CHECK_WAIT_TIME);
 	m_videoDriver->dispatchWhilePaused ();
-	if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
+
+	const uint32_t reasons = this->pauseReasons ();
+	this->logPauseReasons (reasons);
+
+	// fullscreen pauses delay a hotswap, battery/idle pauses take it at once (it may lift them) and show one frame
+	const bool takeHotswap = this->m_hotswapRequested && (reasons & PauseWindows) == 0;
+
+	if (reasons != 0 && !takeHotswap && this->m_context.state.general.keepRunning) {
 	    return;
 	}
+
+	this->m_showFrameWhilePaused = takeHotswap;
 	m_renderContext->setPause (false);
 
 	// account for paused duration in playlist timers
@@ -2681,8 +2934,8 @@ void WallpaperApplication::render () {
 	    }
 	}
 
-	// read every frame, --fps can change with a hotswap
-	const float minimumTime = 1.0f / std::max (1, this->m_context.settings.render.maximumFPS);
+	// per frame: hotswaps and the power source change it
+	const float minimumTime = 1.0f / std::max (1, this->frameRateLimit ());
 	const float frameTime = m_videoDriver->getRenderTime () - rawTimeNow;
 
 	if (frameTime < minimumTime) {
@@ -2719,13 +2972,22 @@ void WallpaperApplication::render () {
 	    }
 	}
 #endif /* DEMOMODE */
-	if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
+	const uint32_t reasons = this->pauseReasons ();
+
+	if (reasons != 0 && !this->m_showFrameWhilePaused && this->m_context.state.general.keepRunning) {
+	    this->logPauseReasons (reasons);
 	    this->m_isPaused = true;
 	    this->m_pauseStart = std::chrono::steady_clock::now ();
 
 	    m_renderContext->setPause (true);
 	    return;
 	}
+
+	if (reasons == 0) {
+	    this->logPauseReasons (0);
+	}
+
+	this->m_showFrameWhilePaused = false;
     }
 
     this->checkHotswapRequest ();

+ 42 - 10
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -20,6 +20,7 @@
 
 #include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Data/Model/Types.h"
+#include "WallpaperEngine/Desktop/PowerMonitor.h"
 #include "WallpaperEngine/Media/MediaSource.h"
 
 #include <set>
@@ -53,6 +54,9 @@ public:
     [[nodiscard]] GLuint getDestinationFramebuffer () const;
 
 private:
+    /** screen= background key, nullopt for every screen */
+    using HotswapTarget = std::optional<std::string>;
+
     /** A project.json ready to be parsed. For presets, json is the base wallpaper's and preset holds the overrides */
     struct ProjectSource {
 	AssetLocatorUniquePtr container;
@@ -126,40 +130,55 @@ private:
     // pushes a volume (0-128, like --volume) live to video players and the SDL mixer
     void applyVolumeHotswap (int volume);
     void applyFpsHotswap (int fps);
+    void applyBatteryFpsHotswap (const std::string& value);
+    void applyIdlePauseHotswap (const std::string& value);
+    void updatePowerMonitor ();
+    [[nodiscard]] int frameRateLimit () const;
+    [[nodiscard]] uint32_t pauseReasons () const;
+    void logPauseReasons (uint32_t reasons);
 
     /** "full"/"normal"/"disabled", or the older "on"/"off"/"toggle" */
     void applyXrayHotswap (const std::string& value);
 
-    // "stretch"/"fit"/"fill"/"center"/"default", live on every screen
-    void applyScalingHotswap (const std::string& value);
+    // "stretch"/"fit"/"fill"/"center"/"default"
+    void applyScalingHotswap (const HotswapTarget& target, const std::string& value);
 
     // e.g. "1.5"
-    void applyZoomHotswap (const std::string& value);
+    void applyZoomHotswap (const HotswapTarget& target, const std::string& value);
 
     // e.g. "0.5,-1"
-    void applyOffsetHotswap (const std::string& value);
+    void applyOffsetHotswap (const HotswapTarget& target, const std::string& value);
     // "position,x,y,zoom" in WE's 0-100/0-200 units
-    void applyAlignmentHotswap (const std::string& value);
+    void applyAlignmentHotswap (const HotswapTarget& target, const std::string& value);
 
     // passthrough to settings.mouse.disableparallax, read every frame; "on"/"off"/"toggle" (or "1"/"0"/"true"/"false")
     void applyParallaxHotswap (const std::string& value);
 
     // hex RGB/RGBA, e.g. "000000" or "#1a1a1aff"; only visible where clamp is border
-    void applyCornerColorHotswap (const std::string& value);
-    /** Merges the fields set in the request into every screen's image settings and applies them live */
-    void applyImageAdjustmentsHotswap (const ImageAdjustments& request);
+    void applyCornerColorHotswap (const HotswapTarget& target, const std::string& value);
+    void applyImageAdjustmentsHotswap (const HotswapTarget& target, const ImageAdjustments& request);
+    /** Without a target: the window, every screen and every span group. update maps old -> new */
+    template <typename T, typename Update>
+    void updateScreenSetting (
+	const HotswapTarget& target, std::map<std::string, T>& screens, T& window,
+	T ApplicationContext::SpanGroup::* spanField, Update update
+    );
+    /** once per wallpaper, a span's is shared by its screens */
+    template <typename Apply> void forEachTargetWallpaper (const HotswapTarget& target, Apply apply) const;
 
     // e.g. "0.5", passthrough to settings.render.playbackSpeed which render() reads every frame
     void applySpeedHotswap (const std::string& value);
 
     /** Video wallpapers restart from the first part, video-start/video-end make it one part */
     void applyVideoSegmentsHotswap (
-	const std::optional<std::string>& start, const std::optional<std::string>& end,
+	const HotswapTarget& target, const std::optional<std::string>& start, const std::optional<std::string>& end,
 	const std::optional<std::string>& segments
     );
+    [[nodiscard]] WallpaperEngine::VideoPlayback::VideoSegments
+    resolveScreenVideoSegments (const std::string& screen) const;
 
     /** Jumps video wallpapers to a position (seconds, m:ss or h:mm:ss), e.g. a few seconds before the loop end */
-    void applyVideoSeekHotswap (const std::string& value);
+    void applyVideoSeekHotswap (const HotswapTarget& target, const std::string& value);
     void applyHwdecHotswap (const std::string& value);
 
     // empty clears the restriction, then re-applies the audio policy
@@ -193,11 +212,15 @@ private:
     [[nodiscard]] glm::ivec2 resolveScreenRenderSize (const std::string& screen) const;
     /** The span group loaded as this "span:<first screen>" key, null for a plain screen */
     [[nodiscard]] const ApplicationContext::SpanGroup* findSpanGroup (const std::string& screen) const;
+    [[nodiscard]] ApplicationContext::SpanGroup* findSpanGroup (const std::string& screen);
     // builds the wallpaper for a screen or span group and puts it on its outputs; throws on failure, the outputs keep
     // what they had
     void installWallpaper (
 	const std::string& screen, const Project& project, const std::filesystem::path& path, bool holdPrevious
     );
+    /** Screen, slot or span key as is, a span member as its span key; nullopt when unknown */
+    [[nodiscard]] std::optional<std::string> resolveHotswapScreen (const std::string& name) const;
+    [[nodiscard]] bool hotswapReaches (const HotswapTarget& target, const std::string& screen) const;
 
     ApplicationContext& m_context;
     std::map<std::string, ProjectUniquePtr> m_backgrounds {};
@@ -218,6 +241,15 @@ private:
     std::mt19937 m_playlistRng { std::random_device {}() };
     std::atomic<bool> m_hotswapRequested { false };
     bool m_isPaused = false;
+    enum PauseReason : uint32_t {
+	PauseWindows = 1,
+	PauseBattery = 2,
+	PauseIdle = 4,
+    };
+    uint32_t m_pauseReasons = 0;
+    // a hotswap during a battery/idle pause draws one frame
+    bool m_showFrameWhilePaused = false;
+    std::unique_ptr<WallpaperEngine::Desktop::PowerMonitor> m_powerMonitor = nullptr;
     bool m_screenShotTaken = false;
     uint32_t m_nextFrameScreenshot = 0;
     std::chrono::steady_clock::time_point m_pauseStart {};

+ 13 - 2
src/WallpaperEngine/Data/JSON.cpp

@@ -64,8 +64,19 @@ JSON JsonExtensions::parseAsset (const std::string& content) {
 	if (c == ',') {
 	    auto next = i + 1;
 
-	    while (next < length && std::isspace (static_cast<unsigned char> (content[next]))) {
-		next++;
+	    // skip whitespace and comments before the bracket
+	    while (next < length) {
+		if (std::isspace (static_cast<unsigned char> (content[next]))) {
+		    next++;
+		} else if (content.compare (next, 2, "//") == 0) {
+		    const auto end = content.find ('\n', next);
+		    next = end == std::string::npos ? length : end;
+		} else if (content.compare (next, 2, "/*") == 0) {
+		    const auto end = content.find ("*/", next + 2);
+		    next = end == std::string::npos ? length : end + 2;
+		} else {
+		    break;
+		}
 	    }
 
 	    if (next < length && (content[next] == ']' || content[next] == '}')) {

+ 541 - 0
src/WallpaperEngine/Desktop/PowerMonitor.cpp

@@ -0,0 +1,541 @@
+#include "PowerMonitor.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <dbus/dbus.h>
+#include <dlfcn.h>
+#include <fstream>
+#include <poll.h>
+#include <string>
+#include <sys/eventfd.h>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/SessionBus.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#ifdef ENABLE_WAYLAND
+#include "WallpaperEngine/Desktop/HostWayland.h"
+#include "ext-idle-notify-v1-protocol.h"
+#include <wayland-client.h>
+#endif /* ENABLE_WAYLAND */
+
+using namespace WallpaperEngine::Desktop;
+
+namespace {
+constexpr auto BATTERY_INTERVAL = std::chrono::seconds (5);
+/** poll fast while idle so the wallpaper resumes quickly */
+constexpr auto IDLE_POLL_ACTIVE = std::chrono::milliseconds (250);
+constexpr auto IDLE_POLL_MAX = std::chrono::milliseconds (5000);
+
+std::string readLine (const std::filesystem::path& path) {
+    std::ifstream file (path);
+    std::string line;
+    std::getline (file, line);
+    return line;
+}
+
+// MIT-SCREEN-SAVER through dlopen, libXss isn't a build dependency
+struct ScreenSaverInfo {
+    unsigned long window;
+    int state;
+    int kind;
+    unsigned long tilOrSince;
+    unsigned long idle;
+    unsigned long eventMask;
+};
+
+class X11Idle {
+public:
+    ~X11Idle () {
+	if (this->m_info != nullptr) {
+	    this->m_free (this->m_info);
+	}
+
+	if (this->m_display != nullptr) {
+	    this->m_closeDisplay (this->m_display);
+	}
+
+	if (this->m_xss != nullptr) {
+	    dlclose (this->m_xss);
+	}
+
+	if (this->m_x11 != nullptr) {
+	    dlclose (this->m_x11);
+	}
+    }
+
+    bool open () {
+	if (std::getenv ("DISPLAY") == nullptr) {
+	    return false;
+	}
+
+	this->m_x11 = dlopen ("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
+	this->m_xss = dlopen ("libXss.so.1", RTLD_NOW | RTLD_LOCAL);
+
+	if (this->m_x11 == nullptr || this->m_xss == nullptr) {
+	    return false;
+	}
+
+	auto openDisplay = reinterpret_cast<void* (*)(const char*)> (dlsym (this->m_x11, "XOpenDisplay"));
+	this->m_closeDisplay = reinterpret_cast<int (*) (void*)> (dlsym (this->m_x11, "XCloseDisplay"));
+	this->m_free = reinterpret_cast<int (*) (void*)> (dlsym (this->m_x11, "XFree"));
+	this->m_rootWindow = reinterpret_cast<unsigned long (*) (void*)> (dlsym (this->m_x11, "XDefaultRootWindow"));
+	auto queryExtension
+	    = reinterpret_cast<int (*) (void*, int*, int*)> (dlsym (this->m_xss, "XScreenSaverQueryExtension"));
+	auto allocInfo = reinterpret_cast<ScreenSaverInfo* (*)()> (dlsym (this->m_xss, "XScreenSaverAllocInfo"));
+	this->m_query = reinterpret_cast<int (*) (void*, unsigned long, ScreenSaverInfo*)> (
+	    dlsym (this->m_xss, "XScreenSaverQueryInfo")
+	);
+
+	if (openDisplay == nullptr || this->m_closeDisplay == nullptr || this->m_free == nullptr
+	    || this->m_rootWindow == nullptr || queryExtension == nullptr || allocInfo == nullptr
+	    || this->m_query == nullptr) {
+	    return false;
+	}
+
+	this->m_display = openDisplay (nullptr);
+
+	if (this->m_display == nullptr) {
+	    return false;
+	}
+
+	int eventBase = 0;
+	int errorBase = 0;
+
+	if (!queryExtension (this->m_display, &eventBase, &errorBase)) {
+	    return false;
+	}
+
+	this->m_info = allocInfo ();
+	return this->m_info != nullptr;
+    }
+
+    std::optional<uint64_t> idleMilliseconds () {
+	if (!this->m_query (this->m_display, this->m_rootWindow (this->m_display), this->m_info)) {
+	    return std::nullopt;
+	}
+
+	return this->m_info->idle;
+    }
+
+private:
+    void* m_x11 = nullptr;
+    void* m_xss = nullptr;
+    void* m_display = nullptr;
+    ScreenSaverInfo* m_info = nullptr;
+    int (*m_closeDisplay) (void*) = nullptr;
+    int (*m_free) (void*) = nullptr;
+    unsigned long (*m_rootWindow) (void*) = nullptr;
+    int (*m_query) (void*, unsigned long, ScreenSaverInfo*) = nullptr;
+};
+
+std::optional<bool> upowerOnBattery (DBusConnection* bus) {
+    DBusMessage* call = dbus_message_new_method_call (
+	"org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", "Get"
+    );
+    const char* interface = "org.freedesktop.UPower";
+    const char* property = "OnBattery";
+    dbus_message_append_args (call, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID);
+
+    std::string error;
+    DBusMessage* reply = callBlocking (bus, call, error);
+
+    if (reply == nullptr) {
+	return std::nullopt;
+    }
+
+    std::optional<bool> result;
+    DBusMessageIter iter;
+    DBusMessageIter variant;
+
+    if (dbus_message_iter_init (reply, &iter) && dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_VARIANT) {
+	dbus_message_iter_recurse (&iter, &variant);
+
+	if (dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_BOOLEAN) {
+	    dbus_bool_t value = FALSE;
+	    dbus_message_iter_get_basic (&variant, &value);
+	    result = value != FALSE;
+	}
+    }
+
+    dbus_message_unref (reply);
+    return result;
+}
+
+std::optional<uint64_t> mutterIdleMilliseconds (DBusConnection* bus) {
+    DBusMessage* call = dbus_message_new_method_call (
+	"org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor",
+	"GetIdletime"
+    );
+
+    std::string error;
+    DBusMessage* reply = callBlocking (bus, call, error);
+
+    if (reply == nullptr) {
+	return std::nullopt;
+    }
+
+    dbus_uint64_t idle = 0;
+    const bool ok = dbus_message_get_args (reply, nullptr, DBUS_TYPE_UINT64, &idle, DBUS_TYPE_INVALID);
+    dbus_message_unref (reply);
+
+    return ok ? std::optional<uint64_t> (idle) : std::nullopt;
+}
+
+DBusConnection* privateBus (DBusBusType type) {
+    DBusError error;
+    dbus_error_init (&error);
+
+    DBusConnection* bus = dbus_bus_get_private (type, &error);
+
+    if (dbus_error_is_set (&error)) {
+	dbus_error_free (&error);
+	return nullptr;
+    }
+
+    dbus_connection_set_exit_on_disconnect (bus, FALSE);
+    return bus;
+}
+
+void closeBus (DBusConnection* bus) {
+    if (bus != nullptr) {
+	dbus_connection_close (bus);
+	dbus_connection_unref (bus);
+    }
+}
+} // namespace
+
+std::optional<bool> WallpaperEngine::Desktop::sysfsOnBattery (const std::filesystem::path& powerSupplies) {
+    std::error_code error;
+    bool anyBattery = false;
+    bool discharging = false;
+    bool externalPower = false;
+
+    for (const auto& entry : std::filesystem::directory_iterator (powerSupplies, error)) {
+	const auto& dir = entry.path ();
+
+	// mice, headsets and controllers have scope Device
+	if (readLine (dir / "scope") == "Device") {
+	    continue;
+	}
+
+	const std::string type = readLine (dir / "type");
+
+	if (type == "Battery") {
+	    anyBattery = true;
+	    discharging = discharging || readLine (dir / "status") == "Discharging";
+	} else if (readLine (dir / "online") == "1") {
+	    externalPower = true;
+	}
+    }
+
+    if (!anyBattery) {
+	return std::nullopt;
+    }
+
+    return discharging && !externalPower;
+}
+
+struct PowerMonitor::Sources {
+    DBusConnection* systemBus = nullptr;
+    DBusConnection* sessionBus = nullptr;
+    bool upowerWorks = true;
+    bool mutterWorks = true;
+    std::unique_ptr<X11Idle> x11;
+    bool x11Tried = false;
+    bool loggedUnavailable = false;
+
+#ifdef ENABLE_WAYLAND
+    wl_display* display = nullptr;
+    wl_registry* registry = nullptr;
+    wl_seat* seat = nullptr;
+    ext_idle_notifier_v1* notifier = nullptr;
+    ext_idle_notification_v1* notification = nullptr;
+#endif /* ENABLE_WAYLAND */
+
+#ifdef ENABLE_WAYLAND
+    void disconnectWayland () {
+	if (this->notification != nullptr) {
+	    ext_idle_notification_v1_destroy (this->notification);
+	}
+
+	if (this->notifier != nullptr) {
+	    ext_idle_notifier_v1_destroy (this->notifier);
+	}
+
+	if (this->seat != nullptr) {
+	    wl_seat_destroy (this->seat);
+	}
+
+	if (this->registry != nullptr) {
+	    wl_registry_destroy (this->registry);
+	}
+
+	if (this->display != nullptr) {
+	    wl_display_disconnect (this->display);
+	}
+
+	this->notification = nullptr;
+	this->notifier = nullptr;
+	this->seat = nullptr;
+	this->registry = nullptr;
+	this->display = nullptr;
+    }
+#endif /* ENABLE_WAYLAND */
+
+    ~Sources () {
+#ifdef ENABLE_WAYLAND
+	this->disconnectWayland ();
+#endif /* ENABLE_WAYLAND */
+
+	closeBus (this->systemBus);
+	closeBus (this->sessionBus);
+    }
+};
+
+#ifdef ENABLE_WAYLAND
+namespace {
+void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
+    auto* sources = static_cast<PowerMonitor::Sources*> (data);
+
+    if (std::strcmp (interface, wl_seat_interface.name) == 0 && sources->seat == nullptr) {
+	sources->seat = static_cast<wl_seat*> (wl_registry_bind (registry, name, &wl_seat_interface, 1));
+    } else if (std::strcmp (interface, ext_idle_notifier_v1_interface.name) == 0) {
+	sources->notifier = static_cast<ext_idle_notifier_v1*> (
+	    wl_registry_bind (registry, name, &ext_idle_notifier_v1_interface, 1)
+	);
+    }
+}
+
+void registryGlobalRemove (void*, wl_registry*, uint32_t) { }
+
+const wl_registry_listener registryListener = {
+    .global = registryGlobal,
+    .global_remove = registryGlobalRemove,
+};
+
+void notificationIdled (void* data, ext_idle_notification_v1*) { static_cast<std::atomic<bool>*> (data)->store (true); }
+
+void notificationResumed (void* data, ext_idle_notification_v1*) {
+    static_cast<std::atomic<bool>*> (data)->store (false);
+}
+
+const ext_idle_notification_v1_listener notificationListener = {
+    .idled = notificationIdled,
+    .resumed = notificationResumed,
+};
+} // namespace
+#endif /* ENABLE_WAYLAND */
+
+PowerMonitor::PowerMonitor () : m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (new Sources) {
+    // UPower and the compositor are queried on the thread, sysfs answers until then
+    this->m_onBattery = sysfsOnBattery ("/sys/class/power_supply").value_or (false);
+
+#ifdef ENABLE_WAYLAND
+    // main thread: connectWayland picks the route to the compositor once (Flatpak helper)
+    if (const char* session = std::getenv ("XDG_SESSION_TYPE");
+	session != nullptr && std::string_view (session) == "wayland" && std::getenv ("WAYLAND_DISPLAY") != nullptr) {
+	this->m_sources->display = connectWayland ();
+    }
+#endif /* ENABLE_WAYLAND */
+
+    this->m_thread = std::thread ([this] { this->run (); });
+}
+
+PowerMonitor::~PowerMonitor () {
+    this->m_stop = true;
+    this->wake ();
+
+    if (this->m_thread.joinable ()) {
+	this->m_thread.join ();
+    }
+
+    delete this->m_sources;
+
+    if (this->m_wakeFd >= 0) {
+	close (this->m_wakeFd);
+    }
+}
+
+void PowerMonitor::setIdleTimeout (int minutes) {
+    this->m_idleMinutes = std::max (0, minutes);
+    this->wake ();
+}
+
+void PowerMonitor::wake () const {
+    if (this->m_wakeFd >= 0) {
+	const uint64_t one = 1;
+	std::ignore = write (this->m_wakeFd, &one, sizeof (one));
+    }
+}
+
+void PowerMonitor::run () {
+    using Clock = std::chrono::steady_clock;
+
+    auto& sources = *this->m_sources;
+    bool lastBattery = this->m_onBattery;
+
+    sources.systemBus = privateBus (DBUS_BUS_SYSTEM);
+
+    if (const auto onBattery = sources.systemBus != nullptr ? upowerOnBattery (sources.systemBus) : std::nullopt;
+	onBattery.has_value ()) {
+	this->m_onBattery = *onBattery;
+    } else {
+	sources.upowerWorks = false;
+    }
+
+#ifdef ENABLE_WAYLAND
+    if (sources.display != nullptr) {
+	sources.registry = wl_display_get_registry (sources.display);
+	wl_registry_add_listener (sources.registry, &registryListener, &sources);
+	wl_display_roundtrip (sources.display);
+
+	if (sources.seat == nullptr || sources.notifier == nullptr) {
+	    sLog.debug ("Power: compositor has no ext-idle-notify-v1");
+	}
+    }
+#endif /* ENABLE_WAYLAND */
+
+    auto nextBatteryCheck = Clock::now () + BATTERY_INTERVAL;
+    int appliedMinutes = 0;
+
+    while (!this->m_stop) {
+	const auto now = Clock::now ();
+
+	if (now >= nextBatteryCheck) {
+	    std::optional<bool> onBattery;
+
+	    if (sources.upowerWorks && sources.systemBus != nullptr) {
+		onBattery = upowerOnBattery (sources.systemBus);
+	    }
+
+	    if (!onBattery.has_value ()) {
+		onBattery = sysfsOnBattery ("/sys/class/power_supply");
+	    }
+
+	    this->m_onBattery = onBattery.value_or (false);
+	    nextBatteryCheck = now + BATTERY_INTERVAL;
+	}
+
+	if (this->m_onBattery != lastBattery) {
+	    lastBattery = this->m_onBattery;
+	    sLog.out ("Power: ", lastBattery ? "running on battery" : "on external power");
+	}
+
+	const int minutes = this->m_idleMinutes;
+	bool waylandIdle = false;
+
+#ifdef ENABLE_WAYLAND
+	waylandIdle = sources.display != nullptr && sources.seat != nullptr && sources.notifier != nullptr;
+
+	if (waylandIdle && minutes != appliedMinutes) {
+	    if (sources.notification != nullptr) {
+		ext_idle_notification_v1_destroy (sources.notification);
+		sources.notification = nullptr;
+	    }
+
+	    this->m_idle = false;
+
+	    if (minutes > 0) {
+		const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
+
+		sources.notification = ext_idle_notifier_v1_get_idle_notification (
+		    sources.notifier, static_cast<uint32_t> (std::min<uint64_t> (timeout, UINT32_MAX)), sources.seat
+		);
+		ext_idle_notification_v1_add_listener (sources.notification, &notificationListener, &this->m_idle);
+	    }
+
+	    wl_display_flush (sources.display);
+	}
+#endif /* ENABLE_WAYLAND */
+
+	auto wait = std::chrono::duration_cast<std::chrono::milliseconds> (nextBatteryCheck - Clock::now ());
+
+	if (!waylandIdle && minutes > 0) {
+	    std::optional<uint64_t> idleMs;
+
+	    if (!sources.x11Tried) {
+		sources.x11Tried = true;
+		sources.x11 = std::make_unique<X11Idle> ();
+
+		if (const char* session = std::getenv ("XDG_SESSION_TYPE");
+		    session == nullptr || std::string_view (session) != "x11" || !sources.x11->open ()) {
+		    sources.x11.reset ();
+		}
+	    }
+
+	    if (sources.x11 != nullptr) {
+		idleMs = sources.x11->idleMilliseconds ();
+	    }
+
+	    if (!idleMs.has_value () && sources.mutterWorks) {
+		if (sources.sessionBus == nullptr) {
+		    sources.sessionBus = privateBus (DBUS_BUS_SESSION);
+		}
+
+		idleMs = sources.sessionBus != nullptr ? mutterIdleMilliseconds (sources.sessionBus) : std::nullopt;
+		sources.mutterWorks = idleMs.has_value ();
+	    }
+
+	    if (idleMs.has_value ()) {
+		const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
+		this->m_idle = *idleMs >= timeout;
+		const auto untilIdle = std::chrono::milliseconds (*idleMs >= timeout ? 0 : timeout - *idleMs);
+		wait = std::min (wait, this->m_idle ? IDLE_POLL_ACTIVE : std::min (untilIdle, IDLE_POLL_MAX));
+	    } else if (!sources.loggedUnavailable) {
+		sources.loggedUnavailable = true;
+		sLog.error (
+		    "Power: --idle-pause has no idle source here (ext-idle-notify-v1, X11 screen saver or Mutter)"
+		);
+	    }
+	} else if (!waylandIdle) {
+	    this->m_idle = false;
+	}
+
+	appliedMinutes = minutes;
+
+	pollfd fds[2] = {
+	    { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
+	    { .fd = -1, .events = POLLIN, .revents = 0 },
+	};
+	nfds_t count = 1;
+
+#ifdef ENABLE_WAYLAND
+	if (sources.display != nullptr) {
+	    while (wl_display_prepare_read (sources.display) != 0) {
+		wl_display_dispatch_pending (sources.display);
+	    }
+
+	    wl_display_flush (sources.display);
+	    fds[1].fd = wl_display_get_fd (sources.display);
+	    count = 2;
+	}
+#endif /* ENABLE_WAYLAND */
+
+	poll (fds, count, static_cast<int> (std::max<int64_t> (0, wait.count ())));
+
+#ifdef ENABLE_WAYLAND
+	if (sources.display != nullptr) {
+	    if (fds[1].revents & POLLIN) {
+		wl_display_read_events (sources.display);
+	    } else {
+		wl_display_cancel_read (sources.display);
+	    }
+
+	    if (fds[1].revents & (POLLERR | POLLHUP) || wl_display_dispatch_pending (sources.display) < 0) {
+		sLog.error ("Power: lost the Wayland connection, idle detection stops");
+		this->m_idle = false;
+		sources.disconnectWayland ();
+	    }
+	}
+#endif /* ENABLE_WAYLAND */
+
+	if (fds[0].revents & POLLIN) {
+	    uint64_t value;
+	    std::ignore = read (this->m_wakeFd, &value, sizeof (value));
+	}
+    }
+}

+ 44 - 0
src/WallpaperEngine/Desktop/PowerMonitor.h

@@ -0,0 +1,44 @@
+#pragma once
+
+#include <atomic>
+#include <filesystem>
+#include <optional>
+#include <thread>
+
+namespace WallpaperEngine::Desktop {
+// a system battery is discharging and no external supply is online, nullopt without a system battery
+std::optional<bool> sysfsOnBattery (const std::filesystem::path& powerSupplies);
+
+/**
+ * Battery (UPower, else sysfs) and idle state (ext-idle-notify-v1, MIT-SCREEN-SAVER or Mutter's IdleMonitor), polled
+ * on its own thread so a slow bus never stalls a frame
+ */
+class PowerMonitor {
+public:
+    PowerMonitor ();
+    ~PowerMonitor ();
+
+    PowerMonitor (const PowerMonitor&) = delete;
+    PowerMonitor& operator= (const PowerMonitor&) = delete;
+
+    [[nodiscard]] bool onBattery () const { return this->m_onBattery; }
+    [[nodiscard]] bool idle () const { return this->m_idle; }
+
+    /** 0 turns idle detection off */
+    void setIdleTimeout (int minutes);
+
+    struct Sources;
+
+private:
+    void run ();
+    void wake () const;
+
+    std::atomic<bool> m_onBattery = false;
+    std::atomic<bool> m_idle = false;
+    std::atomic<int> m_idleMinutes = 0;
+    std::atomic<bool> m_stop = false;
+    int m_wakeFd = -1;
+    Sources* m_sources = nullptr;
+    std::thread m_thread;
+};
+} // namespace WallpaperEngine::Desktop

+ 30 - 5
src/WallpaperEngine/Render/AlbumTexture.cpp

@@ -86,11 +86,7 @@ void AlbumTexture::load () const {
 	    this->m_height = image->height;
 	    this->m_resolution = glm::vec4 (this->m_width, this->m_height, this->m_width, this->m_height);
 
-	    glBindTexture (GL_TEXTURE_2D, this->m_textureID);
-	    glTexImage2D (
-		GL_TEXTURE_2D, 0, GL_RGBA, image->width, image->height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
-		image->rgba.data ()
-	    );
+	    uploadCoverTexture (this->m_textureID, *image);
 	    return;
 	} catch (AssetLoadException&) {
 	    // this is expected if the thumbnail is not available
@@ -98,4 +94,33 @@ void AlbumTexture::load () const {
     }
 }
 
+void WallpaperEngine::Render::uploadCoverTexture (GLuint texture, const Media::CoverImage& image) {
+    // a bound PBO turns the pointer into an offset, row settings shift the rows
+    GLint state[6];
+    glGetIntegerv (GL_PIXEL_UNPACK_BUFFER_BINDING, &state[0]);
+    glGetIntegerv (GL_UNPACK_ALIGNMENT, &state[1]);
+    glGetIntegerv (GL_UNPACK_ROW_LENGTH, &state[2]);
+    glGetIntegerv (GL_UNPACK_SKIP_ROWS, &state[3]);
+    glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &state[4]);
+    glGetIntegerv (GL_TEXTURE_BINDING_2D, &state[5]);
+
+    glBindBuffer (GL_PIXEL_UNPACK_BUFFER, 0);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
+    glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
+    glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
+    glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
+
+    glBindTexture (GL_TEXTURE_2D, texture);
+    glTexImage2D (
+	GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.rgba.data ()
+    );
+
+    glBindBuffer (GL_PIXEL_UNPACK_BUFFER, state[0]);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, state[1]);
+    glPixelStorei (GL_UNPACK_ROW_LENGTH, state[2]);
+    glPixelStorei (GL_UNPACK_SKIP_ROWS, state[3]);
+    glPixelStorei (GL_UNPACK_SKIP_PIXELS, state[4]);
+    glBindTexture (GL_TEXTURE_2D, state[5]);
+}
+
 bool AlbumTexture::isReady () const { return this->m_width > 0 && this->m_height > 0; }

+ 4 - 0
src/WallpaperEngine/Render/AlbumTexture.h

@@ -2,9 +2,13 @@
 
 #include "Helpers/ContextAware.h"
 #include "TextureProvider.h"
+#include "WallpaperEngine/Media/CoverImage.h"
 #include "WallpaperEngine/Media/MediaSource.h"
 
 namespace WallpaperEngine::Render {
+/** Uploads with default unpack state, restoring the caller's afterwards */
+void uploadCoverTexture (GLuint texture, const Media::CoverImage& image);
+
 class AlbumTexture : public TextureProvider, public Helpers::ContextAware {
 public:
     explicit AlbumTexture (RenderContext& context);

+ 53 - 1
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -458,10 +458,57 @@ glm::dvec2 CWallpaper::cursorPosition () const {
     return this->getContext ().getInputContext ().getMouseInput ().position ();
 }
 
+bool CWallpaper::pointerInRegion () const {
+    if (!this->m_pointerRegion.has_value ()) {
+	return true;
+    }
+
+    const auto region = this->toCursorSpace (*this->m_pointerRegion);
+    const glm::dvec2 position = this->cursorPosition ();
+
+    return position.x >= region.x && position.x < region.x + region.z && position.y >= region.y
+	&& position.y < region.y + region.w;
+}
+
+glm::ivec4 CWallpaper::toCursorSpace (const glm::ivec4& rect) const {
+    if (!this->m_cursorMirrorHeight.has_value ()) {
+	return rect;
+    }
+
+    return { rect.x, *this->m_cursorMirrorHeight - rect.y - rect.w, rect.z, rect.w };
+}
+
+WallpaperEngine::Input::MouseClickStatus
+CWallpaper::regionButton (const Input::MouseClickStatus status, PointerPress& press) const {
+    if (!this->m_pointerRegion.has_value ()) {
+	return status;
+    }
+
+    if (status == Input::MouseClickStatus::Released) {
+	press = {};
+	return status;
+    }
+
+    // a press belongs to the slot it started on until release
+    if (!press.held) {
+	press = { .held = true, .owned = this->pointerInRegion () };
+    }
+
+    return press.owned ? status : Input::MouseClickStatus::Released;
+}
+
 WallpaperEngine::Input::MouseClickStatus CWallpaper::cursorLeftClick () const {
     const auto& input = this->getContext ().getInputContext ().getMouseInput ();
 
-    return this->m_spanInfo.has_value () ? input.desktopLeftClick () : input.leftClick ();
+    return this->regionButton (
+	this->m_spanInfo.has_value () ? input.desktopLeftClick () : input.leftClick (), this->m_leftPress
+    );
+}
+
+WallpaperEngine::Input::MouseClickStatus CWallpaper::cursorRightClick () const {
+    return this->regionButton (
+	this->getContext ().getInputContext ().getMouseInput ().rightClick (), this->m_rightPress
+    );
 }
 
 glm::vec4 CWallpaper::getOutputUVs () const {
@@ -504,6 +551,11 @@ void CWallpaper::render (
     }
 
     this->m_screenSize = { sceneViewport.z, sceneViewport.w };
+    // X11 rects count y from the top, the cursor from the bottom; a span's cursor is already in group pixels
+    this->m_cursorMirrorHeight = vflip || this->m_spanInfo.has_value ()
+	? std::nullopt
+	: std::optional (this->getContext ().getOutput ().getFullHeight ());
+    this->m_cursorViewport = this->toCursorSpace (sceneViewport);
     this->m_supersampling
 	= this->rendersAtOutputSize () ? this->supersamplingFor ({ sceneViewport.z, sceneViewport.w }) : 1;
     // the scene reads the visible region from these while it renders

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

@@ -120,13 +120,24 @@ public:
     [[nodiscard]] const SpanInfo* getSpanInfo () const;
     /** Like MouseInput::position, but over the whole group for a span */
     [[nodiscard]] glm::dvec2 cursorPosition () const;
+    /** A split slot keeps a press that started on it until release */
     [[nodiscard]] Input::MouseClickStatus cursorLeftClick () const;
+    [[nodiscard]] Input::MouseClickStatus cursorRightClick () const;
+    /** Split slot rect in output pixels, clicks outside are ignored */
+    void setPointerRegion (const std::optional<glm::ivec4>& region) { this->m_pointerRegion = region; }
+    [[nodiscard]] bool pointerInRegion () const;
+    /** Last rendered viewport, y up from the bottom of the output */
+    [[nodiscard]] const glm::ivec4& cursorViewport () const { return this->m_cursorViewport; }
 
     [[nodiscard]] virtual int getWidth () const = 0;
     [[nodiscard]] virtual int getHeight () const = 0;
     /** Size of the framebuffer the wallpaper renders into, only a scene can make this bigger than getWidth/getHeight */
     [[nodiscard]] virtual int getCanvasWidth () const { return this->getWidth (); }
     [[nodiscard]] virtual int getCanvasHeight () const { return this->getHeight (); }
+    /** 0 when any size fits (web pages); sizes split slots */
+    [[nodiscard]] virtual float getAspectRatio () const {
+	return this->getHeight () > 0 ? static_cast<float> (this->getWidth ()) / this->getHeight () : 0.0f;
+    }
     /** Scenes render at the output's size with the scaling mode folded into their projection, like WE does */
     [[nodiscard]] virtual bool rendersAtOutputSize () const { return false; }
     /** Whether the wallpaper uses pointer buttons, otherwise clicks can pass through to the desktop below */
@@ -254,5 +265,17 @@ private:
     uint32_t m_lastRenderedFrame = UINT32_MAX;
     glm::ivec2 m_screenSize = { 0, 0 };
     std::string m_storageScreen;
+    std::optional<glm::ivec4> m_pointerRegion = std::nullopt;
+    glm::ivec4 m_cursorViewport = { 0, 0, 0, 0 };
+    /** Set when rects count y from the top (X11) but the cursor from the bottom */
+    std::optional<int> m_cursorMirrorHeight = std::nullopt;
+    [[nodiscard]] glm::ivec4 toCursorSpace (const glm::ivec4& rect) const;
+    struct PointerPress {
+	bool held = false;
+	bool owned = false;
+    };
+    [[nodiscard]] Input::MouseClickStatus regionButton (Input::MouseClickStatus status, PointerPress& press) const;
+    mutable PointerPress m_leftPress;
+    mutable PointerPress m_rightPress;
 };
 } // namespace WallpaperEngine::Render

+ 6 - 0
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -532,6 +532,12 @@ void WaylandOutputViewport::createEGLSurface () {
     // stalling the main loop
     eglSwapInterval (m_driver->getEGLContext ()->display, 0);
 
+    if (this->reopenDelay.count () > 0) {
+	sLog.out ("Output ", this->name, ": the compositor took the wallpaper surface again");
+    }
+
+    this->reopenDelay = {};
+    this->reopenAtMaxLogged = false;
     this->m_driver->getOutput ().reset ();
 }
 

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

@@ -56,6 +56,12 @@ namespace Output {
 	bool rendering = false;
 	/** layer surface closed or output removed, set during event dispatch and freed by the driver's main loop */
 	bool closed = false;
+	/** closed because the output went away, not the shell surface */
+	bool outputRemoved = false;
+	/** reopen backoff after a closed shell surface, doubled per close */
+	std::chrono::seconds reopenDelay { 0 };
+	std::chrono::steady_clock::time_point reopenAt = {};
+	bool reopenAtMaxLogged = false;
 
 	wl_egl_window* eglWindow = nullptr;
 	EGLSurface eglSurface = nullptr;

+ 6 - 43
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -129,22 +129,7 @@ void X11Output::discoverOutputs (XRRScreenResources* screenResources) {
 	    continue;
 	}
 
-	bool inSpanGroup = false;
-	for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	    for (const auto& screen : spanGroup.screens) {
-		if (screen == info->name) {
-		    inSpanGroup = true;
-		    break;
-		}
-	    }
-	    if (inSpanGroup) {
-		break;
-	    }
-	}
-
-	if (inSpanGroup
-	    || this->m_context.settings.general.screenBackgrounds.find (info->name)
-		!= this->m_context.settings.general.screenBackgrounds.end ()) {
+	if (this->m_context.isScreenRequested (info->name)) {
 	    sLog.out (
 		"Found requested screen: ", info->name, " -> ", crtc->x, "x", crtc->y, ":", crtc->width, "x",
 		crtc->height
@@ -162,31 +147,9 @@ void X11Output::discoverOutputs (XRRScreenResources* screenResources) {
 }
 
 void X11Output::validateOutputs () const {
-    bool any = false;
-
-    for (const auto& o : this->m_screens) {
-	const auto cur = this->m_context.settings.general.screenBackgrounds.find (o->name);
-
-	if (cur != this->m_context.settings.general.screenBackgrounds.end ()) {
-	    any = true;
-	    break;
-	}
-
-	for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	    for (const auto& screen : spanGroup.screens) {
-		if (screen == o->name) {
-		    any = true;
-		    break;
-		}
-	    }
-	    if (any) {
-		break;
-	    }
-	}
-	if (any) {
-	    break;
-	}
-    }
+    const bool any = std::ranges::any_of (this->m_screens, [this] (const OutputViewport* o) {
+	return this->m_context.isScreenRequested (o->name);
+    });
 
     if (!any) {
 	sLog.error ("No outputs could be initialized, please check the parameters and try again");
@@ -198,8 +161,8 @@ void X11Output::validateOutputs () const {
 
 	sLog.error ("Requested: ");
 
-	for (const auto& o : this->m_context.settings.general.screenBackgrounds | std::views::keys) {
-	    sLog.error ("  ", o);
+	for (const auto& line : this->m_context.describeRequestedScreens ()) {
+	    sLog.error ("  ", line);
 	}
 
 	sLog.exception ("Cannot continue...");

+ 103 - 39
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -33,6 +33,8 @@ using namespace WallpaperEngine::Render::Drivers;
 
 constexpr int EVENT_WAIT_TIMEOUT_MS = 100;
 constexpr auto MISSED_FRAME_TIMEOUT = std::chrono::seconds (1);
+constexpr auto SURFACE_REOPEN_MIN = std::chrono::seconds (1);
+constexpr auto SURFACE_REOPEN_MAX = std::chrono::seconds (30);
 
 static void handlePointerEnter (
     void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface, wl_fixed_t surface_x,
@@ -247,6 +249,7 @@ static void handleGlobalRemoved (void* data, struct wl_registry* registry, uint3
 
     if (it != driver->m_screens.end ()) {
 	(*it)->closed = true;
+	(*it)->outputRemoved = true;
 	(*it)->rendering = false;
     }
 }
@@ -392,20 +395,25 @@ void WaylandOpenGLDriver::finishEGL () const {
     eglReleaseThread ();
 }
 
-void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport) {
-    sLog.error ("Compositor closed our LS, freeing data...");
-
+void WaylandOpenGLDriver::releaseSurface (Output::WaylandOutputViewport* viewport) {
     if (viewport->frameCallback) {
 	wl_callback_destroy (viewport->frameCallback);
 	viewport->frameCallback = nullptr;
     }
 
     if (viewport->eglSurface) {
+	// keep GL usable without a surface (uploads, reloads)
+	if (eglGetCurrentSurface (EGL_DRAW) == viewport->eglSurface) {
+	    this->makeSurfacelessCurrent ();
+	}
+
 	eglDestroySurface (m_eglContext.display, viewport->eglSurface);
+	viewport->eglSurface = nullptr;
     }
 
     if (viewport->eglWindow) {
 	wl_egl_window_destroy (viewport->eglWindow);
+	viewport->eglWindow = nullptr;
     }
 
     if (viewport->colorSurface) {
@@ -413,11 +421,6 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
 	viewport->colorSurface = nullptr;
     }
 
-    if (viewport->colorOutput) {
-	wp_color_management_output_v1_destroy (viewport->colorOutput);
-	viewport->colorOutput = nullptr;
-    }
-
     if (viewport->fractionalScale) {
 	wp_fractional_scale_v1_destroy (viewport->fractionalScale);
 	viewport->fractionalScale = nullptr;
@@ -430,6 +433,7 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
 
     if (viewport->layerSurface) {
 	zwlr_layer_surface_v1_destroy (viewport->layerSurface);
+	viewport->layerSurface = nullptr;
     }
 
     if (viewport->xdgToplevel) {
@@ -449,36 +453,95 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
     }
 #endif
 
-    if (viewport->xdgOutput) {
-	zxdg_output_v1_destroy (viewport->xdgOutput);
-	viewport->xdgOutput = nullptr;
-    }
-
     if (viewport->surface) {
 	wl_surface_destroy (viewport->surface);
+	viewport->surface = nullptr;
     }
 
     if (viewport->cursorSurface) {
 	wl_surface_destroy (viewport->cursorSurface);
+	viewport->cursorSurface = nullptr;
     }
 
     if (viewport->cursorTheme) {
 	wl_cursor_theme_destroy (viewport->cursorTheme);
-    }
-
-    if (viewport->output) {
-	wl_output_release (viewport->output);
+	viewport->cursorTheme = nullptr;
+	viewport->pointer = nullptr;
     }
 
     if (this->viewportInFocus == viewport) {
 	this->viewportInFocus = nullptr;
     }
 
+    viewport->pointerEntered = false;
+    viewport->toplevelConfigured = false;
+    viewport->callbackInitialized = false;
+    viewport->inputPassthrough = false;
+    viewport->closed = false;
+    this->getOutput ().reset ();
+}
+
+void WaylandOpenGLDriver::removeOutput (Output::WaylandOutputViewport* viewport) {
+    sLog.out ("Output ", viewport->name, " was removed");
+
+    this->releaseSurface (viewport);
+
+    if (viewport->xdgOutput) {
+	zxdg_output_v1_destroy (viewport->xdgOutput);
+	viewport->xdgOutput = nullptr;
+    }
+
+    if (viewport->colorOutput) {
+	wp_color_management_output_v1_destroy (viewport->colorOutput);
+	viewport->colorOutput = nullptr;
+    }
+
+    if (viewport->output) {
+	wl_output_release (viewport->output);
+    }
+
     std::erase (this->m_screens, viewport);
     this->getOutput ().reset ();
     delete viewport;
 }
 
+void WaylandOpenGLDriver::onSurfaceClosed (Output::WaylandOutputViewport* viewport) {
+    this->releaseSurface (viewport);
+
+    // river closes layer surfaces while no WM runs, as can an output turning off; with no signal for when to
+    // retry, back off
+    viewport->reopenDelay = std::clamp (viewport->reopenDelay * 2, SURFACE_REOPEN_MIN, SURFACE_REOPEN_MAX);
+    viewport->reopenAt = std::chrono::steady_clock::now () + viewport->reopenDelay;
+
+    if (viewport->reopenDelay == SURFACE_REOPEN_MIN) {
+	sLog.error (
+	    "The compositor closed the wallpaper surface on ", viewport->name,
+	    " (river does this while no window manager runs), trying again"
+	);
+    } else if (viewport->reopenDelay == SURFACE_REOPEN_MAX && !viewport->reopenAtMaxLogged) {
+	viewport->reopenAtMaxLogged = true;
+	sLog.error (
+	    "The compositor keeps closing the wallpaper surface on ", viewport->name, ", trying again every ",
+	    SURFACE_REOPEN_MAX.count (), " s"
+	);
+    }
+
+    if (this->drawnOutputs ().empty () && !this->m_waitingLogged) {
+	this->m_waitingLogged = true;
+	sLog.error ("No output shows a wallpaper, waiting until the compositor takes one");
+    }
+}
+
+void WaylandOpenGLDriver::makeSurfacelessCurrent () {
+    if (eglMakeCurrent (m_eglContext.display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_eglContext.context) == EGL_FALSE) {
+	sLog.exception (
+	    "The compositor shows no wallpaper surface and EGL can't use the GL context without one "
+	    "(EGL_KHR_surfaceless_context), error ",
+	    eglGetError ()
+	);
+    }
+}
+
 WaylandOpenGLDriver::WaylandOpenGLDriver (ApplicationContext& context, WallpaperApplication& app) :
     VideoDriver (app, m_mouseInput), m_output (context, *this), m_requestedExit (false), m_frameCounter (0),
     m_context (context), m_mouseInput (*this) {
@@ -486,6 +549,12 @@ WaylandOpenGLDriver::WaylandOpenGLDriver (ApplicationContext& context, Wallpaper
     initColorManagement ();
     initEGL ();
     setupOutputLayerSurfaces ();
+
+    // all surfaces closed during setup, keep loading and wait for an output
+    if (eglGetCurrentContext () == EGL_NO_CONTEXT) {
+	this->makeSurfacelessCurrent ();
+    }
+
     initGLEW ();
 }
 
@@ -636,7 +705,7 @@ void WaylandOpenGLDriver::setupOutputLayerSurfaces () {
     bool any = false;
 
     for (const auto& o : this->m_screens) {
-	if (!isScreenRequested (o->name)) {
+	if (!m_context.isScreenRequested (o->name)) {
 	    continue;
 	}
 
@@ -658,14 +727,8 @@ void WaylandOpenGLDriver::setupOutputLayerSurfaces () {
 
 	sLog.error ("Requested: ");
 
-	for (const auto& o : m_context.settings.general.screenBackgrounds | std::views::keys) {
-	    sLog.error ("  ", o);
-	}
-
-	for (const auto& spanGroup : m_context.settings.general.spanGroups) {
-	    for (const auto& screen : spanGroup.screens) {
-		sLog.error ("  ", screen, " (span group)");
-	    }
+	for (const auto& line : m_context.describeRequestedScreens ()) {
+	    sLog.error ("  ", line);
 	}
 
 	sLog.exception ("Cannot continue...");
@@ -674,25 +737,18 @@ void WaylandOpenGLDriver::setupOutputLayerSurfaces () {
     this->m_layerSurfacesReady = true;
 }
 
-bool WaylandOpenGLDriver::isScreenRequested (const std::string& name) const {
-    if (m_context.settings.general.screenBackgrounds.contains (name)) {
-	return true;
-    }
-
-    return std::ranges::any_of (m_context.settings.general.spanGroups, [&name] (const auto& spanGroup) {
-	return std::ranges::find (spanGroup.screens, name) != spanGroup.screens.end ();
-    });
-}
-
 void WaylandOpenGLDriver::setupLateOutputs () {
     // KDE often drops and re-adds outputs while it applies the screen layout at login, and monitors can
     // wake up after we started; the wallpapers stay registered by screen name, only the surface is missing
     for (const auto& o : this->m_screens) {
-	if (o->hasShellSurface () || o->closed || !o->initialized || !isScreenRequested (o->name)) {
+	if (o->hasShellSurface () || o->closed || !o->initialized || !m_context.isScreenRequested (o->name)
+	    || std::chrono::steady_clock::now () < o->reopenAt) {
 	    continue;
 	}
 
-	sLog.out ("Output ", o->name, " appeared, attaching the wallpaper");
+	if (o->reopenDelay.count () == 0) {
+	    sLog.out ("Output ", o->name, " appeared, attaching the wallpaper");
+	}
 
 	if (m_waylandContext.xdgOutputManager && !o->xdgOutput) {
 	    o->setupXdgOutput (m_waylandContext.xdgOutputManager);
@@ -703,6 +759,10 @@ void WaylandOpenGLDriver::setupLateOutputs () {
 	} else {
 	    o->setupToplevel ();
 	}
+
+	if (o->eglSurface && !o->closed) {
+	    this->m_waitingLogged = false;
+	}
     }
 }
 
@@ -748,7 +808,11 @@ void WaylandOpenGLDriver::reapClosedOutputs () {
     std::ranges::copy_if (this->m_screens, std::back_inserter (closed), [] (const auto* o) { return o->closed; });
 
     for (auto* viewport : closed) {
-	this->onLayerClose (viewport);
+	if (viewport->outputRemoved) {
+	    this->removeOutput (viewport);
+	} else {
+	    this->onSurfaceClosed (viewport);
+	}
     }
 }
 

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

@@ -107,11 +107,16 @@ public:
      */
     [[nodiscard]] wp_image_description_v1* getHDRDescription () const;
 
-    void onLayerClose (Output::WaylandOutputViewport*);
+    /** destroys shell, EGL and cursor surfaces, keeps the output */
+    void releaseSurface (Output::WaylandOutputViewport*);
+    void removeOutput (Output::WaylandOutputViewport*);
+    /** a new surface is requested later */
+    void onSurfaceClosed (Output::WaylandOutputViewport*);
+    void makeSurfacelessCurrent ();
     /** the cursor position is known without a surface of ours under it */
     [[nodiscard]] bool hasGlobalCursor () const { return this->m_mouseInput.hasGlobalCursor (); }
     [[nodiscard]] Desktop::GnomeShell* getGnomeShell () const { return this->m_gnomeShell.get (); }
-    /** frees the viewports the compositor closed, outside of any event dispatch */
+    /** runs outside event dispatch */
     void reapClosedOutputs ();
     Output::WaylandOutputViewport* surfaceToViewport (const wl_surface*) const;
     [[nodiscard]] std::vector<std::string> drawnOutputs () const;
@@ -135,7 +140,6 @@ private:
     void initWaylandRegistry ();
     void initGnomeShell ();
     void setupOutputLayerSurfaces ();
-    [[nodiscard]] bool isScreenRequested (const std::string& name) const;
     void setupLateOutputs ();
     void initEGL ();
     void initGLEW ();
@@ -147,6 +151,7 @@ private:
     uint32_t m_frameCounter = 0;
     bool m_layerSurfacesReady = false;
     bool m_dispatchingWhilePaused = false;
+    bool m_waitingLogged = false;
     ApplicationContext& m_context;
     std::unique_ptr<Desktop::GnomeShell> m_gnomeShell;
     WaylandMouseInput m_mouseInput;

+ 5 - 1
src/WallpaperEngine/Render/GifAnimation.cpp

@@ -3,6 +3,8 @@
 #include <algorithm>
 #include <cstring>
 
+#include "ImageDecoder.h"
+
 using namespace WallpaperEngine::Render;
 
 namespace {
@@ -69,7 +71,9 @@ bool GifAnimation::readHeader () {
     get8 (); // aspect ratio
     m_transparent = -1;
 
-    if (m_width > 0x1000000 || m_height > 0x1000000) {
+    // WE only stops at a failed malloc, which overcommit never gives; the canvas becomes a texture, so the GPU limit
+    // bounds it. loadNext rereads the header while the canvas is empty
+    if (m_width == 0 || m_height == 0 || exceedsMaxImageSide (m_width, m_height)) {
 	return false;
     }
 

+ 23 - 0
src/WallpaperEngine/Render/ImageDecoder.cpp

@@ -1,10 +1,13 @@
 #include "ImageDecoder.h"
 
+#include <atomic>
 #include <cstdint>
 #include <cstdlib>
 #include <cstring>
 #include <utility>
 
+#include "WallpaperEngine/Logging/Log.h"
+
 namespace {
 uint16_t read16 (const uint8_t* p, bool bigEndian) { return bigEndian ? (p[0] << 8) | p[1] : (p[1] << 8) | p[0]; }
 
@@ -100,11 +103,31 @@ int jpegOrientation (const uint8_t* data, size_t size) {
 int orientationOf (const void* data, size_t size) { return jpegOrientation (static_cast<const uint8_t*> (data), size); }
 
 bool swapsAxes (int orientation) { return orientation >= 5; }
+
+std::atomic<int> maxSide = 0;
 } // namespace
 
 namespace WallpaperEngine::Render {
+void setMaxImageSide (const int side) { maxSide = side; }
+
+int maxImageSide () { return maxSide; }
+
+bool exceedsMaxImageSide (const int width, const int height) {
+    const int limit = maxSide;
+    return limit > 0 && (width > limit || height > limit);
+}
+
 stbi_uc* decodeImageRGBA (const void* data, size_t size, int& width, int& height) {
     int channels;
+
+    if (stbi_info_from_memory (static_cast<const stbi_uc*> (data), static_cast<int> (size), &width, &height, &channels)
+	&& exceedsMaxImageSide (width, height)) {
+	sLog.error (
+	    "Image ", width, "x", height, " is past the GPU's texture size limit ", maxImageSide (), ", skipped"
+	);
+	return nullptr;
+    }
+
     stbi_uc* pixels = stbi_load_from_memory (
 	static_cast<const stbi_uc*> (data), static_cast<int> (size), &width, &height, &channels, 4
     );

+ 5 - 0
src/WallpaperEngine/Render/ImageDecoder.h

@@ -12,4 +12,9 @@ stbi_uc* decodeImageRGBA (const void* data, size_t size, int& width, int& height
 
 // decoded size without decoding
 bool decodedImageSize (const void* data, size_t size, int& width, int& height);
+
+/** GL_MAX_TEXTURE_SIZE, checked before decoding so a bogus header can't allocate gigabytes. 0 = no limit */
+void setMaxImageSide (int side);
+[[nodiscard]] int maxImageSide ();
+[[nodiscard]] bool exceedsMaxImageSide (int width, int height);
 } // namespace WallpaperEngine::Render

+ 23 - 489
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -4,6 +4,7 @@
 
 #include "CMesh.h"
 #include "CRenderable.h"
+#include "PuppetMeshFile.h"
 
 #include <algorithm>
 #include <array>
@@ -83,336 +84,6 @@ std::optional<glm::vec3> findMagentaCompositeTint (const Image& image, const std
     return std::nullopt;
 }
 
-struct PuppetMeshBlock {
-    size_t headerOffset = 0;
-    uint32_t vertexBytes = 0;
-    uint32_t indexBytes = 0;
-};
-
-// byte offsets that could be an MDLV mesh header (vertex and index byte lengths fitting before MDLS), the stride is
-// resolved later (resolvePuppetVertexLayout)
-std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
-    const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize
-) {
-    std::vector<PuppetMeshBlock> candidates;
-
-    for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset; offset++) {
-	reader.base ().seekg (static_cast<std::streamoff> (offset + sizeof (uint32_t)), std::ios::beg);
-	const uint32_t candidateVertexBytes = reader.nextUInt32 ();
-	const size_t verticesOffset = offset + meshHeaderSize;
-	const size_t indexLengthOffset = verticesOffset + candidateVertexBytes;
-
-	if (candidateVertexBytes == 0 || indexLengthOffset + sizeof (uint32_t) > mdlsOffset) {
-	    continue;
-	}
-
-	reader.base ().seekg (static_cast<std::streamoff> (indexLengthOffset), std::ios::beg);
-	const uint32_t candidateIndexBytes = reader.nextUInt32 ();
-	const size_t indicesOffset = indexLengthOffset + sizeof (uint32_t);
-	if (candidateIndexBytes == 0 || candidateIndexBytes % (sizeof (uint16_t) * 3) != 0
-	    || indicesOffset + candidateIndexBytes > mdlsOffset) {
-	    continue;
-	}
-
-	candidates.push_back (
-	    PuppetMeshBlock {
-		.headerOffset = offset, .vertexBytes = candidateVertexBytes, .indexBytes = candidateIndexBytes }
-	);
-    }
-
-    return candidates;
-}
-
-struct PuppetVertexLayout {
-    PuppetMeshBlock block;
-    size_t vertexStride = 0;
-    size_t uvOffset = 0;
-};
-
-// the UV pair is always the last 8 bytes of a vertex, so uvOffset = stride - 8
-struct PuppetMeshData {
-    std::vector<GLfloat> positions;
-    std::vector<GLfloat> texcoords;
-    std::vector<GLushort> indices;
-};
-
-std::optional<PuppetMeshData> readPuppetMeshData (
-    const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
-) {
-    if (block.vertexBytes % vertexStride != 0) {
-	return std::nullopt;
-    }
-
-    const size_t uvOffset = vertexStride - sizeof (GLfloat) * 2;
-    const size_t vertexCount = block.vertexBytes / vertexStride;
-    const size_t verticesOffset = block.headerOffset + meshHeaderSize;
-    const size_t indicesOffset = verticesOffset + block.vertexBytes + sizeof (uint32_t);
-    const size_t indexCount = block.indexBytes / sizeof (uint16_t);
-
-    PuppetMeshData data;
-    data.positions.reserve (vertexCount * 3);
-    data.texcoords.reserve (vertexCount * 2);
-    data.indices.reserve (indexCount);
-
-    for (size_t index = 0; index < vertexCount; index++) {
-	const size_t vertexOffset = verticesOffset + index * vertexStride;
-	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset), std::ios::beg);
-	const float x = reader.nextFloat ();
-	const float y = reader.nextFloat ();
-	const float z = reader.nextFloat ();
-	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + uvOffset), std::ios::beg);
-	const float u = reader.nextFloat ();
-	const float v = reader.nextFloat ();
-
-	data.positions.push_back (x);
-	data.positions.push_back (y);
-	data.positions.push_back (z);
-	data.texcoords.push_back (u);
-	data.texcoords.push_back (v);
-    }
-
-    reader.base ().seekg (static_cast<std::streamoff> (indicesOffset), std::ios::beg);
-    for (size_t index = 0; index < indexCount; index++) {
-	uint16_t value = 0;
-	reader.next (reinterpret_cast<char*> (&value), sizeof (value));
-	if (value >= vertexCount) {
-	    return std::nullopt;
-	}
-	data.indices.push_back (value);
-    }
-
-    return data;
-}
-
-// blend indices/weights are the 32 bytes before the UV pair whatever the stride (docs/rendering/MDL_FILES.md)
-struct PuppetBlendData {
-    std::vector<glm::uvec4> indices;
-    std::vector<glm::vec4> weights;
-};
-
-std::optional<PuppetBlendData> readPuppetBlendData (
-    const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
-) {
-    if (vertexStride < 40 || block.vertexBytes % vertexStride != 0) {
-	return std::nullopt;
-    }
-
-    const size_t blendIndicesOffset = vertexStride - 40;
-    const size_t blendWeightsOffset = vertexStride - 24;
-    const size_t vertexCount = block.vertexBytes / vertexStride;
-    const size_t verticesOffset = block.headerOffset + meshHeaderSize;
-
-    PuppetBlendData data;
-    data.indices.reserve (vertexCount);
-    data.weights.reserve (vertexCount);
-
-    for (size_t index = 0; index < vertexCount; index++) {
-	const size_t vertexOffset = verticesOffset + index * vertexStride;
-
-	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendIndicesOffset), std::ios::beg);
-	glm::uvec4 boneIndices;
-	boneIndices.x = reader.nextUInt32 ();
-	boneIndices.y = reader.nextUInt32 ();
-	boneIndices.z = reader.nextUInt32 ();
-	boneIndices.w = reader.nextUInt32 ();
-
-	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendWeightsOffset), std::ios::beg);
-	glm::vec4 boneWeights;
-	boneWeights.x = reader.nextFloat ();
-	boneWeights.y = reader.nextFloat ();
-	boneWeights.z = reader.nextFloat ();
-	boneWeights.w = reader.nextFloat ();
-
-	data.indices.push_back (boneIndices);
-	data.weights.push_back (boneWeights);
-    }
-
-    return data;
-}
-
-// lower is better: a wrong stride reads bone data as positions and gives huge, inconsistent triangles; nullopt for
-// degenerate meshes
-std::optional<double> scorePuppetMeshCoherence (const PuppetMeshData& data) {
-    if (data.indices.size () < 3) {
-	return std::nullopt;
-    }
-
-    glm::vec3 min (std::numeric_limits<float>::max ());
-    glm::vec3 max (std::numeric_limits<float>::lowest ());
-    const size_t vertexCount = data.positions.size () / 3;
-
-    for (size_t i = 0; i < vertexCount; i++) {
-	const glm::vec3 p (data.positions[i * 3], data.positions[i * 3 + 1], data.positions[i * 3 + 2]);
-	min = glm::min (min, p);
-	max = glm::max (max, p);
-    }
-
-    const double diagonal = glm::length (max - min);
-    if (diagonal <= 0.0) {
-	return std::nullopt;
-    }
-
-    double totalEdgeLength = 0.0;
-    size_t edgeCount = 0;
-
-    for (size_t triangle = 0; triangle + 2 < data.indices.size (); triangle += 3) {
-	const auto vertexPosition = [&data] (size_t index) {
-	    return glm::vec3 (data.positions[index * 3], data.positions[index * 3 + 1], data.positions[index * 3 + 2]);
-	};
-
-	const glm::vec3 a = vertexPosition (data.indices[triangle]);
-	const glm::vec3 b = vertexPosition (data.indices[triangle + 1]);
-	const glm::vec3 c = vertexPosition (data.indices[triangle + 2]);
-
-	totalEdgeLength += glm::length (a - b) + glm::length (b - c) + glm::length (c - a);
-	edgeCount += 3;
-    }
-
-    if (edgeCount == 0) {
-	return std::nullopt;
-    }
-
-    return (totalEdgeLength / static_cast<double> (edgeCount)) / diagonal;
-}
-
-// the same MDLV version comes with different strides, so every plausible stride is tried on every candidate header and
-// the most coherent mesh wins
-std::optional<PuppetVertexLayout>
-resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize) {
-    constexpr size_t minVertexStride = 20; // position (12 bytes) + uv (8 bytes), no bone data at all
-    constexpr size_t maxVertexStride = 256; // covers multi-bone rigs
-    constexpr size_t strideStep = 4; // every field observed so far is a 4-byte float/uint
-
-    const auto candidates = findPuppetMeshBlockCandidates (reader, markerSize, mdlsOffset, meshHeaderSize);
-
-    std::optional<PuppetVertexLayout> best;
-    double bestScore = std::numeric_limits<double>::max ();
-
-    for (const auto& block : candidates) {
-	for (size_t stride = minVertexStride; stride <= maxVertexStride; stride += strideStep) {
-	    const auto data = readPuppetMeshData (reader, block, meshHeaderSize, stride);
-	    if (!data.has_value ()) {
-		continue;
-	    }
-
-	    const auto score = scorePuppetMeshCoherence (*data);
-	    if (!score.has_value ()) {
-		continue;
-	    }
-
-	    if (*score >= bestScore) {
-		continue;
-	    }
-
-	    bestScore = *score;
-	    best = PuppetVertexLayout { .block = block,
-					.vertexStride = stride,
-					.uvOffset = stride - sizeof (GLfloat) * 2 };
-	}
-    }
-
-    return best;
-}
-
-// bounds-checked little endian reads for MDLV/MDMP (sub_140261880)
-class PuppetFileReader {
-public:
-    PuppetFileReader (const std::vector<char>& data, size_t offset) : m_data (data), m_offset (offset) { }
-
-    template <typename T> T next () {
-	if (this->m_offset + sizeof (T) > this->m_data.size ()) {
-	    throw std::runtime_error ("truncated puppet file");
-	}
-
-	T value;
-	std::memcpy (&value, this->m_data.data () + this->m_offset, sizeof (T));
-	this->m_offset += sizeof (T);
-	return value;
-    }
-
-    void string () {
-	while (this->next<char> () != '\0') { }
-    }
-
-    std::string text () {
-	std::string result;
-
-	for (char c = this->next<char> (); c != '\0'; c = this->next<char> ()) {
-	    result.push_back (c);
-	}
-
-	return result;
-    }
-
-    /** u32 size + bytes */
-    std::pair<size_t, uint32_t> blob () {
-	const auto bytes = this->next<uint32_t> ();
-	const size_t start = this->m_offset;
-
-	if (start + bytes > this->m_data.size ()) {
-	    throw std::runtime_error ("truncated puppet file");
-	}
-
-	this->m_offset += bytes;
-	return { start, bytes };
-    }
-
-    void skip (size_t bytes) { this->m_offset += bytes; }
-
-    [[nodiscard]] size_t offset () const { return this->m_offset; }
-
-private:
-    const std::vector<char>& m_data;
-    size_t m_offset;
-};
-
-struct PuppetMeshHeader {
-    uint32_t flags = 0;
-    uint32_t format = 0;
-    size_t vertices = 0;
-    uint32_t vertexBytes = 0;
-    uint32_t indexBytes = 0;
-};
-
-// first mesh header: tag, default format, materials per mesh, mesh count, then per mesh: material names, flags
-// (+u32 with flag 2), bounds (v17+), format (v15+)
-PuppetMeshHeader readPuppetMeshHeader (const std::vector<char>& data) {
-    PuppetFileReader reader (data, 0);
-    reader.string ();
-
-    const int version = std::atoi (data.data () + strlen ("MDLV"));
-    PuppetMeshHeader header;
-    header.format = reader.next<uint32_t> ();
-    const auto materials = reader.next<uint32_t> ();
-    (void)reader.next<uint32_t> ();
-
-    for (uint32_t material = 0; material < materials; material++) {
-	reader.string ();
-    }
-
-    if (version >= 4) {
-	header.flags = reader.next<uint32_t> ();
-
-	if (header.flags & 2) {
-	    (void)reader.next<uint32_t> ();
-	}
-
-	if (version >= 17) {
-	    reader.skip (sizeof (float) * 6);
-	}
-
-	if (version >= 15) {
-	    header.format = reader.next<uint32_t> ();
-	}
-    }
-
-    header.vertexBytes = reader.next<uint32_t> ();
-    header.vertices = reader.offset ();
-    reader.skip (header.vertexBytes);
-    header.indexBytes = reader.next<uint32_t> ();
-    return header;
-}
-
 // float4x3 per bone
 void packPuppetBones (const std::vector<glm::mat4>& skin, std::vector<GLfloat>& out) {
     out.assign (skin.size () * 12, 0.0f);
@@ -426,26 +97,6 @@ void packPuppetBones (const std::vector<glm::mat4>& skin, std::vector<GLfloat>&
     }
 }
 
-// sub_140261880 layout of the first mesh; texcoords not last in the vertex fall back to the heuristic
-std::optional<PuppetVertexLayout> readPuppetVertexLayout (const std::vector<char>& data, size_t meshHeaderSize) {
-    const auto header = readPuppetMeshHeader (data);
-    const uint32_t stride = CMesh::vertexStride (header.format);
-    const auto texcoord = CMesh::vertexComponentOffset (header.format, 0x8);
-
-    if (stride == 0 || header.vertexBytes % stride != 0 || !texcoord.has_value ()
-	|| *texcoord != stride - sizeof (GLfloat) * 2 || header.vertices + header.vertexBytes > data.size ()) {
-	return std::nullopt;
-    }
-
-    return PuppetVertexLayout {
-	.block = PuppetMeshBlock { .headerOffset = header.vertices - meshHeaderSize,
-				   .vertexBytes = header.vertexBytes,
-				   .indexBytes = header.indexBytes },
-	.vertexStride = stride,
-	.uvOffset = *texcoord,
-    };
-}
-
 // first mesh with flag 2 (sub_1401FBAE0, puppet +912), BLENDROWCOUNT = the u32 after its flags (sub_140209540)
 std::optional<PuppetBlendMesh> readPuppetBlendMesh (const std::vector<char>& data) {
     PuppetFileReader reader (data, 0);
@@ -1135,49 +786,20 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	return false;
     }
 
+    const auto& name = *this->getImage ().model->puppet;
+
     try {
-	const auto file = this->getScene ().readModelFile (*this->getImage ().model->puppet);
+	const auto file = this->getScene ().readModelFile (name);
 	const std::vector<char>& data = *file;
+	auto mesh = readPuppetMeshFile (data);
 
-	constexpr size_t markerSize = 9;
-	constexpr size_t meshHeaderSize = sizeof (uint32_t) * 2;
-
-	const std::string puppetVersion
-	    = data.size () >= markerSize ? std::string (data.data (), strlen ("MDLV0021")) : "";
-
-	const size_t mdlsOffset = [&data] () -> size_t {
-	    for (size_t offset = markerSize; offset + strlen ("MDLS") < data.size (); offset++) {
-		if (std::memcmp (data.data () + offset, "MDLS", strlen ("MDLS")) == 0) {
-		    return offset;
-		}
-	    }
-	    return data.size ();
-	}();
-
-	auto meshBuffer = std::make_unique<char[]> (data.size ());
-	std::copy (data.begin (), data.end (), meshBuffer.get ());
-	const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
-
-	std::optional<PuppetVertexLayout> layout;
-
-	try {
-	    layout = readPuppetVertexLayout (data, meshHeaderSize);
-	} catch (const std::exception& ex) {
-	    sLog.error ("Could not read the first mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
-	}
-
-	if (!layout.has_value ()) {
-	    layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
-	}
-	if (!layout.has_value ()) {
-	    sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
+	if (!mesh.has_value ()) {
+	    sLog.error ("Could not find a usable MDLV mesh block in ", name);
 	    return false;
 	}
 
-	const auto mesh = readPuppetMeshData (reader, layout->block, meshHeaderSize, layout->vertexStride);
-	if (!mesh.has_value ()) {
-	    sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
-	    return false;
+	for (const auto& warning : mesh->warnings) {
+	    sLog.error ("Puppet ", name, ": ", warning);
 	}
 
 	this->m_puppetRawPositions = mesh->positions;
@@ -1201,104 +823,25 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 
 	this->loadPuppetBlendMesh (data);
 
-	// the part ranges and clipping records follow the index buffer (sub_140261880)
-	const int version
-	    = puppetVersion.size () > strlen ("MDLV") ? std::atoi (puppetVersion.c_str () + strlen ("MDLV")) : 0;
-	const size_t indexEnd = layout->block.headerOffset + meshHeaderSize + layout->block.vertexBytes
-	    + sizeof (uint32_t) + layout->block.indexBytes;
+	const int version = mesh->version;
+	const size_t indexEnd = mesh->indexEnd;
 	this->m_puppetClipping.reset ();
 	this->m_puppetParts.clear ();
 	this->m_puppetPartOrder.clear ();
 	this->m_puppetMeshIndices.clear ();
 
 	// 4 bone alpha, 8 draw order, 0x1000 morph alpha
-	this->m_puppetMeshFlags = 0;
-	this->m_puppetMeshFormat = 0;
-
-	try {
-	    const auto header = readPuppetMeshHeader (data);
-
-	    if (header.vertices == layout->block.headerOffset + meshHeaderSize) {
-		this->m_puppetMeshFlags = header.flags;
-		this->m_puppetMeshFormat = header.format;
-	    } else {
-		sLog.error (
-		    "The first mesh header of ", *this->getImage ().model->puppet, " isn't where its vertices are"
-		);
-	    }
-	} catch (const std::exception& ex) {
-	    sLog.error ("Could not read the mesh header of ", *this->getImage ().model->puppet, ": ", ex.what ());
-	}
+	this->m_puppetMeshFlags = mesh->flags;
+	this->m_puppetMeshFormat = mesh->format;
 
 	const uint32_t meshFlags = this->m_puppetMeshFlags;
-	const size_t vertexCount = layout->block.vertexBytes / layout->vertexStride;
-	const size_t verticesOffset = layout->block.headerOffset + meshHeaderSize;
 
-	// MDLV 21+: flag, u32 and a block of one vec3 per vertex after the index buffer (a_PositionC1, sub_140261880)
-	this->m_puppetPrelight.auxPositions.clear ();
+	this->m_puppetPrelight.auxPositions = std::move (mesh->auxPositions);
+	this->m_puppetPrelight.normalData = std::move (mesh->normals);
+	this->m_puppetPrelight.tangentData = std::move (mesh->tangents);
 
-	if (version >= 21 && indexEnd < data.size () && data[indexEnd] != 0) {
-	    const size_t blob = indexEnd + 1 + sizeof (uint32_t);
-	    uint32_t bytes = 0;
-
-	    if (blob + sizeof (bytes) <= data.size ()) {
-		std::memcpy (&bytes, data.data () + blob, sizeof (bytes));
-	    }
-
-	    // WE reads three floats per vertex whatever the size says
-	    if (bytes >= vertexCount * sizeof (GLfloat) * 3 && blob + sizeof (bytes) + bytes <= data.size ()) {
-		this->m_puppetPrelight.auxPositions.resize (vertexCount * 3);
-		std::memcpy (
-		    this->m_puppetPrelight.auxPositions.data (), data.data () + blob + sizeof (bytes),
-		    vertexCount * sizeof (GLfloat) * 3
-		);
-	    } else {
-		sLog.error (
-		    "The auxiliary vertex block of ", *this->getImage ().model->puppet,
-		    " is shorter than the mesh, lighting places the bind positions instead"
-		);
-	    }
-	}
-
-	const auto readComponent = [&] (uint32_t bit, size_t floats, std::vector<GLfloat>& out) {
-	    out.clear ();
-	    const auto offset = CMesh::vertexComponentOffset (this->m_puppetMeshFormat, bit);
-
-	    if (!offset.has_value () || *offset + floats * sizeof (GLfloat) > layout->vertexStride) {
-		return;
-	    }
-
-	    out.resize (vertexCount * floats);
-
-	    for (size_t vertex = 0; vertex < vertexCount; vertex++) {
-		std::memcpy (
-		    out.data () + vertex * floats,
-		    data.data () + verticesOffset + vertex * layout->vertexStride + *offset, floats * sizeof (GLfloat)
-		);
-	    }
-	};
-
-	readComponent (0x2, 3, this->m_puppetPrelight.normalData);
-	readComponent (0x4, 4, this->m_puppetPrelight.tangentData);
-
-	// position.w is the morph texel, <= 0 means not morphed
 	this->m_puppetMorph.reset ();
-	this->m_puppetMorphIndices.clear ();
-
-	if (this->m_puppetMeshFormat & 0x10000) {
-	    this->m_puppetMorphIndices.resize (vertexCount);
-
-	    for (size_t vertex = 0; vertex < vertexCount; vertex++) {
-		float w;
-		std::memcpy (
-		    &w, data.data () + verticesOffset + vertex * layout->vertexStride + sizeof (float) * 3, sizeof (w)
-		);
-
-		if (w > 0.0f) {
-		    this->m_puppetMorphIndices[vertex] = static_cast<uint32_t> (w);
-		}
-	    }
-	}
+	this->m_puppetMorphIndices = std::move (mesh->morphIndices);
 
 	if (meshFlags & 8) {
 	    try {
@@ -1339,8 +882,8 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	}
 
 	sLog.out (
-	    "Loaded puppet mesh ", *this->getImage ().model->puppet, " version=", puppetVersion,
-	    " stride=", layout->vertexStride, " vertices=", this->m_puppetRawPositions.size () / 3,
+	    "Loaded puppet mesh ", name, " version=", mesh->tag, " stride=", mesh->layout.vertexStride,
+	    mesh->declaredLayout ? "" : " (guessed)", " vertices=", this->m_puppetRawPositions.size () / 3,
 	    " indices=", this->m_puppetIndexCount
 	);
 
@@ -1349,21 +892,12 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	this->m_puppetBlendWeights.clear ();
 	this->m_puppetSkinnedPositions.clear ();
 
-	const auto blend = readPuppetBlendData (reader, layout->block, meshHeaderSize, layout->vertexStride);
-	if (blend.has_value ()) {
-	    this->m_puppetBlendIndices = blend->indices;
-	    this->m_puppetBlendWeights = blend->weights;
-	}
+	this->m_puppetBlendIndices = std::move (mesh->blendIndices);
+	this->m_puppetBlendWeights = std::move (mesh->blendWeights);
 
-	if (mdlsOffset < data.size () && blend.has_value ()) {
+	if (mesh->skeleton < data.size () && !this->m_puppetBlendIndices.empty ()) {
 	    try {
-		// MDLV header: tag, flags, a second field and the mesh count (2.8.42 sub_140261880)
-		uint32_t meshCount = 0;
-		if (data.size () >= 21) {
-		    std::memcpy (&meshCount, data.data () + 17, sizeof (meshCount));
-		}
-
-		this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
+		this->m_rig.load (data, mesh->sections, mesh->meshCount, name);
 		this->m_rig.drawOrderEnabled = !this->m_puppetParts.empty ();
 		this->m_rig.boneAlphaEnabled = (meshFlags & 4) != 0;
 		this->m_rig.morphBlendClamped = false;

+ 22 - 81
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -13,6 +13,7 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Objects/CRenderable.h"
 #include "WallpaperEngine/Render/Objects/Effects/CPass.h"
+#include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
 #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
@@ -194,59 +195,25 @@ std::vector<MdlMesh> readMdlMeshes (
     const std::vector<char>& data, glm::vec3& boundsMin, glm::vec3& boundsMax, size_t& end, uint32_t& meshCount,
     std::vector<uint32_t>& meshFlags
 ) {
-    MdlReader reader (data);
-    const std::string magic = reader.string ();
-
-    if (!magic.starts_with ("MDLV") || magic.size () < 5) {
-	throw std::runtime_error ("not a MDLV model");
-    }
-
-    const int version = std::stoi (magic.substr (4));
-    const uint32_t defaultFormat = reader.u32 ();
-    const uint32_t materialsPerMesh = reader.u32 ();
-    meshCount = reader.u32 ();
+    const auto file = readMdlvMeshes (data);
     std::vector<MdlMesh> meshes;
 
+    meshCount = static_cast<uint32_t> (file.meshes.size ());
     boundsMin = glm::vec3 (std::numeric_limits<float>::max ());
     boundsMax = glm::vec3 (std::numeric_limits<float>::lowest ());
 
     for (uint32_t index = 0; index < meshCount; index++) {
+	const auto& record = file.meshes[index];
 	MdlMesh mesh;
 	mesh.index = index;
-
-	for (uint32_t material = 0; material < materialsPerMesh; material++) {
-	    mesh.materials.push_back (reader.string ());
-	}
-
+	mesh.materials = record.materials;
 	mesh.material = mesh.materials.empty () ? std::string () : mesh.materials.front ();
+	mesh.flags = record.flags;
+	mesh.format = record.format;
 
-	mesh.format = defaultFormat;
-
-	if (version >= 4) {
-	    mesh.flags = reader.u32 ();
-
-	    if (mesh.flags & 2) {
-		reader.u32 ();
-	    }
-
-	    if (version >= 17) {
-		glm::vec3 min;
-		glm::vec3 max;
-
-		for (int axis = 0; axis < 3; axis++) {
-		    min[axis] = reader.f32 ();
-		}
-		for (int axis = 0; axis < 3; axis++) {
-		    max[axis] = reader.f32 ();
-		}
-
-		boundsMin = glm::min (boundsMin, min);
-		boundsMax = glm::max (boundsMax, max);
-	    }
-
-	    if (version >= 15) {
-		mesh.format = reader.u32 ();
-	    }
+	if (record.bounds.has_value ()) {
+	    boundsMin = glm::min (boundsMin, record.bounds->first);
+	    boundsMax = glm::max (boundsMax, record.bounds->second);
 	}
 
 	for (const auto& component : VERTEX_COMPONENTS) {
@@ -256,46 +223,21 @@ std::vector<MdlMesh> readMdlMeshes (
 	}
 
 	meshFlags.push_back (mesh.flags);
-	mesh.vertices = reader.bytes (reader.u32 ());
-	mesh.indices = reader.bytes (reader.u32 ());
-
-	const bool usable = mesh.stride != 0 && mesh.vertices.size () % mesh.stride == 0;
+	mesh.vertices.assign (
+	    data.begin () + record.vertices.first, data.begin () + record.vertices.first + record.vertices.second
+	);
+	mesh.indices.assign (
+	    data.begin () + record.indices.first, data.begin () + record.indices.first + record.indices.second
+	);
 
-	if (!usable) {
+	if (mesh.stride == 0 || mesh.vertices.size () % mesh.stride != 0) {
 	    sLog.error (
 		"Skipping mesh ", index, " with vertex format ", mesh.format, ", its stride doesn't match its data"
 	    );
+	    continue;
 	}
 
-	// sub_140261880 from version 21: a flag byte with a u32 and a sized blob, a flag byte with a sized blob
-	// (puppets' per bone index ranges); from 23 a count of records (u64, string, u32 flags, two u32 counted u32
-	// lists)
-	if (version >= 21) {
-	    if (reader.u8 () != 0) {
-		reader.u32 ();
-		reader.skip (reader.u32 ());
-	    }
-
-	    if (reader.u8 () != 0) {
-		reader.skip (reader.u32 ());
-	    }
-	}
-
-	if (version >= 23) {
-	    const uint32_t records = reader.u32 ();
-
-	    for (uint32_t record = 0; record < records && reader.has (1); record++) {
-		reader.skip (sizeof (uint64_t));
-		reader.string ();
-		reader.u32 ();
-		reader.skip (sizeof (uint32_t) * reader.u32 ());
-		reader.skip (sizeof (uint32_t) * reader.u32 ());
-	    }
-	}
-
-	if (usable) {
-	    meshes.push_back (std::move (mesh));
-	}
+	meshes.push_back (std::move (mesh));
     }
 
     if (!(boundsMax.x > boundsMin.x)) {
@@ -303,7 +245,7 @@ std::vector<MdlMesh> readMdlMeshes (
 	boundsMax = glm::vec3 (131072.0f);
     }
 
-    end = reader.offset ();
+    end = file.end;
     return meshes;
 }
 
@@ -830,9 +772,8 @@ void CMesh::setup () {
     this->m_cullMin = this->m_boundsMin;
     this->m_cullMax = this->m_boundsMax;
 
-    // version 13+ files name the next section after the last mesh, a skeleton (MDLS) and its clips are loaded the same
-    // way as a puppet's (sub_140261880)
-    if (end + 4 <= data.size () && std::memcmp (data.data () + end, "MDLS", 4) == 0) {
+    // v13+ have sections after the meshes, MDLS and clips load like a puppet's (sub_140261880)
+    if (findMdlSection (data, end, "MDLS").has_value ()) {
 	try {
 	    this->m_rig.load (data, end, meshCount, this->m_mesh.model);
 	    this->m_rig.addSceneLayers (this->m_mesh.animationLayers);

+ 563 - 0
src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp

@@ -0,0 +1,563 @@
+#include "PuppetMeshFile.h"
+
+#include "CMesh.h"
+
+#include <cstdlib>
+#include <limits>
+#include <memory>
+
+#include <glm/glm.hpp>
+
+#include "WallpaperEngine/Data/Utils/BinaryReader.h"
+#include "WallpaperEngine/Data/Utils/MemoryStream.h"
+
+using namespace WallpaperEngine::Render::Objects;
+using namespace WallpaperEngine::Data::Utils;
+
+namespace {
+constexpr size_t MARKER_SIZE = 9;
+constexpr size_t MESH_HEADER_SIZE = sizeof (uint32_t) * 2;
+
+// offsets that could be an MDLV mesh header, stride resolved later
+std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
+    const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize
+) {
+    std::vector<PuppetMeshBlock> candidates;
+
+    for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset; offset++) {
+	reader.base ().seekg (static_cast<std::streamoff> (offset + sizeof (uint32_t)), std::ios::beg);
+	const uint32_t candidateVertexBytes = reader.nextUInt32 ();
+	const size_t verticesOffset = offset + meshHeaderSize;
+	const size_t indexLengthOffset = verticesOffset + candidateVertexBytes;
+
+	if (candidateVertexBytes == 0 || indexLengthOffset + sizeof (uint32_t) > mdlsOffset) {
+	    continue;
+	}
+
+	reader.base ().seekg (static_cast<std::streamoff> (indexLengthOffset), std::ios::beg);
+	const uint32_t candidateIndexBytes = reader.nextUInt32 ();
+	const size_t indicesOffset = indexLengthOffset + sizeof (uint32_t);
+	if (candidateIndexBytes == 0 || candidateIndexBytes % (sizeof (uint16_t) * 3) != 0
+	    || indicesOffset + candidateIndexBytes > mdlsOffset) {
+	    continue;
+	}
+
+	candidates.push_back (
+	    PuppetMeshBlock {
+		.headerOffset = offset, .vertexBytes = candidateVertexBytes, .indexBytes = candidateIndexBytes }
+	);
+    }
+
+    return candidates;
+}
+
+// UVs are always the last 8 bytes of a vertex
+struct PuppetMeshData {
+    std::vector<GLfloat> positions;
+    std::vector<GLfloat> texcoords;
+    std::vector<GLushort> indices;
+};
+
+std::optional<PuppetMeshData> readPuppetMeshData (
+    const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
+) {
+    if (block.vertexBytes % vertexStride != 0) {
+	return std::nullopt;
+    }
+
+    const size_t uvOffset = vertexStride - sizeof (GLfloat) * 2;
+    const size_t vertexCount = block.vertexBytes / vertexStride;
+    const size_t verticesOffset = block.headerOffset + meshHeaderSize;
+    const size_t indicesOffset = verticesOffset + block.vertexBytes + sizeof (uint32_t);
+    const size_t indexCount = block.indexBytes / sizeof (uint16_t);
+
+    PuppetMeshData data;
+    data.positions.reserve (vertexCount * 3);
+    data.texcoords.reserve (vertexCount * 2);
+    data.indices.reserve (indexCount);
+
+    for (size_t index = 0; index < vertexCount; index++) {
+	const size_t vertexOffset = verticesOffset + index * vertexStride;
+	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset), std::ios::beg);
+	const float x = reader.nextFloat ();
+	const float y = reader.nextFloat ();
+	const float z = reader.nextFloat ();
+	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + uvOffset), std::ios::beg);
+	const float u = reader.nextFloat ();
+	const float v = reader.nextFloat ();
+
+	data.positions.push_back (x);
+	data.positions.push_back (y);
+	data.positions.push_back (z);
+	data.texcoords.push_back (u);
+	data.texcoords.push_back (v);
+    }
+
+    reader.base ().seekg (static_cast<std::streamoff> (indicesOffset), std::ios::beg);
+    for (size_t index = 0; index < indexCount; index++) {
+	uint16_t value = 0;
+	reader.next (reinterpret_cast<char*> (&value), sizeof (value));
+	if (value >= vertexCount) {
+	    return std::nullopt;
+	}
+	data.indices.push_back (value);
+    }
+
+    return data;
+}
+
+// blend indices/weights: the 32 bytes before the UVs (docs/rendering/MDL_FILES.md)
+struct PuppetBlendData {
+    std::vector<glm::uvec4> indices;
+    std::vector<glm::vec4> weights;
+};
+
+std::optional<PuppetBlendData> readPuppetBlendData (
+    const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
+) {
+    if (vertexStride < 40 || block.vertexBytes % vertexStride != 0) {
+	return std::nullopt;
+    }
+
+    const size_t blendIndicesOffset = vertexStride - 40;
+    const size_t blendWeightsOffset = vertexStride - 24;
+    const size_t vertexCount = block.vertexBytes / vertexStride;
+    const size_t verticesOffset = block.headerOffset + meshHeaderSize;
+
+    PuppetBlendData data;
+    data.indices.reserve (vertexCount);
+    data.weights.reserve (vertexCount);
+
+    for (size_t index = 0; index < vertexCount; index++) {
+	const size_t vertexOffset = verticesOffset + index * vertexStride;
+
+	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendIndicesOffset), std::ios::beg);
+	glm::uvec4 boneIndices;
+	boneIndices.x = reader.nextUInt32 ();
+	boneIndices.y = reader.nextUInt32 ();
+	boneIndices.z = reader.nextUInt32 ();
+	boneIndices.w = reader.nextUInt32 ();
+
+	reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendWeightsOffset), std::ios::beg);
+	glm::vec4 boneWeights;
+	boneWeights.x = reader.nextFloat ();
+	boneWeights.y = reader.nextFloat ();
+	boneWeights.z = reader.nextFloat ();
+	boneWeights.w = reader.nextFloat ();
+
+	data.indices.push_back (boneIndices);
+	data.weights.push_back (boneWeights);
+    }
+
+    return data;
+}
+
+// lower is better, a wrong stride gives huge inconsistent triangles; nullopt when degenerate
+std::optional<double> scorePuppetMeshCoherence (const PuppetMeshData& data) {
+    if (data.indices.size () < 3) {
+	return std::nullopt;
+    }
+
+    glm::vec3 min (std::numeric_limits<float>::max ());
+    glm::vec3 max (std::numeric_limits<float>::lowest ());
+    const size_t vertexCount = data.positions.size () / 3;
+
+    for (size_t i = 0; i < vertexCount; i++) {
+	const glm::vec3 p (data.positions[i * 3], data.positions[i * 3 + 1], data.positions[i * 3 + 2]);
+	min = glm::min (min, p);
+	max = glm::max (max, p);
+    }
+
+    const double diagonal = glm::length (max - min);
+    if (diagonal <= 0.0) {
+	return std::nullopt;
+    }
+
+    double totalEdgeLength = 0.0;
+    size_t edgeCount = 0;
+
+    for (size_t triangle = 0; triangle + 2 < data.indices.size (); triangle += 3) {
+	const auto vertexPosition = [&data] (size_t index) {
+	    return glm::vec3 (data.positions[index * 3], data.positions[index * 3 + 1], data.positions[index * 3 + 2]);
+	};
+
+	const glm::vec3 a = vertexPosition (data.indices[triangle]);
+	const glm::vec3 b = vertexPosition (data.indices[triangle + 1]);
+	const glm::vec3 c = vertexPosition (data.indices[triangle + 2]);
+
+	totalEdgeLength += glm::length (a - b) + glm::length (b - c) + glm::length (c - a);
+	edgeCount += 3;
+    }
+
+    if (edgeCount == 0) {
+	return std::nullopt;
+    }
+
+    return (totalEdgeLength / static_cast<double> (edgeCount)) / diagonal;
+}
+
+// strides vary within one MDLV version, try them all and keep the most coherent mesh
+std::optional<PuppetVertexLayout>
+resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize) {
+    constexpr size_t minVertexStride = 20; // position + uv
+    constexpr size_t maxVertexStride = 256;
+    constexpr size_t strideStep = 4;
+
+    const auto candidates = findPuppetMeshBlockCandidates (reader, markerSize, mdlsOffset, meshHeaderSize);
+
+    std::optional<PuppetVertexLayout> best;
+    double bestScore = std::numeric_limits<double>::max ();
+
+    for (const auto& block : candidates) {
+	for (size_t stride = minVertexStride; stride <= maxVertexStride; stride += strideStep) {
+	    const auto data = readPuppetMeshData (reader, block, meshHeaderSize, stride);
+	    if (!data.has_value ()) {
+		continue;
+	    }
+
+	    const auto score = scorePuppetMeshCoherence (*data);
+	    if (!score.has_value ()) {
+		continue;
+	    }
+
+	    if (*score >= bestScore) {
+		continue;
+	    }
+
+	    bestScore = *score;
+	    best = PuppetVertexLayout { .block = block,
+					.vertexStride = stride,
+					.uvOffset = stride - sizeof (GLfloat) * 2 };
+	}
+    }
+
+    return best;
+}
+
+struct PuppetMeshHeader {
+    uint32_t flags = 0;
+    uint32_t format = 0;
+    size_t vertices = 0;
+    uint32_t vertexBytes = 0;
+    uint32_t indexBytes = 0;
+};
+
+// tag, default format, materials per mesh, mesh count; per mesh: materials, flags (+u32 with flag 2), bounds (v17+),
+// format (v15+)
+PuppetMeshHeader readPuppetMeshHeader (const std::vector<char>& data) {
+    PuppetFileReader reader (data, 0);
+    reader.string ();
+
+    const int version = std::atoi (data.data () + strlen ("MDLV"));
+    PuppetMeshHeader header;
+    header.format = reader.next<uint32_t> ();
+    const auto materials = reader.next<uint32_t> ();
+    (void)reader.next<uint32_t> ();
+
+    for (uint32_t material = 0; material < materials; material++) {
+	reader.string ();
+    }
+
+    if (version >= 4) {
+	header.flags = reader.next<uint32_t> ();
+
+	if (header.flags & 2) {
+	    (void)reader.next<uint32_t> ();
+	}
+
+	if (version >= 17) {
+	    reader.skip (sizeof (float) * 6);
+	}
+
+	if (version >= 15) {
+	    header.format = reader.next<uint32_t> ();
+	}
+    }
+
+    header.vertexBytes = reader.next<uint32_t> ();
+    header.vertices = reader.offset ();
+    reader.skip (header.vertexBytes);
+    header.indexBytes = reader.next<uint32_t> ();
+    return header;
+}
+
+// sub_140261880 layout, falls back to the heuristic when UVs aren't last
+std::optional<PuppetVertexLayout> readPuppetVertexLayout (const std::vector<char>& data, size_t meshHeaderSize) {
+    const auto header = readPuppetMeshHeader (data);
+    const uint32_t stride = CMesh::vertexStride (header.format);
+    const auto texcoord = CMesh::vertexComponentOffset (header.format, 0x8);
+
+    if (stride == 0 || header.vertexBytes % stride != 0 || !texcoord.has_value ()
+	|| *texcoord != stride - sizeof (GLfloat) * 2 || header.vertices + header.vertexBytes > data.size ()) {
+	return std::nullopt;
+    }
+
+    return PuppetVertexLayout {
+	.block = PuppetMeshBlock { .headerOffset = header.vertices - meshHeaderSize,
+				   .vertexBytes = header.vertexBytes,
+				   .indexBytes = header.indexBytes },
+	.vertexStride = stride,
+	.uvOffset = *texcoord,
+    };
+}
+} // namespace
+
+MdlvMeshes WallpaperEngine::Render::Objects::readMdlvMeshes (const std::vector<char>& data) {
+    PuppetFileReader reader (data, 0);
+    const std::string tag = reader.text ();
+
+    if (!tag.starts_with ("MDLV") || tag.size () <= strlen ("MDLV")) {
+	throw std::runtime_error ("not a MDLV model");
+    }
+
+    MdlvMeshes result;
+    result.version = std::atoi (tag.c_str () + strlen ("MDLV"));
+
+    const auto defaultFormat = reader.next<uint32_t> ();
+    const auto materials = reader.next<uint32_t> ();
+    const auto meshes = reader.next<uint32_t> ();
+
+    for (uint32_t mesh = 0; mesh < meshes; mesh++) {
+	MdlvMeshRecord record;
+	record.format = defaultFormat;
+
+	for (uint32_t material = 0; material < materials; material++) {
+	    record.materials.push_back (reader.text ());
+	}
+
+	if (result.version >= 4) {
+	    record.flags = reader.next<uint32_t> ();
+
+	    if (record.flags & 2) {
+		(void)reader.next<uint32_t> ();
+	    }
+
+	    if (result.version >= 17) {
+		glm::vec3 min;
+		glm::vec3 max;
+
+		for (int axis = 0; axis < 3; axis++) {
+		    min[axis] = reader.next<float> ();
+		}
+
+		for (int axis = 0; axis < 3; axis++) {
+		    max[axis] = reader.next<float> ();
+		}
+
+		record.bounds = { min, max };
+	    }
+
+	    if (result.version >= 15) {
+		record.format = reader.next<uint32_t> ();
+	    }
+	}
+
+	record.vertices = reader.blob ();
+	record.indices = reader.blob ();
+
+	// v21+: flag + u32 + blob, flag + blob (per bone index ranges); v23+: records (u64, string, u32, two u32 lists)
+	if (result.version >= 21) {
+	    if (reader.next<uint8_t> () != 0) {
+		(void)reader.next<uint32_t> ();
+		(void)reader.blob ();
+	    }
+
+	    if (reader.next<uint8_t> () != 0) {
+		(void)reader.blob ();
+	    }
+	}
+
+	if (result.version >= 23) {
+	    const auto records = reader.next<uint32_t> ();
+
+	    for (uint32_t index = 0; index < records && reader.offset () < data.size (); index++) {
+		reader.skip (sizeof (uint64_t));
+		reader.string ();
+		(void)reader.next<uint32_t> ();
+		reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
+		reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
+	    }
+	}
+
+	result.meshes.push_back (std::move (record));
+    }
+
+    result.end = reader.offset ();
+    return result;
+}
+
+std::optional<size_t>
+WallpaperEngine::Render::Objects::findMdlSection (const std::vector<char>& data, size_t first, std::string_view tag) {
+    constexpr size_t HEADER = MARKER_SIZE + sizeof (uint32_t);
+    size_t offset = first;
+
+    while (offset + HEADER <= data.size () && data[offset] != 0) {
+	if (std::string_view (data.data () + offset, tag.size ()) == tag) {
+	    return offset;
+	}
+
+	uint32_t next = 0;
+	std::memcpy (&next, data.data () + offset + MARKER_SIZE, sizeof (next));
+
+	if (next <= offset) {
+	    break;
+	}
+
+	offset = next;
+    }
+
+    return std::nullopt;
+}
+
+size_t WallpaperEngine::Render::Objects::findPuppetSkeleton (const std::vector<char>& data) {
+    // sections start where the meshes end, so "MDLS" inside mesh data never counts
+    try {
+	return findMdlSection (data, readMdlvMeshes (data).end, "MDLS").value_or (data.size ());
+    } catch (const std::exception&) {
+	// unknown mesh layout, search for the tag
+    }
+
+    for (size_t offset = MARKER_SIZE; offset + strlen ("MDLS") < data.size (); offset++) {
+	if (std::memcmp (data.data () + offset, "MDLS", strlen ("MDLS")) == 0) {
+	    return offset;
+	}
+    }
+
+    return data.size ();
+}
+
+std::optional<PuppetMeshFile> WallpaperEngine::Render::Objects::readPuppetMeshFile (const std::vector<char>& data) {
+    PuppetMeshFile file;
+
+    file.tag = data.size () >= MARKER_SIZE ? std::string (data.data (), strlen ("MDLV0021")) : "";
+    file.version = file.tag.size () > strlen ("MDLV") ? std::atoi (file.tag.c_str () + strlen ("MDLV")) : 0;
+    file.skeleton = findPuppetSkeleton (data);
+
+    try {
+	file.sections = readMdlvMeshes (data).end;
+    } catch (const std::exception&) {
+	file.sections = file.skeleton;
+    }
+
+    // tag, flags, a second field, mesh count (sub_140261880)
+    if (data.size () >= 21) {
+	std::memcpy (&file.meshCount, data.data () + 17, sizeof (file.meshCount));
+    }
+
+    auto meshBuffer = std::make_unique<char[]> (data.size ());
+    std::copy (data.begin (), data.end (), meshBuffer.get ());
+    const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
+
+    std::optional<PuppetVertexLayout> layout;
+
+    try {
+	layout = readPuppetVertexLayout (data, MESH_HEADER_SIZE);
+    } catch (const std::exception& ex) {
+	file.warnings.push_back (std::string ("could not read the first mesh: ") + ex.what ());
+    }
+
+    file.declaredLayout = layout.has_value ();
+
+    if (!layout.has_value ()) {
+	layout = resolvePuppetVertexLayout (reader, MARKER_SIZE, file.skeleton, MESH_HEADER_SIZE);
+    }
+
+    if (!layout.has_value ()) {
+	return std::nullopt;
+    }
+
+    auto mesh = readPuppetMeshData (reader, layout->block, MESH_HEADER_SIZE, layout->vertexStride);
+
+    if (!mesh.has_value ()) {
+	return std::nullopt;
+    }
+
+    file.layout = *layout;
+    file.positions = std::move (mesh->positions);
+    file.texcoords = std::move (mesh->texcoords);
+    file.indices = std::move (mesh->indices);
+    file.indexEnd = layout->block.headerOffset + MESH_HEADER_SIZE + layout->block.vertexBytes + sizeof (uint32_t)
+	+ layout->block.indexBytes;
+
+    try {
+	const auto header = readPuppetMeshHeader (data);
+
+	if (header.vertices == layout->block.headerOffset + MESH_HEADER_SIZE) {
+	    file.flags = header.flags;
+	    file.format = header.format;
+	} else {
+	    file.warnings.emplace_back ("the first mesh header isn't where its vertices are");
+	}
+    } catch (const std::exception& ex) {
+	file.warnings.push_back (std::string ("could not read the mesh header: ") + ex.what ());
+    }
+
+    const size_t vertexCount = layout->block.vertexBytes / layout->vertexStride;
+    const size_t verticesOffset = layout->block.headerOffset + MESH_HEADER_SIZE;
+
+    // v21+: flag, u32, one vec3 per vertex (a_PositionC1)
+    if (file.version >= 21 && file.indexEnd < data.size () && data[file.indexEnd] != 0) {
+	const size_t blob = file.indexEnd + 1 + sizeof (uint32_t);
+	uint32_t bytes = 0;
+
+	if (blob + sizeof (bytes) <= data.size ()) {
+	    std::memcpy (&bytes, data.data () + blob, sizeof (bytes));
+	}
+
+	// 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
+	    );
+	} else {
+	    file.warnings.emplace_back (
+		"the auxiliary vertex block is shorter than the mesh, lighting places the bind positions instead"
+	    );
+	}
+    }
+
+    const auto readComponent = [&] (uint32_t bit, size_t floats, std::vector<float>& out) {
+	const auto offset = CMesh::vertexComponentOffset (file.format, bit);
+
+	if (!offset.has_value () || *offset + floats * sizeof (float) > layout->vertexStride) {
+	    return;
+	}
+
+	out.resize (vertexCount * floats);
+
+	for (size_t vertex = 0; vertex < vertexCount; vertex++) {
+	    std::memcpy (
+		out.data () + vertex * floats, data.data () + verticesOffset + vertex * layout->vertexStride + *offset,
+		floats * sizeof (float)
+	    );
+	}
+    };
+
+    readComponent (0x2, 3, file.normals);
+    readComponent (0x4, 4, file.tangents);
+
+    // position.w = morph texel, <= 0 = none
+    if (file.format & 0x10000) {
+	file.morphIndices.resize (vertexCount);
+
+	for (size_t vertex = 0; vertex < vertexCount; vertex++) {
+	    float w;
+	    std::memcpy (
+		&w, data.data () + verticesOffset + vertex * layout->vertexStride + sizeof (float) * 3, sizeof (w)
+	    );
+
+	    if (w > 0.0f) {
+		file.morphIndices[vertex] = static_cast<uint32_t> (w);
+	    }
+	}
+    }
+
+    if (const auto blend = readPuppetBlendData (reader, layout->block, MESH_HEADER_SIZE, layout->vertexStride);
+	blend.has_value ()) {
+	file.blendIndices = blend->indices;
+	file.blendWeights = blend->weights;
+    }
+
+    return file;
+}

+ 143 - 0
src/WallpaperEngine/Render/Objects/PuppetMeshFile.h

@@ -0,0 +1,143 @@
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <optional>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include <glm/vec3.hpp>
+#include <glm/vec4.hpp>
+
+namespace WallpaperEngine::Render::Objects {
+// bounds-checked little endian reads
+class PuppetFileReader {
+public:
+    PuppetFileReader (const std::vector<char>& data, size_t offset) : m_data (data), m_offset (offset) { }
+
+    template <typename T> T next () {
+	if (this->m_offset + sizeof (T) > this->m_data.size ()) {
+	    throw std::runtime_error ("truncated puppet file");
+	}
+
+	T value;
+	std::memcpy (&value, this->m_data.data () + this->m_offset, sizeof (T));
+	this->m_offset += sizeof (T);
+	return value;
+    }
+
+    void string () {
+	while (this->next<char> () != '\0') { }
+    }
+
+    std::string text () {
+	std::string result;
+
+	for (char c = this->next<char> (); c != '\0'; c = this->next<char> ()) {
+	    result.push_back (c);
+	}
+
+	return result;
+    }
+
+    std::pair<size_t, uint32_t> blob () {
+	const auto bytes = this->next<uint32_t> ();
+	const size_t start = this->m_offset;
+
+	if (start + bytes > this->m_data.size ()) {
+	    throw std::runtime_error ("truncated puppet file");
+	}
+
+	this->m_offset += bytes;
+	return { start, bytes };
+    }
+
+    void skip (size_t bytes) { this->m_offset += bytes; }
+
+    [[nodiscard]] size_t offset () const { return this->m_offset; }
+
+private:
+    const std::vector<char>& m_data;
+    size_t m_offset;
+};
+
+/** headerOffset is 8 bytes before the vertices */
+struct PuppetMeshBlock {
+    size_t headerOffset = 0;
+    uint32_t vertexBytes = 0;
+    uint32_t indexBytes = 0;
+};
+
+struct PuppetVertexLayout {
+    PuppetMeshBlock block;
+    size_t vertexStride = 0;
+    size_t uvOffset = 0;
+};
+
+/** First mesh of a puppet .mdl, read like sub_140261880 where the header holds up */
+struct PuppetMeshFile {
+    /** 0 when the tag has none */
+    int version = 0;
+    std::string tag;
+    /** file size without MDLS */
+    size_t skeleton = 0;
+    /** after the meshes (MDLS, MDAT, MDLA... in any order), or the skeleton when the meshes don't parse */
+    size_t sections = 0;
+    uint32_t meshCount = 0;
+    PuppetVertexLayout layout;
+    /** false when the stride was guessed */
+    bool declaredLayout = false;
+    /** part ranges and clipping records follow */
+    size_t indexEnd = 0;
+    /** flags: 4 bone alpha, 8 draw order, 0x1000 morph alpha; 0 when the header doesn't match the mesh */
+    uint32_t flags = 0;
+    uint32_t format = 0;
+    std::vector<float> positions;
+    std::vector<float> texcoords;
+    std::vector<uint16_t> indices;
+    /** empty without bone data */
+    std::vector<glm::uvec4> blendIndices;
+    std::vector<glm::vec4> blendWeights;
+    /** v21+, one vec3 per vertex */
+    std::vector<float> auxPositions;
+    std::vector<float> normals;
+    std::vector<float> tangents;
+    /** position.w with format 0x10000, none where w <= 0 */
+    std::vector<std::optional<uint32_t>> morphIndices;
+    /** why optional data was dropped */
+    std::vector<std::string> warnings;
+};
+
+/** One MDLV mesh as sub_140261880 reads it */
+struct MdlvMeshRecord {
+    std::vector<std::string> materials;
+    uint32_t flags = 0;
+    /** v17+ */
+    std::optional<std::pair<glm::vec3, glm::vec3>> bounds;
+    uint32_t format = 0;
+    std::pair<size_t, uint32_t> vertices;
+    std::pair<size_t, uint32_t> indices;
+};
+
+struct MdlvMeshes {
+    int version = 0;
+    std::vector<MdlvMeshRecord> meshes;
+    size_t end = 0;
+};
+
+/** throws std::runtime_error on another tag or a truncated file */
+MdlvMeshes readMdlvMeshes (const std::vector<char>& data);
+
+/** Sections are "TAGnnnn\0" + absolute offset of the next, until an empty tag or EOF */
+std::optional<size_t> findMdlSection (const std::vector<char>& data, size_t first, std::string_view tag);
+
+/** nullopt when no usable mesh is found, never throws */
+std::optional<PuppetMeshFile> readPuppetMeshFile (const std::vector<char>& data);
+
+/** Like WE's loader; the first "MDLS" past the first mesh when the meshes don't parse, file size without one */
+size_t findPuppetSkeleton (const std::vector<char>& data);
+} // namespace WallpaperEngine::Render::Objects

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

@@ -6,6 +6,7 @@
 #include <cstring>
 #include <limits>
 #include <set>
+#include <stdexcept>
 #include <string_view>
 #include <strings.h>
 #include <utility>
@@ -17,6 +18,7 @@
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
 #include "WallpaperEngine/Data/Utils/MemoryStream.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
 
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render::Objects;
@@ -217,6 +219,11 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	);
     }
 
+    // the reader returns garbage past the end instead of failing
+    if (!reader.base ().good ()) {
+	throw std::runtime_error ("the skeleton is cut short");
+    }
+
     // the rest of MDLS as 2.8.42 reads it (sub_140261880), only the two counts matter here
     const int version = std::atoi (header + 4);
 
@@ -913,14 +920,21 @@ glm::mat4 WallpaperEngine::Render::Objects::samplePuppetBoneChain (
 
 void PuppetRig::clear () { *this = PuppetRig (); }
 
-void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name) {
+void PuppetRig::load (const std::vector<char>& data, size_t sections, uint32_t meshCount, const std::string& name) {
     this->clear ();
 
+    // MDLS first, the bones size everything else
+    const auto mdlsOffset = findMdlSection (data, sections, "MDLS");
+
+    if (!mdlsOffset.has_value ()) {
+	throw std::runtime_error ("the file has no skeleton");
+    }
+
     auto buffer = std::make_unique<char[]> (data.size ());
     std::copy (data.begin (), data.end (), buffer.get ());
     const BinaryReader reader (std::make_shared<MemoryStream> (std::move (buffer), data.size ()));
 
-    auto boneSet = parsePuppetBones (reader, mdlsOffset);
+    auto boneSet = parsePuppetBones (reader, *mdlsOffset);
 
     std::vector<int> bindParents (boneSet.bones.size ());
     std::vector<glm::mat4> bindLocals (boneSet.bones.size ());
@@ -954,10 +968,10 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
     this->hasRestPose
 	= std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.restLocal != bone.bindLocal; });
 
-    // sub_140261880 walks the sections after MDLS in whatever order they come: every one is "TAGnnnn\0" and the
+    // sub_140261880 walks the sections after the meshes in whatever order they come: every one is "TAGnnnn\0" and the
     // absolute offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP
     // morph targets (read by the model), MDLA the clips
-    size_t offset = boneSet.nextSectionOffset;
+    size_t offset = sections;
     std::set<size_t> visited;
 
     while (offset + 13 <= data.size () && data[offset] != 0 && visited.insert (offset).second) {

+ 2 - 1
src/WallpaperEngine/Render/Objects/PuppetRig.h

@@ -201,7 +201,8 @@ struct PuppetLayerSample {
 class PuppetRig {
 public:
     /** Reads MDLS at mdlsOffset and the MDAT/MDLA sections it leads to (sub_140261880). Throws on a broken file */
-    void load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name);
+    /** sections: start of the sections after the meshes */
+    void load (const std::vector<char>& data, size_t sections, uint32_t meshCount, const std::string& name);
     void clear ();
 
     [[nodiscard]] PuppetActiveAnimation* findLayer (size_t serial);

+ 152 - 41
src/WallpaperEngine/Render/RenderContext.cpp

@@ -3,7 +3,9 @@
 #include <GL/glew.h>
 
 #include "CWallpaper.h"
+#include "ImageDecoder.h"
 #include "RenderContext.h"
+#include "SplitLayout.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Logging/Log.h"
@@ -44,7 +46,11 @@ RenderContext::RenderContext (
     Drivers::VideoDriver& driver, WallpaperApplication& app, Media::MediaSource& mediaSource
 ) :
     m_driver (driver), m_app (app), m_mediaSource (mediaSource),
-    m_textureCache (std::make_unique<TextureCache> (*this)) { }
+    m_textureCache (std::make_unique<TextureCache> (*this)) {
+    GLint maxTextureSize = 0;
+    glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTextureSize);
+    setMaxImageSide (maxTextureSize);
+}
 
 void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
     if (frameStatsEnabled ()) {
@@ -61,14 +67,7 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
 #endif /* DEBUG */
 
-    if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
-	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
-	viewport->setWantsPointerButtons (ref->second->wantsPointerButtons ());
-	ref->second->render (
-	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
-	);
-	this->drawHeldFrame (*viewport, *ref->second);
-    }
+    this->drawWallpapers (*viewport);
 
 #if !NDEBUG
     glPopDebugGroup ();
@@ -96,14 +95,7 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
 
     const auto sceneStart = Clock::now ();
 
-    if (const auto ref = this->m_wallpapers.find (viewport->name); ref != this->m_wallpapers.end ()) {
-	ref->second->setOutputHDR (viewport->isHDR (), viewport->getHDRLuminance ());
-	viewport->setWantsPointerButtons (ref->second->wantsPointerButtons ());
-	ref->second->render (
-	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
-	);
-	this->drawHeldFrame (*viewport, *ref->second);
-    }
+    this->drawWallpapers (*viewport);
 
     glFinish ();
 
@@ -140,6 +132,96 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     stats = FrameStats { .lastFrame = stats.lastFrame };
 }
 
+void RenderContext::drawWallpapers (Drivers::Output::OutputViewport& viewport) {
+    if (const auto* split = this->m_app.getContext ().findSplitScreen (viewport.name); split != nullptr) {
+	this->drawSplitScreen (viewport, *split);
+	return;
+    }
+
+    const auto ref = this->m_wallpapers.find (viewport.name);
+
+    if (ref == this->m_wallpapers.end ()) {
+	return;
+    }
+
+    ref->second->setOutputHDR (viewport.isHDR (), viewport.getHDRLuminance ());
+    viewport.setWantsPointerButtons (ref->second->wantsPointerButtons ());
+    ref->second->render (
+	viewport.viewport, this->getOutput ().renderVFlip (), viewport.globalPosition, viewport.logicalSize
+    );
+    this->drawHeldFrame (viewport.name, viewport.viewport, *ref->second);
+}
+
+void RenderContext::drawSplitScreen (
+    Drivers::Output::OutputViewport& viewport, const Application::ApplicationContext::SplitScreen& split
+) {
+    const glm::ivec4 output = viewport.viewport;
+    const bool vflip = this->getOutput ().renderVFlip ();
+    std::vector<CWallpaper*> wallpapers;
+    std::vector<float> aspects;
+
+    for (const auto& slot : split.slots) {
+	const auto it = this->m_wallpapers.find (slot);
+	auto* wallpaper = it != this->m_wallpapers.end () ? it->second.get () : nullptr;
+
+	wallpapers.push_back (wallpaper);
+	aspects.push_back (wallpaper != nullptr ? wallpaper->getAspectRatio () : 0.0f);
+    }
+
+    const auto rects = splitSlotRects ({ output.z, output.w }, aspects, split.layout, vflip);
+
+    // bars around centered slots and failed slots
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+    glEnable (GL_SCISSOR_TEST);
+    glScissor (output.x, output.y, output.z, output.w);
+    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
+    glClear (GL_COLOR_BUFFER_BIT);
+    glDisable (GL_SCISSOR_TEST);
+
+    bool wantsPointerButtons = false;
+
+    for (std::size_t i = 0; i < split.slots.size (); i++) {
+	const glm::ivec4 rect { output.x + rects[i].x, output.y + rects[i].y, rects[i].z, rects[i].w };
+
+	this->m_slotRects.insert_or_assign (split.slots[i], rect);
+
+	if (wallpapers[i] == nullptr || rect.z <= 0 || rect.w <= 0) {
+	    continue;
+	}
+
+	wallpapers[i]->setOutputHDR (viewport.isHDR (), viewport.getHDRLuminance ());
+	wallpapers[i]->setPointerRegion (rect);
+	wantsPointerButtons = wantsPointerButtons || wallpapers[i]->wantsPointerButtons ();
+	wallpapers[i]->render (rect, vflip, viewport.globalPosition, viewport.logicalSize);
+	this->drawHeldFrame (split.slots[i], rect, *wallpapers[i]);
+    }
+
+    viewport.setWantsPointerButtons (wantsPointerButtons);
+}
+
+std::optional<RenderContext::DrawTarget> RenderContext::findDrawTarget (const std::string& display) const {
+    const auto& viewports = this->getOutput ().getViewports ();
+
+    if (const auto* split = this->m_app.getContext ().findSplitScreen (display); split != nullptr) {
+	const auto viewport = viewports.find (split->screen);
+	const auto rect = this->m_slotRects.find (display);
+
+	if (viewport == viewports.end () || rect == this->m_slotRects.end ()) {
+	    return std::nullopt;
+	}
+
+	return DrawTarget { .viewport = viewport->second, .rect = rect->second };
+    }
+
+    const auto viewport = viewports.find (display);
+
+    if (viewport == viewports.end ()) {
+	return std::nullopt;
+    }
+
+    return DrawTarget { .viewport = viewport->second, .rect = viewport->second->viewport };
+}
+
 void RenderContext::setWallpaper (
     const std::string& display, std::shared_ptr<CWallpaper> wallpaper, const bool holdPrevious
 ) {
@@ -156,10 +238,9 @@ void RenderContext::setWallpaper (
 
 void RenderContext::holdFrame (const std::string& display) {
     const auto current = this->m_wallpapers.find (display);
-    const auto& viewports = this->getOutput ().getViewports ();
-    const auto viewport = viewports.find (display);
+    const auto target = this->findDrawTarget (display);
 
-    if (current == this->m_wallpapers.end () || viewport == viewports.end ()) {
+    if (current == this->m_wallpapers.end () || !target.has_value ()) {
 	this->releaseHeldFrame (display);
 	return;
     }
@@ -171,30 +252,19 @@ void RenderContext::holdFrame (const std::string& display) {
 
     this->releaseHeldFrame (display);
 
-    const glm::ivec4 rect = viewport->second->viewport;
+    const glm::ivec4 rect = target->rect;
 
     if (rect.z <= 0 || rect.w <= 0) {
 	return;
     }
 
-    viewport->second->makeCurrent ();
+    target->viewport->makeCurrent ();
 
     HeldFrame held { .viewport = rect };
 
-    glGenTextures (1, &held.texture);
-    glBindTexture (GL_TEXTURE_2D, held.texture);
-    // keep HDR values above 1
-    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA16F, rect.z, rect.w, 0, GL_RGBA, GL_HALF_FLOAT, nullptr);
-    glBindTexture (GL_TEXTURE_2D, 0);
-    glGenFramebuffers (1, &held.framebuffer);
-    glBindFramebuffer (GL_FRAMEBUFFER, held.framebuffer);
-    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, held.texture, 0);
-
-    if (glCheckFramebufferStatus (GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+    if (!allocateHeldFrame (held)) {
 	sLog.error ("Cannot keep the previous wallpaper on ", display, " while the new one loads");
 	glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
-	glDeleteFramebuffers (1, &held.framebuffer);
-	glDeleteTextures (1, &held.texture);
 	return;
     }
 
@@ -203,7 +273,7 @@ void RenderContext::holdFrame (const std::string& display) {
 
     current->second->setDestinationFramebuffer (held.framebuffer);
     current->second->present (
-	{ 0, 0, rect.z, rect.w }, viewport->second->globalPosition, viewport->second->logicalSize
+	{ 0, 0, rect.z, rect.w }, target->viewport->globalPosition, target->viewport->logicalSize
     );
     current->second->setDestinationFramebuffer (this->m_app.getDestinationFramebuffer ());
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
@@ -223,20 +293,37 @@ void RenderContext::releaseHeldFrame (const std::string& display) {
     this->m_heldFrames.erase (held);
 }
 
-void RenderContext::drawHeldFrame (const Drivers::Output::OutputViewport& viewport, const CWallpaper& wallpaper) {
-    const auto held = this->m_heldFrames.find (viewport.name);
+void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4& rect, const CWallpaper& wallpaper) {
+    auto held = this->m_heldFrames.find (display);
 
     if (held == this->m_heldFrames.end ()) {
 	return;
     }
 
-    const glm::ivec4 rect = viewport.viewport;
-
-    if (wallpaper.hasContent () || held->second.viewport != rect) {
-	this->releaseHeldFrame (viewport.name);
+    if (wallpaper.hasContent ()) {
+	this->releaseHeldFrame (display);
 	return;
     }
 
+    // the old frame is stretched over the new slot rect, via a copy since multisampled outputs only take 1:1 blits
+    if (held->second.viewport.z != rect.z || held->second.viewport.w != rect.w) {
+	HeldFrame resized { .viewport = rect };
+
+	if (rect.z <= 0 || rect.w <= 0 || !allocateHeldFrame (resized)) {
+	    this->releaseHeldFrame (display);
+	    glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+	    return;
+	}
+
+	glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
+	glBindFramebuffer (GL_DRAW_FRAMEBUFFER, resized.framebuffer);
+	glBlitFramebuffer (
+	    0, 0, held->second.viewport.z, held->second.viewport.w, 0, 0, rect.z, rect.w, GL_COLOR_BUFFER_BIT, GL_LINEAR
+	);
+	this->releaseHeldFrame (display);
+	held = this->m_heldFrames.insert_or_assign (display, resized).first;
+    }
+
     glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
     glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
     glBlitFramebuffer (
@@ -245,6 +332,24 @@ void RenderContext::drawHeldFrame (const Drivers::Output::OutputViewport& viewpo
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
 }
 
+bool RenderContext::allocateHeldFrame (HeldFrame& held) {
+    glGenTextures (1, &held.texture);
+    glBindTexture (GL_TEXTURE_2D, held.texture);
+    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA16F, held.viewport.z, held.viewport.w, 0, GL_RGBA, GL_HALF_FLOAT, nullptr);
+    glBindTexture (GL_TEXTURE_2D, 0);
+    glGenFramebuffers (1, &held.framebuffer);
+    glBindFramebuffer (GL_FRAMEBUFFER, held.framebuffer);
+    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, held.texture, 0);
+
+    if (glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
+	return true;
+    }
+
+    glDeleteFramebuffers (1, &held.framebuffer);
+    glDeleteTextures (1, &held.texture);
+    return false;
+}
+
 void RenderContext::pruneTextures () const { this->m_textureCache->prune (); }
 
 void RenderContext::setPause (const bool newState) const {
@@ -277,4 +382,10 @@ const std::map<std::string, std::shared_ptr<CWallpaper>>& RenderContext::getWall
 
 Media::MediaSource& RenderContext::getMediaSource () const { return this->m_mediaSource; }
 
+std::optional<glm::ivec4> RenderContext::getSlotRect (const std::string& slot) const {
+    const auto rect = this->m_slotRects.find (slot);
+
+    return rect != this->m_slotRects.end () ? std::optional (rect->second) : std::nullopt;
+}
+
 } // namespace WallpaperEngine::Render

+ 18 - 1
src/WallpaperEngine/Render/RenderContext.h

@@ -2,6 +2,7 @@
 
 #include <glm/vec4.hpp>
 #include <memory>
+#include <optional>
 #include <vector>
 
 #include "TextureCache.h"
@@ -54,18 +55,33 @@ namespace Render {
 	findLoadedTexture (const std::string& name, const Data::Model::Project& project) const;
 	[[nodiscard]] const std::map<std::string, std::shared_ptr<CWallpaper>>& getWallpapers () const;
 	[[nodiscard]] Media::MediaSource& getMediaSource () const;
+	/** Last frame's rect in the output framebuffer */
+	[[nodiscard]] std::optional<glm::ivec4> getSlotRect (const std::string& slot) const;
 
     private:
 	void renderWithStats (Drivers::Output::OutputViewport* viewport);
+	void drawWallpapers (Drivers::Output::OutputViewport& viewport);
+	void drawSplitScreen (
+	    Drivers::Output::OutputViewport& viewport, const Application::ApplicationContext::SplitScreen& split
+	);
 	void holdFrame (const std::string& display);
 	void releaseHeldFrame (const std::string& display);
-	void drawHeldFrame (const Drivers::Output::OutputViewport& viewport, const CWallpaper& wallpaper);
+	void drawHeldFrame (const std::string& display, const glm::ivec4& rect, const CWallpaper& wallpaper);
+
+	struct DrawTarget {
+	    Drivers::Output::OutputViewport* viewport = nullptr;
+	    glm::ivec4 rect {};
+	};
+
+	[[nodiscard]] std::optional<DrawTarget> findDrawTarget (const std::string& display) const;
 
 	struct HeldFrame {
 	    GLuint framebuffer = GL_NONE;
 	    GLuint texture = GL_NONE;
 	    glm::ivec4 viewport {};
 	};
+	/** RGBA16F of the viewport's size, false on failure */
+	static bool allocateHeldFrame (HeldFrame& held);
 
 	Drivers::VideoDriver& m_driver;
 	std::map<std::string, std::shared_ptr<CWallpaper>> m_wallpapers = {};
@@ -73,6 +89,7 @@ namespace Render {
 	Media::MediaSource& m_mediaSource;
 	std::unique_ptr<TextureCache> m_textureCache = nullptr;
 	std::map<std::string, HeldFrame> m_heldFrames = {};
+	std::map<std::string, glm::ivec4> m_slotRects = {};
     };
 } // namespace Render
 } // namespace WallpaperEngine

+ 73 - 0
src/WallpaperEngine/Render/SplitLayout.cpp

@@ -0,0 +1,73 @@
+#include "SplitLayout.h"
+
+#include <cmath>
+#include <numeric>
+
+namespace WallpaperEngine::Render {
+std::vector<glm::ivec4> splitSlotRects (
+    const glm::ivec2& size, const std::vector<float>& aspects,
+    const Application::ApplicationContext::SplitScreen::Layout layout, const bool yUp
+) {
+    using SplitScreen = Application::ApplicationContext::SplitScreen;
+
+    const auto count = aspects.size ();
+
+    if (count == 0 || size.x <= 0 || size.y <= 0) {
+	return std::vector<glm::ivec4> (count, glm::ivec4 (0));
+    }
+
+    // portrait screens stack the slots
+    const bool columns = size.x >= size.y;
+    const double length = columns ? size.x : size.y;
+    const double across = columns ? size.y : size.x;
+
+    std::vector<double> weights (count, 0.0);
+    double known = 0.0;
+    int knownCount = 0;
+
+    for (std::size_t i = 0; i < count; i++) {
+	if (aspects[i] > 0.0f && std::isfinite (aspects[i])) {
+	    weights[i] = columns ? aspects[i] : 1.0 / aspects[i];
+	    known += weights[i];
+	    knownCount++;
+	}
+    }
+
+    // sizeless pages get the average, or an equal share
+    const double fallback = knownCount > 0 ? known / knownCount : length / across / count;
+
+    for (auto& weight : weights) {
+	if (weight <= 0.0 || layout == SplitScreen::LAYOUT_EQUAL) {
+	    weight = layout == SplitScreen::LAYOUT_EQUAL ? 1.0 : fallback;
+	}
+    }
+
+    const double total = std::accumulate (weights.begin (), weights.end (), 0.0);
+    double scale = length / total;
+    double start = 0.0;
+
+    if (layout == SplitScreen::LAYOUT_CENTER && total * across <= length) {
+	scale = across;
+	start = (length - total * across) / 2.0;
+    }
+
+    std::vector<glm::ivec4> rects;
+    rects.reserve (count);
+    double edge = start;
+
+    for (const auto weight : weights) {
+	const int from = static_cast<int> (std::lround (edge));
+	edge += weight * scale;
+	const int to = static_cast<int> (std::lround (edge));
+
+	if (columns) {
+	    rects.emplace_back (from, 0, to - from, size.y);
+	} else {
+	    const int top = yUp ? size.y - to : from;
+	    rects.emplace_back (0, top, size.x, to - from);
+	}
+    }
+
+    return rects;
+}
+} // namespace WallpaperEngine::Render

+ 19 - 0
src/WallpaperEngine/Render/SplitLayout.h

@@ -0,0 +1,19 @@
+#pragma once
+
+#include <vector>
+
+#include <glm/vec2.hpp>
+#include <glm/vec4.hpp>
+
+#include "WallpaperEngine/Application/ApplicationContext.h"
+
+namespace WallpaperEngine::Render {
+/**
+ * Slot rects (x, y, w, h), first slot left or top on portrait. aspects: width / height, 0 for any size.
+ * yUp: row 0 is the bottom of the screen
+ */
+[[nodiscard]] std::vector<glm::ivec4> splitSlotRects (
+    const glm::ivec2& size, const std::vector<float>& aspects,
+    Application::ApplicationContext::SplitScreen::Layout layout, bool yUp
+);
+} // namespace WallpaperEngine::Render

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

@@ -484,7 +484,7 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     // anything is simulated, boids pick their sample block with it
     this->m_frameCounter++;
     VideoPlayback::MPV::GLPlayer::advanceFrame ();
-    timeStep ("updateMouse", [&] { this->updateMouse (viewport); });
+    timeStep ("updateMouse", [&] { this->updateMouse (this->cursorViewport ()); });
 
     // WE: init () while loading, then the static camera (sub_140186C90), then the first update
     this->getScriptEngine ().initializePending ();

+ 2 - 0
src/WallpaperEngine/Render/Wallpapers/CSplat.h

@@ -29,6 +29,8 @@ public:
 
     [[nodiscard]] int getWidth () const override { return this->m_width; }
     [[nodiscard]] int getHeight () const override { return this->m_height; }
+    // fits any size
+    [[nodiscard]] float getAspectRatio () const override { return 0.0f; }
 
 protected:
     void renderFrame (const glm::ivec4& viewport) override;

+ 6 - 7
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -261,20 +261,21 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
 	this->setSize (viewport.z, viewport.w);
     }
 
-    this->updateMouse (viewport);
+    this->updateMouse (this->cursorViewport ());
     this->updateMedia ();
     this->m_streamVolume->update ();
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glViewport (0, 0, this->getWidth (), this->getHeight ());
 
-    if ((this->m_shm->frameSlot.load (std::memory_order_acquire) & WebHostSharedMemory::FRAME_DIRTY) == 0) {
+    const auto taken = this->m_shm->takeFrame (this->m_frontSlot);
+
+    if (!taken.has_value ()) {
 	// nothing new, but the next frame is still due
 	this->requestPageFrame ();
 	return;
     }
 
-    const uint32_t taken = this->m_shm->frameSlot.exchange (this->m_frontSlot, std::memory_order_acq_rel);
-    this->m_frontSlot = taken & WebHostSharedMemory::FRAME_SLOT_MASK;
+    this->m_frontSlot = *taken;
 
     const uint32_t frameWidth = this->m_shm->slotWidth[this->m_frontSlot].load (std::memory_order_relaxed);
     const uint32_t frameHeight = this->m_shm->slotHeight[this->m_frontSlot].load (std::memory_order_relaxed);
@@ -453,8 +454,6 @@ void CWeb::updateMedia () {
 }
 
 void CWeb::updateMouse (const glm::ivec4& viewport) {
-    auto& input = this->getContext ().getInputContext ().getMouseInput ();
-
     const glm::dvec2 position = this->cursorPosition ();
 
     // GL y up to CEF y down; written every frame, the host only forwards clicks when the value changes
@@ -464,7 +463,7 @@ void CWeb::updateMouse (const glm::ivec4& viewport) {
     this->m_shm->mouseX.store (static_cast<double> (x), std::memory_order_relaxed);
     this->m_shm->mouseY.store (static_cast<double> (y), std::memory_order_relaxed);
     this->m_shm->leftClick.store (static_cast<int32_t> (this->cursorLeftClick ()), std::memory_order_relaxed);
-    this->m_shm->rightClick.store (static_cast<int32_t> (input.rightClick ()), std::memory_order_relaxed);
+    this->m_shm->rightClick.store (static_cast<int32_t> (this->cursorRightClick ()), std::memory_order_relaxed);
 }
 
 CWeb::~CWeb () {

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

@@ -37,6 +37,7 @@ public:
     [[nodiscard]] int getWidth () const override { return this->m_width; }
 
     [[nodiscard]] int getHeight () const override { return this->m_height; }
+    [[nodiscard]] float getAspectRatio () const override { return 0.0f; }
 
     void setSize (int width, int height);
 

+ 12 - 19
src/WallpaperEngine/Scripting/LocalStorageObject.cpp

@@ -1,8 +1,6 @@
 #include "LocalStorageObject.h"
 
 #include "JS.h"
-#include "ScriptEngine.h"
-#include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
 #include <strings.h>
 
@@ -12,12 +10,12 @@ namespace {
 constexpr char VALUE_MAGIC[] = "LSKV0001";
 
 LocalStorageObject& storageOf (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    return ScriptEngine::from (info.GetIsolate ()).getLocalStorageObject ();
+    return *static_cast<LocalStorageObject*> (info.Data ().As<v8::External> ()->Value ());
 }
 
 // WE throws at module top level, messages copied as is
 bool rejectGlobalScope (const v8::FunctionCallbackInfo<v8::Value>& info, const char* message) {
-    if (!ScriptEngine::from (info.GetIsolate ()).isEvaluatingModuleBody ()) {
+    if (!storageOf (info).evaluatingModuleBody ()) {
 	return false;
     }
 
@@ -120,17 +118,16 @@ void localstorage_clear (const v8::FunctionCallbackInfo<v8::Value>& info) {
 }
 } // namespace
 
-LocalStorageObject::LocalStorageObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene) :
-    m_scene (scene), m_engine (engine) {
-    const auto isolate = engine.getIsolate ();
-    const auto context = engine.getContext ();
+LocalStorageObject::LocalStorageObject (v8::Isolate* isolate, v8::Local<v8::Context> context, Host host) :
+    m_isolate (isolate), m_host (std::move (host)) {
     const v8::Local<v8::Object> instance = v8::Object::New (isolate);
     const auto constant = static_cast<v8::PropertyAttribute> (v8::ReadOnly | v8::DontEnum | v8::DontDelete);
+    const v8::Local<v8::External> self = v8::External::New (isolate, this);
 
-    JS::set (context, instance, "set", JS::function (context, localstorage_set));
-    JS::set (context, instance, "get", JS::function (context, localstorage_get));
-    JS::set (context, instance, "delete", JS::function (context, localstorage_delete));
-    JS::set (context, instance, "clear", JS::function (context, localstorage_clear));
+    JS::set (context, instance, "set", JS::function (context, localstorage_set, self));
+    JS::set (context, instance, "get", JS::function (context, localstorage_get, self));
+    JS::set (context, instance, "delete", JS::function (context, localstorage_delete, self));
+    JS::set (context, instance, "clear", JS::function (context, localstorage_clear, self));
     instance
 	->DefineOwnProperty (context, JS::name (isolate, "LOCATION_GLOBAL"), JS::string (isolate, "global"), constant)
 	.Check ();
@@ -141,19 +138,15 @@ LocalStorageObject::LocalStorageObject (ScriptEngine& engine, Render::Wallpapers
     this->m_instance.Reset (isolate, instance);
 }
 
-v8::Local<v8::Object> LocalStorageObject::getInstance () const {
-    return this->m_instance.Get (this->m_engine.getIsolate ());
-}
+v8::Local<v8::Object> LocalStorageObject::getInstance () const { return this->m_instance.Get (this->m_isolate); }
 
 LocalStorage::Store& LocalStorageObject::getStore (const bool global) {
     auto& store = global ? this->m_globalStore : this->m_screenStore;
 
     if (!store) {
 	// sub_140113C80: sha1 of the scene path, plus the screen string for the screen store
-	const std::string identity = this->m_scene.getSceneFile ().generic_string ();
-	store = LocalStorage::open (
-	    LocalStorage::sha1Hex (global ? identity : identity + this->m_scene.getStorageScreen ())
-	);
+	const std::string identity = this->m_host.identity ();
+	store = LocalStorage::open (LocalStorage::sha1Hex (global ? identity : identity + this->m_host.screen ()));
     }
 
     return *store;

+ 18 - 9
src/WallpaperEngine/Scripting/LocalStorageObject.h

@@ -5,29 +5,38 @@
 #include <v8-local-handle.h>
 #include <v8-persistent-handle.h>
 
+#include <functional>
 #include <memory>
+#include <string>
 
 namespace v8 {
+class Context;
+class Isolate;
 class Object;
-}
+} // namespace v8
 
-namespace WallpaperEngine::Render::Wallpapers {
-class CScene;
-}
 namespace WallpaperEngine::Scripting {
-class ScriptEngine;
 /** scenescript64 2.8.42 localStorage (sub_181647AA0, sub_181658680..sub_181659150) */
 class LocalStorageObject {
 public:
-    LocalStorageObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene);
+    struct Host {
+	/** scene file, the global store's key (sub_140113C80) */
+	std::function<std::string ()> identity;
+	/** appended for the screen store; lazy, the screen is known after the engine */
+	std::function<std::string ()> screen;
+	/** calls throw while a module body runs */
+	std::function<bool ()> evaluatingModuleBody;
+    };
+
+    LocalStorageObject (v8::Isolate* isolate, v8::Local<v8::Context> context, Host host);
 
     v8::Local<v8::Object> getInstance () const;
-    /** Lazy, the scene learns its screen after the engine exists */
     LocalStorage::Store& getStore (bool global);
+    [[nodiscard]] bool evaluatingModuleBody () const { return this->m_host.evaluatingModuleBody (); }
 
 protected:
-    Render::Wallpapers::CScene& m_scene;
-    ScriptEngine& m_engine;
+    v8::Isolate* m_isolate;
+    Host m_host;
     std::shared_ptr<LocalStorage::Store> m_screenStore;
     std::shared_ptr<LocalStorage::Store> m_globalStore;
 

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

@@ -400,7 +400,14 @@ ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& media
     this->m_inputObject = std::make_unique<InputObject> (*this, scene);
     this->m_sceneObject = std::make_unique<SceneObject> (*this, scene);
     this->m_consoleObject = std::make_unique<ConsoleObject> (*this, scene);
-    this->m_localStorageObject = std::make_unique<LocalStorageObject> (*this, scene);
+    this->m_localStorageObject = std::make_unique<LocalStorageObject> (
+	this->m_isolate, context,
+	LocalStorageObject::Host {
+	    .identity = [&scene] { return scene.getSceneFile ().generic_string (); },
+	    .screen = [&scene] { return scene.getStorageScreen (); },
+	    .evaluatingModuleBody = [this] { return this->isEvaluatingModuleBody (); },
+	}
+    );
     this->m_scriptPropertiesObject = std::make_unique<ScriptPropertiesObject> (*this, scene);
 
     this->installBuiltins ();

+ 153 - 0
src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp

@@ -0,0 +1,153 @@
+#include <GL/glew.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+#include <catch2/catch_test_macros.hpp>
+
+#include <array>
+
+#include "WallpaperEngine/Render/AlbumTexture.h"
+
+namespace {
+// windowless GL via Mesa's surfaceless platform
+struct SurfacelessContext {
+    SurfacelessContext () {
+	const auto getPlatformDisplay
+	    = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC> (eglGetProcAddress ("eglGetPlatformDisplayEXT"));
+
+	if (getPlatformDisplay == nullptr) {
+	    return;
+	}
+
+	display = getPlatformDisplay (EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, nullptr);
+
+	if (display == EGL_NO_DISPLAY || !eglInitialize (display, nullptr, nullptr) || !eglBindAPI (EGL_OPENGL_API)) {
+	    return;
+	}
+
+	const EGLint configAttributes[]
+	    = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE };
+	EGLConfig config = nullptr;
+	EGLint count = 0;
+
+	if (!eglChooseConfig (display, configAttributes, &config, 1, &count) || count != 1) {
+	    return;
+	}
+
+	const EGLint surfaceAttributes[] = { EGL_WIDTH, 4, EGL_HEIGHT, 4, EGL_NONE };
+	const EGLint contextAttributes[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE };
+
+	surface = eglCreatePbufferSurface (display, config, surfaceAttributes);
+	context = eglCreateContext (display, config, EGL_NO_CONTEXT, contextAttributes);
+
+	if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT
+	    || !eglMakeCurrent (display, surface, surface, context)) {
+	    return;
+	}
+
+	// GLEW gives up under EGL looking for GLX, load entry points first
+	glewExperimental = GL_TRUE;
+	std::ignore = glewInit ();
+
+	while (glGetError () != GL_NO_ERROR) { }
+
+	ready = glBindBuffer != nullptr;
+    }
+
+    ~SurfacelessContext () {
+	if (display == EGL_NO_DISPLAY) {
+	    return;
+	}
+
+	eglMakeCurrent (display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+
+	if (context != EGL_NO_CONTEXT) {
+	    eglDestroyContext (display, context);
+	}
+
+	if (surface != EGL_NO_SURFACE) {
+	    eglDestroySurface (display, surface);
+	}
+
+	eglTerminate (display);
+    }
+
+    EGLDisplay display = EGL_NO_DISPLAY;
+    EGLSurface surface = EGL_NO_SURFACE;
+    EGLContext context = EGL_NO_CONTEXT;
+    bool ready = false;
+};
+
+std::array<uint8_t, 8> firstPixels (GLuint texture) {
+    std::array<uint8_t, 8> pixels {};
+    GLint previous = 0;
+
+    glGetIntegerv (GL_TEXTURE_BINDING_2D, &previous);
+    glBindTexture (GL_TEXTURE_2D, texture);
+    glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data ());
+    glBindTexture (GL_TEXTURE_2D, previous);
+    return pixels;
+}
+
+GLint integer (GLenum name) {
+    GLint value = 0;
+    glGetIntegerv (name, &value);
+    return value;
+}
+} // namespace
+
+TEST_CASE ("Covers upload whatever unpack state the frame left, which stays as it was") {
+    SurfacelessContext gl;
+
+    if (!gl.ready) {
+	SKIP ("no surfaceless EGL context here");
+    }
+
+    GLuint textures[3] {};
+    glGenTextures (3, textures);
+
+    // state left behind by another upload
+    GLuint unpackBuffer = 0;
+    glGenBuffers (1, &unpackBuffer);
+    glBindBuffer (GL_PIXEL_UNPACK_BUFFER, unpackBuffer);
+    glBufferData (GL_PIXEL_UNPACK_BUFFER, 1024, nullptr, GL_STATIC_DRAW);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, 8);
+    glPixelStorei (GL_UNPACK_ROW_LENGTH, 9);
+    glPixelStorei (GL_UNPACK_SKIP_ROWS, 1);
+    glPixelStorei (GL_UNPACK_SKIP_PIXELS, 2);
+    glBindTexture (GL_TEXTURE_2D, textures[2]);
+
+    const WallpaperEngine::Media::CoverImage cyan { .width = 2,
+						    .height = 1,
+						    .rgba = { 20, 220, 240, 255, 1, 2, 3, 4 } };
+    const WallpaperEngine::Media::CoverImage orange { .width = 2,
+						      .height = 1,
+						      .rgba = { 240, 50, 20, 255, 5, 6, 7, 8 } };
+
+    WallpaperEngine::Render::uploadCoverTexture (textures[0], cyan);
+    WallpaperEngine::Render::uploadCoverTexture (textures[1], cyan);
+
+    CHECK (integer (GL_PIXEL_UNPACK_BUFFER_BINDING) == static_cast<GLint> (unpackBuffer));
+    CHECK (integer (GL_UNPACK_ALIGNMENT) == 8);
+    CHECK (integer (GL_UNPACK_ROW_LENGTH) == 9);
+    CHECK (integer (GL_UNPACK_SKIP_ROWS) == 1);
+    CHECK (integer (GL_UNPACK_SKIP_PIXELS) == 2);
+    CHECK (integer (GL_TEXTURE_BINDING_2D) == static_cast<GLint> (textures[2]));
+
+    CHECK (firstPixels (textures[0]) == std::array<uint8_t, 8> { 20, 220, 240, 255, 1, 2, 3, 4 });
+
+    WallpaperEngine::Render::uploadCoverTexture (textures[0], orange);
+
+    CHECK (firstPixels (textures[0]) == std::array<uint8_t, 8> { 240, 50, 20, 255, 5, 6, 7, 8 });
+    CHECK (firstPixels (textures[1]) == std::array<uint8_t, 8> { 20, 220, 240, 255, 1, 2, 3, 4 });
+    CHECK (glGetError () == GL_NO_ERROR);
+
+    glBindBuffer (GL_PIXEL_UNPACK_BUFFER, 0);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
+    glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
+    glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
+    glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
+    glDeleteBuffers (1, &unpackBuffer);
+    glDeleteTextures (3, textures);
+}

+ 84 - 0
src/WallpaperEngine/Testing/Cases/AuthoringJson.cpp

@@ -0,0 +1,84 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include "WallpaperEngine/Assets/AssetLocator.h"
+#include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Model/Material.h"
+#include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Parsers/MaterialParser.h"
+#include "WallpaperEngine/FileSystem/Container.h"
+
+using WallpaperEngine::Data::JSON::JSON;
+
+TEST_CASE ("Asset JSON takes comments and trailing commas and leaves strings alone") {
+    const auto value = JSON::parseAsset (R"({
+	// a line comment
+	"url": "https://example.test/a//b/*c*/",
+	"escaped": "quote \" // still text",
+	"slashes": "\\/* not a comment */",
+	"commas": "[1,] {\"a\":1,}",
+	/* a block
+	   comment */
+	"items": [1, /* between */ 2,],
+	"nested": { "a": [ { "b": 1, }, ], },
+    })");
+
+    CHECK (value["url"] == "https://example.test/a//b/*c*/");
+    CHECK (value["escaped"] == "quote \" // still text");
+    CHECK (value["slashes"] == "\\/* not a comment */");
+    CHECK (value["commas"] == "[1,] {\"a\":1,}");
+    REQUIRE (value["items"].size () == 2);
+    CHECK (value["items"][1] == 2);
+    CHECK (value["nested"]["a"][0]["b"] == 1);
+}
+
+TEST_CASE ("A trailing comma followed by a comment is still dropped") {
+    const auto value = JSON::parseAsset ("{\n  \"a\": 1, // the last one\n  \"b\": [2, /* end */ ],\n  /* x */\n}");
+
+    CHECK (value["a"] == 1);
+    CHECK (value["b"].size () == 1);
+}
+
+TEST_CASE ("Broken asset JSON still fails with the position") {
+    try {
+	(void)JSON::parseAsset ("{\n  \"items\": [1,,]\n}");
+	FAIL ("a doubled comma parsed");
+    } catch (const nlohmann::json::parse_error& e) {
+	CHECK (std::string (e.what ()).find ("line 2") != std::string::npos);
+    }
+
+    CHECK_THROWS (JSON::parseAsset ("{\n  /* never closed"));
+    CHECK_THROWS (JSON::parseAsset ("{\"value\": 1e10000}"));
+    CHECK_THROWS (JSON::parseAsset ("{\"unterminated\": \"text}"));
+}
+
+namespace {
+WallpaperEngine::Data::Model::Project projectWith (const std::string& file, const std::string& content) {
+    auto container = std::make_unique<WallpaperEngine::FileSystem::Container> ();
+    container->getVFS ().add (file, content);
+
+    WallpaperEngine::Data::Model::Project project {};
+    project.assetLocator = std::make_unique<WallpaperEngine::Assets::AssetLocator> (std::move (container));
+    return project;
+}
+} // namespace
+
+TEST_CASE ("Materials load from asset JSON, a broken one becomes WE's error pass") {
+    using WallpaperEngine::Data::Parsers::MaterialParser;
+
+    const auto project = projectWith ("materials/test.json", R"({
+	"passes": [ { "shader": "genericimage2", "combos": { "TEST": 2, }, }, ],
+    })");
+    const auto material = MaterialParser::load (project, "materials/test.json");
+
+    REQUIRE (material->passes.size () == 1);
+    CHECK (material->passes[0]->shader == "genericimage2");
+    CHECK (material->passes[0]->combos.at ("TEST") == 2);
+
+    // sub_1401515B0: an unparsable material becomes one "error" shader pass
+    const auto broken = projectWith ("materials/broken.json", "{\n  \"passes\": [1,,]\n}");
+    const auto fallback = MaterialParser::load (broken, "materials/broken.json");
+
+    REQUIRE (fallback->passes.size () == 1);
+    CHECK (fallback->passes[0]->shader == "error");
+}

+ 397 - 0
src/WallpaperEngine/Testing/Cases/EncodedImages.cpp

@@ -0,0 +1,397 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <array>
+#include <cstdlib>
+#include <string>
+#include <vector>
+
+#include <stb_image_write.h>
+
+#include "WallpaperEngine/Render/GifAnimation.h"
+#include "WallpaperEngine/Render/ImageDecoder.h"
+
+using WallpaperEngine::Render::GifAnimation;
+using Pixel = std::array<uint8_t, 4>;
+
+namespace {
+// hand-built GIFs: literal LZW codes, a clear code before the table would widen them
+class GifWriter {
+public:
+    GifWriter (int width, int height, const std::vector<std::array<uint8_t, 3>>& palette, int background) {
+	bytes = "GIF89a";
+	u16 (width);
+	u16 (height);
+	bytes += static_cast<char> (0x80 | 1);
+	bytes += static_cast<char> (background);
+	bytes += '\0';
+
+	for (size_t i = 0; i < 4; i++) {
+	    const auto color = i < palette.size () ? palette[i] : std::array<uint8_t, 3> {};
+	    bytes.append (reinterpret_cast<const char*> (color.data ()), 3);
+	}
+    }
+
+    GifWriter& control (int disposal, int delayCentiseconds, int transparent = -1) {
+	bytes += "\x21\xF9\x04";
+	bytes += static_cast<char> ((disposal << 2) | (transparent >= 0 ? 1 : 0));
+	u16 (delayCentiseconds);
+	bytes += static_cast<char> (transparent >= 0 ? transparent : 0);
+	bytes += '\0';
+	return *this;
+    }
+
+    GifWriter&
+    image (int x, int y, int width, int height, const std::vector<uint8_t>& indices, bool interlaced = false) {
+	bytes += '\x2C';
+	u16 (x);
+	u16 (y);
+	u16 (width);
+	u16 (height);
+	bytes += static_cast<char> (interlaced ? 0x40 : 0);
+
+	constexpr int lzwSize = 2;
+	constexpr int clear = 1 << lzwSize;
+	constexpr int codeSize = lzwSize + 1;
+	std::string packed;
+	uint32_t bits = 0;
+	int count = 0;
+
+	const auto emit = [&] (int code) {
+	    bits |= static_cast<uint32_t> (code) << count;
+	    count += codeSize;
+
+	    while (count >= 8) {
+		packed += static_cast<char> (bits & 0xFF);
+		bits >>= 8;
+		count -= 8;
+	    }
+	};
+
+	for (size_t i = 0; i < indices.size (); i++) {
+	    if (i % (clear - 2) == 0) {
+		emit (clear);
+	    }
+
+	    emit (indices[i]);
+	}
+
+	emit (clear + 1);
+
+	if (count > 0) {
+	    packed += static_cast<char> (bits & 0xFF);
+	}
+
+	bytes += static_cast<char> (lzwSize);
+
+	for (size_t offset = 0; offset < packed.size (); offset += 255) {
+	    const auto block = packed.substr (offset, 255);
+	    bytes += static_cast<char> (block.size ());
+	    bytes += block;
+	}
+
+	bytes += '\0';
+	return *this;
+    }
+
+    std::string finish () { return bytes + '\x3B'; }
+
+    std::string bytes;
+
+private:
+    void u16 (int value) {
+	bytes += static_cast<char> (value & 0xFF);
+	bytes += static_cast<char> ((value >> 8) & 0xFF);
+    }
+};
+
+const std::vector<std::array<uint8_t, 3>> PALETTE = { { 0, 0, 0 }, { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } };
+
+Pixel pixelAt (const GifAnimation& gif, int x, int y) {
+    const uint8_t* pixel = gif.pixels () + (static_cast<size_t> (y) * gif.width () + x) * 4;
+    return { pixel[0], pixel[1], pixel[2], pixel[3] };
+}
+
+constexpr Pixel RED = { 255, 0, 0, 255 };
+constexpr Pixel GREEN = { 0, 255, 0, 255 };
+constexpr Pixel BLUE = { 0, 0, 255, 255 };
+constexpr Pixel CLEAR = { 0, 0, 0, 0 };
+} // namespace
+
+TEST_CASE ("GIF frames follow their own delays and start over after the trailer") {
+    const auto bytes = GifWriter (2, 1, PALETTE, 0)
+			   .control (1, 10)
+			   .image (0, 0, 2, 1, { 1, 1 })
+			   .control (1, 20)
+			   .image (0, 0, 2, 1, { 2, 2 })
+			   .control (1, 5)
+			   .image (0, 0, 2, 1, { 3, 3 })
+			   .finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif != nullptr);
+    REQUIRE (gif->advance (0.0f));
+    CHECK (gif->width () == 2);
+    CHECK (gif->height () == 1);
+    CHECK (pixelAt (*gif, 1, 0) == RED);
+
+    // 100ms on the first frame
+    CHECK_FALSE (gif->advance (0.06f));
+    REQUIRE (gif->advance (0.05f));
+    CHECK (pixelAt (*gif, 0, 0) == GREEN);
+
+    // the 10ms overshoot carries over
+    CHECK_FALSE (gif->advance (0.18f));
+    REQUIRE (gif->advance (0.02f));
+    CHECK (pixelAt (*gif, 0, 0) == BLUE);
+
+    REQUIRE (gif->advance (0.05f));
+    CHECK (pixelAt (*gif, 0, 0) == RED);
+}
+
+TEST_CASE ("GIF frames draw over the previous one and skip transparent pixels") {
+    const auto bytes = GifWriter (2, 2, PALETTE, 0)
+			   .control (1, 10)
+			   .image (0, 0, 2, 2, { 1, 1, 1, 1 })
+			   .control (1, 10, 0)
+			   .image (0, 0, 2, 2, { 0, 3, 0, 0 })
+			   .finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif->advance (0.0f));
+    REQUIRE (gif->advance (0.1f));
+    CHECK (pixelAt (*gif, 0, 0) == RED);
+    CHECK (pixelAt (*gif, 1, 0) == BLUE);
+    CHECK (pixelAt (*gif, 0, 1) == RED);
+}
+
+TEST_CASE ("GIF disposal 2 fills with the background entry as resourceutil64 stores it") {
+    // WE copies the palette entry as BGRA, so red index 1 comes out blue
+    const auto bytes = GifWriter (2, 2, PALETTE, 1)
+			   .control (2, 10)
+			   .image (0, 0, 1, 1, { 2 })
+			   .control (1, 10)
+			   .image (1, 1, 1, 1, { 3 })
+			   .finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif->advance (0.0f));
+    CHECK (pixelAt (*gif, 0, 0) == GREEN);
+    CHECK (pixelAt (*gif, 1, 0) == BLUE);
+
+    REQUIRE (gif->advance (0.1f));
+    CHECK (pixelAt (*gif, 0, 0) == BLUE);
+    CHECK (pixelAt (*gif, 1, 1) == BLUE);
+}
+
+TEST_CASE ("GIF disposal 2 without a background clears to transparent") {
+    // background index 0 = none in resourceutil64
+    const auto bytes = GifWriter (2, 1, PALETTE, 0)
+			   .control (2, 10)
+			   .image (0, 0, 2, 1, { 1, 2 })
+			   .control (1, 10)
+			   .image (1, 0, 1, 1, { 3 })
+			   .finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif->advance (0.0f));
+    REQUIRE (gif->advance (0.1f));
+    CHECK (pixelAt (*gif, 0, 0) == CLEAR);
+    CHECK (pixelAt (*gif, 1, 0) == BLUE);
+}
+
+TEST_CASE ("GIF disposal 3 restores the last frame that was kept") {
+    const auto bytes = GifWriter (2, 2, PALETTE, 0)
+			   .control (1, 10)
+			   .image (0, 0, 2, 2, { 1, 1, 1, 1 })
+			   .control (3, 10)
+			   .image (0, 0, 1, 1, { 2 })
+			   .control (1, 10)
+			   .image (1, 1, 1, 1, { 3 })
+			   .finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif->advance (0.0f));
+    REQUIRE (gif->advance (0.1f));
+    CHECK (pixelAt (*gif, 0, 0) == GREEN);
+
+    REQUIRE (gif->advance (0.1f));
+    CHECK (pixelAt (*gif, 0, 0) == RED);
+    CHECK (pixelAt (*gif, 1, 1) == BLUE);
+}
+
+TEST_CASE ("Interlaced GIF rows land in pass order") {
+    // passes write rows 0, 4, then 2, 6, then 1, 3, 5, 7
+    const auto bytes
+	= GifWriter (1, 8, PALETTE, 0).control (1, 10).image (0, 0, 1, 8, { 1, 1, 2, 2, 3, 3, 3, 3 }, true).finish ();
+    auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+    REQUIRE (gif->advance (0.0f));
+
+    const std::array<Pixel, 8> rows = { RED, BLUE, GREEN, BLUE, RED, BLUE, GREEN, BLUE };
+
+    for (int y = 0; y < 8; y++) {
+	CHECK (pixelAt (*gif, 0, y) == rows[y]);
+    }
+}
+
+TEST_CASE ("Broken GIFs fail without decoding or allocating the claimed canvas") {
+    CHECK (GifAnimation::open ("PNG", 3) == nullptr);
+
+    const auto huge = std::string ("GIF89a\xff\xff\xff\xff\x80\x00\x00", 13) + std::string (12, '\0') + "\x3B";
+    const auto empty = std::string ("GIF89a\0\0\0\0\x80\x00\x00", 13) + std::string (12, '\0') + "\x3B";
+
+    for (const auto& bytes : { std::string ("GIF89a"), huge, empty }) {
+	auto gif = GifAnimation::open (bytes.data (), bytes.size ());
+
+	REQUIRE (gif != nullptr);
+	CHECK_FALSE (gif->advance (0.0f));
+    }
+
+    // a frame reaching past the logical screen
+    const auto outside = GifWriter (2, 2, PALETTE, 0).control (1, 10).image (1, 1, 2, 2, { 1, 1, 1, 1 }).finish ();
+    auto gif = GifAnimation::open (outside.data (), outside.size ());
+
+    CHECK_FALSE (gif->advance (0.0f));
+
+    // a raster that starts with a data code instead of a clear code
+    auto noClear = GifWriter (1, 1, PALETTE, 0).control (1, 10).bytes;
+    noClear += std::string ("\x2C\0\0\0\0\x01\0\x01\0\0\x02\x01\x01\0\x3B", 16);
+    gif = GifAnimation::open (noClear.data (), noClear.size ());
+
+    CHECK_FALSE (gif->advance (0.0f));
+}
+
+namespace {
+constexpr int BLOCK = 16;
+const std::array<std::array<uint8_t, 3>, 6> BLOCK_COLORS
+    = { { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 0 } } };
+
+// 3x2 solid blocks, row by row
+std::string blockJpeg () {
+    std::vector<uint8_t> rgb (3 * BLOCK * 2 * BLOCK * 3);
+
+    for (int y = 0; y < 2 * BLOCK; y++) {
+	for (int x = 0; x < 3 * BLOCK; x++) {
+	    const auto& color = BLOCK_COLORS[(y / BLOCK) * 3 + x / BLOCK];
+	    std::copy (color.begin (), color.end (), rgb.begin () + (y * 3 * BLOCK + x) * 3);
+	}
+    }
+
+    std::string out;
+    stbi_write_jpg_to_func (
+	[] (void* context, void* data, int size) {
+	    static_cast<std::string*> (context)->append (static_cast<const char*> (data), size);
+	},
+	&out, 3 * BLOCK, 2 * BLOCK, 3, rgb.data (), 100
+    );
+    return out;
+}
+
+// APP1 Exif after SOI, one Orientation (0x0112) SHORT entry
+std::string withOrientation (const std::string& jpeg, int orientation, bool bigEndian) {
+    std::string tiff = bigEndian ? std::string ("MM\0\x2A\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01", 18)
+				 : std::string ("II\x2A\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0", 18);
+
+    if (bigEndian) {
+	tiff += '\0';
+	tiff += static_cast<char> (orientation);
+    } else {
+	tiff += static_cast<char> (orientation);
+	tiff += '\0';
+    }
+
+    tiff += std::string (6, '\0');
+
+    const std::string payload = std::string ("Exif\0\0", 6) + tiff;
+    const size_t length = payload.size () + 2;
+
+    return jpeg.substr (0, 2) + "\xFF\xE1" + static_cast<char> (length >> 8) + static_cast<char> (length & 0xFF)
+	+ payload + jpeg.substr (2);
+}
+
+bool near (const uint8_t* pixel, const std::array<uint8_t, 3>& color) {
+    for (int c = 0; c < 3; c++) {
+	if (std::abs (pixel[c] - color[c]) > 24) {
+	    return false;
+	}
+    }
+
+    return pixel[3] == 255;
+}
+} // namespace
+
+TEST_CASE ("JPEGs come out in their EXIF orientation and size probing agrees") {
+    const auto jpeg = blockJpeg ();
+    REQUIRE (jpeg.size () > 100);
+
+    // source block per position, row by row over the oriented image
+    const std::array<std::array<int, 6>, 8> expected { {
+	{ { 0, 1, 2, 3, 4, 5 } },
+	{ { 2, 1, 0, 5, 4, 3 } },
+	{ { 5, 4, 3, 2, 1, 0 } },
+	{ { 3, 4, 5, 0, 1, 2 } },
+	{ { 0, 3, 1, 4, 2, 5 } },
+	{ { 3, 0, 4, 1, 5, 2 } },
+	{ { 5, 2, 4, 1, 3, 0 } },
+	{ { 2, 5, 1, 4, 0, 3 } },
+    } };
+
+    for (const bool bigEndian : { false, true }) {
+	for (int orientation = 1; orientation <= 8; orientation++) {
+	    INFO ("orientation " << orientation << (bigEndian ? " big endian" : " little endian"));
+
+	    const auto tagged = withOrientation (jpeg, orientation, bigEndian);
+	    int width = 0;
+	    int height = 0;
+	    int probeWidth = 0;
+	    int probeHeight = 0;
+	    stbi_uc* pixels = WallpaperEngine::Render::decodeImageRGBA (tagged.data (), tagged.size (), width, height);
+
+	    REQUIRE (pixels != nullptr);
+	    REQUIRE (
+		WallpaperEngine::Render::decodedImageSize (tagged.data (), tagged.size (), probeWidth, probeHeight)
+	    );
+	    CHECK (probeWidth == width);
+	    CHECK (probeHeight == height);
+
+	    const bool swapped = orientation >= 5;
+	    const int columns = swapped ? 2 : 3;
+
+	    CHECK (width == columns * BLOCK);
+	    CHECK (height == (swapped ? 3 : 2) * BLOCK);
+
+	    for (int block = 0; block < 6; block++) {
+		const int x = (block % columns) * BLOCK + BLOCK / 2;
+		const int y = (block / columns) * BLOCK + BLOCK / 2;
+
+		CHECK (near (
+		    pixels + (static_cast<size_t> (y) * width + x) * 4, BLOCK_COLORS[expected[orientation - 1][block]]
+		));
+	    }
+
+	    stbi_image_free (pixels);
+	}
+    }
+}
+
+TEST_CASE ("Broken or missing EXIF data leaves the image as it is") {
+    const auto jpeg = blockJpeg ();
+
+    std::string badTiff = withOrientation (jpeg, 6, false);
+    // neither II nor MM
+    badTiff[2 + 4 + 6] = 'X';
+
+    std::string badValue = withOrientation (jpeg, 9, false);
+
+    for (const auto& bytes : { jpeg, badTiff, badValue }) {
+	int width = 0;
+	int height = 0;
+	stbi_uc* pixels = WallpaperEngine::Render::decodeImageRGBA (bytes.data (), bytes.size (), width, height);
+
+	REQUIRE (pixels != nullptr);
+	CHECK (width == 3 * BLOCK);
+	CHECK (height == 2 * BLOCK);
+	CHECK (near (pixels + (BLOCK / 2 * width + BLOCK / 2) * 4, BLOCK_COLORS[0]));
+	stbi_image_free (pixels);
+    }
+}

+ 77 - 0
src/WallpaperEngine/Testing/Cases/PowerSupply.cpp

@@ -0,0 +1,77 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <filesystem>
+#include <fstream>
+#include <map>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/PowerMonitor.h"
+
+using WallpaperEngine::Desktop::sysfsOnBattery;
+
+namespace {
+struct PowerSupplies {
+    std::filesystem::path path
+	= std::filesystem::temp_directory_path () / ("lwe-power-test-" + std::to_string (getpid ()));
+
+    PowerSupplies () { std::filesystem::create_directories (path); }
+    ~PowerSupplies () { std::filesystem::remove_all (path); }
+
+    void supply (const std::string& name, const std::map<std::string, std::string>& files) const {
+	std::filesystem::create_directories (path / name);
+
+	for (const auto& [file, value] : files) {
+	    std::ofstream (path / name / file) << value << "\n";
+	}
+    }
+};
+} // namespace
+
+TEST_CASE ("A desktop without a battery has no answer") {
+    PowerSupplies supplies;
+
+    CHECK_FALSE (sysfsOnBattery (supplies.path).has_value ());
+
+    supplies.supply ("hidpp_battery_0", { { "type", "Battery" }, { "scope", "Device" }, { "status", "Discharging" } });
+
+    CHECK_FALSE (sysfsOnBattery (supplies.path).has_value ());
+}
+
+TEST_CASE ("A discharging laptop battery is battery power") {
+    PowerSupplies supplies;
+    supplies.supply ("AC", { { "type", "Mains" }, { "online", "0" } });
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Discharging" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == true);
+}
+
+TEST_CASE ("Charging, full or plugged in is not battery power") {
+    PowerSupplies supplies;
+    supplies.supply ("AC", { { "type", "Mains" }, { "online", "0" } });
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Charging" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == false);
+
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Full" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == false);
+
+    // a weak USB-C charger can still leave the battery discharging
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Discharging" } });
+    supplies.supply ("ucsi-source-psy-USBC000:001", { { "type", "USB" }, { "online", "1" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == false);
+}
+
+TEST_CASE ("Peripheral batteries are ignored") {
+    PowerSupplies supplies;
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Charging" } });
+    supplies.supply ("hidpp_battery_0", { { "type", "Battery" }, { "scope", "Device" }, { "status", "Discharging" } });
+    supplies.supply ("hid-headset", { { "type", "USB" }, { "scope", "Device" }, { "online", "1" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == false);
+
+    supplies.supply ("BAT0", { { "type", "Battery" }, { "status", "Discharging" } });
+
+    CHECK (sysfsOnBattery (supplies.path) == true);
+}

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

@@ -0,0 +1,398 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <algorithm>
+#include <array>
+#include <bit>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "WallpaperEngine/Render/Objects/PuppetClipping.h"
+#include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
+#include "WallpaperEngine/Render/Objects/PuppetRig.h"
+
+using namespace WallpaperEngine::Render::Objects;
+
+namespace {
+// position, blend indices, blend weights, uv: 52 bytes
+constexpr uint32_t SKINNED = 0x1 | 0x800000 | 0x1000000 | 0x8;
+
+struct Builder {
+    std::vector<char> bytes;
+
+    void u8 (uint8_t value) { bytes.push_back (static_cast<char> (value)); }
+
+    void u32 (uint32_t value) {
+	for (int shift = 0; shift < 32; shift += 8) {
+	    bytes.push_back (static_cast<char> (value >> shift));
+	}
+    }
+
+    void f32 (float value) { u32 (std::bit_cast<uint32_t> (value)); }
+
+    void text (const std::string& value) {
+	bytes.insert (bytes.end (), value.begin (), value.end ());
+	bytes.push_back ('\0');
+    }
+
+    [[nodiscard]] size_t size () const { return bytes.size (); }
+};
+
+struct Options {
+    int version = 23;
+    uint32_t format = SKINNED;
+    uint32_t flags = 0;
+    std::string material = "materials/puppet.json";
+    /** padding before the UVs, a stride the format doesn't describe */
+    size_t padding = 0;
+    std::vector<uint16_t> indices = { 0, 1, 2 };
+    /** v21 auxiliary block and its declared size */
+    std::optional<uint32_t> auxBytes;
+    /** v21 part ranges as (bone, order, first, count) */
+    std::vector<std::array<uint32_t, 4>> parts;
+    /** v23 clipping records: targets, then sources */
+    std::vector<std::pair<std::vector<uint32_t>, std::vector<uint32_t>>> records;
+    bool skeleton = false;
+    bool attachmentsFirst = false;
+};
+
+struct Fixture {
+    std::vector<char> bytes;
+    size_t vertices = 0;
+    size_t indexEnd = 0;
+    size_t skeleton = 0;
+    size_t sections = 0;
+};
+
+uint32_t strideOf (uint32_t format) {
+    uint32_t stride = 0;
+    stride += format & 0x1 ? 12 : 0;
+    stride += format & 0x2 ? 12 : 0;
+    stride += format & 0x800000 ? 16 : 0;
+    stride += format & 0x1000000 ? 16 : 0;
+    stride += format & 0x8 ? 8 : 0;
+    stride += format & 0x8000 ? 16 : 0;
+    return stride;
+}
+
+// one three-vertex mesh as WE's resource compiler writes it
+Fixture puppet (const Options& options = {}) {
+    Builder out;
+    Fixture fixture;
+    const std::string tag
+	= "MDLV" + std::string (options.version < 10 ? "000" : "00") + std::to_string (options.version);
+
+    out.text (tag);
+    out.u32 (options.format);
+    out.u32 (1);
+    out.u32 (1);
+    out.text (options.material);
+    out.u32 (options.flags);
+
+    if (options.flags & 2) {
+	out.u32 (1);
+    }
+
+    if (options.version >= 17) {
+	for (int i = 0; i < 6; i++) {
+	    out.f32 (static_cast<float> (i));
+	}
+    }
+
+    if (options.version >= 15) {
+	out.u32 (options.format);
+    }
+
+    const uint32_t stride = strideOf (options.format) + static_cast<uint32_t> (options.padding);
+    out.u32 (stride * 3);
+    fixture.vertices = out.size ();
+
+    for (int vertex = 0; vertex < 3; vertex++) {
+	out.f32 (vertex == 1 ? 100.0f : 0.0f);
+	out.f32 (vertex == 2 ? 100.0f : 0.0f);
+	out.f32 (0.0f);
+
+	if (options.format & 0x2) {
+	    out.f32 (0.0f);
+	    out.f32 (0.0f);
+	    out.f32 (1.0f);
+	}
+
+	if (options.format & 0x800000) {
+	    out.u32 (0);
+	    out.u32 (1);
+	    out.u32 (0);
+	    out.u32 (0);
+	}
+
+	if (options.format & 0x1000000) {
+	    out.f32 (0.25f);
+	    out.f32 (0.75f);
+	    out.f32 (0.0f);
+	    out.f32 (0.0f);
+	}
+
+	for (size_t i = 0; i < options.padding; i++) {
+	    out.u8 (0);
+	}
+
+	if (options.format & 0x8) {
+	    out.f32 (vertex == 1 ? 1.0f : 0.0f);
+	    out.f32 (vertex == 2 ? 1.0f : 0.0f);
+	}
+
+	if (options.format & 0x8000) {
+	    out.f32 (1.0f);
+	    out.f32 (1.0f);
+	    out.f32 (1.0f);
+	    out.f32 (1.0f);
+	}
+    }
+
+    out.u32 (static_cast<uint32_t> (options.indices.size () * sizeof (uint16_t)));
+
+    for (const uint16_t index : options.indices) {
+	out.u8 (index & 0xFF);
+	out.u8 (index >> 8);
+    }
+
+    fixture.indexEnd = out.size ();
+
+    if (options.version >= 21) {
+	out.u8 (options.auxBytes.has_value () ? 1 : 0);
+
+	if (options.auxBytes.has_value ()) {
+	    out.u32 (0);
+	    out.u32 (*options.auxBytes);
+
+	    for (uint32_t i = 0; i < *options.auxBytes / 4; i++) {
+		out.f32 (static_cast<float> (i));
+	    }
+	}
+
+	out.u8 (options.parts.empty () ? 0 : 1);
+
+	if (!options.parts.empty ()) {
+	    out.u32 (static_cast<uint32_t> (options.parts.size () * 16));
+
+	    for (const auto& part : options.parts) {
+		for (const uint32_t value : part) {
+		    out.u32 (value);
+		}
+	    }
+	}
+    }
+
+    if (options.version >= 23) {
+	out.u32 (static_cast<uint32_t> (options.records.size ()));
+
+	for (const auto& [targets, sources] : options.records) {
+	    out.u32 (0);
+	    out.u32 (0);
+	    out.text ("masks/clip");
+	    out.u32 (0);
+
+	    for (const auto* list : { &targets, &sources }) {
+		out.u32 (static_cast<uint32_t> (list->size ()));
+
+		for (const uint32_t part : *list) {
+		    out.u32 (part);
+		}
+	    }
+	}
+    }
+
+    fixture.sections = out.size ();
+
+    if (options.attachmentsFirst) {
+	out.text ("MDAT0001");
+	out.u32 (static_cast<uint32_t> (out.size () + sizeof (uint32_t) * 2));
+	out.u32 (0);
+    }
+
+    fixture.skeleton = out.size ();
+
+    if (options.skeleton) {
+	// one root bone: no name, parent -1, identity bind matrix, no physics
+	out.text ("MDLS0001");
+	out.u32 (0);
+	out.u32 (1);
+	out.u32 (0);
+	out.u32 (0xFFFFFFFF);
+	out.u32 (64);
+
+	for (int i = 0; i < 16; i++) {
+	    out.f32 (i % 5 == 0 ? 1.0f : 0.0f);
+	}
+
+	out.text ("");
+    } else {
+	out.u8 (0);
+    }
+
+    fixture.bytes = std::move (out.bytes);
+    return fixture;
+}
+} // namespace
+
+TEST_CASE ("The first puppet mesh is read from its header") {
+    for (const int version : { 13, 15, 17, 21, 23 }) {
+	INFO ("MDLV" << version);
+
+	const auto fixture = puppet ({ .version = version });
+	const auto mesh = readPuppetMeshFile (fixture.bytes);
+
+	REQUIRE (mesh.has_value ());
+	CHECK (mesh->version == version);
+	CHECK (mesh->layout.vertexStride == 52);
+	CHECK (mesh->layout.block.headerOffset + 8 == fixture.vertices);
+	CHECK (mesh->indexEnd == fixture.indexEnd);
+	REQUIRE (mesh->positions.size () == 9);
+	CHECK (mesh->positions[3] == 100.0f);
+	CHECK (mesh->positions[7] == 100.0f);
+	CHECK (mesh->texcoords[2] == 1.0f);
+	CHECK (mesh->indices == std::vector<uint16_t> { 0, 1, 2 });
+	REQUIRE (mesh->blendIndices.size () == 3);
+	CHECK (mesh->blendIndices[2].y == 1);
+	CHECK (mesh->blendWeights[2].y == 0.75f);
+	CHECK (mesh->warnings.empty ());
+    }
+}
+
+TEST_CASE ("MDLS bytes in a material name or the vertices don't frame the skeleton") {
+    const auto withName = puppet ({ .material = "materials/MDLS_embedded.json" });
+
+    CHECK (findPuppetSkeleton (withName.bytes) == withName.bytes.size ());
+
+    const auto withSkeleton = puppet ({ .material = "materials/MDLS_embedded.json", .skeleton = true });
+
+    CHECK (findPuppetSkeleton (withSkeleton.bytes) == withSkeleton.skeleton);
+
+    // the padding in every vertex spells MDLS too
+    auto inVertices = puppet ({ .padding = 4, .skeleton = true });
+    const uint32_t stride = 56;
+
+    for (int vertex = 0; vertex < 3; vertex++) {
+	std::copy_n ("MDLS", 4, inVertices.bytes.begin () + inVertices.vertices + vertex * stride + 44);
+    }
+
+    CHECK (findPuppetSkeleton (inVertices.bytes) == inVertices.skeleton);
+
+    const auto mesh = readPuppetMeshFile (withSkeleton.bytes);
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->skeleton == withSkeleton.skeleton);
+    CHECK (mesh->meshCount == 1);
+}
+
+TEST_CASE ("MDLS is found among the sections after the meshes in any order") {
+    const auto later = puppet ({ .skeleton = true, .attachmentsFirst = true });
+
+    REQUIRE (later.skeleton > later.sections);
+    CHECK (findPuppetSkeleton (later.bytes) == later.skeleton);
+    CHECK (findMdlSection (later.bytes, later.sections, "MDAT") == later.sections);
+    CHECK_FALSE (findMdlSection (later.bytes, later.sections, "MDLA").has_value ());
+
+    const auto mesh = readPuppetMeshFile (later.bytes);
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->skeleton == later.skeleton);
+    CHECK (mesh->sections == later.sections);
+
+    PuppetRig rig;
+    REQUIRE_NOTHROW (rig.load (later.bytes, mesh->sections, mesh->meshCount, "test"));
+    CHECK (rig.bones.size () == 1);
+
+    const auto first = puppet ({ .skeleton = true });
+    CHECK (readPuppetMeshFile (first.bytes)->sections == first.skeleton);
+}
+
+TEST_CASE ("Meshes the header doesn't describe fall back to the stride search") {
+    // UVs not last (a colour follows), so the declared format isn't used
+    const auto colourLast = puppet ({ .format = SKINNED | 0x8000 });
+    auto mesh = readPuppetMeshFile (colourLast.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK_FALSE (mesh->declaredLayout);
+
+    const auto padded = puppet ({ .padding = 4 });
+    mesh = readPuppetMeshFile (padded.bytes);
+
+    // one triangle can't rank strides, any usable mesh will do
+    REQUIRE (mesh.has_value ());
+    CHECK_FALSE (mesh->declaredLayout);
+    CHECK (mesh->indices.size () == 3);
+
+    const auto declared = puppet ();
+    mesh = readPuppetMeshFile (declared.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->declaredLayout);
+    CHECK (mesh->flags == 0);
+    CHECK (mesh->format == SKINNED);
+}
+
+TEST_CASE ("Broken puppet meshes are refused without throwing") {
+    const auto good = puppet ();
+
+    const auto pastEnd = puppet ({ .indices = { 0, 1, 7 } });
+    CHECK_NOTHROW (readPuppetMeshFile (pastEnd.bytes));
+    CHECK_FALSE (readPuppetMeshFile (pastEnd.bytes).has_value ());
+
+    for (const size_t length : { size_t (0), size_t (5), size_t (40), good.vertices + 20, good.indexEnd - 1 }) {
+	INFO ("cut at " << length);
+	const std::vector<char> cut (good.bytes.begin (), good.bytes.begin () + length);
+
+	CHECK_NOTHROW (readPuppetMeshFile (cut));
+	CHECK_NOTHROW (findPuppetSkeleton (cut));
+    }
+}
+
+TEST_CASE ("Bad optional puppet data leaves the plain mesh") {
+    // an auxiliary block shorter than one vec3 per vertex is dropped with a warning
+    const auto shortAux = puppet ({ .version = 21, .auxBytes = 12 });
+    auto mesh = readPuppetMeshFile (shortAux.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->auxPositions.empty ());
+    CHECK (mesh->warnings.size () == 1);
+    CHECK (mesh->positions.size () == 9);
+
+    const auto aux = puppet ({ .version = 21, .auxBytes = 36 });
+    mesh = readPuppetMeshFile (aux.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->auxPositions.size () == 9);
+    CHECK (mesh->auxPositions[8] == 8.0f);
+
+    // bad part ranges or records throw, CImage draws the mesh without them
+    const auto badParts = puppet ({ .flags = 8, .parts = { { 0, 0, 0, 9 } } });
+    mesh = readPuppetMeshFile (badParts.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK_THROWS (PuppetClipping::readParts (badParts.bytes, mesh->indexEnd, mesh->version, mesh->indices.size ()));
+
+    const auto badRecord = puppet ({ .parts = { { 0, 0, 0, 3 } }, .records = { { { 0 }, { 4 } } } });
+    mesh = readPuppetMeshFile (badRecord.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK_THROWS (PuppetClipping::read (badRecord.bytes, mesh->indexEnd, mesh->version, mesh->indices.size ()));
+
+    const auto goodRecord = puppet ({ .parts = { { 0, 0, 0, 3 } }, .records = { { { 0 }, {} } } });
+    const auto clipping = PuppetClipping::read (
+	goodRecord.bytes, goodRecord.indexEnd, 23, readPuppetMeshFile (goodRecord.bytes)->indices.size ()
+    );
+
+    REQUIRE (clipping.has_value ());
+    CHECK (clipping->records.size () == 1);
+
+    // truncated skeleton fails, CImage keeps the bind pose
+    auto cutSkeleton = puppet ({ .skeleton = true });
+    cutSkeleton.bytes.resize (cutSkeleton.skeleton + 20);
+    mesh = readPuppetMeshFile (cutSkeleton.bytes);
+
+    REQUIRE (mesh.has_value ());
+    CHECK (mesh->skeleton == cutSkeleton.skeleton);
+
+    PuppetRig rig;
+    CHECK_THROWS (rig.load (cutSkeleton.bytes, mesh->skeleton, mesh->meshCount, "cut.mdl"));
+}

+ 182 - 0
src/WallpaperEngine/Testing/Cases/ScriptLocalStorage.cpp

@@ -0,0 +1,182 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <filesystem>
+#include <memory>
+#include <string>
+#include <unistd.h>
+
+#include "WallpaperEngine/Scripting/JS.h"
+#include "WallpaperEngine/Scripting/LocalStorageObject.h"
+
+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") {
+	JS::platform ();
+	allocator.reset (v8::ArrayBuffer::Allocator::NewDefaultAllocator ());
+	v8::Isolate::CreateParams params;
+	params.array_buffer_allocator = allocator.get ();
+	isolate = v8::Isolate::New (params);
+
+	const v8::Isolate::Scope isolateScope (isolate);
+	const v8::HandleScope handleScope (isolate);
+	const auto local = v8::Context::New (isolate);
+	const v8::Context::Scope contextScope (local);
+
+	context.Reset (isolate, local);
+	storage = std::make_unique<LocalStorageObject> (
+	    isolate, local,
+	    LocalStorageObject::Host {
+		.identity = [scene] { return scene; },
+		.screen = [screen] { return screen; },
+		.evaluatingModuleBody = [this] { return moduleBody; },
+	    }
+	);
+	JS::set (local, local->Global (), "localStorage", storage->getInstance ());
+    }
+
+    ~Script () {
+	storage.reset ();
+	context.Reset ();
+	isolate->Dispose ();
+    }
+
+    /** JSON, or "throws: <message>" */
+    std::string run (const std::string& source) {
+	const v8::Isolate::Scope isolateScope (isolate);
+	const v8::HandleScope handleScope (isolate);
+	const auto local = context.Get (isolate);
+	const v8::Context::Scope contextScope (local);
+	const v8::TryCatch tryCatch (isolate);
+
+	v8::Local<v8::Script> script;
+	v8::Local<v8::Value> result;
+
+	if (!v8::Script::Compile (local, JS::string (isolate, source)).ToLocal (&script)
+	    || !script->Run (local).ToLocal (&result)) {
+	    return "throws: " + JS::toString (isolate, tryCatch.Exception ());
+	}
+
+	if (result->IsUndefined ()) {
+	    return "undefined";
+	}
+
+	v8::Local<v8::String> json;
+	return v8::JSON::Stringify (local, result).ToLocal (&json) ? JS::toString (isolate, json) : "?";
+    }
+
+    std::unique_ptr<v8::ArrayBuffer::Allocator> allocator;
+    v8::Isolate* isolate;
+    v8::Global<v8::Context> context;
+    std::unique_ptr<LocalStorageObject> storage;
+    bool moduleBody = false;
+};
+
+void useTemporaryDirectory (const std::string& name) {
+    const auto dir
+	= std::filesystem::temp_directory_path () / ("lwe-script-storage-" + std::to_string (getpid ())) / name;
+    std::filesystem::remove_all (dir);
+    std::filesystem::create_directories (dir);
+    LocalStorage::setDirectory (dir);
+}
+} // namespace
+
+TEST_CASE ("Script localStorage hands values back as JSON") {
+    useTemporaryDirectory ("values");
+    Script script ("/scenes/values/scene.pkg");
+
+    CHECK (script.run ("localStorage.set('n', 1.5); localStorage.get('n')") == "1.5");
+    CHECK (script.run ("localStorage.set('s', 'text'); localStorage.get('s')") == "\"text\"");
+    CHECK (script.run ("localStorage.set('b', false); localStorage.get('b')") == "false");
+    CHECK (
+	script.run ("localStorage.set('o', {a: [1, {b: null}]}); localStorage.get('o')") == "{\"a\":[1,{\"b\":null}]}"
+    );
+    CHECK (script.run ("localStorage.set('z', null); localStorage.get('z')") == "null");
+    CHECK (script.run ("localStorage.get('missing')") == "undefined");
+
+    // JSON.stringify gives undefined for a function and throws on a cycle, both store just the header
+    CHECK (script.run ("localStorage.set('f', function () {}); localStorage.get('f')") == "null");
+    CHECK (script.run ("var c = {}; c.c = c; localStorage.set('cycle', c); localStorage.get('cycle')") == "null");
+}
+
+TEST_CASE ("Script localStorage keeps the screen and global stores apart") {
+    useTemporaryDirectory ("locations");
+    Script script ("/scenes/locations/scene.pkg");
+
+    CHECK (script.run ("[localStorage.LOCATION_GLOBAL, localStorage.LOCATION_SCREEN]") == "[\"global\",\"screen\"]");
+    script.run ("localStorage.set('k', 'screen'); localStorage.set('k', 'global', 'global')");
+
+    CHECK (script.run ("localStorage.get('k')") == "\"screen\"");
+    CHECK (script.run ("localStorage.get('k', 'screen')") == "\"screen\"");
+    // any capitalisation of "global" counts, anything else is the screen store
+    CHECK (script.run ("localStorage.get('k', 'GLOBAL')") == "\"global\"");
+    CHECK (script.run ("localStorage.get('k', localStorage.LOCATION_GLOBAL)") == "\"global\"");
+    CHECK (script.run ("localStorage.get('k', 1)") == "\"screen\"");
+
+    Script other ("/scenes/other/scene.pkg");
+    CHECK (other.run ("localStorage.get('k', 'global')") == "undefined");
+}
+
+TEST_CASE ("Script localStorage has one store in a window") {
+    useTemporaryDirectory ("window");
+    // a window has no screen, both stores are the scene file's
+    Script script ("/scenes/window/scene.pkg", "");
+
+    script.run ("localStorage.set('k', 1, 'global')");
+    CHECK (script.run ("localStorage.get('k')") == "1");
+    CHECK (script.run ("localStorage.get('k', 'global')") == "1");
+}
+
+TEST_CASE ("Script localStorage follows WE's argument rules") {
+    useTemporaryDirectory ("arguments");
+    Script script ("/scenes/arguments/scene.pkg");
+
+    // set with undefined is delete with the same arguments, whose location then is the undefined value: the screen
+    script.run ("localStorage.set('k', 'screen'); localStorage.set('k', 'global', 'global')");
+    script.run ("localStorage.set('k', undefined, 'global')");
+    CHECK (script.run ("localStorage.get('k')") == "undefined");
+    CHECK (script.run ("localStorage.get('k', 'global')") == "\"global\"");
+
+    CHECK (script.run ("localStorage.delete('k', 'global')") == "true");
+    CHECK (script.run ("localStorage.delete('k', 'global')") == "false");
+    CHECK (script.run ("localStorage.set('a', 1); localStorage.clear()") == "true");
+    CHECK (script.run ("localStorage.get('a')") == "undefined");
+
+    CHECK (script.run ("localStorage.set(5, 1)") == "throws: SyntaxError: LocalStorageSet key not a string.");
+    CHECK (script.run ("localStorage.get()") == "throws: SyntaxError: LocalStorageSet key not a string.");
+
+    // 100000 byte limit
+    CHECK (script.run ("localStorage.set('big', 'x'.repeat (99000))") == "undefined");
+    CHECK (
+	script.run ("localStorage.set('more', 'x'.repeat (2000))")
+	== "throws: SyntaxError: LocalStorageSet failed, possibly out of memory."
+    );
+}
+
+TEST_CASE ("Script localStorage throws at a module's top level") {
+    useTemporaryDirectory ("toplevel");
+    Script script ("/scenes/toplevel/scene.pkg");
+    script.moduleBody = true;
+
+    CHECK (
+	script.run ("localStorage.set('k', 1)")
+	== "throws: SyntaxError: LocalStorageSet cannot be cleared from global scope."
+    );
+    CHECK (
+	script.run ("localStorage.get('k')")
+	== "throws: SyntaxError: LocalStorageGet cannot be cleared from global scope."
+    );
+    CHECK (
+	script.run ("localStorage.delete('k')")
+	== "throws: SyntaxError: LocalStorageDelete cannot be cleared from global scope."
+    );
+    CHECK (
+	script.run ("localStorage.clear()")
+	== "throws: SyntaxError: LocalStorageClear cannot be cleared from global scope."
+    );
+
+    script.moduleBody = false;
+    CHECK (script.run ("localStorage.get('k')") == "undefined");
+}

+ 71 - 0
src/WallpaperEngine/Testing/Cases/SplitLayout.cpp

@@ -0,0 +1,71 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include "WallpaperEngine/Render/SplitLayout.h"
+
+using WallpaperEngine::Render::splitSlotRects;
+using Split = WallpaperEngine::Application::ApplicationContext::SplitScreen;
+
+TEST_CASE ("Aspect layout sizes slots from the wallpapers and fills the screen") {
+    // two 9:16 and one 16:9 on 3440x1440
+    const auto rects
+	= splitSlotRects ({ 3440, 1440 }, { 9.0f / 16.0f, 9.0f / 16.0f, 16.0f / 9.0f }, Split::LAYOUT_ASPECT, true);
+
+    REQUIRE (rects.size () == 3);
+    // 810 + 810 + 2560 px at full height, shrunk to 3440
+    CHECK (rects[0] == glm::ivec4 (0, 0, 667, 1440));
+    CHECK (rects[1] == glm::ivec4 (667, 0, 666, 1440));
+    CHECK (rects[2] == glm::ivec4 (1333, 0, 2107, 1440));
+}
+
+TEST_CASE ("Equal layout gives every slot the same share without gaps") {
+    const auto rects = splitSlotRects ({ 1920, 1080 }, { 0.5f, 2.0f, 1.0f }, Split::LAYOUT_EQUAL, true);
+
+    REQUIRE (rects.size () == 3);
+    CHECK (rects[0] == glm::ivec4 (0, 0, 640, 1080));
+    CHECK (rects[1] == glm::ivec4 (640, 0, 640, 1080));
+    CHECK (rects[2] == glm::ivec4 (1280, 0, 640, 1080));
+}
+
+TEST_CASE ("Center layout keeps the wallpapers' shapes and centers them") {
+    // two 1080x1920 on 1920x1080: 607.5 px each, 352.5 px bars
+    const auto rects = splitSlotRects ({ 1920, 1080 }, { 0.5625f, 0.5625f }, Split::LAYOUT_CENTER, true);
+
+    REQUIRE (rects.size () == 2);
+    CHECK (rects[0].x == 353);
+    CHECK (rects[0].z + rects[1].z == 1215);
+    CHECK (rects[1].x == rects[0].x + rects[0].z);
+    CHECK (rects[1].x + rects[1].z == 1568);
+    CHECK (rects[0].w == 1080);
+}
+
+TEST_CASE ("Center layout falls back to filling the screen when the wallpapers don't fit") {
+    const auto rects = splitSlotRects ({ 1920, 1080 }, { 16.0f / 9.0f, 16.0f / 9.0f }, Split::LAYOUT_CENTER, true);
+
+    CHECK (rects[0] == glm::ivec4 (0, 0, 960, 1080));
+    CHECK (rects[1] == glm::ivec4 (960, 0, 960, 1080));
+}
+
+TEST_CASE ("A web page takes the average of the others, or an equal share") {
+    const auto mixed = splitSlotRects ({ 2000, 1000 }, { 0.5f, 0.0f, 1.5f }, Split::LAYOUT_ASPECT, true);
+
+    CHECK (mixed[0].z == 333);
+    CHECK (mixed[1].z == 667);
+    CHECK (mixed[2].z == 1000);
+
+    const auto pages = splitSlotRects ({ 1920, 1080 }, { 0.0f, 0.0f }, Split::LAYOUT_CENTER, true);
+
+    CHECK (pages[0] == glm::ivec4 (0, 0, 960, 1080));
+    CHECK (pages[1] == glm::ivec4 (960, 0, 960, 1080));
+}
+
+TEST_CASE ("A portrait screen stacks the slots, the first one on top") {
+    const auto up = splitSlotRects ({ 1080, 1920 }, { 16.0f / 9.0f, 16.0f / 9.0f }, Split::LAYOUT_ASPECT, true);
+
+    CHECK (up[0] == glm::ivec4 (0, 960, 1080, 960));
+    CHECK (up[1] == glm::ivec4 (0, 0, 1080, 960));
+
+    const auto down = splitSlotRects ({ 1080, 1920 }, { 16.0f / 9.0f, 16.0f / 9.0f }, Split::LAYOUT_ASPECT, false);
+
+    CHECK (down[0] == glm::ivec4 (0, 0, 1080, 960));
+    CHECK (down[1] == glm::ivec4 (0, 960, 1080, 960));
+}

+ 140 - 0
src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp

@@ -0,0 +1,140 @@
+#include "WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.h"
+#include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
+
+#undef CHECK
+#include <catch2/catch_test_macros.hpp>
+
+#include <string>
+#include <vector>
+
+using namespace WallpaperEngine::WebBrowser;
+
+namespace {
+constexpr uint32_t WIDTH = 8;
+constexpr uint32_t HEIGHT = 4;
+
+// both mappings of the segment, like CWeb and runWebHost
+struct Segment {
+    Segment () {
+	main = IPC::createSharedMemory (name, WIDTH, HEIGHT);
+	host = IPC::attachSharedMemory (name, WIDTH, HEIGHT);
+    }
+
+    ~Segment () {
+	IPC::closeSharedMemory (host, name, WIDTH, HEIGHT, false);
+
+	if (main != nullptr) {
+	    IPC::closeSharedMemory (main, name, WIDTH, HEIGHT, true);
+	}
+    }
+
+    void releaseMain () {
+	IPC::closeSharedMemory (main, name, WIDTH, HEIGHT, true);
+	main = nullptr;
+    }
+
+    std::string name;
+    IPC::WebHostSharedMemory* main = nullptr;
+    IPC::WebHostSharedMemory* host = nullptr;
+};
+
+void paint (CEF::SharedMemoryRenderHandler& handler, uint8_t value, int width = WIDTH, int height = HEIGHT) {
+    const std::vector<uint8_t> pixels (static_cast<size_t> (width) * height * 4, value);
+    handler.OnPaint (nullptr, PET_VIEW, {}, pixels.data (), width, height);
+}
+} // namespace
+
+TEST_CASE ("Web frames hand over through three slots that are never shared") {
+    Segment segment;
+    REQUIRE (segment.main != nullptr);
+    REQUIRE (segment.host != nullptr);
+
+    CefRefPtr<CEF::SharedMemoryRenderHandler> handler = new CEF::SharedMemoryRenderHandler (segment.host);
+    // CWeb starts on slot 2, the host on 0, slot 1 sits in between
+    uint32_t front = 2;
+
+    CHECK_FALSE (segment.main->takeFrame (front).has_value ());
+
+    paint (*handler, 10);
+
+    auto taken = segment.main->takeFrame (front);
+    REQUIRE (taken.has_value ());
+    front = *taken;
+    CHECK (segment.main->frameBuffer (front)[0] == 10);
+    CHECK (segment.main->slotWidth[front].load () == WIDTH);
+    CHECK_FALSE (segment.main->takeFrame (front).has_value ());
+
+    // two frames published: the newer one is taken, the older slot returns to the host
+    paint (*handler, 20);
+    paint (*handler, 30);
+
+    taken = segment.main->takeFrame (front);
+    REQUIRE (taken.has_value ());
+    front = *taken;
+    CHECK (segment.main->frameBuffer (front)[0] == 30);
+
+    for (uint8_t value = 40; value < 100; value += 10) {
+	paint (*handler, value);
+
+	// the host never paints into the held front slot
+	CHECK (segment.main->frameBuffer (front)[0] == 30);
+    }
+
+    taken = segment.main->takeFrame (front);
+    REQUIRE (taken.has_value ());
+    CHECK (segment.main->frameBuffer (*taken)[0] == 90);
+
+    const uint32_t between = segment.main->frameSlot.load () & IPC::WebHostSharedMemory::FRAME_SLOT_MASK;
+    CHECK (between == front);
+    CHECK (between != *taken);
+}
+
+TEST_CASE ("Web paints that don't fit the segment are dropped") {
+    Segment segment;
+    CefRefPtr<CEF::SharedMemoryRenderHandler> handler = new CEF::SharedMemoryRenderHandler (segment.host);
+    const uint32_t before = segment.main->frameSlot.load ();
+
+    paint (*handler, 1, WIDTH + 1, HEIGHT);
+    paint (*handler, 1, WIDTH, HEIGHT * 2);
+    paint (*handler, 1, 0, HEIGHT);
+
+    const std::vector<uint8_t> pixels (WIDTH * HEIGHT * 4, 1);
+    handler->OnPaint (nullptr, PET_POPUP, {}, pixels.data (), WIDTH, HEIGHT);
+
+    CHECK (segment.main->frameSlot.load () == before);
+
+    // sizes must be nonzero and fit the segment
+    CefRect rect;
+    segment.main->desiredWidth = 0;
+    segment.main->desiredHeight = 0;
+    handler->GetViewRect (nullptr, rect);
+    CHECK (rect.width == 1);
+    CHECK (rect.height == 1);
+
+    segment.main->desiredWidth = 4000;
+    segment.main->desiredHeight = 3;
+    handler->GetViewRect (nullptr, rect);
+    CHECK (rect.width == static_cast<int> (WIDTH));
+    CHECK (rect.height == 3);
+}
+
+TEST_CASE ("The web host keeps painting after the main process let go of the segment") {
+    Segment segment;
+    CefRefPtr<CEF::SharedMemoryRenderHandler> handler = new CEF::SharedMemoryRenderHandler (segment.host);
+
+    segment.main->desiredWidth = WIDTH;
+    segment.main->desiredHeight = HEIGHT;
+    // CEF may still paint after CWeb unmaps and unlinks
+    segment.releaseMain ();
+
+    paint (*handler, 50);
+    paint (*handler, 60);
+
+    CefRect rect;
+    handler->GetViewRect (nullptr, rect);
+    CHECK (rect.width == static_cast<int> (WIDTH));
+
+    const auto slot = segment.host->takeFrame (2);
+    REQUIRE (slot.has_value ());
+    CHECK (segment.host->frameBuffer (*slot)[0] == 60);
+}

+ 12 - 0
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -24,6 +24,15 @@ uint64_t GLPlayer::s_frame = 0;
 // counter at the last transfer
 static constexpr uint64_t UNUSED_FRAMES_BEFORE_PAUSE = 30;
 
+// mpv leaves a PBO and row settings bound, later glTexImage2D calls expect GL's defaults
+static void resetUnpackState () {
+    glBindBuffer (GL_PIXEL_UNPACK_BUFFER, 0);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
+    glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
+    glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
+    glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
+}
+
 // the synchronous mpv_set_property/mpv_command wait for mpv's core thread, which can take a few hundred ms
 // while it's busy, and these are called from the render thread (scripts pausing/seeking videos on click)
 static void setPropertyAsync (mpv_handle* handle, const char* name, const char* value) {
@@ -477,6 +486,7 @@ void GLPlayer::render () const {
 
 		if (info.flags & MPV_RENDER_FRAME_INFO_PRESENT) {
 		    mpv_render_context_render (this->m_renderContext, params);
+		    resetUnpackState ();
 		}
 
 		return;
@@ -506,12 +516,14 @@ void GLPlayer::render () const {
 
     if (!collectStats) {
 	mpv_render_context_render (this->m_renderContext, params);
+	resetUnpackState ();
 	return;
     }
 
     glFinish ();
     const auto start = std::chrono::steady_clock::now ();
     mpv_render_context_render (this->m_renderContext, params);
+    resetUnpackState ();
     glFinish ();
     s_statsMillis += std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now () - start).count ();
 }

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

@@ -37,9 +37,5 @@ void SharedMemoryRenderHandler::OnPaint (
     this->m_shm->slotWidth[this->m_backSlot].store (static_cast<uint32_t> (width), std::memory_order_relaxed);
     this->m_shm->slotHeight[this->m_backSlot].store (static_cast<uint32_t> (height), std::memory_order_relaxed);
 
-    const uint32_t previous = this->m_shm->frameSlot.exchange (
-	this->m_backSlot | WebHostSharedMemory::FRAME_DIRTY, std::memory_order_acq_rel
-    );
-
-    this->m_backSlot = previous & WebHostSharedMemory::FRAME_SLOT_MASK;
+    this->m_backSlot = this->m_shm->publishFrame (this->m_backSlot);
 }

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

@@ -3,6 +3,7 @@
 #include <atomic>
 #include <cstddef>
 #include <cstdint>
+#include <optional>
 #include <string>
 
 namespace WallpaperEngine::WebBrowser::IPC {
@@ -80,6 +81,20 @@ struct WebHostSharedMemory {
 	    + static_cast<std::size_t> (slot) * maxWidth * maxHeight * 4;
     }
 
+    // host: publish the painted slot, get the next one
+    uint32_t publishFrame (uint32_t backSlot) {
+	return frameSlot.exchange (backSlot | FRAME_DIRTY, std::memory_order_acq_rel) & FRAME_SLOT_MASK;
+    }
+
+    // main process: swap the front slot for the latest frame, nullopt when none
+    std::optional<uint32_t> takeFrame (uint32_t frontSlot) {
+	if ((frameSlot.load (std::memory_order_acquire) & FRAME_DIRTY) == 0) {
+	    return std::nullopt;
+	}
+
+	return frameSlot.exchange (frontSlot, std::memory_order_acq_rel) & FRAME_SLOT_MASK;
+    }
+
     // Main process: asks the host to produce a frame and wakes it if it's sleeping in waitForFrameRequest()
     void requestFrame ();
 

+ 36 - 1
tests/desktops/test_gnome.py

@@ -249,7 +249,7 @@ def test_focused_window_pauses_with_pause_on_focus(gnome, engine, tmp_path):
 
 
 # DING: own desktop window on GNOME 50, bottom-layer normal one on Ubuntu 46
-@pytest.fixture(params=["gnome-ding", "gnome46-ding", "gnome45-ding"])
+@pytest.fixture(params=["gnome-ding", "gnome49-ding", "gnome48-ding", "gnome47-ding", "gnome46-ding", "gnome45-ding"])
 def ding(request, desktop_factory):
     return desktop_factory(request.param)
 
@@ -277,3 +277,38 @@ def test_wallpaper_stays_under_desktop_icons(ding, engine, tmp_path):
     finally:
         process.terminate()
         process.wait(10)
+
+
+def _mean_difference(a, b):
+    import numpy
+    from PIL import Image
+
+    first = numpy.asarray(Image.open(a).convert("RGB"), dtype=numpy.float32)
+    second = numpy.asarray(Image.open(b).convert("RGB"), dtype=numpy.float32)
+    return float(numpy.abs(first - second).mean())
+
+
+@pytest.mark.parametrize("desktop", ["gnome-hdr"], indirect=True)
+def test_hdr_output(desktop, engine, tmp_path):
+    """--hdr on a monitor Mutter runs in HDR: the surface is PQ and composites back to what SDR shows"""
+    shots = {}
+    for mode in ("sdr", "hdr"):
+        log = tmp_path / f"{mode}.log"
+        process = desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                                  desktop.output_names()[0], "--silent", "--fps", "30",
+                                  *(["--hdr"] if mode == "hdr" else []), engine["wallpaper"]],
+                                 log=log, env={"WAYLAND_DEBUG": "1"} if mode == "hdr" else None)
+        try:
+            time.sleep(10)
+            assert process.poll() is None, log.read_text(errors="replace")[-1500:]
+            shots[mode] = tmp_path / f"{mode}.png"
+            desktop.shot(shots[mode])
+        finally:
+            process.terminate()
+            process.wait(10)
+        text = log.read_text(errors="replace")
+        if mode == "hdr":
+            assert "runs in HDR, drawing PQ" in text, text[-1500:]
+            assert "wp_color_management_surface_v1" in text and ".set_image_description(" in text
+    difference = _mean_difference(shots["sdr"], shots["hdr"])
+    assert difference < 6, f"the PQ frame composites to a different picture than SDR (mean difference {difference:.1f})"

+ 44 - 0
tests/desktops/test_river.py

@@ -0,0 +1,44 @@
+"""river 0.4 closes every layer surface while no window manager runs: the engine has to wait for one, not crash or quit."""
+import time
+
+import pytest
+
+from conftest import changed_fraction
+from test_kde import _engine
+
+
+def _wait_log(log, text, timeout):
+    deadline = time.monotonic() + timeout
+    while time.monotonic() < deadline:
+        if text in log.read_text(errors="replace"):
+            return True
+        time.sleep(0.5)
+    return False
+
+
+@pytest.mark.parametrize("desktop", ["river"], indirect=True)
+def test_waits_for_a_window_manager(desktop, engine, tmp_path):
+    desktop.stop_window_manager()
+    before = tmp_path / "before.png"
+    desktop.shot(before)
+    log = tmp_path / "engine.log"
+    process = _engine(desktop, engine, log, desktop.output_names()[0])
+    try:
+        assert _wait_log(log, "The compositor closed the wallpaper surface", 30), log.read_text()[-1500:]
+        assert "No output shows a wallpaper" in log.read_text()
+        time.sleep(5)
+        assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+
+        desktop.start_window_manager()
+        assert _wait_log(log, "the compositor took the wallpaper surface again", 45), log.read_text()[-1500:]
+        after = tmp_path / "after.png"
+        time.sleep(3)
+        desktop.shot(after)
+        fraction = changed_fraction(before, after)
+        assert fraction >= 0.03, f"{fraction:.0%} of the screen changed once the window manager runs"
+        assert process.poll() is None
+    finally:
+        process.terminate()
+        process.wait(10)
+        if desktop.window_manager is None:
+            desktop.start_window_manager()

+ 182 - 0
tests/desktops/test_split.py

@@ -0,0 +1,182 @@
+"""--screen-slot: several wallpapers side by side on one output, each in its own rect with its own cursor and clicks"""
+import json
+import os
+import re
+import signal
+import time
+
+import pytest
+from PIL import Image
+
+RED, GREEN, BLUE = (255, 0, 0), (0, 255, 0), (0, 0, 255)
+
+
+@pytest.fixture
+def sway(desktop_factory):
+    return desktop_factory("sway")
+
+
+def _probe(directory, tag, size, color):
+    """a solid colour scene of the given projection size that logs its cursor and presses with a tag"""
+    directory.mkdir(parents=True, exist_ok=True)
+    width, height = size
+    script = ("'use strict';\n"
+              f"export function cursorMove(event) {{ console.log('LWE-POS-{tag} ' + input.cursorScreenPosition.x.toFixed(1)"
+              " + ' ' + input.cursorScreenPosition.y.toFixed(1)); }\n"
+              f"export function cursorDown(event) {{ console.log('LWE-DOWN-{tag}'); }}\n"
+              "export function update(value) { return value; }\n")
+    scene = {
+        "version": 3,
+        "camera": {"center": "0 0 -1", "eye": "0 0 0", "up": "0 1 0"},
+        "general": {"orthogonalprojection": {"width": width, "height": height}, "clearcolor": "0 0 0",
+                    "bloom": False, "cameraparallax": False},
+        "objects": [{"id": 1, "name": "probe", "image": "models/util/solidlayer.json", "size": f"{width} {height}",
+                     "origin": f"{width / 2} {height / 2} 0", "color": " ".join(str(c / 255) for c in color),
+                     "visible": True, "alpha": {"script": script, "value": 1.0}}],
+    }
+    (directory / "scene.json").write_text(json.dumps(scene))
+    (directory / "project.json").write_text(json.dumps({"file": "scene.json", "type": "scene", "title": tag,
+                                                        "general": {"properties": {}}}))
+    return directory
+
+
+def _engine(sway, engine, log, *slots, after=(), control=None):
+    output = sway.output_names()[0]
+    argv = [engine["binary"], "--assets-dir", engine["assets"], "--silent", "--fps", "30"]
+    if control is not None:
+        argv += ["--control-file", str(control)]
+    for wallpaper in slots:
+        argv += ["--screen-slot", output, "--bg", str(wallpaper)]
+    argv += after
+    return sway.client(argv, log=log, env={"LWE_SCRIPT_LOG": "1"})
+
+
+def _pixel(sway, tmp_path, x, y):
+    path = tmp_path / "shot.png"
+    sway.shot(path)
+    return Image.open(path).convert("RGB").getpixel((x, y))
+
+
+def _wait_for_pixel(sway, tmp_path, process, x, y, color, log):
+    seen = None
+    for _ in range(20):
+        assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+        seen = _pixel(sway, tmp_path, x, y)
+        if all(abs(a - b) < 8 for a, b in zip(seen, color)):
+            return
+        time.sleep(1)
+    pytest.fail(f"{x},{y} is {seen}, expected {color}")
+
+
+def _stop(process):
+    if process is not None:
+        process.terminate()
+        process.wait(10)
+
+
+def test_slots_are_sized_from_the_wallpapers(sway, engine, tmp_path):
+    # 1080x1920 + 1920x1080 on 1920x1080: the first slot ends at 462
+    portrait = _probe(tmp_path / "a", "A", (1080, 1920), RED)
+    landscape = _probe(tmp_path / "b", "B", (1920, 1080), GREEN)
+    log = tmp_path / "engine.log"
+    process = _engine(sway, engine, log, portrait, landscape)
+    try:
+        _wait_for_pixel(sway, tmp_path, process, 455, 540, RED, log)
+        _wait_for_pixel(sway, tmp_path, process, 470, 540, GREEN, log)
+        _wait_for_pixel(sway, tmp_path, process, 1910, 1070, GREEN, log)
+    finally:
+        _stop(process)
+
+
+def test_center_layout_leaves_bars(sway, engine, tmp_path):
+    first = _probe(tmp_path / "a", "A", (1080, 1920), RED)
+    second = _probe(tmp_path / "b", "B", (1080, 1920), GREEN)
+    log = tmp_path / "engine.log"
+    process = _engine(sway, engine, log, first, second, after=("--split-layout", "center"))
+    try:
+        # two 607.5 px slots from 352.5 to 1567.5
+        _wait_for_pixel(sway, tmp_path, process, 340, 540, (0, 0, 0), log)
+        _wait_for_pixel(sway, tmp_path, process, 365, 540, RED, log)
+        _wait_for_pixel(sway, tmp_path, process, 1555, 540, GREEN, log)
+        _wait_for_pixel(sway, tmp_path, process, 1580, 540, (0, 0, 0), log)
+    finally:
+        _stop(process)
+
+
+def test_portrait_output_stacks_slots(sway, engine, tmp_path):
+    output = sway.output_names()[0]
+    first = _probe(tmp_path / "a", "A", (1920, 1080), RED)
+    second = _probe(tmp_path / "b", "B", (1920, 1080), GREEN)
+    log = tmp_path / "engine.log"
+    process = None
+    try:
+        sway.run(["swaymsg", f"output {output} transform 90"], sway.extra)
+        process = _engine(sway, engine, log, first, second)
+        # 1080x1920 split in two 1080x960 rows, the first on top
+        _wait_for_pixel(sway, tmp_path, process, 540, 940, RED, log)
+        _wait_for_pixel(sway, tmp_path, process, 540, 980, GREEN, log)
+    finally:
+        _stop(process)
+        sway.run(["swaymsg", f"output {output} transform normal"], sway.extra)
+
+
+def test_cursor_and_clicks_belong_to_the_slot_under_the_pointer(sway, engine, tmp_path):
+    first = _probe(tmp_path / "a", "A", (1920, 1080), RED)
+    second = _probe(tmp_path / "b", "B", (1920, 1080), GREEN)
+    log = tmp_path / "engine.log"
+    process = _engine(sway, engine, log, first, second)
+    pointer = sway.virtual_pointer()
+    width, height = sway.size
+
+    def send(line):
+        pointer.stdin.write(line + "\n")
+        pointer.stdin.flush()
+        pointer.stdout.readline()
+
+    try:
+        _wait_for_pixel(sway, tmp_path, process, 100, 100, RED, log)
+        # equal 960 px slots, pointer logged in slot pixels, y from the top
+        for x, y, tag, expected in ((300, 200, "A", (300, 200)), (1500, 700, "B", (540, 700))):
+            seen = None
+            for _ in range(10):
+                for dx in (1, 0):
+                    send(f"abs {x + dx} {y} {width} {height}")
+                    time.sleep(0.3)
+                lines = re.findall(rf"LWE-POS-{tag} [-\d.]+ [-\d.]+", log.read_text(errors="replace"))
+                seen = lines[-1] if lines else None
+                if seen == f"LWE-POS-{tag} {expected[0]:.1f} {expected[1]:.1f}":
+                    break
+            assert seen == f"LWE-POS-{tag} {expected[0]:.1f} {expected[1]:.1f}"
+
+        send(f"abs 1500 700 {width} {height}")
+        time.sleep(0.5)
+        send("button 272 1")
+        time.sleep(0.5)
+        send("button 272 0")
+        time.sleep(1)
+        text = log.read_text(errors="replace")
+        assert "LWE-DOWN-B" in text
+        assert "LWE-DOWN-A" not in text
+    finally:
+        pointer.stdin.write("quit\n")
+        pointer.stdin.flush()
+        pointer.wait(10)
+        _stop(process)
+
+
+def test_hotswap_reaches_only_the_named_slot(sway, engine, tmp_path):
+    output = sway.output_names()[0]
+    first = _probe(tmp_path / "a", "A", (1920, 1080), RED)
+    second = _probe(tmp_path / "b", "B", (1920, 1080), GREEN)
+    third = _probe(tmp_path / "c", "C", (1920, 1080), BLUE)
+    control = tmp_path / "control"
+    log = tmp_path / "engine.log"
+    process = _engine(sway, engine, log, first, second, control=control)
+    try:
+        _wait_for_pixel(sway, tmp_path, process, 1500, 540, GREEN, log)
+        control.write_text(f"screen={output}#2\npath={third}\n")
+        os.kill(process.pid, signal.SIGUSR1)
+        _wait_for_pixel(sway, tmp_path, process, 1500, 540, BLUE, log)
+        _wait_for_pixel(sway, tmp_path, process, 400, 540, RED, log)
+    finally:
+        _stop(process)

+ 1 - 3
tests/desktops/test_wallpaper.py

@@ -8,9 +8,7 @@ from conftest import KINDS, Unsupported, changed_fraction
 KNOWN_GAPS = {}
 
 # what the lab cannot show, not the engine
-LAB_LIMITS = {
-    "river": "river 0.4 closes every layer surface unless a window manager client runs, and none is packaged",
-}
+LAB_LIMITS = {}
 
 
 def _param(name):

+ 16 - 11
tools/desktops/__main__.py

@@ -20,28 +20,33 @@ def _apt(archive):
             'DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@"', "apt"]
 
 
-def setup_ding():
-    """Desktop Icons NG for the GNOME 50 lab, from extensions.gnome.org (not packaged in Fedora)"""
+def setup_ding(shell):
+    """Desktop Icons NG from extensions.gnome.org for the GNOME 49/50 labs (Fedora doesn't package it)"""
     import json
     import urllib.request
     import zipfile
-    from .session import DING_DIR
+    from .session import ding_dir
+    target = ding_dir(shell)
     base = "https://extensions.gnome.org"
-    with urllib.request.urlopen(f"{base}/extension-info/?uuid=ding@rastersoft.com&shell_version=50") as reply:
+    with urllib.request.urlopen(f"{base}/extension-info/?uuid=ding@rastersoft.com&shell_version={shell}") as reply:
         info = json.load(reply)
-    archive = DING_DIR.parent / "ding.zip"
+    archive = target.parent / "ding.zip"
     archive.parent.mkdir(parents=True, exist_ok=True)
     urllib.request.urlretrieve(base + info["download_url"], archive)
     with zipfile.ZipFile(archive) as extension:
-        extension.extractall(DING_DIR)
-    subprocess.run(["glib-compile-schemas", str(DING_DIR / "schemas")], check=True)
-    print(f"Desktop Icons NG {info.get('version')} in {DING_DIR}")
+        extension.extractall(target)
+        # zipfile drops mode bits, DING runs app/ding.js directly
+        for member in extension.infolist():
+            if mode := member.external_attr >> 16 & 0o777:
+                (target / member.filename).chmod(mode)
+    subprocess.run(["glib-compile-schemas", str(target / "schemas")], check=True)
+    print(f"Desktop Icons NG {info.get('version')} in {target}")
 
 
 def setup(which):
     """the rootfs a session runs in where its programs are not installed natively"""
-    if which == "ding":
-        return setup_ding()
+    if which in ("ding", "ding49"):
+        return setup_ding(50 if which == "ding" else 49)
     script = str(REPO / "tools/distro_rootfs.sh")
     image, packages, install = {
         "fedora": ("fedora:44", FEDORA_PACKAGES, ["dnf", "install", "-y", "--setopt=install_weak_deps=False"]),
@@ -71,7 +76,7 @@ def main():
     sub = parser.add_subparsers(dest="command", required=True)
     sub.add_parser("list", help="the sessions and where each would run")
     sub.add_parser("setup", help="create the rootfs for sessions that are not installed natively").add_argument(
-        "which", choices=("fedora", "arch", "gnome45", "gnome46", "gnome47", "gnome48", "gnome49", "kde5", "ding"))
+        "which", choices=("fedora", "arch", "gnome45", "gnome46", "gnome47", "gnome48", "gnome49", "kde5", "ding", "ding49"))
     start = sub.add_parser("start", help="start a session")
     start.add_argument("name", choices=sorted(KINDS))
     start.add_argument("--size", default="1920x1080")

+ 191 - 0
tools/desktops/river-layer-shell-v1.xml

@@ -0,0 +1,191 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="river_layer_shell_v1">
+  <copyright>
+    SPDX-FileCopyrightText: © 2025 Isaac Freund
+    SPDX-License-Identifier: MIT
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to
+    deal in the Software without restriction, including without limitation the
+    rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+    sell copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+    IN THE SOFTWARE.
+  </copyright>
+
+  <description summary="optional layer shell support">
+    This protocol allows the river-window-management-v1 window manager to
+    support the wlr-layer-shell-unstable-v1 protocol.
+
+    The key words "must", "must not", "required", "shall", "shall not",
+    "should", "should not", "recommended", "may", and "optional" in this
+    document are to be interpreted as described in IETF RFC 2119.
+  </description>
+
+  <interface name="river_layer_shell_v1" version="1">
+    <description summary="river layer shell global interface">
+      This global interface should only be advertised to the client if the
+      river_window_manager_v1 global is also advertised. Binding this interface
+      indicates that the window manager supports layer shell.
+
+      If the window manager does not bind this interface, the compositor should
+      not allow clients to map layer surfaces. This can be achieved by
+      closing layer surfaces immediately.
+    </description>
+
+    <enum name="error">
+      <entry name="object_already_created" value="0"
+        summary="the layer_shell_output/seat object was already created."/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the river_layer_shell_v1 object">
+        This request indicates that the client will no longer use the
+        river_layer_shell_v1 object.
+      </description>
+    </request>
+
+    <request name="get_output">
+      <description summary="get layer shell output state">
+        It is a protocol error to make this request more than once for a given
+        river_output_v1 object.
+      </description>
+      <arg name="id" type="new_id" interface="river_layer_shell_output_v1"/>
+      <arg name="output" type="object" interface="river_output_v1"/>
+    </request>
+
+    <request name="get_seat">
+      <description summary="get layer shell seat state">
+        It is a protocol error to make this request more than once for a given
+        river_seat_v1 object.
+      </description>
+      <arg name="id" type="new_id" interface="river_layer_shell_seat_v1"/>
+      <arg name="seat" type="object" interface="river_seat_v1"/>
+    </request>
+  </interface>
+
+  <interface name="river_layer_shell_output_v1" version="1">
+    <description summary="layer shell output state">
+      The lifetime of this object is tied to the corresponding river_output_v1.
+      This object is made inert when the river_output_v1.removed event is sent
+      and should be destroyed.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the object">
+        This request indicates that the client will no longer use the
+        river_layer_shell_output_v1 object and that it may be safely destroyed.
+
+        This request should be made after the river_output_v1.removed event is
+        received to complete destruction of the output.
+      </description>
+    </request>
+
+    <event name="non_exclusive_area">
+      <description summary="area left after subtracting exclusive zones">
+        This event indicates the area of the output remaining after subtracting
+        the exclusive zones of layer surfaces. Exclusive zones are a hint, the
+        window manager is free to ignore this area hint if it wishes.
+
+        The x and y values are in the global coordinate space, not relative to
+        the position of the output.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="x" type="int" summary="global x coordinate"/>
+      <arg name="y" type="int" summary="global y coordinate"/>
+      <arg name="width" type="int" summary="area width"/>
+      <arg name="height" type="int" summary="area height"/>
+    </event>
+
+    <request name="set_default">
+      <description summary="Set default output for layer surfaces">
+        Mark this output as the default for new layer surfaces which do not
+        request a specific output themselves. This request overrides any
+        previous set_default request on any river_layer_shell_output_v1 object.
+
+        If no set_default request is made or if the default output is destroyed,
+        the default output is undefined until the next set_default request.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="river_layer_shell_seat_v1" version="1">
+    <description summary="layer shell seat state">
+      The lifetime of this object is tied to the corresponding river_seat_v1.
+      This object is made inert when the river_seat_v1.removed event is sent and
+      should be destroyed.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the object">
+        This request indicates that the client will no longer use the
+        river_layer_shell_seat_v1 object and that it may be safely destroyed.
+
+        This request should be made after the river_seat_v1.removed event is
+        received to complete destruction of the seat.
+      </description>
+    </request>
+
+    <event name="focus_exclusive">
+      <description summary="layer shell surface has exclusive focus">
+        A layer shell surface will be given exclusive keyboard focus at the end
+        of the manage sequence in which this event is sent. The window manager
+        may want to update window decorations or similar to indicate that no
+        window is focused.
+
+        Until the focus_non_exclusive or focus_none event is sent, all window
+        manager requests to change focus are ignored.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="focus_non_exclusive">
+      <description summary="layer shell surface wants non-exclusive focus">
+        A layer shell surface will be given non-exclusive keyboard focus at the
+        end of the manage sequence in which this event is sent. The window
+        manager may want to update window decorations or similar to indicate
+        that no window is focused.
+
+        The window manager continues to control focus and may choose to focus a
+        different window/shell surface at any time. If the window manager sets
+        focus during the same manage sequence in which this event is sent, the
+        layer surface will not be focused.
+
+        If the layer surface with non-exclusive focus is closed or the window
+        manager chooses to move focus away from the layer surface, a focus_none
+        event will be sent in the next manage sequence.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="focus_none">
+      <description summary="no layer shell surface has focus">
+        No layer shell surface will have keyboard focus at the end of the manage
+        sequence in which this event is sent. The window manager may want to
+        return focus to whichever window last had focus, for example.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+  </interface>
+</protocol>

+ 1911 - 0
tools/desktops/river-window-management-v1.xml

@@ -0,0 +1,1911 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="river_window_management_v1">
+  <copyright>
+    SPDX-FileCopyrightText: © 2024 Isaac Freund
+    SPDX-License-Identifier: MIT
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to
+    deal in the Software without restriction, including without limitation the
+    rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+    sell copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+    IN THE SOFTWARE.
+  </copyright>
+
+  <description summary="frame-perfect window management">
+    This protocol allows a single "window manager" client to determine the
+    window management policy of the compositor. State is globally
+    double-buffered allowing for frame perfect state changes involving multiple
+    windows.
+
+    The key words "must", "must not", "required", "shall", "shall not",
+    "should", "should not", "recommended", "may", and "optional" in this
+    document are to be interpreted as described in IETF RFC 2119.
+  </description>
+
+  <interface name="river_window_manager_v1" version="5">
+    <description summary="window manager global interface">
+      This global interface should only be advertised to the window manager
+      process. Only one window management client may be active at a time. The
+      compositor should use the unavailable event if necessary to enforce this.
+
+      There are two disjoint categories of state managed by this protocol:
+
+      Window management state influences the communication between the
+      compositor and individual windows (e.g. xdg_toplevels). Window management
+      state includes window dimensions, fullscreen state, keyboard focus,
+      keyboard bindings, and more.
+
+      Rendering state only affects the rendered output of the compositor and
+      does not influence communication between the compositor and individual
+      windows. Rendering state includes the position and rendering order of
+      windows, shell surfaces, decoration surfaces, borders, and more.
+
+      Window management state may only be modified by the window manager as part
+      of a manage sequence. A manage sequence is started with the manage_start
+      event and ended with the manage_finish request. It is a protocol error to
+      modify window management state outside of a manage sequence.
+
+      A manage sequence is always followed by at least one render sequence. A
+      render sequence is started with the render_start event and ended with the
+      render_finish request.
+
+      Rendering state may be modified by the window manager during a manage
+      sequence or a render sequence. Regardless of when the rendering state is
+      modified, it is applied with the next render_finish request. It is a
+      protocol error to modify rendering state outside of a manage or render
+      sequence.
+
+      The server will start a manage sequence by sending new state and the
+      manage_start event as soon as possible whenever there is a change in state
+      that must be communicated with the window manager.
+
+      If the window manager client needs to ensure a manage sequence is started
+      due to a state change the compositor is not aware of, it may send the
+      manage_dirty request.
+
+      The server will start a render sequence by sending new state and the
+      render_start event as soon as possible whenever there is a change in
+      window dimensions that must be communicated with the window manager.
+      Multiple render sequences may be made consecutively without a manage
+      sequence in between, for example if a window independently changes its own
+      dimensions.
+
+      To summarize, the main loop of this protocol is as follows:
+
+      1. The server sends events indicating all changes since the last
+         manage sequence followed by the manage_start event.
+
+      2. The client sends requests modifying window management state or
+         rendering state (as defined above) followed by the manage_finish
+         request.
+
+      3. The server sends new state to windows and waits for responses.
+
+      4. The server sends new window dimensions to the client followed by the
+         render_start event.
+
+      5. The client sends requests modifying rendering state (as defined above)
+         followed by the render_finish request.
+
+      6. If window dimensions change, loop back to step 4.
+         If state that requires a manage sequence changes or if the client makes
+         a manage_dirty request, loop back to step 1.
+
+      For the purposes of frame perfection, the server may delay rendering new
+      state committed by the windows in step 3 until after step 5 is finished.
+
+      It is a protocol error for the client to make a manage_finish or
+      render_finish request that violates this ordering.
+    </description>
+
+    <enum name="error">
+      <entry name="sequence_order" value="0"
+        summary="request violates manage/render sequence ordering"/>
+      <entry name="role" value="1"
+        summary="given wl_surface already has a role"/>
+      <entry name="unresponsive" value="2"
+        summary="window manager unresponsive"/>
+    </enum>
+
+    <event name="unavailable">
+      <description summary="window management unavailable">
+        This event indicates that window management is not available to the
+        client, perhaps due to another window management client already running.
+        The circumstances causing this event to be sent are compositor policy.
+
+        If sent, this event is guaranteed to be the first and only event sent by
+        the server.
+
+        The server will send no further events on this object. The client should
+        destroy this object and all objects created through this interface.
+      </description>
+    </event>
+
+    <request name="stop">
+      <description summary="stop sending events">
+        This request indicates that the client no longer wishes to receive
+        events on this object.
+
+        The Wayland protocol is asynchronous, which means the server may send
+        further events until the stop request is processed. The client must wait
+        for a river_window_manager_v1.finished event before destroying this
+        object.
+      </description>
+    </request>
+
+    <event name="finished">
+      <description summary="the server has finished with the window manager">
+        This event indicates that the server will send no further events on this
+        object. The client should destroy the object. See
+        river_window_manager_v1.destroy for more information.
+      </description>
+    </event>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the river_window_manager_v1 object">
+        This request should be called after the finished event has been received
+        to complete destruction of the object.
+
+        If a client wishes to destroy this object it should send a
+        river_window_manager_v1.stop request and wait for a
+        river_window_manager_v1.finished event. Once the finished event is
+        received it is safe to destroy this object and any other objects created
+        through this interface.
+      </description>
+    </request>
+
+    <event name="manage_start">
+      <description summary="start a manage sequence">
+        This event indicates that the server has sent events indicating all
+        state changes since the last manage sequence.
+
+        In response to this event, the client should make requests modifying
+        window management state as it chooses. Then, the client must make the
+        manage_finish request.
+
+        See the description of the river_window_manager_v1 interface for a
+        complete overview of the manage/render sequence loop.
+      </description>
+    </event>
+
+    <request name="manage_finish">
+      <description summary="finish a manage sequence">
+        This request indicates that the client has made all changes to window
+        management state it wishes to include in the current manage sequence and
+        that the server should atomically send these state changes to the
+        windows and continue with the manage sequence.
+
+        After sending this request, it is a protocol error for the client to
+        make further changes to window management state until the next
+        manage_start event is received.
+
+        See the description of the river_window_manager_v1 interface for a
+        complete overview of the manage/render sequence loop.
+      </description>
+    </request>
+
+    <request name="manage_dirty">
+      <description summary="ensure a manage sequence is started">
+        This request ensures a manage sequence is started and that a
+        manage_start event is sent by the server. If this request is made during
+        an ongoing manage sequence, a new manage sequence will be started as
+        soon as the current one is completed.
+
+        The client may want to use this request due to an internal state change
+        that the compositor is not aware of (e.g. a dbus event) which should
+        affect window management or rendering state.
+      </description>
+    </request>
+
+    <event name="render_start">
+      <description summary="start a render sequence">
+        This event indicates that the server has sent all
+        river_window_v1.dimensions events necessary.
+
+        In response to this event, the client should make requests modifying
+        rendering state as it chooses. Then, the client must make the
+        render_finish request.
+
+        See the description of the river_window_manager_v1 interface for a
+        complete overview of the manage/render sequence loop.
+      </description>
+    </event>
+
+    <request name="render_finish">
+      <description summary="finish a render sequence">
+        This request indicates that the client has made all changes to rendering
+        state it wishes to include in the current manage sequence and that the
+        server should atomically apply and display these state changes to the
+        user.
+
+        After sending this request, it is a protocol error for the client to
+        make further changes to rendering state until the next manage_start or
+        render_start event is received, whichever comes first.
+
+        See the description of the river_window_manager_v1 interface for a
+        complete overview of the manage/render sequence loop.
+      </description>
+    </request>
+
+    <event name="session_locked">
+      <description summary="the session has been locked">
+        This event indicates that the session has been locked.
+
+        The window manager may wish to restrict which key bindings are available
+        while locked or otherwise use this information.
+
+        If the session is currently locked when the river_window_manager_v1
+        object is created, the session_locked event will be sent in the first
+        manage sequence.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="session_unlocked">
+      <description summary="the session has been unlocked">
+        This event indicates that the session has been unlocked.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="window">
+      <description summary="new window">
+        A new window has been created.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="id" type="new_id" interface="river_window_v1" summary="new window"/>
+    </event>
+
+    <event name="output">
+      <description summary="new output">
+        A new logical output has been created, perhaps due to a new physical
+        monitor being plugged in or perhaps due to a change in configuration.
+
+        This event will be followed by river_output_v1.position and dimensions
+        events as well as a manage_start event after all other new state has
+        been sent by the server.
+      </description>
+      <arg name="id" type="new_id" interface="river_output_v1" summary="new output"/>
+    </event>
+
+    <event name="seat">
+      <description summary="new seat">
+        A new seat has been created.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="id" type="new_id" interface="river_seat_v1" summary="new seat"/>
+    </event>
+
+    <request name="get_shell_surface">
+      <description summary="assign the river_shell_surface_v1 surface role">
+        Create a new shell surface for window manager UI and assign the
+        river_shell_surface_v1 role to the surface.
+
+        Providing a wl_surface which already has a role or already has a buffer
+        attached or committed is a protocol error.
+      </description>
+      <arg name="id" type="new_id" interface="river_shell_surface_v1"
+        summary="new river shell surface"/>
+      <arg name="surface" type="object" interface="wl_surface"
+        summary="base surface"/>
+    </request>
+
+    <request name="exit_session" since="4">
+      <description summary="exit the Wayland session">
+        End the current Wayland session and exit the compositor.
+        All Wayland clients running in the current session, including
+        the window manager, will be disconnected.
+
+        Window managers should only make this request if the user explicitly
+        asks to exit the Wayland session, not for example on normal window
+        manager termination.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="river_window_v1" version="5">
+    <description summary="a logical window">
+      This represents a logical window. For example, a window may correspond to
+      an xdg_toplevel or Xwayland window.
+
+      A newly created window will not be displayed until the window manager
+      makes a propose_dimensions or fullscreen request as part of a manage
+      sequence, the server replies with a dimensions event as part of a render
+      sequence, and that render sequence is finished.
+    </description>
+
+    <enum name="error">
+      <entry name="node_exists" value="0"
+        summary="window already has a node object"/>
+      <entry name="invalid_dimensions" value="1"
+        summary="proposed dimensions out of bounds"/>
+      <entry name="invalid_border" value="2"
+        summary="invalid arg to set_borders"/>
+      <entry name="invalid_clip_box" value="3"
+        summary="invalid arg to set_clip_box"/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the window object">
+        This request indicates that the client will no longer use the window
+        object and that it may be safely destroyed.
+
+        This request should be made after the river_window_v1.closed event or
+        river_window_manager_v1.finished is received to complete destruction of
+        the window.
+      </description>
+    </request>
+
+    <event name="closed">
+      <description summary="the window has been closed">
+        The window has been closed by the server, perhaps due to an
+        xdg_toplevel.close request or similar.
+
+        The server will send no further events on this object and ignore any
+        request other than river_window_v1.destroy made after this event is
+        sent. The client should destroy this object with the
+        river_window_v1.destroy request to free up resources.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <request name="close">
+      <description summary="request that the window be closed">
+        Request that the window be closed. The window may ignore this request or
+        only close after some delay, perhaps opening a dialog asking the user to
+        save their work or similar.
+
+        The server will send a river_window_v1.closed event if/when the window
+        has been closed.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="get_node">
+      <description summary="get the window's render list node">
+        Get the node in the render list corresponding to the window.
+
+        It is a protocol error to make this request more than once for a single
+        window.
+      </description>
+      <arg name="id" type="new_id" interface="river_node_v1" summary="new node"/>
+    </request>
+
+    <event name="dimensions_hint">
+      <description summary="the window's preferred min/max dimensions">
+        This event informs the window manager of the window's preferred min/max
+        dimensions. These preferences are a hint, and the window manager is free
+        to propose dimensions outside of these bounds.
+
+        All min/max width/height values must be strictly greater than or equal
+        to 0. A value of 0 indicates that the window has no preference for that
+        value.
+
+        If the max_width/max_height is greater than 0, the min_width/min_height
+        must be strictly less than or equal to the max_width/max_height.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="min_width" type="int" summary="minimum width"/>
+      <arg name="min_height" type="int" summary="minimum height"/>
+      <arg name="max_width" type="int" summary="maximum width"/>
+      <arg name="max_height" type="int" summary="maximum height"/>
+    </event>
+
+    <event name="dimensions">
+      <description summary="window dimensions">
+        This event indicates the dimensions of the window in the compositor's
+        logical coordinate space. The width and height must be strictly greater
+        than zero.
+
+        Note that the dimensions of a river_window_v1 refer to the dimensions of
+        the window content and are unaffected by the presence of borders or
+        decoration surfaces.
+
+        This event is sent as part of a render sequence before the render_start
+        event.
+
+        It may be sent due to a propose_dimensions or fullscreen request in a
+        previous manage sequence or because a window independently decides to
+        change its dimensions.
+
+        The window will not be displayed until the first dimensions event is
+        received and the render sequence is finished.
+      </description>
+      <arg name="width" type="int" summary="window content width"/>
+      <arg name="height" type="int" summary="window content height"/>
+    </event>
+
+    <request name="propose_dimensions">
+      <description summary="propose window dimensions">
+        This request proposes dimensions for the window in the compositor's
+        logical coordinate space.
+
+        The width and height must be greater than or equal to zero. If the width
+        or height is zero the window will be allowed to decide its own
+        dimensions.
+
+        The window may not take the exact dimensions proposed. The actual
+        dimensions taken by the window will be sent in a subsequent
+        river_window_v1.dimensions event. For example, a terminal emulator may
+        only allow dimensions that are multiple of the cell size.
+
+        When a propose_dimensions request is made, the server must send a
+        dimensions event in response as soon as possible. It may not be possible
+        to send a dimensions event in the very next render sequence if, for
+        example, the window takes too long to respond to the proposed
+        dimensions. In this case, the server will send the dimensions event in a
+        future render sequence.
+
+        Note that the dimensions of a river_window_v1 refer to the dimensions of
+        the window content and are unaffected by the presence of borders or
+        decoration surfaces.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="width" type="int" summary="proposed content width"/>
+      <arg name="height" type="int" summary="proposed content height"/>
+    </request>
+
+    <request name="hide">
+      <description summary="request that the window be hidden">
+        Request that the window be hidden. Has no effect if the window is
+        already hidden. Hides any window borders and decorations as well.
+
+        Newly created windows are considered shown unless explicitly hidden with
+        the hide request.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="show">
+      <description summary="request that the window be shown">
+        Request that the window be shown. Has no effect if the window is not
+        hidden. Does not guarantee that the window is visible as it may be
+        completely obscured by other windows placed above it for example.
+
+        Newly created windows are considered shown unless explicitly hidden with
+        the hide request.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="app_id">
+      <description summary="the window set an application ID">
+        The window set an application ID.
+
+        The app_id argument will be null if the window has never set an
+        application ID or if the window cleared its application ID. (Xwayland
+        windows may do this for example, though xdg-toplevels may not.)
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="app_id" type="string" allow-null="true"
+        summary="window application ID"/>
+    </event>
+
+    <event name="title">
+      <description summary="the window set a title">
+        The window set a title.
+
+        The title argument will be null if the window has never set a title or
+        if the window cleared its title. (Xwayland windows may do this for
+        example, though xdg-toplevels may not.)
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="title" type="string" allow-null="true" summary="window title"/>
+    </event>
+
+    <event name="parent">
+      <description summary="the window set a parent">
+        The window set a parent window. If this event is never received or if
+        the parent argument is null then the window has no parent.
+
+        A surface with a parent set might be a dialog, file picker, or similar
+        for the parent window.
+
+        Child windows should generally be rendered directly above their parent.
+
+        The compositor must guarantee that there are no loops in the window
+        tree: a parent must not be the descendant of one of its children.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="parent" type="object" allow-null="true"
+        interface="river_window_v1" summary="parent window, if any"/>
+    </event>
+
+    <enum name="decoration_hint">
+      <entry name="only_supports_csd" value="0"
+        summary="only supports client side decoration"/>
+      <entry name="prefers_csd" value="1"
+        summary="client side decoration preferred, both CSD and SSD supported"/>
+      <entry name="prefers_ssd" value="2"
+        summary="server side decoration preferred, both CSD and SSD supported"/>
+      <entry name="no_preference" value="3"
+        summary="no preference, both CSD and SSD supported"/>
+    </enum>
+
+    <event name="decoration_hint">
+      <description summary="supported/preferred decoration style">
+        Information from the window about the supported and preferred client
+        side/server side decoration options.
+
+        This event may be sent multiple times over the lifetime of the window if
+        the window changes its preferences.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="hint" type="uint" enum="decoration_hint" summary="decoration hint"/>
+    </event>
+
+    <request name="use_csd">
+      <description summary="tell the client to use CSD">
+        Tell the client to use client side decoration and draw its own title
+        bar, borders, etc.
+
+        This is the default if neither this request nor the use_ssd request is
+        ever made.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="use_ssd">
+      <description summary="tell the client to use SSD">
+        Tell the client to use server side decoration and not draw any client
+        side decorations.
+
+        This request will have no effect if the client only supports client side
+        decoration, see the decoration_hint event.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <enum name="edges" bitfield="true">
+      <entry name="none" value="0"/>
+      <entry name="top" value="1"/>
+      <entry name="bottom" value="2"/>
+      <entry name="left" value="4"/>
+      <entry name="right" value="8"/>
+    </enum>
+
+    <request name="set_borders">
+      <description summary="set window borders">
+        This request decorates the window with borders drawn by the compositor
+        on the specified edges of the window. Borders are drawn above the window
+        content.
+
+        Corners are drawn only between borders on adjacent edges. If e.g. the
+        left edge has a border and the top edge does not, the border drawn on
+        the left edge will not extend vertically beyond the top edge of the
+        window.
+
+        Borders are not drawn while the window is fullscreen.
+
+        The color is defined by four 32-bit RGBA values. Unless specified in
+        another protocol extension, the RGBA values use pre-multiplied alpha.
+
+        The valid range for the RGBA values is from 0x00000000 to 0xffffffff.
+        These values are interpreted as a percentage:
+        - 0x00000000 means 0% of the given color component
+        - 0xffffffff means 100% of the given color component
+
+        Setting the edges to none or the width to 0 disables the borders.
+        Setting a negative width is a protocol error.
+
+        This request completely overrides all previous set_borders requests.
+        Only the most recent set_borders request has an effect.
+
+        Note that the position/dimensions of a river_window_v1 refer to the
+        position/dimensions of the window content and are unaffected by the
+        presence of borders or decoration surfaces.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="edges" type="uint" enum="edges" summary="border edges"/>
+      <arg name="width" type="int" summary="border width"/>
+      <arg name="r" type="uint" summary="32-bit red value"/>
+      <arg name="g" type="uint" summary="32-bit green value"/>
+      <arg name="b" type="uint" summary="32-bit blue value"/>
+      <arg name="a" type="uint" summary="32-bit alpha value"/>
+    </request>
+
+    <request name="set_tiled">
+      <description summary="set window tiled state">
+        Inform the window that it is part of a tiled layout and adjacent to
+        other elements in the tiled layout on the given edges.
+
+        The window should use this information to change the style of its client
+        side decorations and avoid drawing e.g. drop shadows outside of the
+        window dimensions on the tiled edges.
+
+        Setting the edges argument to none informs the window that it is not
+        part of a tiled layout. If this request is never made, the window is
+        informed that it is not part of a tiled layout.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="edges" type="uint" enum="edges" summary="tiled edges"/>
+    </request>
+
+    <request name="get_decoration_above">
+      <description summary="create a decoration above the window in z-order">
+        Create a decoration surface and assign the river_decoration_v1 role to
+        the surface. The created decoration is placed above the window in
+        rendering order, see the description of river_decoration_v1.
+
+        Providing a wl_surface which already has a role or already has a buffer
+        attached or committed is a protocol error.
+      </description>
+      <arg name="id" type="new_id" interface="river_decoration_v1"
+        summary="new decoration surface"/>
+      <arg name="surface" type="object" interface="wl_surface"
+        summary="base surface"/>
+    </request>
+
+    <request name="get_decoration_below">
+      <description summary="create a decoration below the window in z-order">
+        Create a decoration surface and assign the river_decoration_v1 role to
+        the surface. The created decoration is placed below the window in
+        rendering order, see the description of river_decoration_v1.
+
+        Providing a wl_surface which already has a role or already has a buffer
+        attached or committed is a protocol error.
+      </description>
+      <arg name="id" type="new_id" interface="river_decoration_v1"
+        summary="new decoration surface"/>
+      <arg name="surface" type="object" interface="wl_surface"
+        summary="base surface"/>
+    </request>
+
+    <event name="pointer_move_requested">
+      <description summary="window requested interactive pointer move">
+        This event informs the window manager that the window has requested to
+        be interactively moved using the pointer. The seat argument indicates the
+        seat for the move.
+
+        The xdg-shell protocol for example allows windows to request that an
+        interactive move be started, perhaps when a client-side rendered
+        titlebar is dragged.
+
+        The window manager may use the river_seat_v1.op_start_pointer request to
+        interactively move the window or ignore this event entirely.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="seat" type="object" interface="river_seat_v1"
+        summary="requested seat"/>
+    </event>
+
+    <event name="pointer_resize_requested">
+      <description summary="window requested interactive pointer resize">
+        This event informs the window manager that the window has requested to
+        be interactively resized using the pointer. The seat argument indicates
+        the seat for the resize.
+
+        The edges argument indicates which edges the window has requested to be
+        resized from. The edges argument will never be none and will never have
+        both top and bottom or both left and right edges set.
+
+        The xdg-shell protocol for example allows windows to request that an
+        interactive resize be started, perhaps when the corner of client-side
+        rendered decorations is dragged.
+
+        The window manager may use the river_seat_v1.op_start_pointer request to
+        interactively resize the window or ignore this event entirely.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="seat" type="object" interface="river_seat_v1"
+        summary="requested seat"/>
+      <arg name="edges" type="uint" enum="edges"
+        summary="requested edges"/>
+    </event>
+
+    <request name="inform_resize_start">
+      <description summary="inform the window it is being resized">
+        Inform the window that it is being resized. The window manager should
+        use this request to inform windows that are the target of an interactive
+        resize for example.
+
+        The window manager remains responsible for handling the position and
+        dimensions of the window while it is resizing.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="inform_resize_end">
+      <description summary="inform the window it no longer being resized">
+        Inform the window that it is no longer being resized. The window manager
+        should use this request to inform windows that are the target of an
+        interactive resize that the interactive resize has ended for example.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <enum name="capabilities" bitfield="true">
+      <entry name="window_menu" value="1"/>
+      <entry name="maximize" value="2"/>
+      <entry name="fullscreen" value="4"/>
+      <entry name="minimize" value="8"/>
+    </enum>
+
+    <request name="set_capabilities">
+      <description summary="inform window of supported capabilities">
+        This request informs the window of the capabilities supported by the
+        window manager. If the window manager, for example, ignores requests to
+        be maximized from the window it should not tell the window that it
+        supports the maximize capability.
+
+        The window might use this information to, for example, only show a
+        maximize button if the window manager supports the maximize capability.
+
+        The window manager client should use this request to set capabilities
+        for all new windows. If this request is never made, the compositor will
+        inform windows that all capabilities are supported.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="caps" type="uint" enum="capabilities"
+        summary="supported capabilities"/>
+    </request>
+
+    <event name="show_window_menu_requested">
+      <description summary="window requested that the window menu be shown">
+        The xdg-shell protocol for example allows windows to request that a
+        window menu be shown, for example when the user right clicks on client
+        side window decorations.
+
+        A window menu might include options to maximize or minimize the window.
+
+        The window manager is free to ignore this request and decide what the
+        window menu contains if it does choose to show one.
+
+        The x and y arguments indicate where the window requested that the
+        window menu be shown.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="x" type="int" summary="x offset from top left corner"/>
+      <arg name="y" type="int" summary="y offset from top left corner"/>
+    </event>
+
+    <event name="maximize_requested">
+      <description summary="the window requested to be maximized">
+        The xdg-shell protocol for example allows windows to request to be
+        maximized.
+
+        The window manager is free to honor this request using
+        river_window_v1.inform_maximized or ignore it.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="unmaximize_requested">
+      <description summary="the window requested to be unmaximized">
+        The xdg-shell protocol for example allows windows to request to be
+        unmaximized.
+
+        The window manager is free to honor this request using
+        river_window_v1.inform_unmaximized or ignore it.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <request name="inform_maximized">
+      <description summary="inform the window that it is maximized">
+        Inform the window that it is maximized. The window might use this
+        information to adapt the style of its client-side window decorations for
+        example.
+
+        The window manager remains responsible for handling the position and
+        dimensions of the window while it is maximized.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="inform_unmaximized">
+      <description summary="inform the window that it is unmaximized">
+        Inform the window that it is unmaximized. The window might use this
+        information to adapt the style of its client-side window decorations for
+        example.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="fullscreen_requested">
+      <description summary="the window requested to be fullscreen">
+        The xdg-shell protocol for example allows windows to request that they
+        be made fullscreen and allows them to provide an optional output hint.
+
+        If the output argument is null, the window has no preference and the
+        window manager should choose an output.
+
+        The window manager is free to honor this request using
+        river_window_v1.fullscreen or ignore it.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="output" type="object" allow-null="true"
+        interface="river_output_v1" summary="fullscreen output requested"/>
+    </event>
+
+    <event name="exit_fullscreen_requested">
+      <description summary="the window requested to exit fullscreen">
+        The xdg-shell protocol for example allows windows to request to exit
+        fullscreen.
+
+        The window manager is free to honor this request using
+        river_window_v1.exit_fullscreen or ignore it.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <request name="inform_fullscreen">
+      <description summary="inform the window that it is fullscreen">
+        Inform the window that it is fullscreen. The window might use this
+        information to adapt the style of its client-side window decorations for
+        example.
+
+        This request does not affect the size/position of the window or cause it
+        to become the only window rendered, see the river_window_v1.fullscreen
+        and exit_fullscreen requests for that.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="inform_not_fullscreen">
+      <description summary="inform the window that it is not fullscreen">
+        Inform the window that it is not fullscreen. The window might use this
+        information to adapt the style of its client-side window decorations for
+        example.
+
+        This request does not affect the size/position of the window or cause it
+        to become the only window rendered, see the river_window_v1.fullscreen
+        and exit_fullscreen requests for that.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="fullscreen">
+      <description summary="make the window fullscreen">
+        Make the window fullscreen on the given output. If multiple windows are
+        fullscreen on the same output at the same time only the "top" window in
+        rendering order shall be displayed.
+
+        All river_shell_surface_v1 objects above the top fullscreen window in
+        the rendering order will continue to be rendered.
+
+        The compositor will handle the position and dimensions of the window
+        while it is fullscreen. The set_position and propose_dimensions requests
+        shall not affect the current position and dimensions of a fullscreen
+        window.
+
+        When a fullscreen request is made, the server must send a dimensions
+        event in response as soon as possible. It may not be possible to send a
+        dimensions event in the very next render sequence if, for example, the
+        window takes too long to respond. In this case, the server will send the
+        dimensions event in a future render sequence.
+
+        The compositor will clip window content, decoration surfaces, and
+        borders to the given output's dimensions while the window is fullscreen.
+        The effects of set_clip_box and set_content_clip_box are ignored while
+        the window is fullscreen.
+
+        If the output on which a window is currently fullscreen is removed, the
+        windowing state is modified as if there were an exit_fullscreen request
+        made in the same manage sequence as the river_output_v1.removed event.
+
+        This request does not inform the window that it is fullscreen, see the
+        river_window_v1.inform_fullscreen and inform_not_fullscreen requests.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="output" type="object" interface="river_output_v1"
+        summary="fullscreen output"/>
+    </request>
+
+    <request name="exit_fullscreen">
+      <description summary="make the window not fullscreen">
+        Make the window not fullscreen.
+
+        The position and dimensions are undefined after this request is made
+        until a manage sequence in which the window manager makes the
+        propose_dimensions and set_position requests is completed.
+
+        The window manager should make propose_dimensions and set_position
+        requests in the same manage sequence as the exit_fullscreen request for
+        frame perfection.
+
+        This request does not inform the window that it is fullscreen, see the
+        river_window_v1.inform_fullscreen and inform_not_fullscreen requests.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="minimize_requested">
+      <description summary="the window requested to be minimized">
+        The xdg-shell protocol for example allows windows to request to be
+        minimized.
+
+        The window manager is free to ignore this request, hide the window, or
+        do whatever else it chooses.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <request name="set_clip_box" since="2">
+      <description summary="clip the window to a given box">
+        Clip the window, including borders and decoration surfaces, to the box
+        specified by the x, y, width, and height arguments. The x/y position of
+        the box is relative to the top left corner of the window.
+
+        The width and height arguments must be greater than or equal to 0.
+
+        Setting a clip box with 0 width or height disables clipping.
+
+        The clip box is ignored while the window is fullscreen.
+
+        Both set_clip_box and set_content_clip_box may be enabled simultaneously.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="x" type="int" summary="x relative to top left window corner"/>
+      <arg name="y" type="int" summary="y relative to top left window corner"/>
+      <arg name="width" type="int" summary="clip box width"/>
+      <arg name="height" type="int" summary="clip box height"/>
+    </request>
+
+    <event name="unreliable_pid" since="2">
+      <description summary="unreliable PID of the window's creator">
+        This event gives an unreliable PID of the process that created the
+        window. Obtaining this information is inherently racy due to PID reuse.
+        Therefore, this PID must not be used for anything security sensitive.
+
+        Note also that a single process may create multiple windows, so there is
+        not necessarily a 1-to-1 mapping from PID to window. Multiple windows
+        may have the same PID.
+
+        This event is sent once when the river_window_v1 is created and never
+        sent again.
+      </description>
+      <arg name="unreliable_pid" type="int" summary="unreliable PID"/>
+    </event>
+
+    <request name="set_content_clip_box" since="3">
+      <description summary="clip the window content to a given box">
+        Clip the content of the window, excluding borders and decoration
+        surfaces, to the box specified by the x, y, width, and height arguments.
+        The x/y position of the box is relative to the top left corner of the
+        window.
+
+        Borders drawn by the compositor (see set_borders) are placed around the
+        intersection of the window content (as defined by the dimensions event)
+        and the content clip box when content clipping is enabled.
+
+        The width and height arguments must be greater than or equal to 0.
+
+        Setting a box with 0 width or height disables content clipping.
+
+        The content clip box is ignored while the window is fullscreen.
+
+        Both set_clip_box and set_content_clip_box may be enabled simultaneously.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="x" type="int" summary="x relative to top left window corner"/>
+      <arg name="y" type="int" summary="y relative to top left window corner"/>
+      <arg name="width" type="int" summary="clip box width"/>
+      <arg name="height" type="int" summary="clip box height"/>
+    </request>
+
+    <event name="presentation_hint" since="4">
+      <description summary="presentation hint set by the window">
+        This event communicates the window's preferred presentation mode.
+
+        This event will be followed by a render_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="hint" type="uint" enum="river_output_v1.presentation_mode"
+        summary="presentation hint"/>
+    </event>
+
+    <event name="identifier" since="4">
+      <description summary="unique window identifier">
+        The identifier is a string that contains up to 32 printable ASCII bytes.
+        The identifier must not be an empty string.
+
+        It is compositor policy how the identifier is generated, but the following
+        properties must be upheld:
+
+        1. The identifier must uniquely identify the window. Two windows must not
+           share the same identifier.
+
+        2. The identifier must not be reused. This avoids races around window
+           creation/destruction when identifiers are used in out-of-band IPC.
+
+        If the compositor implements the ext-foreign-toplevel-list-v1 protocol,
+        the river_window_v1.identifier event must match the corresponding
+        ext_foreign_toplevel_handle_v1.identifier event.
+
+        This event is sent once when the river_window_v1 is created and never
+        sent again.
+      </description>
+      <arg name="identifier" type="string" summary="unique identifier"/>
+    </event>
+
+    <request name="set_dimension_bounds" since="4">
+      <description summary="recommend maximum dimensions to the window">
+        Recommend that the window keep its dimensions within a given
+        maximum width/height. This recommendation is only a hint and the window
+        may ignore it.
+
+        Setting the width and height to 0 indicates that there are no bounds
+        and is equivalent to having never made this request.
+
+        Setting width or height to a negative value is a protocol error.
+
+        The server should communicate this hint to an xdg_toplevel window with
+        the xdg_toplevel.configure_bounds event for example.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="max_width" type="int" summary="maximum width"/>
+      <arg name="max_height" type="int" summary="maximum height"/>
+    </request>
+
+    <event name="capture_sessions" since="5">
+      <description summary="window screen capture sessions">
+        This event informs the window manager of the number of active screen
+        capture sessions for the window.
+
+        This event is sent once when the river_window_v1 is created and again
+        whenever the number of capture sessions changes.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="count" type="uint" summary="count of screen capture sessions"/>
+    </event>
+  </interface>
+
+  <interface name="river_decoration_v1" version="5">
+    <description summary="a window decoration">
+      The rendering order of windows with decorations is follows:
+
+      1. Decorations created with get_decoration_below at the bottom
+      2. Window content
+      3. Borders configured with river_window_v1.set_borders
+      4. Decorations created with get_decoration_above at the top
+
+      The relative ordering of decoration surfaces above/below a window is
+      undefined by this protocol and left up to the compositor.
+    </description>
+
+    <enum name="error">
+      <entry name="no_commit" value="0"
+        summary="failed to commit the surface before the window manager commit"/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the decoration object">
+        This request indicates that the client will no longer use the decoration
+        object and that it may be safely destroyed.
+      </description>
+    </request>
+
+    <request name="set_offset">
+      <description summary="set offset from the window's top left corner">
+        This request sets the offset of the decoration surface from the top left
+        corner of the window.
+
+        If this request is never sent, the x and y offsets are undefined by this
+        protocol and left up to the compositor.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="x" type="int" summary="x relative to top left window corner"/>
+      <arg name="y" type="int" summary="y relative to top left window corner"/>
+    </request>
+
+    <request name="sync_next_commit">
+      <description summary="sync next commit with other rendering state">
+        Synchronize application of the next wl_surface.commit request on the
+        decoration surface with rest of the state atomically applied with the
+        next river_window_manager_v1.render_finish request.
+
+        The client must make a wl_surface.commit request on the decoration
+        surface after this request and before the render_finish request, failure
+        to do so is a protocol error.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="river_shell_surface_v1" version="5">
+    <description summary="a surface for window manager UI">
+      The window manager might use a shell surface to display a status bar,
+      background image, desktop notifications, launcher, desktop menu, or
+      whatever else it wants.
+    </description>
+
+    <enum name="error">
+      <entry name="node_exists" value="0"
+        summary="shell surface already has a node object"/>
+      <entry name="no_commit" value="1"
+        summary="failed to commit the surface before the window manager commit"/>
+    </enum>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the shell surface object">
+        This request indicates that the client will no longer use the shell
+        surface object and that it may be safely destroyed.
+      </description>
+    </request>
+
+    <request name="get_node">
+      <description summary="get the shell surface's render list node">
+        Get the node in the render list corresponding to the shell surface.
+
+        It is a protocol error to make this request more than once for a single
+        shell surface.
+      </description>
+      <arg name="id" type="new_id" interface="river_node_v1" summary="new node"/>
+    </request>
+
+    <request name="sync_next_commit">
+      <description summary="sync next surface commit to window manager commit">
+        Synchronize application of the next wl_surface.commit request on the
+        shell surface with rest of the rendering state atomically applied with
+        the next river_window_manager_v1.render_finish request.
+
+        The client must make a wl_surface.commit request on the shell surface
+        after this request and before the render_finish request, failure to do
+        so is a protocol error.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+  </interface>
+
+  <interface name="river_node_v1" version="5">
+    <description summary="a node in the render list">
+      The render list is a list of nodes that determines the rendering order of
+      the compositor. Nodes may correspond to windows or shell surfaces. The
+      relative ordering of nodes may be changed with the place_above and
+      place_below requests, changing the rendering order.
+
+      The initial position of a node in the render list is undefined, the window
+      manager client must use the place_above or place_below request to
+      guarantee a specific rendering order.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the decoration object">
+        This request indicates that the client will no longer use the node
+        object and that it may be safely destroyed.
+      </description>
+    </request>
+
+    <request name="set_position">
+      <description summary="set absolute position of the node">
+        Set the absolute position of the node in the compositor's logical
+        coordinate space. The x and y coordinates may be positive or negative.
+
+        Note that the position of a river_window_v1 refers to the position of
+        the window content and is unaffected by the presence of borders or
+        decoration surfaces.
+
+        If this request is never sent, the position of the node is undefined by
+        this protocol and left up to the compositor.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="x" type="int" summary="global x coordinate"/>
+      <arg name="y" type="int" summary="global y coordinate"/>
+    </request>
+
+    <request name="place_top">
+      <description summary="place node above all other nodes">
+        This request places the node above all other nodes in the compositor's
+        render list.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="place_bottom">
+      <description summary="place node below all other nodes">
+        This request places the node below all other nodes in the compositor's
+        render list.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="place_above">
+      <description summary="place node above another node">
+        This request places the node directly above another node in the
+        compositor's render list.
+
+        Attempting to place a node above itself has no effect.
+
+        Given nodes A, B, C currently rendered in that order with C on top
+        and A on the bottom, the following example demonstrates the behavior
+        of this request and the meaning of "directly above":
+
+        1. A.place_above(C) -> B, C, A
+        2. A.place_above(B) -> B, A, C
+        3. B.place_above(A) -> A, B, C
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="other" type="object" interface="river_node_v1"
+        summary="other node"/>
+    </request>
+
+    <request name="place_below">
+      <description summary="place node below another node">
+        This request places the node directly below another node in the
+        compositor's render list.
+
+        Attempting to place a node below itself has no effect.
+
+        Given nodes A, B, C currently rendered in that order with C on top
+        and A on the bottom, the following example demonstrates the behavior
+        of this request and the meaning of "directly below":
+
+        1. C.place_below(A) -> C, A, B
+        2. C.place_below(B) -> A, C, B
+        3. B.place_below(C) -> A, B, C
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="other" type="object" interface="river_node_v1"
+        summary="other node"/>
+    </request>
+  </interface>
+
+  <interface name="river_output_v1" version="5">
+    <description summary="a logical output">
+      An area in the compositor's logical coordinate space that should be
+      treated as a single output for window management purposes. This area may
+      correspond to a single physical output or multiple physical outputs in the
+      case of mirroring or tiled monitors depending on the hardware and
+      compositor configuration.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the output object">
+        This request indicates that the client will no longer use the output
+        object and that it may be safely destroyed.
+
+        This request should be made after the river_output_v1.removed event is
+        received to complete destruction of the output.
+      </description>
+    </request>
+
+    <event name="removed">
+      <description summary="the output is removed">
+        This event indicates that the logical output is no longer conceptually
+        part of window management space.
+
+        The server will send no further events on this object and ignore any
+        request (other than river_output_v1.destroy) made after this event is
+        sent. The client should destroy this object with the
+        river_output_v1.destroy request to free up resources.
+
+        This event may be sent because a corresponding physical output has been
+        physically unplugged or because some output configuration has changed.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="wl_output">
+      <description summary="corresponding wl_output">
+        The wl_output object corresponding to the river_output_v1. The argument
+        is the global name of the wl_output advertised with wl_registry.global.
+
+        It is guaranteed that the corresponding wl_output is advertised before
+        this event is sent.
+
+        This event is sent exactly once. The wl_output associated with a
+        river_output_v1 cannot change. It is guaranteed that there is a 1-to-1
+        mapping between wl_output and river_output_v1 objects.
+
+        The global_remove event for the corresponding wl_output may be sent
+        before the river_output_v1.removed event. This is due to the fact that
+        river_output_v1 state changes are synced to the river window management
+        manage sequence while changes to globals are not.
+
+        Rationale: The window manager may need information provided by the
+        wl_output interface such as the name/description. It also may need the
+        wl_output object to start screencopy for example.
+      </description>
+      <arg name="name" type="uint" summary="name of the wl_output global"/>
+    </event>
+
+    <event name="position">
+      <description summary="output position">
+        This event indicates the position of the output in the compositor's
+        logical coordinate space. The x and y coordinates may be positive or
+        negative.
+
+        This event is sent once when the river_output_v1 is created and again
+        whenever the position changes.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+
+        The server must guarantee that the position and dimensions events do not
+        cause the areas of multiple logical outputs to overlap when the
+        corresponding manage_start event is received.
+      </description>
+      <arg name="x" type="int" summary="global x coordinate"/>
+      <arg name="y" type="int" summary="global y coordinate"/>
+    </event>
+
+    <event name="dimensions">
+      <description summary="output dimensions">
+        This event indicates the dimensions of the output in the compositor's
+        logical coordinate space. The width and height will always be strictly
+        greater than zero.
+
+        This event is sent once when the river_output_v1 is created and again
+        whenever the dimensions change.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+
+        The server must guarantee that the position and dimensions events do not
+        cause the areas of multiple logical outputs to overlap when the
+        corresponding manage_start event is received.
+      </description>
+      <arg name="width" type="int" summary="output width"/>
+      <arg name="height" type="int" summary="output height"/>
+    </event>
+
+    <enum name="error" since="4">
+      <entry name="invalid_presentation_mode" value="0" since="4"
+        summary="invalid presentation mode enum value"/>
+    </enum>
+
+    <enum name="presentation_mode" since="4">
+      <entry name="vsync" value="0">
+        <description summary="tearing-free presentation">
+          Output page-flips should be synchronized to the vertical blanking
+          period, eliminating tearing. This is the default presentation mode.
+        </description>
+      </entry>
+      <entry name="async" value="1">
+        <description summary="asynchronous presentation">
+          Output page-flips should not be synchronized to the vertical blanking
+          period, visual screen tearing may occur.
+        </description>
+      </entry>
+    </enum>
+
+    <request name="set_presentation_mode" since="4">
+      <description summary="set the preferred presentation mode">
+        Set the preferred presentation mode of the output. The compositor should
+        always respect the preference of the window manager if possible. If this
+        request is never made, the preferred presentation mode is vsync.
+
+        This request modifies rendering state and may only be made as part of a
+        render sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="mode" type="uint" enum="presentation_mode"
+        summary="preferred presentation mode"/>
+    </request>
+
+    <event name="capture_sessions" since="5">
+      <description summary="output screen capture sessions">
+        This event informs the window manager of the number of active screen
+        capture sessions for the output.
+
+        This event is sent once when the river_output_v1 is created and again
+        whenever the number of capture sessions changes.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="count" type="uint" summary="count of screen capture sessions"/>
+    </event>
+  </interface>
+
+  <interface name="river_seat_v1" version="5">
+    <description summary="a window management seat">
+      This object represents a single user's collection of input devices. It
+      allows the window manager to route keyboard input to windows, get
+      high-level information about pointer input, define pointer bindings, etc.
+
+      For keyboard bindings, see the river-xkb-bindings-v1 protocol.
+
+      Since version 4: The cursor surface/shape set by the window manager on the
+      wl_pointer of this seat is used when no client has pointer focus, for
+      example during a pointer operation. Since the window manager is allowed to
+      set cursor surface/shape even when it does not have pointer focus, the
+      compositor must ignore the serial argument of wl_pointer.set_cursor and
+      wp_cursor_shape_device_v1.set_shape requests made by the window manager.
+
+      The most recent cursor surface/shape set by the window manager is
+      remembered by the compositor and restored whenever no client has pointer
+      focus. If the window manager never sets a cursor surface/shape, the
+      "default" shape is used.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the seat object">
+        This request indicates that the client will no longer use the seat
+        object and that it may be safely destroyed.
+
+        This request should be made after the river_seat_v1.removed event is
+        received to complete destruction of the seat.
+      </description>
+    </request>
+
+    <event name="removed">
+      <description summary="the seat is removed">
+        This event indicates that seat is no longer in use and should be
+        destroyed.
+
+        The server will send no further events on this object and ignore any
+        request (other than river_seat_v1.destroy) made after this event is
+        sent.  The client should destroy this object with the
+        river_seat_v1.destroy request to free up resources.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="wl_seat">
+      <description summary="corresponding wl_seat">
+        The wl_seat object corresponding to the river_seat_v1. The argument is
+        the global name of the wl_seat advertised with wl_registry.global.
+
+        It is guaranteed that the corresponding wl_seat is advertised before
+        this event is sent.
+
+        This event is sent exactly once. The wl_seat associated with a
+        river_seat_v1 cannot change. It is guaranteed that there is a 1-to-1
+        mapping between wl_seat and river_seat_v1 objects.
+
+        The global_remove event for the corresponding wl_seat may be sent before
+        the river_seat_v1.removed event. This is due to the fact that
+        river_seat_v1 state changes are synced to the river window management
+        manage sequence while changes to globals are not.
+
+        Rationale: The window manager may want to trigger window management
+        state changes based on normal input events received by its shell
+        surfaces for example.
+      </description>
+      <arg name="name" type="uint" summary="name of the wl_seat global"/>
+    </event>
+
+    <request name="focus_window">
+      <description summary="give keyboard focus to a window">
+        Request that the compositor send keyboard input to the given window.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="window" type="object" interface="river_window_v1"
+        summary="window to focus"/>
+    </request>
+
+    <request name="focus_shell_surface">
+      <description summary="give keyboard focus to a shell_surface">
+        Request that the compositor send keyboard input to the given shell
+        surface.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="shell_surface" type="object" interface="river_shell_surface_v1"
+        summary="shell surface to focus"/>
+    </request>
+
+    <request name="clear_focus">
+      <description summary="clear keyboard focus">
+        Request that the compositor not send keyboard input to any client.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="pointer_enter">
+      <description summary="pointer entered a window">
+        The seat's pointer entered the given window's area.
+
+        The area of a window is defined to include the area defined by the
+        window dimensions, borders configured using river_window_v1.set_borders,
+        and the input regions of decoration surfaces. In particular, it does not
+        include input regions of surfaces belonging to the window that extend
+        outside the window dimensions.
+
+        The pointer of a seat may only enter a single window at a time. When the
+        pointer moves between windows, the pointer_leave event for the old
+        window must be sent before the pointer_enter event for the new window.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="window" type="object" interface="river_window_v1"
+        summary="window entered"/>
+    </event>
+
+    <event name="pointer_leave">
+      <description summary="pointer left the entered window">
+        The seat's pointer left the window for which pointer_enter was most
+        recently sent. See pointer_enter for details.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <event name="window_interaction">
+      <description summary="a window has been interacted with">
+        A window has been interacted with beyond the pointer merely passing over
+        it. This event might be sent due to a pointer button press or due to a
+        touch/tablet tool interaction with the window.
+
+        There are no guarantees regarding how this event is sent in relation to
+        the pointer_enter and pointer_leave events as the interaction may use
+        touch or tablet tool input.
+
+        Rationale: this event gives window managers necessary information to
+        determine when to send keyboard focus, raise a window that already has
+        keyboard focus, etc. Rather than expose all pointer, touch, and tablet
+        events to window managers, a policy over mechanism approach is taken.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="window" type="object" interface="river_window_v1"
+        summary="window interacted with"/>
+    </event>
+
+    <event name="shell_surface_interaction">
+      <description summary="a shell surface has been interacted with">
+        A shell surface has been interacted with beyond the pointer merely
+        passing over it. This event might be sent due to a pointer button press
+        or due to a touch/tablet tool interaction with the shell_surface.
+
+        There are no guarantees regarding how this event is sent in relation to
+        the pointer_enter and pointer_leave events as the interaction may use
+        touch or tablet tool input.
+
+        Rationale: While the shell surface does receive all wl_pointer,
+        wl_touch, etc. input events for the surface directly, these events do
+        not necessarily trigger a manage sequence and therefore do not allow the
+        window manager to update focus or perform other actions in response to
+        the input in a race-free way.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="shell_surface" type="object" interface="river_shell_surface_v1"
+        summary="shell surface interacted with"/>
+    </event>
+
+    <request name="op_start_pointer">
+      <description summary="start an interactive pointer operation">
+        Start an interactive pointer operation. During the operation, op_delta
+        events will be sent based on pointer input.
+
+        When all pointer buttons are released, the op_release event is sent.
+
+        The pointer operation continues until the op_end request is made during
+        a manage sequence and that manage sequence is finished.
+
+        The window manager may use this operation to implement interactive
+        move/resize of windows by setting the position of windows and proposing
+        dimensions based off of the op_delta events.
+
+        This request is ignored if an operation is already in progress.
+
+        The compositor must ensure that no client has pointer focus from this
+        seat during the pointer operation. This means that the window manager
+        has control over the pointer's cursor surface/shape during the pointer
+        operation. See the river_seat_v1 description.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="op_delta">
+      <description summary="total cumulative motion since op start">
+        This event indicates the total change in position since the start of the
+        operation of the pointer/touch point/etc.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+      <arg name="dx" type="int" summary="total change in x"/>
+      <arg name="dy" type="int" summary="total change in y"/>
+    </event>
+
+    <event name="op_release">
+      <description summary="operation input has been released">
+        The input driving the current interactive operation has been released.
+        For a pointer op for example, all pointer buttons have been released.
+
+        Depending on the op type, op_delta events may continue to be sent until
+        the op is ended with the op_end request.
+
+        This event is sent at most once during an interactive operation.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+      </description>
+    </event>
+
+    <request name="op_end">
+      <description summary="end an interactive operation">
+        End an interactive operation.
+
+        This request is ignored if there is no operation in progress.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <enum name="modifiers" bitfield="true">
+      <description summary="a set of keyboard modifiers">
+        This enum is used to describe the keyboard modifiers that must be held
+        down to trigger a key binding or pointer binding.
+
+        Note that river and wlroots use the values 2 and 16 for capslock and
+        numlock internally. It doesn't make sense to use locked modifiers for
+        bindings however so these values are not included in this enum.
+      </description>
+      <entry name="none" value="0"/>
+      <entry name="shift" value="1"/>
+      <entry name="ctrl" value="4"/>
+      <entry name="mod1" value="8" summary="commonly called alt"/>
+      <entry name="mod3" value="32"/>
+      <entry name="mod4" value="64" summary="commonly called super or logo"/>
+      <entry name="mod5" value="128"/>
+    </enum>
+
+    <request name="get_pointer_binding">
+      <description summary="define a new pointer binding">
+        Define a pointer binding in terms of a pointer button, keyboard
+        modifiers, and other configurable properties.
+
+        The button argument is a Linux input event code defined in the
+        linux/input-event-codes.h header file (e.g. BTN_RIGHT).
+
+        The new pointer binding is not enabled until initial configuration is
+        completed and the enable request is made during a manage sequence.
+      </description>
+      <arg name="id" type="new_id" interface="river_pointer_binding_v1"
+        summary="new pointer binding"/>
+      <arg name="button" type="uint" summary="a Linux input event code"/>
+      <arg name="modifiers" type="uint" enum="modifiers"
+        summary="keyboard modifiers"/>
+    </request>
+
+    <request name="set_xcursor_theme" since="2">
+      <description summary="set the xcursor theme for the seat">
+        Set the XCursor theme for the seat. This theme is used for cursors
+        rendered by the compositor, but not necessarily for cursors rendered by
+        clients.
+
+        Note: The window manager may also wish to set the XCURSOR_THEME and
+        XCURSOR_SIZE environment variable for programs it starts.
+      </description>
+      <arg name="name" type="string" summary="xcursor theme name"/>
+      <arg name="size" type="uint" summary="cursor size"/>
+    </request>
+
+    <event name="pointer_position" since="2">
+      <description summary="The current position of the pointer">
+        The current position of the pointer in the compositor's logical
+        coordinate space.
+
+        This state is special in that a change in pointer position alone must
+        not cause the compositor to start a manage sequence.
+
+        Assuming the seat has a pointer, this event must be sent in every manage
+        sequence unless there is no change in x/y position since the last time this
+        event was sent.
+      </description>
+      <arg name="x" type="int" summary="global x coordinate"/>
+      <arg name="y" type="int" summary="global y coordinate"/>
+    </event>
+
+    <request name="pointer_warp" since="3">
+      <description summary="warp the pointer to a given position">
+        Warp the pointer to the given position in the compositor's logical
+        coordinate space.
+
+        If the given position is outside the bounds of all outputs, the pointer
+        will be warped to the closest point inside an output instead.
+
+        If an op_start_pointer request is made during the same manage sequence
+        as a pointer_warp request, the warp is applied first by the server
+        regardless of the relative ordering of the two requests.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+      <arg name="x" type="int" summary="global x coordinate"/>
+      <arg name="y" type="int" summary="global y coordinate"/>
+    </request>
+  </interface>
+
+  <interface name="river_pointer_binding_v1" version="5">
+    <description summary="configure a pointer binding, receive trigger events">
+      This object allows the window manager to configure a pointer binding and
+      receive events when the binding is triggered.
+
+      The new pointer binding is not enabled until the enable request is made
+      during a manage sequence.
+
+      Normally, all pointer button events are sent to the surface with pointer
+      focus by the compositor. Pointer button events that trigger a pointer
+      binding are not sent to the surface with pointer focus.
+
+      If multiple pointer bindings would be triggered by a single physical
+      pointer event on the compositor side, it is compositor policy which
+      pointer binding(s) will receive press/release events or if all of the
+      matched pointer bindings receive press/release events.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="destroy the pointer binding object">
+        This request indicates that the client will no longer use the pointer
+        binding object and that it may be safely destroyed.
+      </description>
+    </request>
+
+    <request name="enable">
+      <description summary="enable the pointer binding">
+        This request should be made after all initial configuration has been
+        completed and the window manager wishes the pointer binding to be able
+        to be triggered.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <request name="disable">
+      <description summary="disable the pointer binding">
+        This request may be used to temporarily disable the pointer binding. It
+        may be later re-enabled with the enable request.
+
+        This request modifies window management state and may only be made as
+        part of a manage sequence, see the river_window_manager_v1 description.
+      </description>
+    </request>
+
+    <event name="pressed">
+      <description summary="the bound pointer button has been pressed">
+        This event indicates that the pointer button triggering the binding has
+        been pressed.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+
+        The compositor should wait for the manage sequence to complete before
+        processing further input events. This allows the window manager client
+        to, for example, modify key bindings and keyboard focus without racing
+        against future input events. The window manager should of course respond
+        as soon as possible as the capacity of the compositor to buffer incoming
+        input events is finite.
+      </description>
+    </event>
+
+    <event name="released">
+      <description summary="the bound pointer button has been released">
+        This event indicates that the pointer button triggering the binding has
+        been released.
+
+        Releasing the modifiers for the binding without releasing the pointer
+        button does not trigger the release event. This event is sent when the
+        pointer button is released, even if the modifiers have changed since the
+        pressed event.
+
+        This event will be followed by a manage_start event after all other new
+        state has been sent by the server.
+
+        The compositor should wait for the manage sequence to complete before
+        processing further input events. This allows the window manager client
+        to, for example, modify key bindings and keyboard focus without racing
+        against future input events. The window manager should of course respond
+        as soon as possible as the capacity of the compositor to buffer incoming
+        input events is finite.
+      </description>
+    </event>
+  </interface>
+</protocol>

+ 74 - 0
tools/desktops/river_min_wm.c

@@ -0,0 +1,74 @@
+// Minimal river 0.4 WM: ends every manage/render sequence at once and binds river_layer_shell_v1, without which
+// river closes all layer surfaces. Exits when the WM role is taken or the connection ends.
+#include <stdio.h>
+#include <string.h>
+#include <wayland-client.h>
+
+#include "river-layer-shell-v1-client-protocol.h"
+#include "river-window-management-v1-client-protocol.h"
+
+static struct river_window_manager_v1* wm;
+static struct river_layer_shell_v1* layer_shell;
+static int running = 1;
+
+static void global (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
+    if (strcmp (interface, river_window_manager_v1_interface.name) == 0) {
+	wm = wl_registry_bind (registry, name, &river_window_manager_v1_interface, 1);
+    } else if (strcmp (interface, river_layer_shell_v1_interface.name) == 0) {
+	layer_shell = wl_registry_bind (registry, name, &river_layer_shell_v1_interface, 1);
+    }
+}
+
+static void global_remove (void* data, struct wl_registry* registry, uint32_t name) { }
+
+static const struct wl_registry_listener registry_listener = { global, global_remove };
+
+static void unavailable (void* data, struct river_window_manager_v1* wm) {
+    fprintf (stderr, "another window manager is running\n");
+    running = 0;
+}
+
+static void finished (void* data, struct river_window_manager_v1* wm) { running = 0; }
+
+static void manage_start (void* data, struct river_window_manager_v1* wm) { river_window_manager_v1_manage_finish (wm); }
+
+static void render_start (void* data, struct river_window_manager_v1* wm) { river_window_manager_v1_render_finish (wm); }
+
+static void session_locked (void* data, struct river_window_manager_v1* wm) { }
+
+static void session_unlocked (void* data, struct river_window_manager_v1* wm) { }
+
+static void window (void* data, struct river_window_manager_v1* wm, struct river_window_v1* window) { }
+
+static void output (void* data, struct river_window_manager_v1* wm, struct river_output_v1* output) { }
+
+static void seat (void* data, struct river_window_manager_v1* wm, struct river_seat_v1* seat) { }
+
+static const struct river_window_manager_v1_listener wm_listener = {
+    unavailable, finished, manage_start, render_start, session_locked, session_unlocked, window, output, seat,
+};
+
+int main (void) {
+    struct wl_display* display = wl_display_connect (NULL);
+
+    if (!display) {
+	fprintf (stderr, "no wayland display\n");
+	return 1;
+    }
+
+    wl_registry_add_listener (wl_display_get_registry (display), &registry_listener, NULL);
+    wl_display_roundtrip (display);
+
+    if (!wm || !layer_shell) {
+	fprintf (stderr, "the compositor has no river_window_manager_v1 or river_layer_shell_v1\n");
+	return 1;
+    }
+
+    river_window_manager_v1_add_listener (wm, &wm_listener, NULL);
+    printf ("ready\n");
+    fflush (stdout);
+
+    while (running && wl_display_dispatch (display) != -1) { }
+
+    return 0;
+}

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

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

+ 102 - 16
tools/desktops/session.py

@@ -22,6 +22,32 @@ class Unsupported(Exception):
     pass
 
 
+
+def build_wayland_tool(name, protocols):
+    """tools/desktops/<name>.c built once against the client headers of its vendored protocol files"""
+    tool = BASE / name
+    source = REPO / f"tools/desktops/{name}.c"
+    inputs = [source, *(REPO / "tools/desktops" / xml for xml in protocols)]
+    if tool.exists() and all(tool.stat().st_mtime >= path.stat().st_mtime for path in inputs):
+        return tool
+    build = BASE / f"{name}-build"
+    build.mkdir(parents=True, exist_ok=True)
+    code = []
+    for xml in inputs[1:]:
+        stem = xml.name.removesuffix(".xml")
+        subprocess.run(["wayland-scanner", "client-header", str(xml), str(build / f"{stem}-client-protocol.h")], check=True)
+        subprocess.run(["wayland-scanner", "private-code", str(xml), str(build / f"{stem}.c")], check=True)
+        code.append(str(build / f"{stem}.c"))
+    subprocess.run(["cc", "-o", str(tool), str(source), *code, f"-I{build}", "-lwayland-client"], check=True)
+    return tool
+
+
+def _comm(pid):
+    try:
+        return Path(f"/proc/{pid}/comm").read_text().strip()
+    except OSError:
+        return ""
+
 class Session:
     name = ""
     # short, Hyprland's IPC socket path has to fit in 108 bytes
@@ -212,17 +238,7 @@ class Session:
 
     def virtual_pointer(self):
         """a pointer that stays while it runs (wlroots-style compositors): write "abs x y width height" lines to its stdin"""
-        tool = BASE / "wlr_virtual_pointer"
-        source = REPO / "tools/desktops/wlr_virtual_pointer.c"
-        if not tool.exists() or tool.stat().st_mtime < source.stat().st_mtime:
-            build = BASE / "wlr-virtual-pointer"
-            build.mkdir(parents=True, exist_ok=True)
-            xml = REPO / "tools/desktops/wlr-virtual-pointer-unstable-v1.xml"
-            for mode, out in (("client-header", "wlr-virtual-pointer-unstable-v1-client-protocol.h"),
-                              ("private-code", "wlr-virtual-pointer.c")):
-                subprocess.run(["wayland-scanner", mode, str(xml), str(build / out)], check=True)
-            subprocess.run(["cc", "-o", str(tool), str(source), str(build / "wlr-virtual-pointer.c"), f"-I{build}",
-                            "-lwayland-client"], check=True)
+        tool = build_wayland_tool("wlr_virtual_pointer", ["wlr-virtual-pointer-unstable-v1.xml"])
         return subprocess.Popen([str(tool)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
                                 env={**self.client_env(), "PATH": os.environ.get("PATH", "")})
 
@@ -365,8 +381,12 @@ class Wayfire(Wlroots):
 
 
 class River(Wlroots):
+    """river 0.4 leaves window management to a client and closes every layer surface while none runs, the session
+    runs tools/desktops/river_min_wm.c"""
+
     name, short, program, desktop = "river", "r", "river", "river"
     needs = ("river", "wlr-randr", "grim")
+    window_manager = None
 
     def _config(self):
         init = self.dir / "init"
@@ -374,6 +394,33 @@ class River(Wlroots):
         init.chmod(0o755)
         return ["-c", str(init)]
 
+    def _ready(self):
+        super()._ready()
+        self.start_window_manager()
+
+    def start_window_manager(self):
+        tool = build_wayland_tool("river_min_wm", ["river-window-management-v1.xml", "river-layer-shell-v1.xml"])
+        self.window_manager = subprocess.Popen(
+            [str(tool)], env={**self.client_env(), "PATH": os.environ.get("PATH", "")}, stdout=subprocess.PIPE,
+            stderr=open(self.dir / "river_min_wm.log", "ab"), text=True,
+        )
+        self.pids.append(self.window_manager.pid)
+        if self.window_manager.stdout.readline().strip() != "ready":
+            raise RuntimeError(f"river_min_wm did not start: {(self.dir / 'river_min_wm.log').read_text()[-500:]}")
+        self._save()
+
+    def stop_window_manager(self):
+        if self.window_manager is None:
+            for pid in [pid for pid in self.pids if _comm(pid) == "river_min_wm"]:
+                terminate([pid])
+                self.pids.remove(pid)
+        else:
+            self.window_manager.terminate()
+            self.window_manager.wait(10)
+            self.pids.remove(self.window_manager.pid)
+            self.window_manager = None
+        self._save()
+
 
 class Nested(Session):
     """Hyprland, niri and COSMIC have no headless backend (they would take the GPU through DRM), they run as a window
@@ -555,8 +602,9 @@ class Gnome(Session):
         for source in self.EXTENSIONS:
             (target / source.name).symlink_to(source)
         for uuid, folder in self.extra_extensions:
+            # copied, a rootfs session only sees the repo and session folders
             if folder is not None:
-                (target / uuid).symlink_to(folder)
+                shutil.copytree(folder, target / uuid, symlinks=True)
         for name in self.desktop_files:
             path = self.home / "Desktop" / name
             path.parent.mkdir(parents=True, exist_ok=True)
@@ -570,6 +618,8 @@ class Gnome(Session):
             if result.returncode != 0:
                 raise RuntimeError(f"gsettings {key}: {result.stderr.strip()}")
 
+    shell_env = {}
+
     def _launch(self):
         width, height = self.size
         env = {"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "GNOME", "XDG_SESSION_DESKTOP": "gnome",
@@ -579,7 +629,7 @@ class Gnome(Session):
         monitors = [arg for _ in range(self.outputs) for arg in ("--virtual-monitor", f"{width}x{height}")]
         # no Xwayland, mutter could pick the real desktop's display number
         self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--no-x11", *monitors, "--wayland-display",
-                             "lwe-gnome"], env)
+                             "lwe-gnome"], {**env, **self.shell_env})
         self.session_env["WAYLAND_DISPLAY"] = "lwe-gnome"
         self.wait_socket("lwe-gnome")
         wait_for("the lab extension", self._unsafe_mode, 40)
@@ -614,6 +664,13 @@ class Gnome(Session):
             raise RuntimeError(f"Shell screenshot failed: {result.stdout.strip()} {result.stderr.strip()}")
 
 
+class GnomeHdr(Gnome):
+    """GNOME 50 with every monitor forced into HDR (MUTTER_DEBUG_FORCE_HDR), for --hdr without an HDR monitor"""
+
+    name, short = "gnome-hdr", "gh"
+    shell_env = {"MUTTER_DEBUG_FORCE_HDR": "1"}
+
+
 class Gnome46(Gnome):
     """GNOME Shell 46 from the Ubuntu 24.04 rootfs (setup gnome46): no Meta.Window.set_type, the helper path"""
 
@@ -649,8 +706,12 @@ class Gnome49(Gnome):
     userlands = ("gnome49",)
 
 
-# DING for GNOME 50 comes from `setup ding`
-DING_DIR = Path.home() / ".local/share/lwe-lab/ding50/ding@rastersoft.com"
+def ding_dir(shell):
+    """DING from extensions.gnome.org for the sessions without a distribution package, `setup ding` / `setup ding49`"""
+    return Path.home() / f".local/share/lwe-lab/ding{shell}/ding@rastersoft.com"
+
+
+DING_DIR = ding_dir(50)
 
 
 class GnomeDing(Gnome):
@@ -678,6 +739,31 @@ class Gnome45Ding(Gnome45):
     desktop_files = GnomeDing.desktop_files
 
 
+class Gnome47Ding(Gnome47):
+    """GNOME 47 with Ubuntu's Desktop Icons NG package"""
+
+    name, short = "gnome47-ding", "g7d"
+    extra_extensions = (("ding@rastersoft.com", None),)
+    desktop_files = GnomeDing.desktop_files
+
+
+class Gnome48Ding(Gnome48):
+    """GNOME 48 with Ubuntu's Desktop Icons NG package"""
+
+    name, short = "gnome48-ding", "g8d"
+    extra_extensions = (("ding@rastersoft.com", None),)
+    desktop_files = GnomeDing.desktop_files
+
+
+class Gnome49Ding(Gnome49):
+    """GNOME 49 (Fedora 43, which doesn't package it) with Desktop Icons NG from extensions.gnome.org"""
+
+    name, short = "gnome49-ding", "g9d"
+    extra_extensions = (("ding@rastersoft.com", ding_dir(49)),)
+    desktop_files = GnomeDing.desktop_files
+    requires = (ding_dir(49),)
+
+
 class X11(Session):
     """a desktop environment or window manager on an X server of its own"""
 
@@ -808,5 +894,5 @@ WM_CLASSES = [
 
 KINDS = {
     kind.name: kind
-    for kind in (Sway, SwayDual, Labwc, LabwcDual, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Kde5, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
+    for kind in (Sway, SwayDual, Labwc, LabwcDual, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Kde5, Gnome, GnomeHdr, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Gnome47Ding, Gnome48Ding, Gnome49Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
 }

+ 7 - 2
tools/desktops/wlr_virtual_pointer.c

@@ -1,6 +1,6 @@
 // One virtual pointer for wlroots-style compositors (sway, labwc, Hyprland, niri), kept for as long as stdin is open:
 // wlrctl makes a new device per call and the seat's pointer capability comes and goes with it.
-// stdin lines: "abs <x> <y> <width> <height>" (position within a layout extent), "quit"; each answered with "ok"
+// stdin: "abs <x> <y> <w> <h>", "button <code> <1|0>" (272 = left), "quit"; each answered with "ok"
 #include <stdio.h>
 #include <string.h>
 #include <wayland-client.h>
@@ -45,11 +45,16 @@ int main (void) {
     wl_display_roundtrip (display);
 
     while (fgets (line, sizeof line, stdin)) {
-	unsigned x, y, width, height;
+	unsigned x, y, width, height, button, pressed;
 
 	if (sscanf (line, "abs %u %u %u %u", &x, &y, &width, &height) == 4) {
 	    zwlr_virtual_pointer_v1_motion_absolute (pointer, time++, x, y, width, height);
 	    zwlr_virtual_pointer_v1_frame (pointer);
+	} else if (sscanf (line, "button %u %u", &button, &pressed) == 2) {
+	    zwlr_virtual_pointer_v1_button (
+		pointer, time++, button, pressed ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED
+	    );
+	    zwlr_virtual_pointer_v1_frame (pointer);
 	} else if (strncmp (line, "quit", 4) == 0) {
 	    break;
 	}

+ 3 - 0
tools/headless_render.sh

@@ -23,6 +23,8 @@
 # - The engine is stopped as soon as the screenshot file appears (HEADLESS_RENDER_KEEP_RUNNING=1 disables
 #   that and runs until HEADLESS_RENDER_TIMEOUT, default 60s).
 # - HEADLESS_RENDER_SIZE=WxH changes the window size (default 1920x1080).
+# - The system bus is dead unless HEADLESS_RENDER_SYSTEM_BUS names one (e.g. dbusmock UPower), else the battery
+#   check uses /sys/class/power_supply.
 # - LWE_HEADLESS_CURSOR=x,y puts the GPU path's pointer at that fraction of the output (default 0.5,0.5).
 # - HEADLESS_RENDER_WEB=1 makes web wallpapers work in a container: a private Xvfb (HEADLESS_RENDER_WEB_DISPLAY,
 #   default :96), no Chromium sandbox (LWE_CEF_NO_SANDBOX=1) and libcef.so preloaded into the host
@@ -108,6 +110,7 @@ fi
 ISOLATE=(-u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u KDE_FULL_SESSION -u KDE_SESSION_VERSION
     -u DESKTOP_SESSION -u XDG_CURRENT_DESKTOP -u XDG_SESSION_DESKTOP XDG_RUNTIME_DIR="$RUNTIME_DIR"
     DBUS_SESSION_BUS_ADDRESS="$BUS_ADDRESS"
+    DBUS_SYSTEM_BUS_ADDRESS="${HEADLESS_RENDER_SYSTEM_BUS:-unix:path=/nonexistent-system-bus}"
     PULSE_SERVER="$PULSE" PIPEWIRE_REMOTE=/nonexistent-pipewire)
 if [ -n "$USE_GPU" ]; then
     SESSION=(env -u DISPLAY "${ISOLATE[@]}" XDG_SESSION_TYPE=headless)

+ 105 - 0
tools/linuxvm/fake_github.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""Stands in for api.github.com inside a test VM, for we_manager's update checks and downloads.
+
+    fake_github.py <dir> [--release REPO=TAG:FILE[,FILE...]]... [--port 443]
+
+<dir> gets a CA and a certificate for api.github.com on the first run (ca.pem, cert.pem, key.pem; needs openssl).
+The VM resolves api.github.com to this server (/etc/hosts) and trusts ca.pem, e.g. NODE_EXTRA_CA_CERTS for
+Electron's main process. GET /repos/<REPO>/releases/latest answers with the release given for it (assets with size
+and a sha256 digest like GitHub's, downloaded from this server), every other repo with 404. Requests are logged to
+stdout.
+"""
+import argparse
+import hashlib
+import http.server
+import json
+import ssl
+import subprocess
+import sys
+from pathlib import Path
+
+HOST = "api.github.com"
+
+
+def make_certificate(folder):
+    if (folder / "cert.pem").exists():
+        return
+    folder.mkdir(parents=True, exist_ok=True)
+
+    def openssl(*args):
+        subprocess.run(["openssl", *args], check=True, cwd=folder, capture_output=True)
+
+    openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "30", "-subj", "/CN=fake github test CA",
+            "-keyout", "ca-key.pem", "-out", "ca.pem")
+    openssl("req", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={HOST}", "-keyout", "key.pem", "-out", "cert.csr")
+    (folder / "ext.cnf").write_text(f"subjectAltName=DNS:{HOST}\nextendedKeyUsage=serverAuth\n")
+    openssl("x509", "-req", "-in", "cert.csr", "-CA", "ca.pem", "-CAkey", "ca-key.pem", "-CAcreateserial", "-days", "30",
+            "-extfile", "ext.cnf", "-out", "cert.pem")
+
+
+def release(repo, spec):
+    tag, _, files = spec.partition(":")
+    assets = []
+    for name in filter(None, files.split(",")):
+        path = Path(name).resolve()
+        digest = hashlib.sha256(path.read_bytes()).hexdigest()
+        assets.append({"name": path.name, "size": path.stat().st_size, "digest": f"sha256:{digest}",
+                       "browser_download_url": f"https://{HOST}/download/{tag}/{path.name}", "path": str(path)})
+    return {"tag_name": tag, "html_url": f"https://github.com/{repo}/releases/tag/{tag}", "body": f"Test release {tag}",
+            "published_at": "2026-10-15T12:00:00Z", "assets": assets}
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+    parser.add_argument("dir", type=Path)
+    parser.add_argument("--release", action="append", default=[], metavar="REPO=TAG:FILE[,FILE...]")
+    parser.add_argument("--port", type=int, default=443)
+    args = parser.parse_args()
+    make_certificate(args.dir)
+
+    releases = {}
+    for item in args.release:
+        repo, _, spec = item.partition("=")
+        releases[repo] = release(repo, spec)
+    files = {f"/download/{entry['tag_name']}/{asset['name']}": asset["path"]
+             for entry in releases.values() for asset in entry["assets"]}
+
+    class Handler(http.server.BaseHTTPRequestHandler):
+        def do_GET(self):
+            print(self.command, self.path, flush=True)
+            if self.path in files:
+                data = Path(files[self.path]).read_bytes()
+                self.send_response(200)
+                self.send_header("Content-Type", "application/octet-stream")
+                self.send_header("Content-Length", str(len(data)))
+                self.end_headers()
+                self.wfile.write(data)
+                return
+            parts = self.path.strip("/").split("/")
+            repo = "/".join(parts[1:3])
+            if parts[:1] == ["repos"] and parts[3:] == ["releases", "latest"] and repo in releases:
+                body = json.dumps({**releases[repo], "assets": [
+                    {key: value for key, value in asset.items() if key != "path"} for asset in releases[repo]["assets"]
+                ]}).encode()
+                self.send_response(200)
+            else:
+                body = b'{"message": "Not Found"}'
+                self.send_response(404)
+            self.send_header("Content-Type", "application/json")
+            self.send_header("Content-Length", str(len(body)))
+            self.end_headers()
+            self.wfile.write(body)
+
+        def log_message(self, *args):
+            pass
+
+    server = http.server.ThreadingHTTPServer(("0.0.0.0", args.port), Handler)
+    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+    context.load_cert_chain(args.dir / "cert.pem", args.dir / "key.pem")
+    server.socket = context.wrap_socket(server.socket, server_side=True)
+    print(f"serving {', '.join(releases) or 'no releases'} on port {args.port}", flush=True)
+    server.serve_forever()
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 8 - 3
tools/linuxvm/linuxvm.sh

@@ -4,8 +4,8 @@
 # (uid 1000, password "lab", passwordless sudo), reached over ssh on a localhost port. The guest GPU is virtio-vga-gl
 # with QEMU's egl-headless display on the container's render node (virgl), so nothing ever shows on the desktop's
 # display; screenshots and pointer input go through QMP. No audio device.
-#   fetch                 downloads the cloud images (Fedora 44, Arch)
-#   create <vm> <image>   new VM from images/<image>.qcow2 (fedora-44, arch), 60G overlay
+#   fetch                 downloads the cloud images (Fedora 44, Arch, Ubuntu 24.04)
+#   create <vm> <image>   new VM from images/<image>.qcow2 (fedora-44, arch, ubuntu-24.04), 60G overlay
 #   start <vm>            boots it (LINUXVM_CPUS, LINUXVM_MEM, LINUXVM_SIZE=WxH for the display)
 #   ssh <vm> [cmd]        runs a command as lab (or a shell)
 #   scp <vm> <src> <dst>  copies into the VM (dst relative to /home/lab)
@@ -36,6 +36,8 @@ fetch)
     [ -f fedora-44.qcow2 ] || curl -fLo fedora-44.qcow2 \
         https://download.fedoraproject.org/pub/fedora/linux/releases/44/Cloud/x86_64/images/Fedora-Cloud-Base-Generic-44-1.7.x86_64.qcow2
     [ -f arch.qcow2 ] || curl -fLo arch.qcow2 https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2
+    [ -f ubuntu-24.04.qcow2 ] || curl -fLo ubuntu-24.04.qcow2 \
+        https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img
     cd "$LINUXVM/rpms" && dnf download --arch x86_64 qemu-device-display-virtio-gpu qemu-device-display-virtio-gpu-gl \
         qemu-device-display-virtio-gpu-pci qemu-device-display-virtio-gpu-pci-gl qemu-device-display-virtio-vga \
         qemu-device-display-virtio-vga-gl qemu-ui-egl-headless qemu-ui-opengl virglrenderer
@@ -53,6 +55,9 @@ create)
     p=2250
     while echo "$used" | grep -qx $p; do p=$((p + 1)); done
     echo $p > "$dir/port"
+    # Ubuntu has no wheel group
+    admin=wheel
+    case $3 in ubuntu*) admin=sudo ;; esac
     cat > "$dir/seed/meta-data" <<EOF
 instance-id: $vm
 local-hostname: $vm
@@ -62,7 +67,7 @@ EOF
 users:
   - name: lab
     uid: "1000"
-    groups: [wheel, video, render, input]
+    groups: [$admin, video, render, input]
     shell: /bin/bash
     sudo: ALL=(ALL) NOPASSWD:ALL
     lock_passwd: false

+ 3 - 2
tools/package_release.sh

@@ -67,8 +67,7 @@ if [ "$portable" = 1 ]; then
         'libBrokenLocale' 'libnsl' 'libstdc\+\+' 'libgcc_s'
         # GPU, display servers, input
         'libGL' 'libGLX' 'libGLdispatch' 'libOpenGL' 'libEGL' 'libGLESv1_CM' 'libGLESv2' 'libgbm' 'libdrm.*'
-        # libva: an older bundled one can't load newer drivers
-        'libvulkan' 'libva' 'libva-(drm|x11|wayland)' 'libwayland-.*' 'libX11' 'libX11-xcb' 'libXau'
+        'libvulkan' 'libwayland-.*' 'libX11' 'libX11-xcb' 'libXau'
         'libXdmcp' 'libXext' 'libXrender' 'libXfixes' 'libXrandr' 'libXi' 'libXcursor' 'libXinerama' 'libXdamage'
         'libXcomposite' 'libXxf86vm' 'libxkbcommon.*' 'libxshmfence' 'libSM' 'libICE' 'libudev' 'libinput'
         'libevdev'
@@ -90,6 +89,8 @@ if [ "$portable" = 1 ]; then
         'libgpg-error' 'libssl' 'libcrypto' 'libbrotli(common|dec|enc)' 'liblzma' 'libzstd' 'liblz4' 'libbz2'
         'libexpat' 'libpng16' 'libfreetype' 'libfontconfig' 'libharfbuzz' 'libgraphite2' 'libfribidi' 'libxml2'
         'libkrb5.*' 'libk5crypto' 'libcom_err' 'libgssapi_krb5' 'libkeyutils'
+        # a bundled libva can't load newer system drivers; Ubuntu minimal may lack libva, but then has no drivers either
+        'libva' 'libva-(drm|x11|wayland)'
     )
     fallback_re="^($(IFS='|'; echo "${fallback_libs[*]}"))\.so(\..*)?$"
 

+ 49 - 3
tools/wecompare/README.md

@@ -95,6 +95,51 @@ Data locations (all overridable):
 - `repack_pkg.py in.pkg out.pkg name=file ...` - replaces files inside a scene.pkg (test variants of scenes
   whose texture names Wine can't open in folder mode).
 
+## Proton
+
+`wine/proton.sh` installs Proton builds next to the system Wine and gives every WE script a third backend:
+`WE_PROTON=<name>` on `render_we.py` (frames go to `$WE_LIVE_DIR/refs_proton/<name>`), `we_full.sh`, `we_cursor.sh`,
+`we_capture.sh`, `we_resize.sh`, `we_span.sh` and `sharedvideo/run.sh`; `eval "$(wine/proton.sh env <name>)"` sets
+`WE_WINE_DIR`/`WE_PREFIX` for anything else (e.g. the `videotex` kit's `we_video.sh`).
+
+    wine/proton.sh available                       # GE-Proton and proton-cachyos releases, Valve branches
+    wine/proton.sh install GE-Proton11-9           # GitHub tarball, sha512 checked, into ~/.local/share/proton
+    wine/proton.sh install proton-experimental     # Valve, from Steam's CDN
+    WE_PROTON=GE-Proton11-9 ./render_we.py 1367456719
+
+- The shim (`$PROTON_DIR/<name>/shim/bin/wine`) runs Proton's own `run` path through `proton_run.py`, which only
+  swaps the last step (starting the program through steam.exe) for a plain `wine <program>`. `runinprefix` is not
+  enough: Proton adds its DXVK/vkd3d-proton dll overrides in the prefix setup that only `run` does, so WE silently
+  ran on wined3d. Valve's steam.exe also asserts without a Steam client. Each prefix is
+  `$WE_LIVE_DIR/proton/<name>/pfx`, `SteamAppId` is 431960, xalia is off. Check `wallpaper64_d3d11.log` in
+  `$WE_LIVE_DIR` for the DXVK version Proton brought (GE 11-9: 3.1.1-75).
+- No Steam Linux Runtime container: pressure-vessel needs user namespaces, which Docker doesn't give, so Proton runs on
+  the image's libraries (the Mesa/RADV a Steam user's container imports anyway). Proton's wine starts every program
+  through the i386 preloader, so the image needs `glibc.i686` and the 32-bit libraries in the Dockerfile; without them
+  `wine/proton.sh i686` unpacks a private glibc and the shim runs Proton under proot (slower, no timing work).
+- Valve builds come from Steam with DepotDownloader (`wine/proton_valve.sh`, tools in `~/.local/share/proton/tools`).
+  Anonymous logins only get Proton Experimental, `STEAM_USER=<account>` the numbered branches (asks for the password
+  and Steam Guard code, run it in a terminal). DepotDownloader writes symlinks as empty files and leaves their targets
+  encrypted, `steam_manifest_links.py` restores them (1896 in Experimental) with the depot key, plus the executable bits
+  and `steampipe_fixups.json`. steamcmd refuses anonymous Proton downloads ("No subscription").
+
+Compared with system Wine 11.0 + DXVK 3.1.1 (2026-10-15, GE-Proton11-9, proton-cachyos 11.0-20261005, Valve
+experimental-11.0-20261008):
+
+| case | Wine 11.0 | GE | CachyOS | Valve experimental |
+|---|---|---|---|---|
+| scenes (1111948150, 2488408736) | ok | same frames | same | same |
+| `systemfont_*` texts (2431040693's clock) | not drawn | drawn | drawn | drawn |
+| video wallpaper (1367456719) | black | plays | black | Proton's color bar placeholder |
+| video textures in scenes (`tests/videotex`) | one pass, then cleared | WE crashes | WE crashes | WE crashes |
+| web wallpapers | white page | Chromium browser window | same | same |
+
+Video textures: under every Proton build the source resolver hands WE's wrapper media source a null inner source
+("Unimplemented flags 0x11", Valve: "Unsupported demuxer"), and WE dereferences it in
+`CreatePresentationDescriptor` (`sub_1400F1780`, crash at `wallpaper64.exe+0xF178D`); `PROTON_MEDIA_FORCE_GST=1`
+(CachyOS) doesn't change it. `media_engine_SetLoop` is a stub in all of them too, so the loop seam still needs the
+Windows VM. So: GE-Proton for video wallpapers and texts with system fonts, plain Wine for video textures.
+
 ## Windows VM (`winvm/`)
 
 For what only real Windows shows (Media Foundation's video loop, anything Wine emulates instead of running). Needs
@@ -157,8 +202,9 @@ cp wine/rd_trigger.py $WE_LIVE_DIR/`, and `cp wine/qrenderdoc_analytics.json ~/.
 - Scores are only a triage hint: scroll/shake/particles, wall-clock texts and heavily downscaled 8K scenes score
   high while matching. Check `frames.py` before calling something different.
 - Web wallpapers can't be compared (WE's CEF under Wine renders a white page, this engine renders black
-  headless). The video wallpaper type is black in WE under Wine (video textures inside scenes do play), use the
-  Windows VM.
-- Texts using `systemfont_*` aren't drawn by WE under Wine (the prefix has no Windows fonts).
+  headless). The video wallpaper type is black in WE under Wine (video textures inside scenes do play), use
+  `WE_PROTON=GE-Proton11-9` (see Proton) or the Windows VM.
+- Texts using `systemfont_*` aren't drawn by WE under Wine (the prefix has no Windows fonts); Proton prefixes have
+  its font set and draw them.
 - Folder scenes with CJK texture names fail to load textures in WE under Wine: pass scene.pkg (or repack).
 - Crop: WE window = `[30:1080, 4:1920]` of the :98 screen, ours `[0:1050, 0:1916]`.

+ 14 - 2
tools/wecompare/render_we.py

@@ -10,6 +10,8 @@ isn't a flat colour any more (the first rendered frame), then SETTLE seconds, th
 seconds apart (env overrides). -control openWallpaper sent to a running instance doesn't switch wallpapers under
 Wine (it only brings the UI window back), hence one instance per item.
 Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
+WE_PROTON=<name> runs an installed Proton build (wine/proton.sh) with frames in $WE_LIVE_DIR/refs_proton/<name>,
+WE_WINE_DIR/WE_PREFIX another Wine build like the wine/ scripts.
 """
 import os, shutil, subprocess, sys, time
 import resource
@@ -22,7 +24,14 @@ S = os.environ.get('WE_LIVE_DIR', os.path.expanduser('~/.local/share/we_live'))
 HERE = os.path.dirname(os.path.abspath(__file__)) + '/wine'
 W = os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960')
 LIB = os.environ.get('LWE_LIBRARY_DIR', os.path.expanduser('~/.local/share/lwe-library'))
-REFS = os.environ.get('REFS', S + '/refs')
+PROTON = os.environ.get('WE_PROTON')
+if PROTON:
+    out = subprocess.run(['bash', HERE + '/proton.sh', 'env', PROTON], capture_output=True, text=True)
+    if out.returncode:
+        sys.exit(out.stdout + out.stderr)
+    for k, v in (kv.split('=', 1) for kv in out.stdout.split()[1:]):
+        os.environ[k] = v
+REFS = os.environ.get('REFS', S + ('/refs_proton/' + PROTON if PROTON else '/refs'))
 D = ':98'
 FRAMES = int(os.environ.get('FRAMES', 5))
 INTERVAL = float(os.environ.get('INTERVAL', 1.0))
@@ -32,11 +41,14 @@ RETRIES = int(os.environ.get('RETRIES', 3))
 
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 env = {k: v for k, v in os.environ.items() if k not in ('WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'DBUS_SESSION_BUS_ADDRESS')}
-env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=S + '/wineprefix', DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
+env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=os.environ.get('WE_PREFIX', S + '/wineprefix'), DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
            PULSE_SERVER=f'unix:{S}/run/no-pulse', PIPEWIRE_REMOTE=f'{S}/run/no-pipewire', ALSA_CONFIG_PATH=S + '/run/asound-null.conf')
 # Debian keeps the 64-bit loader out of PATH, Fedora's wine is the wow64 build
 WINE = '/usr/lib/wine/wine64' if os.path.exists('/usr/lib/wine/wine64') else shutil.which('wine')
 WINESERVER = '/usr/lib/wine/wineserver' if os.path.exists('/usr/lib/wine/wineserver') else shutil.which('wineserver')
+if os.environ.get('WE_WINE_DIR'):
+    WINE = os.environ['WE_WINE_DIR'] + '/bin/wine'
+    WINESERVER = os.environ['WE_WINE_DIR'] + '/bin/wineserver'
 we_proc = None
 log = None
 

+ 131 - 0
tools/wecompare/wine/proton.sh

@@ -0,0 +1,131 @@
+#!/bin/bash
+# Proton builds for live WE, next to the system Wine rig (README "Proton")
+#   proton.sh available [ge|cachyos|valve]   releases that can be installed
+#   proton.sh install <name>                 GE-Proton11-9, cachyos-11.0-20261005-slr, proton-experimental (Valve)
+#   proton.sh list                           installed builds
+#   proton.sh env <name>                     WE_WINE_DIR/WE_PREFIX for the we_*.sh scripts (also WE_PROTON=<name>)
+#   proton.sh remove <name>
+#   proton.sh i686                           private i686 glibc for images without /lib/ld-linux.so.2 (see below)
+# Each build gets a shim dir ($PROTON_DIR/<name>/shim/bin/wine, wineserver): wine goes through Proton's `run`
+# (proton_run.py), so WE sees the environment and prefix setup (DXVK, vkd3d-proton, fonts, wine-mono) Steam would
+# give it, minus the Steam Linux Runtime container (no user namespaces here, host libraries are used).
+# The prefix is $WE_LIVE_DIR/proton/<name>/pfx, created on the first wine call. Setup output and Proton's own
+# messages go to the caller's stderr like Wine's.
+# Proton's wine always starts through the i386 preloader (also for 64-bit programs), which needs the 32-bit
+# /lib/ld-linux.so.2. The image has glibc.i686 for that; without it the shim runs Proton under proot with a private
+# copy bound there (`proton.sh i686` fetches it, ptrace overhead, so timings are off).
+S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
+HERE=$(cd "$(dirname "$0")" && pwd)
+P=${PROTON_DIR:-$HOME/.local/share/proton}
+mkdir -p "$P/dl"
+
+gh_releases() {
+    curl -fsSL "https://api.github.com/repos/$1/releases?per_page=${2:-15}"
+}
+
+shim() {
+    local name=$1 root=$P/$1
+    mkdir -p "$root/shim/bin" "$P/steam"
+    cat > "$root/shim/bin/wine" <<SH
+#!/bin/bash
+# WINEPREFIX=<compat dir>/pfx as the we_*.sh scripts set it from WE_PREFIX
+export STEAM_COMPAT_DATA_PATH=\${WINEPREFIX%/pfx} STEAM_COMPAT_CLIENT_INSTALL_PATH=$P/steam
+export SteamAppId=\${SteamAppId:-431960} SteamGameId=\${SteamGameId:-431960}
+mkdir -p "\$STEAM_COMPAT_DATA_PATH"
+# the image's global d3d overrides would hide Proton's own; WE_WINED3D=1 sets dxgi=b, Proton's wined3d switch
+case "\$WINEDLLOVERRIDES" in *dxgi=b*) export PROTON_USE_WINED3D=1 ;; esac
+unset WINEDLLOVERRIDES
+# xalia (gamepad UI navigation, a mono process per prefix) has nothing to do with rendering
+export PROTON_USE_XALIA=\${PROTON_USE_XALIA:-0}
+run=()
+if [ ! -e /lib/ld-linux.so.2 ]; then
+    [ -e "$P/i686/root/usr/lib/ld-linux.so.2" ] || { echo "no /lib/ld-linux.so.2, run proton.sh i686" >&2; exit 1; }
+    export LD_LIBRARY_PATH=\${LD_LIBRARY_PATH:+\$LD_LIBRARY_PATH:}$P/i686/root/usr/lib
+    run=(proot -b "$P/i686/root/usr/lib/ld-linux.so.2:/lib/ld-linux.so.2")
+fi
+# Proton's "run" path (prefix setup, DXVK overrides) with the program started directly, see proton_run.py
+exec "\${run[@]}" python3 "$HERE/proton_run.py" "$root/proton" "\$@"
+SH
+    cat > "$root/shim/bin/wineserver" <<SH
+#!/bin/bash
+exec "$root/files/bin/wineserver" "\$@"
+SH
+    chmod +x "$root/shim/bin/wine" "$root/shim/bin/wineserver"
+}
+
+case $1 in
+available)
+    case ${2:-all} in ge|all)
+        echo "# GE-Proton (GloriousEggroll/proton-ge-custom)"
+        gh_releases GloriousEggroll/proton-ge-custom | python3 -c '
+import json, sys
+for r in json.load(sys.stdin):
+    if any(a["name"].endswith("x86_64.tar.gz") for a in r["assets"]): print(r["tag_name"], r["published_at"][:10])'
+    esac
+    case ${2:-all} in cachyos|all)
+        echo "# proton-cachyos (CachyOS/proton-cachyos)"
+        gh_releases CachyOS/proton-cachyos | python3 -c '
+import json, sys
+for r in json.load(sys.stdin):
+    if any(a["name"].endswith("-x86_64.tar.xz") for a in r["assets"]): print(r["tag_name"], r["published_at"][:10])'
+    esac
+    case ${2:-all} in valve|all)
+        echo "# Valve Proton (current build of each branch, all but experimental need STEAM_USER)"
+        printf '%s\n' proton-experimental proton-11 proton-10 proton-9 proton-8 proton-7 proton-hotfix
+    esac
+    ;;
+install)
+    name=$2; [ -n "$name" ] || { echo "usage: proton.sh install <name>"; exit 1; }
+    [ -x "$P/$name/proton" ] && { shim "$name"; echo "$name already installed"; exit 0; }
+    case $name in
+    GE-Proton*)
+        base=https://github.com/GloriousEggroll/proton-ge-custom/releases/download/$name
+        file=$name-x86_64.tar.gz; sum=$name-x86_64.sha512sum
+        ;;
+    cachyos-*)
+        base=https://github.com/CachyOS/proton-cachyos/releases/download/$name
+        file=proton-$name-x86_64.tar.xz; sum=proton-$name-x86_64.sha512sum
+        ;;
+    proton-*)
+        exec bash "$(dirname "$0")/proton_valve.sh" "$name"
+        ;;
+    *) echo "unknown build $name (see proton.sh available)"; exit 1 ;;
+    esac
+    cd "$P/dl" || exit 1
+    curl -fL --progress-bar -o "$file" "$base/$file" && curl -fsSL -o "$sum" "$base/$sum" || exit 1
+    sha512sum -c "$sum" || exit 1
+    tmp=$(mktemp -d "$P/dl/x.XXXX")
+    tar -xf "$file" -C "$tmp" || exit 1
+    top=$(ls "$tmp"); [ "$(echo "$top" | wc -l)" = 1 ] || { echo "unexpected archive layout"; exit 1; }
+    mv "$tmp/$top" "$P/$name" && rmdir "$tmp" && rm -f "$file"
+    shim "$name"
+    echo "installed $P/$name ($(cat "$P/$name/version"))"
+    ;;
+list)
+    for d in "$P"/*/; do
+        [ -x "$d/proton" ] || continue
+        n=$(basename "$d"); printf '%-36s %s' "$n" "$(cut -d' ' -f2- "$d/version" 2>/dev/null)"
+        [ -d "$S/proton/$n/pfx" ] && printf '  (prefix)'
+        echo
+    done
+    ;;
+env)
+    name=$2; [ -x "$P/$name/proton" ] || { echo "echo 'proton.sh: $name is not installed' >&2; exit 1"; exit 1; }
+    [ -x "$P/$name/shim/bin/wine" ] || shim "$name"
+    echo "export WE_WINE_DIR=$P/$name/shim WE_PREFIX=$S/proton/$name/pfx"
+    ;;
+i686)
+    mkdir -p "$P/i686/rpms" "$P/i686/root" && cd "$P/i686/rpms" || exit 1
+    dnf download --setopt=cachedir="$P/i686/dnfcache" --arch=i686 glibc libgcc libstdc++ || exit 1
+    cd "$P/i686/root" && for r in "$P"/i686/rpms/*.rpm; do rpm2cpio "$r" | cpio -idm --quiet; done
+    rm -rf "$P/i686/dnfcache"
+    ;;
+remove)
+    name=$2; [ -n "$name" ] && [ -d "$P/$name" ] || { echo "not installed"; exit 1; }
+    rm -rf "${P:?}/$name" "${S:?}/proton/$name"
+    ;;
+*)
+    sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//'
+    exit 1
+    ;;
+esac

+ 36 - 0
tools/wecompare/wine/proton_run.py

@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Runs a program the way Steam's `proton run` does, minus steam.exe: the prefix setup and the per-run environment
+(DXVK/vkd3d-proton dll overrides, fonts, protonfixes) all come from Proton's own `run` path, only its last step,
+starting the program through steam.exe, becomes `wine <args>`. `runinprefix` is no substitute, it skips the setup
+and with it the d3d11/dxgi=n overrides, so WE ends up on wined3d. Valve's steam.exe also asserts without a running
+Steam client (GE's only warns), the dialog blocks the run.
+
+    proton_run.py <proton script> <program> [args...]     with STEAM_COMPAT_DATA_PATH etc. set like for proton
+"""
+import os, sys, textwrap
+
+path = sys.argv[1]
+args = sys.argv[2:]
+src = open(path).read()
+head, sep, body = src.partition('\nif __name__ == "__main__":\n')
+if not sep:
+    sys.exit('%s: no main block' % path)
+# the script imports filelock, protonfixes etc. from its own folder
+sys.path.insert(0, os.path.dirname(os.path.abspath(path)))
+g = {'__name__': 'proton', '__file__': path}
+sys.argv = [path, 'run'] + args
+exec(compile(head, path, 'exec'), g)
+
+
+def run(self):
+    return self.run_proc([g['g_proton'].wine_bin] + args)
+
+
+g['Session'].run = run
+# the block ends at the first unindented line (the file ends with pylint/vim comments)
+lines = []
+for line in body.splitlines(True):
+    if line.strip() and not line[0].isspace():
+        break
+    lines.append(line)
+exec(compile(textwrap.dedent(''.join(lines)), path, 'exec'), g)

+ 54 - 0
tools/wecompare/wine/proton_valve.sh

@@ -0,0 +1,54 @@
+#!/bin/bash
+# usage: proton_valve.sh <proton-experimental|proton-11|proton-10|proton-9|proton-8|proton-7|proton-hotfix>
+# Valve's Proton builds from Steam's CDN, the current build of that branch into $PROTON_DIR/<name> (run again to
+# update). Files come from DepotDownloader, which writes symlinks as empty files and keeps their targets encrypted,
+# so steam_manifest_links.py fixes them up with the depot key (from the python steam package in a venv).
+# Only Proton Experimental is served to anonymous logins (steamcmd refuses even that one: "No subscription");
+# the others need STEAM_USER=<account>, which asks for the password / Steam Guard code (run it in a terminal).
+HERE=$(cd "$(dirname "$0")" && pwd)
+P=${PROTON_DIR:-$HOME/.local/share/proton}
+DDV=3.4.0
+DD=$P/tools/depotdownloader/DepotDownloader
+PY=$P/tools/steampy/bin/python
+case $1 in
+proton-experimental) app=1493710 ;;
+proton-11) app=4628710 ;;
+proton-10) app=3658110 ;;
+proton-9) app=2805730 ;;
+proton-8) app=2348590 ;;
+proton-7) app=1887720 ;;
+proton-hotfix) app=2180100 ;;
+*) echo "unknown Valve build $1"; exit 1 ;;
+esac
+# the main depot is app id + 1, the others are optional contrib dlls
+depot=$((app + 1))
+if [ ! -x "$DD" ]; then
+    mkdir -p "$P/tools/depotdownloader" && cd "$P/tools/depotdownloader" || exit 1
+    curl -fsSLO "https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_$DDV/DepotDownloader-linux-x64.zip" || exit 1
+    unzip -oq DepotDownloader-linux-x64.zip && chmod +x DepotDownloader && rm DepotDownloader-linux-x64.zip
+fi
+if [ ! -x "$PY" ]; then
+    # gevent in the steam package doesn't build on 3.14 yet
+    python3.13 -m venv "$P/tools/steampy" && "$P/tools/steampy/bin/pip" -q install "steam[client]" || exit 1
+fi
+login=()
+[ -n "$STEAM_USER" ] && login=(-username "$STEAM_USER" -remember-password)
+cd "$P/tools/depotdownloader" || exit 1
+"$DD" -app $app -depot $depot -dir "$P/$1" -validate "${login[@]}" || exit 1
+key=$("$PY" -I - $app $depot "$STEAM_USER" <<'PY'
+import sys
+from steam.client import SteamClient
+app, depot, user = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
+c = SteamClient()
+if (c.cli_login(user) if user else c.anonymous_login()) != 1:
+    sys.exit('steam login failed')
+r = c.get_depot_key(app, depot)
+if r.eresult != 1:
+    sys.exit('no depot key (eresult %d)' % r.eresult)
+print(r.depot_encryption_key.hex())
+PY
+) || exit 1
+"$PY" -I "$HERE/steam_manifest_links.py" "$P/$1" "$key" || exit 1
+[ -x "$P/$1/proton" ] || { echo "no proton script in $P/$1"; exit 1; }
+bash "$HERE/proton.sh" env "$1" >/dev/null
+echo "installed $P/$1 ($(cat "$P/$1/version"))"

+ 2 - 0
tools/wecompare/wine/sharedvideo/run.sh

@@ -4,6 +4,8 @@
 ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 HERE=$(cd "$(dirname "$0")" && pwd)
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$HERE/../proton.sh" env "$WE_PROTON")" || exit 1; }
 OUT=${SV_OUT:-$S/sharedvideo}
 mkdir -p "$OUT"
 CXX=${MINGW_CXX:-$HOME/.local/share/mingw-root/usr/bin/x86_64-w64-mingw32-g++}

+ 89 - 0
tools/wecompare/wine/steam_manifest_links.py

@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Restores what DepotDownloader leaves out of a Steam depot: symlinks (written as empty files), the executable bit
+Steam gives every file on Linux, and steampipe_fixups.json (empty dirs, read-only files) when the depot has one.
+
+    steam_manifest_links.py <install dir> [depot key hex]     reads <install dir>/.DepotDownloader/*.manifest
+
+Link targets stay encrypted in the saved manifest (only file names get decrypted), the depot key decrypts them
+(Steam's symmetric scheme: AES-256-ECB encrypted IV, then AES-256-CBC). Needs pycryptodomex for that (the
+steam package's venv has it).
+"""
+import base64, glob, os, stat, struct, subprocess, sys
+
+PAYLOAD_MAGIC = 0x71F617D0
+FLAG_SYMLINK = 0x200
+FLAG_DIRECTORY = 0x40
+
+
+def varint(b, i):
+    v = s = 0
+    while True:
+        c = b[i]; i += 1
+        v |= (c & 0x7f) << s; s += 7
+        if c < 0x80:
+            return v, i
+
+
+def fields(b):
+    i = 0
+    while i < len(b):
+        key, i = varint(b, i)
+        num, wt = key >> 3, key & 7
+        if wt == 0:
+            v, i = varint(b, i)
+        elif wt == 2:
+            n, i = varint(b, i)
+            v = b[i:i + n]; i += n
+        elif wt == 1:
+            v = b[i:i + 8]; i += 8
+        elif wt == 5:
+            v = b[i:i + 4]; i += 4
+        else:
+            raise ValueError('wire type %d' % wt)
+        yield num, v
+
+
+def mappings(path):
+    data = open(path, 'rb').read()
+    magic, n = struct.unpack_from('<II', data, 0)
+    if magic != PAYLOAD_MAGIC:
+        sys.exit('%s: not a Steam manifest payload' % path)
+    for num, m in fields(data[8:8 + n]):
+        if num != 1:
+            continue
+        f = dict(fields(m))
+        yield f.get(1, b'').decode().replace('\\', '/'), f.get(3, 0), f.get(7, b'').decode()
+
+
+def decrypt(target, key):
+    from Cryptodome.Cipher import AES
+    from Cryptodome.Util.Padding import unpad
+    raw = base64.b64decode(target)
+    iv = AES.new(key, AES.MODE_ECB).decrypt(raw[:16])
+    return unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(raw[16:]), 16).rstrip(b'\0').decode()
+
+
+root = sys.argv[1]
+key = bytes.fromhex(sys.argv[2]) if len(sys.argv) > 2 else None
+links = 0
+for man in glob.glob(os.path.join(root, '.DepotDownloader', '*.manifest')):
+    for name, flags, target in mappings(man):
+        p = os.path.join(root, name)
+        if flags & FLAG_SYMLINK and target:
+            if key:
+                target = decrypt(target, key)
+            if os.path.islink(p) or (os.path.isfile(p) and os.path.getsize(p) == 0):
+                os.remove(p)
+            if not os.path.lexists(p):
+                os.makedirs(os.path.dirname(p), exist_ok=True)
+                os.symlink(target, p)
+                links += 1
+for d, _, files in os.walk(root):
+    for f in files:
+        p = os.path.join(d, f)
+        if not os.path.islink(p):
+            os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+fix = os.path.join(root, 'steampipe_fixups.py')
+if os.path.exists(fix):
+    subprocess.run([sys.executable, '-I', fix, 'restore', root], check=True)
+print('%d symlinks restored' % links)

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

@@ -7,6 +7,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
 WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
 WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=:98 WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S

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

@@ -7,6 +7,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=:98
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
 WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
 WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S

+ 2 - 0
tools/wecompare/wine/we_full.sh

@@ -13,6 +13,8 @@ S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=${WE_DISPLAY:-:98}
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }
 # WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
 WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; [ -x /usr/lib/wine/wine64 ] && SYS_WINE=/usr/lib/wine/wine64 || SYS_WINE=$(command -v wine); WINE=${WINE:-$SYS_WINE}
 WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; [ -x /usr/lib/wine/wineserver ] && SYS_WINESERVER=/usr/lib/wine/wineserver || SYS_WINESERVER=$(command -v wineserver); WINESERVER=${WINESERVER:-$SYS_WINESERVER}
 export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S

+ 2 - 0
tools/wecompare/wine/we_resize.sh

@@ -13,6 +13,8 @@ MINGW=${MINGW_CC:-$(command -v x86_64-w64-mingw32-gcc || echo $HOME/.local/share
 bash "$HERE/span_display.sh" start 2560x1440+0+0 >/dev/null || exit 1
 eval "$(bash "$HERE/span_display.sh" env)"
 X=$DISPLAY WL=$WAYLAND_DISPLAY WLR=$XDG_RUNTIME_DIR
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
 WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-$(command -v wine)}
 WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-$(command -v wineserver)}
 export WINEPREFIX=${WE_PREFIX:-$P/wineprefix} DISPLAY=$X WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$P

+ 2 - 0
tools/wecompare/wine/we_span.sh

@@ -16,6 +16,8 @@ MONITORS=${WE_SPAN_MONITORS:-1920x1080+0+0 1280x1024+2120+200}
 bash "$HERE/span_display.sh" start $MONITORS >/dev/null || exit 1
 eval "$(bash "$HERE/span_display.sh" env)"
 X=$DISPLAY WL=$WAYLAND_DISPLAY WLR=$XDG_RUNTIME_DIR
+# WE_PROTON=<name> picks an installed Proton build (proton.sh) instead
+[ -n "$WE_PROTON" ] && { eval "$(bash "$(dirname "$0")/proton.sh" env "$WE_PROTON")" || exit 1; }
 WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-$(command -v wine)}
 WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-$(command -v wineserver)}
 export WINEPREFIX=${WE_PREFIX:-$P/wineprefix} DISPLAY=$X WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$P