Jelajahi Sumber

Pause on session lock and blanked display, session bus quota hardening, --render-scale, CEF 156, hotswap memory fix, audio bars idle fix, Tracy profiling zones and shader translation cache

SessionMonitor pauses the wallpaper while logind's LockedHint or a screen saver reports locked, and while DPMS or Mutter's PowerSaveMode blanks the display (--no-lock-pause, live toggle through hotswap). The cursor script is unloaded while paused, unread D-Bus and MPRIS messages are drained, and the session bus connection is private so a dropped bus no longer ends the process. New --render-scale draws an output below native size behind wp_viewporter. CEF 146 -> 156. glibc allocator tuning stops hotswap growth. PulseAudio and PipeWire silence no longer leaves a residue that makes spectrum bars climb. The compat rewrites are cached on disk, keyed by a hash of the shader sources. Optional Tracy zones (LWE_TRACY). Fixes the tests target missing LWE_SHADER_CACHE_ID and a V550 float compare.
UwU 1 bulan lalu
induk
melakukan
22bbf8937d
65 mengubah file dengan 2354 tambahan dan 228 penghapusan
  1. 1 1
      .github/workflows/aur.yml
  2. 3 3
      .github/workflows/cmake.yml
  3. 48 2
      CMakeLists.txt
  4. 7 1
      README.md
  5. 2 2
      nix/package.nix
  6. 1 1
      src/External/Catch2
  7. 1 1
      src/External/json
  8. 1 1
      src/External/kissfft
  9. 1 1
      src/External/msdfgen
  10. 1 1
      src/External/stb
  11. 46 0
      src/WallpaperEngine/Application/ApplicationContext.cpp
  12. 4 0
      src/WallpaperEngine/Application/ApplicationContext.h
  13. 83 14
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  14. 7 0
      src/WallpaperEngine/Application/WallpaperApplication.h
  15. 67 1
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  16. 16 0
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  17. 5 1
      src/WallpaperEngine/Data/Parsers/ProjectParser.cpp
  18. 31 0
      src/WallpaperEngine/Debugging/Profiling.h
  19. 5 0
      src/WallpaperEngine/Desktop/KWinScript.cpp
  20. 6 39
      src/WallpaperEngine/Desktop/PowerMonitor.cpp
  21. 46 1
      src/WallpaperEngine/Desktop/SessionBus.cpp
  22. 14 0
      src/WallpaperEngine/Desktop/SessionBus.h
  23. 484 0
      src/WallpaperEngine/Desktop/SessionMonitor.cpp
  24. 39 0
      src/WallpaperEngine/Desktop/SessionMonitor.h
  25. 155 11
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  26. 13 1
      src/WallpaperEngine/Input/Drivers/KDECursorInput.h
  27. 21 0
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  28. 2 0
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  29. 4 0
      src/WallpaperEngine/Input/InputContext.cpp
  30. 2 0
      src/WallpaperEngine/Input/InputContext.h
  31. 2 0
      src/WallpaperEngine/Input/MouseInput.h
  32. 190 13
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  33. 26 1
      src/WallpaperEngine/Media/DBusMediaSource.h
  34. 3 0
      src/WallpaperEngine/Media/MediaSource.h
  35. 106 89
      src/WallpaperEngine/Render/CTexture.cpp
  36. 5 1
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  37. 30 4
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  38. 2 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  39. 45 12
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  40. 3 0
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  41. 31 2
      src/WallpaperEngine/Render/RenderContext.cpp
  42. 1 0
      src/WallpaperEngine/Render/RenderContext.h
  43. 22 8
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  44. 20 0
      src/WallpaperEngine/Render/Shaders/ShaderCache.cpp
  45. 3 0
      src/WallpaperEngine/Render/Shaders/ShaderCache.h
  46. 32 11
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  47. 7 1
      src/WallpaperEngine/Render/TextureCache.cpp
  48. 15 3
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  49. 2 0
      src/WallpaperEngine/Render/Wallpapers/CVideo.cpp
  50. 4 0
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  51. 2 0
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  52. 1 1
      src/WallpaperEngine/WebBrowser/CEF/BrowserApp.cpp
  53. 37 0
      src/main.cpp
  54. 25 0
      tests/desktops/test_fractional_scale.py
  55. 123 0
      tests/desktops/test_kde.py
  56. 155 0
      tests/desktops/test_lock_pause.py
  57. 21 0
      tools/dbus_quota_watch.sh
  58. 27 0
      tools/desktops/mpris_flood.py
  59. 37 0
      tools/desktops/screen_saver_owner.py
  60. 12 0
      tools/linuxvm/RELEASE_TESTING.md
  61. 40 0
      tools/linuxvm/guest_test.sh
  62. 63 0
      tools/nocore.c
  63. 42 0
      tools/runtime_analysis.py
  64. 51 0
      tools/tracy_profile.sh
  65. 53 0
      tools/tracy_summary.py

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

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

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

@@ -164,7 +164,7 @@ jobs:
 
       - name: Restore ccache
         if: steps.prebuilt.outputs.hit != 'true'
-        uses: actions/cache/restore@v4
+        uses: actions/cache/restore@v6
         with:
           path: /tmp/libnode-ccache
           key: libnode-ccache-${{ steps.libnode.outputs.version }}
@@ -183,7 +183,7 @@ jobs:
       # saved right away, a later failure in this run must not throw the build away
       - name: Save ccache
         if: steps.prebuilt.outputs.hit != 'true'
-        uses: actions/cache/save@v4
+        uses: actions/cache/save@v6
         with:
           path: /tmp/libnode-ccache
           key: libnode-ccache-${{ steps.libnode.outputs.version }}
@@ -410,7 +410,7 @@ jobs:
 
       - name: Publish linux-wallpaperengine-kde-bin to the AUR
         if: env.HAS_AUR_KEY == 'true'
-        uses: KSXGitHub/github-actions-deploy-aur@2ac5a4c1d7035885d46b10e3193393be8460b6f1 # v4.1.1
+        uses: KSXGitHub/github-actions-deploy-aur@084b0d9b15415bf9cdb65d44dad1efe37a354050 # v4.2.0
         with:
           pkgname: linux-wallpaperengine-kde-bin
           pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD

+ 48 - 2
CMakeLists.txt

@@ -35,6 +35,29 @@ if(LWE_SANITIZE)
     set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=${lwe_sanitize_list}")
 endif()
 
+option(LWE_TRACY "Build with Tracy profiler zones on the render loop (off by default, connect tracy-profiler or tracy-capture)" OFF)
+option(LWE_TRACY_ON_DEMAND "Tracy only records once a profiler is connected (off: startup and loading are recorded too, which tools/tracy_profile.sh needs for the loader zones)" ON)
+set(LWE_TRACY_DIR "" CACHE PATH "A Tracy 0.14.1 source tree to use instead of downloading it")
+if(LWE_TRACY)
+    if(NOT LWE_TRACY_DIR)
+        include(FetchContent)
+        FetchContent_Declare(tracy
+            URL https://github.com/wolfpld/tracy/archive/refs/tags/v0.14.1.tar.gz
+            URL_HASH SHA256=bf4af567e9c7524d07f3caa745fad02fb33bd5694f11910750382d1efbb251c1)
+        FetchContent_Populate(tracy)
+        set(LWE_TRACY_DIR ${tracy_SOURCE_DIR})
+    endif()
+    # TracyClient.cpp alone is the whole client, the library it ends up in is a shared one so it needs PIC
+    add_library(tracy-client STATIC ${LWE_TRACY_DIR}/public/TracyClient.cpp)
+    target_include_directories(tracy-client SYSTEM PUBLIC ${LWE_TRACY_DIR}/public)
+    target_compile_definitions(tracy-client PUBLIC LWE_TRACY TRACY_ENABLE)
+    if(LWE_TRACY_ON_DEMAND)
+        target_compile_definitions(tracy-client PUBLIC TRACY_ON_DEMAND)
+    endif()
+    set_target_properties(tracy-client PROPERTIES POSITION_INDEPENDENT_CODE ON)
+    target_link_libraries(tracy-client PUBLIC ${CMAKE_DL_LIBS} pthread)
+endif()
+
 find_package(X11)
 find_package(OpenGL REQUIRED)
 find_package(GLEW REQUIRED)
@@ -59,9 +82,9 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 set(KISSFFT_TEST OFF)
 set(KISSFFT_TOOLS OFF)
 
-set(CEF_VERSION "146.0.11+g3a0fcf1+chromium-146.0.7680.179")
+set(CEF_VERSION "156.0.14+g4fa4ab5+chromium-156.0.8078.48")
 # SHA256 of the archives for that version, a CEF_SHA256_<platform> per distribution that is pinned (bump with CEF_VERSION)
-set(CEF_SHA256_linux64_minimal "4320d0a18a8d7fbae1e2539030a9315094b34af8a2000999ad8caa7befda7625")
+set(CEF_SHA256_linux64_minimal "4191ac920a91a052eba04afb6ed830d47aed46a3e246c434a2f062c23588dc8a")
 if(CMAKE_BUILD_TYPE STREQUAL "Debug")
     set(default_cef_dist "standard")
 else()
@@ -487,6 +510,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Desktop/KWinScript.cpp
     src/WallpaperEngine/Desktop/SessionBus.h
     src/WallpaperEngine/Desktop/SessionBus.cpp
+    src/WallpaperEngine/Desktop/SessionMonitor.h
+    src/WallpaperEngine/Desktop/SessionMonitor.cpp
     src/WallpaperEngine/Desktop/PowerMonitor.h
     src/WallpaperEngine/Desktop/PowerMonitor.cpp
     src/WallpaperEngine/Desktop/HyprlandIPC.h
@@ -837,6 +862,7 @@ add_library(
     ${DEMOMODE_SOURCES})
 
 target_link_libraries (linux-wallpaperengine-lib PUBLIC
+    $<$<BOOL:${LWE_TRACY}>:tracy-client>
     ${OPENGL_LIBRARIES}
     GLEW::GLEW
     ${GLUT_LIBRARIES}
@@ -891,11 +917,31 @@ if (BUILD_TESTING)
         V8::V8)
 endif()
 
+# the shader caches under ~/.cache hold what these sources and compilers made, so their content is the key (a build date
+# stays the same in reproducible builds)
+set(SHADER_CACHE_SOURCES
+    ${CMAKE_CURRENT_SOURCE_DIR}/src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/src/WallpaperEngine/Render/Shaders/GLSLContext.cpp)
+set(SHADER_CACHE_ID "")
+foreach(SHADER_CACHE_SOURCE ${SHADER_CACHE_SOURCES})
+    file(SHA256 ${SHADER_CACHE_SOURCE} SHADER_CACHE_HASH)
+    string(APPEND SHADER_CACHE_ID ${SHADER_CACHE_HASH})
+    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SHADER_CACHE_SOURCE})
+endforeach()
+foreach(SHADER_CACHE_DEP glslang-WallpaperEngine SPIRV-Cross-WallpaperEngine)
+    execute_process(
+        COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR}/src/External/${SHADER_CACHE_DEP} rev-parse HEAD
+        OUTPUT_VARIABLE SHADER_CACHE_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
+    string(APPEND SHADER_CACHE_ID ${SHADER_CACHE_REVISION})
+endforeach()
+string(SHA256 SHADER_CACHE_ID "${SHADER_CACHE_ID}")
+target_compile_definitions(linux-wallpaperengine-lib PRIVATE "LWE_SHADER_CACHE_ID=\"${SHADER_CACHE_ID}\"")
 target_compile_definitions(linux-wallpaperengine-lib PUBLIC ERRORONLY=${ERRORONLY})
 target_compile_definitions(linux-wallpaperengine-lib PUBLIC DEMOMODE=${DEMOMODE})
 
 if (BUILD_TESTING)
     target_compile_definitions(tests PRIVATE ERRORONLY=0)
+    target_compile_definitions(tests PRIVATE "LWE_SHADER_CACHE_ID=\"${SHADER_CACHE_ID}\"")
     target_compile_definitions(tests PRIVATE DEMOMODE=0)
 endif()
 

+ 7 - 1
README.md

@@ -33,6 +33,7 @@ Rendering:
 - 3D models: skinning and morphs on the GPU, root motion, frustum culling and shadow casting.
 - Puppets (2D characters): `.mdl` parsing, animation layers with their blending and fades, additive layers, bone physics, IK and rope chains, constraint blend rules, bone alpha, morph targets, clipping masks, hit boxes, draw order tracks, and the script bone API.
 - Video wallpapers and video textures: when a texture video plays, pauses and loops, and the `IVideoTexture` object of scripts.
+- Depth: scenes draw with a reversed 0 to 1 depth range like Wallpaper Engine's float depth buffer (needs `ARB_clip_control` or GL 4.5, `LWE_FORWARD_DEPTH=1` switches it off), and the jitter of volumetric light matches Wallpaper Engine's bit for bit on most pixels.
 
 Sound:
 
@@ -51,8 +52,10 @@ SceneScript and properties:
 Desktop behavior:
 
 - Pause rules: fullscreen, maximized and focused windows pause per monitor by Wallpaper Engine's rules (minimized and other desktop windows do not count), with its defaults.
+- Frame pacing: the FPS limit shares a one second budget between the frames of that second like Wallpaper Engine's main loop (`--frame-limiter fixed` brings back a fixed sleep per frame).
+- Playlists: with `videosequence` a video plays once and its end advances the playlist, `playintro` plays the first item once at startup, and an item that fails to load is skipped for that round only.
 - Stretch (span) groups: one wallpaper over the bounding box of several monitors, cursor included, pixel identical to Wallpaper Engine's stretch layout.
-- Web wallpapers run on CEF 146, the version Wallpaper Engine ships, with its property, audio and file API.
+- Web wallpapers run on CEF 156 with its property, audio and file API.
 
 Everything not listed here, or listed under Limitations, is either specific to this fork (see below) or not a copy yet.
 
@@ -268,6 +271,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--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 |
+| `--render-scale <factor>` | Render this output below its native size, `0.1` to `1` (`0.5` draws a quarter of the pixels), and let the compositor scale it up. Wayland with `wp_viewporter` only; for secondary or very large outputs. Applies to the previous `--screen-root`, every screen of the previous `--screen-span` group or the screen of the previous `--screen-slot` |
 | `--offset <X,Y>` | Move the visible crop window of a cropping `--scaling`/`--zoom`, each axis in [-1, 1] |
 | `--alignment-position <0-100>` | Wallpaper Engine's alignment position: where `fill`/`default` crop and `fit` letterboxes (default 50) |
 | `--alignment-x <0-100>`, `--alignment-y <0-100>` | Placement for `center` and `free` (default 50, 0 = left/top) |
@@ -317,6 +321,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--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 |
+| `--no-lock-pause` | Keep rendering while the session is locked. By default the wallpaper pauses while logind's `LockedHint` is set or a screen saver (`org.freedesktop.ScreenSaver`, GNOME, Cinnamon, MATE) reports itself active, and while an X server's DPMS or GNOME's `PowerSaveMode` has the display blanked. Other Wayland compositors are left to their frame callbacks, which most stop for a blanked output |
 | `--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 |
@@ -427,6 +432,7 @@ Platform and setup:
 - On Wayland, web wallpapers and scene wallpapers with click handlers (e.g. bone dragging) take all mouse clicks on the desktop, so the right click menu of the desktop doesn't open while they are shown. A Wayland input region can't be limited to one mouse button, and a click can't be passed on to the surface below. Wallpapers without click handlers don't take clicks where the compositor gives the pointer position (KDE Plasma, Hyprland, GNOME).
 - KDE Plasma 5 on Wayland doesn't pause behind windows: KWin 5 has no `workspace.windowList` in its scripting API (Plasma 6 is fine).
 - elementary OS (Pantheon) has no `wlr-layer-shell`, so the engine draws through XWayland. XWayland only reports the pointer over its own windows, so the wallpaper keeps its input region to follow the cursor (parallax, cursor effects) and takes all clicks on the desktop: the desktop's right click menu doesn't open. That is a limit of XWayland, not something the engine can work around. Windows that cover an output pause it, maximized windows don't.
+- Web wallpapers pass their frames to the engine as GPU buffers (dmabuf) where that was checked: AMD on Mesa and the VM matrix. With the NVIDIA proprietary driver `--web-frames auto` stays on shared memory frames, which costs more CPU, since dmabuf is not verified there. On Intel and with amdgpu user mode queues `auto` uses dmabuf but it was not checked for tearing, `--web-frames shm` switches back if a page shows stale frames.
 - Windows fonts (`systemfont_*`) are replaced by the closest installed match through fontconfig, so text can look slightly different if Arial, Segoe UI etc. or their metric-compatible clones aren't installed.
 - RGB lighting (`--leds`) goes through an OpenRGB server only (no iCUE or Razer Chroma SDK) and only scene wallpapers feed it, not video or web ones. OpenRGB has no led positions, so a keyboard keeps its grid and the other zones become rows; Wallpaper Engine places every led by its real position.
 - The Arch distribution build needs `libnode` (a Node.js built with `--shared`, Arch's `nodejs` has no shared library). The AUR has it, and the CI keeps a prebuilt package as an asset of the [`libnode-arch` release](https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/releases/tag/libnode-arch): `sudo pacman -U libnode-*-x86_64.pkg.tar.zst`. we_manager's build section has an "Install libnode" button on Arch that does exactly this. The portable build and `-bin` bring their own V8.

+ 2 - 2
nix/package.nix

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

+ 1 - 1
src/External/Catch2

@@ -1 +1 @@
-Subproject commit b3fb4b9feafcd8d91c5cb510a4775143fdbef02f
+Subproject commit 08092139210881f01a34e60c5f2fd6afa0ea4024

+ 1 - 1
src/External/json

@@ -1 +1 @@
-Subproject commit 4424a0fcc1c7fa640b5c87d26776d99150dacd10
+Subproject commit 55f93686c01528224f448c19128836e7df245f72

+ 1 - 1
src/External/kissfft

@@ -1 +1 @@
-Subproject commit febd4caeed32e33ad8b2e0bb5ea77542c40f18ec
+Subproject commit f3fd3a58f1b98972d0f06a1db775a984198cb788

+ 1 - 1
src/External/msdfgen

@@ -1 +1 @@
-Subproject commit 6574da1310df433c97ca0fddcab7e463c31e58f8
+Subproject commit 1874bcf7d9624ccc85b4bc9a85d78116f690f35b

+ 1 - 1
src/External/stb

@@ -1 +1 @@
-Subproject commit f0569113c93ad095470c54bf34a17b36646bbbb5
+Subproject commit 003501f6d7a8668ce8b6d875e34dd97ad0d5d5b5

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

@@ -771,6 +771,43 @@ void ApplicationContext::loadSettingsFromArgv () {
 	})
 	.append ();
 
+    backgroundGroup.add_argument ("--render-scale")
+	.help (
+	    "Renders the output below its native size, between 0.1 and 1 (0.5 draws a quarter of the pixels), and lets "
+	    "the compositor scale it up. Wayland only, needs wp_viewporter. Meant for secondary or very large "
+	    "outputs; this applies to the previous --screen-root output, every screen of the previous --screen-span "
+	    "group or the screen of the previous --screen-slot"
+	)
+	.action ([this, &lastScreen] (const std::string& value) -> void {
+	    float scale;
+
+	    try {
+		scale = parseFiniteFloat (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid render scale value: ", value);
+	    }
+
+	    if (scale < 0.1f || scale > 1.0f) {
+		sLog.exception ("--render-scale must be between 0.1 and 1, got ", value);
+	    }
+
+	    if (lastScreen.empty () || this->settings.render.mode != DESKTOP_BACKGROUND) {
+		sLog.error ("--render-scale only applies after a --screen-root or --screen-span, ignoring it");
+		return;
+	    }
+
+	    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		for (const auto& screen : this->settings.general.spanGroups.back ().screens) {
+		    this->settings.general.screenRenderScales[screen] = scale;
+		}
+	    } else if (const auto hash = lastScreen.rfind ('#'); hash != std::string::npos) {
+		this->settings.general.screenRenderScales[lastScreen.substr (0, hash)] = scale;
+	    } else {
+		this->settings.general.screenRenderScales[lastScreen] = scale;
+	    }
+	})
+	.append ();
+
     backgroundGroup.add_argument ("--offset")
 	.help (
 	    "Re-centers the visible crop window a cropping scaling mode (e.g. --scaling fill) or --zoom produces, "
@@ -1101,6 +1138,15 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.idlePauseMinutes = minutes;
 	});
 
+    performanceGroup.add_argument ("--no-lock-pause")
+	.help (
+	    "Keeps rendering while the session is locked. By default the background pauses while logind's LockedHint "
+	    "is set or a screen saver (org.freedesktop.ScreenSaver, GNOME, Cinnamon, MATE) reports itself active. "
+	    "Control file: lock-pause=on|off"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.render.pauseOnLock = false; });
+
     performanceGroup.add_argument ("--speed")
 	.help (
 	    "Global playback speed multiplier for animations, particles and effects (e.g. 0.5 for half speed, "

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

@@ -135,6 +135,7 @@ public:
 	    std::map<std::string, WallpaperEngine::Render::WallpaperState::TextureUVsScaling> screenScalings;
 	    std::map<std::string, TextureFlags> screenClamps;
 	    std::map<std::string, float> screenZooms;
+	    std::map<std::string, float> screenRenderScales;
 	    std::map<std::string, glm::vec2> screenOffsets;
 	    std::map<std::string, WallpaperEngine::Render::WallpaperState::Alignment> screenAlignments;
 	    std::map<std::string, glm::vec4> screenCornerColors;
@@ -173,6 +174,7 @@ public:
 	    std::vector<std::string> fullscreenPauseIgnoreAppIds;
 	    std::optional<int> batteryFPS;
 	    int idlePauseMinutes;
+	    bool pauseOnLock;
 	    bool hdr;
 	    struct {
 		bool baseOnly;
@@ -260,6 +262,7 @@ public:
             .screenScalings = {},
             .screenClamps = {},
             .screenZooms = {},
+            .screenRenderScales = {},
             .screenOffsets = {},
             .screenAlignments = {},
             .screenCornerColors = {},
@@ -295,6 +298,7 @@ public:
             .fullscreenPauseIgnoreAppIds = {},
             .batteryFPS = std::nullopt,
             .idlePauseMinutes = 0,
+            .pauseOnLock = true,
             .hdr = false,
             .debug = {
                 .baseOnly = false,

+ 83 - 14
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -1,4 +1,5 @@
 #include "WallpaperApplication.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 
 #include "ControlFileOwner.h"
 #include "WallpaperEngine/Render/Transition.h"
@@ -67,6 +68,7 @@
 using WallpaperEngine::Data::Utils::parseFiniteFloat;
 
 #define FULLSCREEN_CHECK_WAIT_TIME 250000
+#define INPUT_SUSPEND_AFTER std::chrono::seconds (3)
 
 float g_Time;
 float g_TimeLast;
@@ -382,6 +384,7 @@ void WallpaperApplication::applyPreset (
 }
 
 ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) try {
+    LWE_ZONE_TEXT ("load background", bg);
     auto [container, json, preset, directory] = this->openProjectSource (bg);
 
     if (this->m_context.settings.screenshot.take) {
@@ -733,6 +736,7 @@ struct HotswapRequest {
     std::optional<int> fps;
     std::optional<std::string> batteryFps;
     std::optional<std::string> idlePause;
+    std::optional<std::string> lockPause;
     std::optional<std::string> xray;
     std::optional<std::string> scaling;
     std::optional<std::string> zoom;
@@ -838,6 +842,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.batteryFps = value;
 	} else if (key == "idle-pause") {
 	    request.idlePause = value;
+	} else if (key == "lock-pause") {
+	    request.lockPause = value;
 	} else if (key == "xray") {
 	    request.xray = value;
 	} else if (key == "scaling") {
@@ -995,15 +1001,16 @@ void WallpaperApplication::checkHotswapRequest () {
 
     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 ()
-	&& !request.imageAdjustmentsProvided && !request.speed.has_value () && !request.videoStart.has_value ()
-	&& !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
-	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
-	&& !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
-	&& !request.disableAnimations.has_value () && !request.hwdec.has_value () && !request.hrtf.has_value ()
-	&& !request.transition.has_value () && !request.transitionDuration.has_value ()) {
+	&& !request.lockPause.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 () && !request.imageAdjustmentsProvided
+	&& !request.speed.has_value () && !request.videoStart.has_value () && !request.videoEnd.has_value ()
+	&& !request.videoSegments.has_value () && !request.videoSeek.has_value () && !request.audioScreen.has_value ()
+	&& !request.ambientVolume.has_value () && !request.propertiesProvided && !request.audioSensitivityProvided
+	&& !request.soundVolumeProvided && !request.effectsProvided && !request.disableAnimations.has_value ()
+	&& !request.hwdec.has_value () && !request.hrtf.has_value () && !request.transition.has_value ()
+	&& !request.transitionDuration.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -1115,6 +1122,10 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applyIdlePauseHotswap (*request.idlePause);
     }
 
+    if (request.lockPause.has_value ()) {
+	this->applyLockPauseHotswap (*request.lockPause);
+    }
+
     if (request.xray.has_value ()) {
 	this->applyXrayHotswap (*request.xray);
     }
@@ -1602,6 +1613,26 @@ void WallpaperApplication::applyIdlePauseHotswap (const std::string& value) {
     sLog.out ("Hotswap: applied idle-pause ", minutes, " live");
 }
 
+void WallpaperApplication::applyLockPauseHotswap (const std::string& value) {
+    if (value != "on" && value != "off" && value != "1" && value != "0" && value != "true" && value != "false") {
+	sLog.error ("Hotswap: ignoring invalid lock-pause value: ", value);
+	return;
+    }
+
+    this->m_context.settings.render.pauseOnLock = value == "on" || value == "1" || value == "true";
+    this->updateSessionMonitor ();
+
+    sLog.out ("Hotswap: applied lock-pause ", this->m_context.settings.render.pauseOnLock ? "on" : "off", " live");
+}
+
+void WallpaperApplication::updateSessionMonitor () {
+    if (!this->m_context.settings.render.pauseOnLock) {
+	this->m_sessionMonitor.reset ();
+    } else if (!this->m_sessionMonitor) {
+	this->m_sessionMonitor = std::make_unique<WallpaperEngine::Desktop::SessionMonitor> ();
+    }
+}
+
 void WallpaperApplication::updatePowerMonitor () {
     const auto& render = this->m_context.settings.render;
 
@@ -1646,6 +1677,17 @@ uint32_t WallpaperApplication::pauseReasons () const {
 	}
     }
 
+    // a screenshot run has to reach its frame whatever the session does meanwhile
+    if (render.pauseOnLock && this->m_sessionMonitor && !this->m_context.settings.screenshot.take) {
+	if (this->m_sessionMonitor->locked ()) {
+	    reasons |= PauseLocked;
+	}
+
+	if (this->m_sessionMonitor->displayOff ()) {
+	    reasons |= PauseDisplayOff;
+	}
+    }
+
     return reasons;
 }
 
@@ -1664,7 +1706,8 @@ void WallpaperApplication::logPauseReasons (uint32_t reasons) {
     std::string names;
 
     for (const auto& [bit, name] : { std::pair { PauseWindows, "windows" }, std::pair { PauseBattery, "battery" },
-				     std::pair { PauseIdle, "idle" } }) {
+				     std::pair { PauseIdle, "idle" }, std::pair { PauseLocked, "lock" },
+				     std::pair { PauseDisplayOff, "display off" } }) {
 	if (reasons & bit) {
 	    names += names.empty () ? name : std::string (", ") + name;
 	}
@@ -2936,6 +2979,7 @@ void WallpaperApplication::installWallpaper (
     const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious,
     const bool animate
 ) try {
+    LWE_ZONE_TEXT ("install wallpaper", screen);
     const auto& general = this->m_context.settings.general;
     const auto& window = this->m_context.settings.render.window;
     const auto* spanGroup = this->findSpanGroup (screen);
@@ -3050,6 +3094,7 @@ void WallpaperApplication::setup () {
     this->prepareOutputs ();
     this->setupOpenGLDebugging ();
     this->updatePowerMonitor ();
+    this->updateSessionMonitor ();
 
     if (this->m_context.settings.general.dumpStructure) {
 	auto prettyPrinter = Data::Dumpers::StringPrinter ();
@@ -3077,10 +3122,22 @@ void WallpaperApplication::setup () {
 void WallpaperApplication::render () {
     static float rawTimeLast = 0.0f;
 
+    LWE_ZONE ("main loop");
+
     if (this->m_isPaused) {
 	usleep (FULLSCREEN_CHECK_WAIT_TIME);
 	m_videoDriver->dispatchWhilePaused ();
 
+	// unread messages count against the session bus quota, once it is used up the broker kicks other programs
+	m_videoDriver->getInputContext ().drain ();
+	m_mediaSource->discard ();
+
+	// the delay spares the script reloads for alt-tab
+	if (!this->m_inputSuspended && std::chrono::steady_clock::now () - this->m_pauseStart >= INPUT_SUSPEND_AFTER) {
+	    m_videoDriver->getInputContext ().suspend (true);
+	    this->m_inputSuspended = true;
+	}
+
 	// automute keeps following other programs' sound, or the music stays on until the wallpaper resumes
 	if (this->m_audioDriver != nullptr) {
 	    this->m_audioDriver->getAudioDetector ().update ();
@@ -3109,6 +3166,11 @@ void WallpaperApplication::render () {
 	    }
 	}
 
+	if (this->m_inputSuspended) {
+	    m_videoDriver->getInputContext ().suspend (false);
+	    this->m_inputSuspended = false;
+	}
+
 	this->m_isPaused = false;
     } else {
 	const time_t seconds = time (nullptr);
@@ -3136,9 +3198,12 @@ void WallpaperApplication::render () {
 	    );
 	}
 	g_RealTime = fixedTimestep > 0.0f ? g_RealTime + fixedTimestep : rawTimeNow;
-	m_audioDriver->update (rawDelta * this->m_context.settings.render.playbackSpeed);
-	m_mediaSource->update ();
-	m_videoDriver->getInputContext ().update ();
+	{
+	    LWE_ZONE ("audio media input");
+	    m_audioDriver->update (rawDelta * this->m_context.settings.render.playbackSpeed);
+	    m_mediaSource->update ();
+	    m_videoDriver->getInputContext ().update ();
+	}
 
 	// LWE_HOTSWAP_AT_FRAME=<n>: read the control file before frame n as if SIGUSR1 came in (regression tests)
 	static const int64_t hotswapFrame = [] {
@@ -3151,7 +3216,10 @@ void WallpaperApplication::render () {
 	    this->checkHotswapRequest ();
 	}
 
-	m_videoDriver->dispatchEventQueue ();
+	{
+	    LWE_ZONE ("dispatch events");
+	    m_videoDriver->dispatchEventQueue ();
+	}
 
 	// spritesheetrefreshsync: sleep until the first image's next sprite frame (sub_140110630)
 	if (fixedTimestep <= 0.0f && !this->m_context.settings.render.freezeAnimations) {
@@ -3190,6 +3258,7 @@ void WallpaperApplication::render () {
 	);
 
 	if (pause > std::chrono::nanoseconds::zero ()) {
+	    LWE_ZONE ("frame limiter sleep");
 	    std::this_thread::sleep_for (pause);
 	}
 

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

@@ -22,6 +22,7 @@
 #include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Data/Model/Types.h"
 #include "WallpaperEngine/Desktop/PowerMonitor.h"
+#include "WallpaperEngine/Desktop/SessionMonitor.h"
 #include "WallpaperEngine/Media/MediaSource.h"
 
 #include <set>
@@ -123,6 +124,8 @@ private:
     void applyFpsHotswap (int fps);
     void applyBatteryFpsHotswap (const std::string& value);
     void applyIdlePauseHotswap (const std::string& value);
+    void applyLockPauseHotswap (const std::string& value);
+    void updateSessionMonitor ();
     void updatePowerMonitor ();
     [[nodiscard]] int frameRateLimit () const;
     [[nodiscard]] uint32_t pauseReasons () const;
@@ -209,14 +212,18 @@ private:
     std::mt19937 m_playlistRng { std::random_device {}() };
     std::atomic<bool> m_hotswapRequested { false };
     bool m_isPaused = false;
+    bool m_inputSuspended = false;
     enum PauseReason : uint32_t {
 	PauseWindows = 1,
 	PauseBattery = 2,
 	PauseIdle = 4,
+	PauseLocked = 8,
+	PauseDisplayOff = 16,
     };
     uint32_t m_pauseReasons = 0;
     bool m_showFrameWhilePaused = false;
     std::unique_ptr<WallpaperEngine::Desktop::PowerMonitor> m_powerMonitor = nullptr;
+    std::unique_ptr<WallpaperEngine::Desktop::SessionMonitor> m_sessionMonitor = nullptr;
     bool m_screenShotTaken = false;
     mutable std::jthread m_screenshotWriter;
 

+ 67 - 1
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp

@@ -1,9 +1,11 @@
 #include "PulseAudioPlaybackRecorder.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
 #include <algorithm>
 #include <chrono>
 #include <cmath>
+#include <cstdlib>
 #include <cstring>
 #include <ctime>
 #include <iomanip>
@@ -15,6 +17,7 @@ namespace {
     constexpr int CAPTURE_RATE = 44100;
     constexpr int CAPTURE_CHANNELS = 2;
     constexpr auto CAPTURE_TIMEOUT = std::chrono::milliseconds (1000);
+    constexpr auto SILENCE_HOLD = std::chrono::milliseconds (50);
 
     std::string wallClockTimestamp () {
 	const auto now = std::chrono::system_clock::now ();
@@ -220,6 +223,7 @@ void pa_context_notify_cb (pa_context* ctx, void* userdata) {
 
 PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder () :
     m_captureData ({ .owner = this, .captureStream = nullptr, .captureLost = false }), m_analyzer (CAPTURE_RATE) {
+    this->m_stats.enabled = std::getenv ("LWE_AUDIO_STATS") != nullptr;
     this->m_dataMutex = SDL_CreateMutex ();
     this->m_mainloop = pa_mainloop_new ();
     this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop);
@@ -293,9 +297,27 @@ void PulseAudioPlaybackRecorder::captureLoop () {
 	}
 
 	cleared = stale;
+	this->logStats ();
     }
 }
 
+void PulseAudioPlaybackRecorder::logStats () {
+    auto& stats = this->m_stats;
+    const auto now = std::chrono::steady_clock::now ();
+
+    if (!stats.enabled || now - stats.since < std::chrono::seconds (1)) {
+	return;
+    }
+
+    sLog.out (
+	"Audio capture: ", stats.packets, " packets, ", stats.holes, " holes, ", stats.blocks, " blocks, peak ",
+	stats.peak, ", dc ", stats.count > 0.0 ? stats.sum / stats.count : 0.0, ", bands low ", stats.lowMax, " high ",
+	stats.highMax, ", stream ", this->m_captureData.captureLost ? "lost" : "up"
+    );
+
+    stats = { .enabled = true, .since = now };
+}
+
 void PulseAudioPlaybackRecorder::clearCaptured () {
     constexpr float silence[128] = {};
 
@@ -305,14 +327,58 @@ void PulseAudioPlaybackRecorder::clearCaptured () {
     this->notifySpectrumListeners (silence);
 }
 
-void PulseAudioPlaybackRecorder::dropBlock () { this->m_analyzer.reset (); }
+void PulseAudioPlaybackRecorder::dropBlock () {
+    this->m_stats.holes++;
+    this->m_analyzer.reset ();
+}
 
 void PulseAudioPlaybackRecorder::consumeSamples (const float* samples, std::size_t frames) {
+    if (this->m_stats.enabled) {
+	this->m_stats.packets++;
+
+	for (std::size_t i = 0; i < frames * CAPTURE_CHANNELS; i++) {
+	    this->m_stats.sum += samples[i];
+	    this->m_stats.peak = std::max (this->m_stats.peak, std::fabs (samples[i]));
+	}
+
+	this->m_stats.count += static_cast<double> (frames * CAPTURE_CHANNELS);
+    }
+
+    // WASAPI's loopback sends nothing while nothing plays and WE zeroes the spectrum after a second without data, while
+    // PipeWire and PulseAudio keep sending zeros: their FFT leaves a 1e-7 residue that pages with their own gain
+    // (CWAV's monstercat) stretch to full height once the peak they follow has decayed
+    if (std::all_of (samples, samples + frames * CAPTURE_CHANNELS, [] (float sample) {
+	    return Data::Utils::isZero (sample);
+	})) {
+	const auto now = std::chrono::steady_clock::now ();
+
+	if (this->m_silentSince == std::chrono::steady_clock::time_point {}) {
+	    this->m_silentSince = now;
+	}
+
+	this->m_analyzer.reset ();
+
+	if (!this->m_silenceCleared && now - this->m_silentSince >= SILENCE_HOLD) {
+	    this->m_silenceCleared = true;
+	    this->clearCaptured ();
+	}
+
+	return;
+    }
+
+    this->m_silentSince = {};
+    this->m_silenceCleared = false;
     this->m_lastSamples = std::chrono::steady_clock::now ();
 
     float bands[SpectrumAnalyzer::BANDS * 2];
 
     if (this->m_analyzer.feed (samples, frames, CAPTURE_CHANNELS, bands)) {
+	if (this->m_stats.enabled) {
+	    this->m_stats.blocks++;
+	    this->m_stats.lowMax = std::max (this->m_stats.lowMax, *std::max_element (bands, bands + 16));
+	    this->m_stats.highMax = std::max (this->m_stats.highMax, *std::max_element (bands + 16, bands + 64));
+	}
+
 	this->lock ();
 	std::copy_n (bands, 128, this->m_captured);
 	this->unlock ();

+ 16 - 0
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h

@@ -34,6 +34,7 @@ public:
 private:
     void captureLoop ();
     void clearCaptured ();
+    void logStats ();
 
     pa_mainloop* m_mainloop;
     pa_mainloop_api* m_mainloopApi;
@@ -43,6 +44,21 @@ private:
     // only ever touched from the capture thread
     WallpaperEngine::Audio::SpectrumAnalyzer m_analyzer;
     std::chrono::steady_clock::time_point m_lastSamples = std::chrono::steady_clock::now ();
+    std::chrono::steady_clock::time_point m_silentSince {};
+    bool m_silenceCleared = false;
+
+    struct CaptureStats {
+	bool enabled = false;
+	std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now ();
+	unsigned packets = 0;
+	unsigned holes = 0;
+	unsigned blocks = 0;
+	double sum = 0.0;
+	double count = 0.0;
+	float peak = 0.0f;
+	float lowMax = 0.0f;
+	float highMax = 0.0f;
+    } m_stats;
 
     std::thread m_captureThread;
     mutable SDL_mutex* m_dataMutex = nullptr;

+ 5 - 1
src/WallpaperEngine/Data/Parsers/ProjectParser.cpp

@@ -1,6 +1,7 @@
 #include <algorithm>
 
 #include "ProjectParser.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include "WallpaperParser.h"
@@ -41,7 +42,10 @@ ProjectUniquePtr ProjectParser::parse (const JSON& data, AssetLocatorUniquePtr c
 	.assetLocator = std::move (container),
     });
 
-    result->wallpaper = WallpaperParser::parse (JSON (mainFile), *result);
+    {
+	LWE_ZONE_TEXT ("parse wallpaper", mainFile);
+	result->wallpaper = WallpaperParser::parse (JSON (mainFile), *result);
+    }
 
     return result;
 }

+ 31 - 0
src/WallpaperEngine/Debugging/Profiling.h

@@ -0,0 +1,31 @@
+#pragma once
+
+#ifdef LWE_TRACY
+#include <GL/glew.h>
+#include <string>
+#include <tracy/Tracy.hpp>
+#include <tracy/TracyOpenGL.hpp>
+
+#define LWE_ZONE(name) ZoneScopedN (name)
+#define LWE_ZONE_TEXT(name, text)                                                                                      \
+    ZoneScopedN (name);                                                                                                \
+    {                                                                                                                  \
+	const std::string& zoneText = (text);                                                                          \
+	ZoneText (zoneText.c_str (), zoneText.size ());                                                                \
+    }
+#define LWE_ZONE_NAMED(text)                                                                                           \
+    const std::string lweZoneName = (text);                                                                            \
+    ZoneTransientN (lweZone, lweZoneName.c_str (), true)
+#define LWE_GPU_ZONE(name) TracyGpuZone (name)
+#define LWE_GPU_COLLECT() TracyGpuCollect
+#define LWE_FRAME_MARK() FrameMark
+#define LWE_PLOT(name, value) TracyPlot (name, value)
+#else
+#define LWE_ZONE(name) ((void)0)
+#define LWE_ZONE_TEXT(name, text) ((void)0)
+#define LWE_ZONE_NAMED(text) ((void)0)
+#define LWE_GPU_ZONE(name) ((void)0)
+#define LWE_GPU_COLLECT() ((void)0)
+#define LWE_FRAME_MARK() ((void)0)
+#define LWE_PLOT(name, value) ((void)0)
+#endif

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

@@ -11,6 +11,7 @@
 #include <cstdlib>
 #include <cstring>
 #include <fcntl.h>
+#include <mutex>
 #include <set>
 #include <spawn.h>
 #include <sys/file.h>
@@ -161,6 +162,9 @@ private:
     }
 
     void send (const std::string& line) {
+	// scripts are loaded and unloaded from a worker thread as well
+	const std::lock_guard lock (this->m_mutex);
+
 	if (!this->m_started) {
 	    this->start ();
 	}
@@ -171,6 +175,7 @@ private:
 	}
     }
 
+    std::mutex m_mutex;
     int m_pipe = -1;
     bool m_started = false;
 };

+ 6 - 39
src/WallpaperEngine/Desktop/PowerMonitor.cpp

@@ -133,32 +133,20 @@ private:
 };
 
 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);
+    DBusMessage* reply
+	= getProperty (bus, "org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "OnBattery");
 
     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;
-	}
+    if (propertyValue (reply, variant) && 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);
@@ -185,27 +173,6 @@ std::optional<uint64_t> mutterIdleMilliseconds (DBusConnection* bus) {
     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);
-    }
-}
 }
 
 std::optional<bool> WallpaperEngine::Desktop::sysfsOnBattery (const std::filesystem::path& powerSupplies) {

+ 46 - 1
src/WallpaperEngine/Desktop/SessionBus.cpp

@@ -10,7 +10,7 @@
 namespace {
 constexpr int CALL_TIMEOUT_MS = 2000;
 /** per-frame cap, a read pulls ~2KB at most */
-constexpr int MAX_READS_PER_DRAIN = 64;
+constexpr int MAX_READS_PER_DRAIN = 512;
 }
 
 bool WallpaperEngine::Desktop::desktopListHas (std::string_view name) {
@@ -122,6 +122,51 @@ bool WallpaperEngine::Desktop::drainBus (DBusConnection* connection) {
     return true;
 }
 
+DBusMessage* WallpaperEngine::Desktop::getProperty (
+    DBusConnection* connection, const char* service, const char* path, const char* interface, const char* property,
+    bool autoStart
+) {
+    DBusMessage* call = dbus_message_new_method_call (service, path, "org.freedesktop.DBus.Properties", "Get");
+    dbus_message_set_auto_start (call, autoStart ? TRUE : FALSE);
+    dbus_message_append_args (call, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID);
+
+    std::string error;
+    return callBlocking (connection, call, error);
+}
+
+bool WallpaperEngine::Desktop::propertyValue (DBusMessage* reply, DBusMessageIter& value) {
+    DBusMessageIter iter;
+
+    if (!dbus_message_iter_init (reply, &iter) || dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_VARIANT) {
+	return false;
+    }
+
+    dbus_message_iter_recurse (&iter, &value);
+    return true;
+}
+
+DBusConnection* WallpaperEngine::Desktop::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 WallpaperEngine::Desktop::closeBus (DBusConnection* bus) {
+    if (bus != nullptr) {
+	dbus_connection_close (bus);
+	dbus_connection_unref (bus);
+    }
+}
+
 int WallpaperEngine::Desktop::receiveDescriptor (int connection) {
     char byte = 0;
     iovec data = { .iov_base = &byte, .iov_len = 1 };

+ 14 - 0
src/WallpaperEngine/Desktop/SessionBus.h

@@ -21,4 +21,18 @@ int receiveDescriptor (int connection);
 DBusMessage* callBlocking (DBusConnection* connection, DBusMessage* call, std::string& error);
 
 bool drainBus (DBusConnection* connection);
+
+/** Properties.Get of one property, the reply or null when the call fails. Without autoStart the call never starts the
+ * service that owns it */
+DBusMessage* getProperty (
+    DBusConnection* connection, const char* service, const char* path, const char* interface, const char* property,
+    bool autoStart = true
+);
+
+bool propertyValue (DBusMessage* reply, DBusMessageIter& value);
+
+/** A connection of its own that survives the bus going away without ending the process, null when there is no bus */
+DBusConnection* privateBus (DBusBusType type);
+
+void closeBus (DBusConnection* bus);
 }

+ 484 - 0
src/WallpaperEngine/Desktop/SessionMonitor.cpp

@@ -0,0 +1,484 @@
+#include "SessionMonitor.h"
+
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <cstdint>
+#include <cstdlib>
+#include <dlfcn.h>
+#include <memory>
+#include <optional>
+#include <poll.h>
+#include <string>
+#include <string_view>
+#include <sys/eventfd.h>
+#include <tuple>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/SessionBus.h"
+#include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
+
+using namespace WallpaperEngine::Desktop;
+
+namespace {
+// signals can be missed when a screen locker restarts, so the state is asked again now and then
+constexpr auto RECHECK_INTERVAL = std::chrono::seconds (30);
+constexpr int DPMS_POLL_MS = 1000;
+
+struct ScreenSaverName {
+    const char* service;
+    const char* path;
+    const char* interface;
+};
+
+constexpr std::array SCREEN_SAVERS = {
+    ScreenSaverName { "org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver" },
+    ScreenSaverName { "org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver" },
+    ScreenSaverName { "org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "org.gnome.ScreenSaver" },
+    ScreenSaverName { "org.cinnamon.ScreenSaver", "/org/cinnamon/ScreenSaver", "org.cinnamon.ScreenSaver" },
+    ScreenSaverName { "org.mate.ScreenSaver", "/org/mate/ScreenSaver", "org.mate.ScreenSaver" },
+};
+
+// DPMS through dlopen, libXext isn't a build dependency
+class X11Dpms {
+public:
+    ~X11Dpms () {
+	if (this->m_display != nullptr) {
+	    this->m_closeDisplay (this->m_display);
+	}
+
+	if (this->m_xext != nullptr) {
+	    dlclose (this->m_xext);
+	}
+
+	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_xext = dlopen ("libXext.so.6", RTLD_NOW | RTLD_LOCAL);
+
+	if (this->m_x11 == nullptr || this->m_xext == 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"));
+	auto queryExtension
+	    = reinterpret_cast<int (*) (void*, int*, int*)> (dlsym (this->m_xext, "DPMSQueryExtension"));
+	auto capable = reinterpret_cast<int (*) (void*)> (dlsym (this->m_xext, "DPMSCapable"));
+	this->m_info
+	    = reinterpret_cast<int (*) (void*, unsigned short*, unsigned char*)> (dlsym (this->m_xext, "DPMSInfo"));
+
+	if (openDisplay == nullptr || this->m_closeDisplay == nullptr || queryExtension == nullptr || capable == nullptr
+	    || this->m_info == nullptr) {
+	    return false;
+	}
+
+	this->m_display = openDisplay (nullptr);
+
+	int eventBase = 0;
+	int errorBase = 0;
+
+	return this->m_display != nullptr && queryExtension (this->m_display, &eventBase, &errorBase)
+	    && capable (this->m_display);
+    }
+
+    /** DPMS off, standby and suspend all mean a blank screen. Nothing when DPMS is not enabled on the server */
+    std::optional<bool> blanked () {
+	unsigned short level = 0;
+	unsigned char enabled = 0;
+
+	if (!this->m_info (this->m_display, &level, &enabled)) {
+	    return std::nullopt;
+	}
+
+	return enabled != 0 && level != 0;
+    }
+
+private:
+    void* m_x11 = nullptr;
+    void* m_xext = nullptr;
+    void* m_display = nullptr;
+    int (*m_closeDisplay) (void*) = nullptr;
+    int (*m_info) (void*, unsigned short*, unsigned char*) = nullptr;
+};
+
+DBusMessage* methodCall (const char* service, const char* path, const char* interface, const char* method) {
+    DBusMessage* call = dbus_message_new_method_call (service, path, interface, method);
+
+    // asking must never start a screen saver the session doesn't run
+    dbus_message_set_auto_start (call, FALSE);
+    return call;
+}
+
+std::optional<bool> readBoolean (DBusMessage* reply) {
+    DBusMessageIter iter;
+    dbus_bool_t value = FALSE;
+
+    if (!dbus_message_iter_init (reply, &iter)) {
+	return std::nullopt;
+    }
+
+    if (dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_VARIANT) {
+	DBusMessageIter variant;
+	dbus_message_iter_recurse (&iter, &variant);
+
+	if (dbus_message_iter_get_arg_type (&variant) != DBUS_TYPE_BOOLEAN) {
+	    return std::nullopt;
+	}
+
+	dbus_message_iter_get_basic (&variant, &value);
+	return value != FALSE;
+    }
+
+    if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_BOOLEAN) {
+	return std::nullopt;
+    }
+
+    dbus_message_iter_get_basic (&iter, &value);
+    return value != FALSE;
+}
+
+std::optional<bool> screenSaverActive (DBusConnection* bus, const ScreenSaverName& name) {
+    std::string error;
+    DBusMessage* reply = callBlocking (bus, methodCall (name.service, name.path, name.interface, "GetActive"), error);
+
+    if (reply == nullptr) {
+	return std::nullopt;
+    }
+
+    const auto active = readBoolean (reply);
+    dbus_message_unref (reply);
+    return active;
+}
+
+std::string logindSessionPath (DBusConnection* bus) {
+    const auto objectPath = [] (DBusMessage* reply) -> std::string {
+	const char* path = nullptr;
+	std::string result;
+
+	if (reply != nullptr) {
+	    if (dbus_message_get_args (reply, nullptr, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID)) {
+		result = path;
+	    }
+
+	    dbus_message_unref (reply);
+	}
+
+	return result;
+    };
+    std::string error;
+
+    DBusMessage* byPid = methodCall (
+	"org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID"
+    );
+    const dbus_uint32_t pid = static_cast<dbus_uint32_t> (getpid ());
+    dbus_message_append_args (byPid, DBUS_TYPE_UINT32, &pid, DBUS_TYPE_INVALID);
+
+    if (auto path = objectPath (callBlocking (bus, byPid, error)); !path.empty ()) {
+	return path;
+    }
+
+    // a Flatpak's pid is not the one logind knows
+    if (const char* id = std::getenv ("XDG_SESSION_ID"); id != nullptr && *id != '\0') {
+	DBusMessage* byId = methodCall (
+	    "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSession"
+	);
+	dbus_message_append_args (byId, DBUS_TYPE_STRING, &id, DBUS_TYPE_INVALID);
+	return objectPath (callBlocking (bus, byId, error));
+    }
+
+    return {};
+}
+
+std::optional<bool> logindLockedHint (DBusConnection* bus, const std::string& session) {
+    DBusMessage* reply = getProperty (
+	bus, "org.freedesktop.login1", session.c_str (), "org.freedesktop.login1.Session", "LockedHint", false
+    );
+
+    if (reply == nullptr) {
+	return std::nullopt;
+    }
+
+    const auto hint = readBoolean (reply);
+    dbus_message_unref (reply);
+    return hint;
+}
+
+// 0 is on, 1 standby, 2 suspend, 3 off
+std::optional<bool> mutterDisplayOff (DBusConnection* bus) {
+    DBusMessage* reply = getProperty (
+	bus, "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig",
+	"PowerSaveMode", false
+    );
+
+    if (reply == nullptr) {
+	return std::nullopt;
+    }
+
+    std::optional<bool> off;
+    DBusMessageIter variant;
+
+    if (propertyValue (reply, variant) && dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_INT32) {
+	dbus_int32_t mode = 0;
+	dbus_message_iter_get_basic (&variant, &mode);
+	off = mode > 0;
+    }
+
+    dbus_message_unref (reply);
+    return off;
+}
+
+void addMatch (DBusConnection* bus, const std::string& rule) {
+    DBusError error;
+    dbus_error_init (&error);
+    dbus_bus_add_match (bus, rule.c_str (), &error);
+
+    if (dbus_error_is_set (&error)) {
+	dbus_error_free (&error);
+    }
+}
+
+}
+
+struct SessionMonitor::Sources {
+    DBusConnection* systemBus = nullptr;
+    DBusConnection* sessionBus = nullptr;
+    std::string session;
+    std::atomic<bool> changed = true;
+    // the argument of the last ActiveChanged, -1 before the first one; a locker that doesn't answer GetActive still
+    // sends it
+    std::atomic<int> screenSaverSignal = -1;
+    bool hint = false;
+    bool screenSaver = false;
+    std::unique_ptr<X11Dpms> dpms;
+    bool mutterOff = false;
+};
+
+namespace {
+DBusHandlerResult noteSignal (DBusConnection*, DBusMessage* message, void* data) {
+    auto& sources = *static_cast<SessionMonitor::Sources*> (data);
+
+    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) {
+	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+    }
+
+    dbus_bool_t active = FALSE;
+
+    if (dbus_message_is_signal (message, "org.freedesktop.ScreenSaver", "ActiveChanged")
+	|| dbus_message_is_signal (message, "org.gnome.ScreenSaver", "ActiveChanged")
+	|| dbus_message_is_signal (message, "org.cinnamon.ScreenSaver", "ActiveChanged")
+	|| dbus_message_is_signal (message, "org.mate.ScreenSaver", "ActiveChanged")) {
+	if (dbus_message_get_args (message, nullptr, DBUS_TYPE_BOOLEAN, &active, DBUS_TYPE_INVALID)) {
+	    sources.screenSaverSignal = active != FALSE;
+	}
+    }
+
+    sources.changed = true;
+    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}
+}
+
+SessionMonitor::SessionMonitor () :
+    m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (std::make_unique<Sources> ()) {
+    try {
+	this->m_thread = std::thread ([this] {
+	    WallpaperEngine::Logging::guardThread ("Session monitor", [this] { this->run (); });
+	});
+    } catch (...) {
+	if (this->m_wakeFd >= 0) {
+	    close (this->m_wakeFd);
+	}
+
+	throw;
+    }
+}
+
+SessionMonitor::~SessionMonitor () {
+    this->m_stop = true;
+    this->wake ();
+
+    if (this->m_thread.joinable ()) {
+	this->m_thread.join ();
+    }
+
+    closeBus (this->m_sources->systemBus);
+    closeBus (this->m_sources->sessionBus);
+
+    if (this->m_wakeFd >= 0) {
+	close (this->m_wakeFd);
+    }
+}
+
+void SessionMonitor::wake () const {
+    if (this->m_wakeFd >= 0) {
+	const uint64_t one = 1;
+	std::ignore = write (this->m_wakeFd, &one, sizeof (one));
+    }
+}
+
+void SessionMonitor::run () {
+    auto& sources = *this->m_sources;
+
+    sources.systemBus = privateBus (DBUS_BUS_SYSTEM);
+    sources.sessionBus = privateBus (DBUS_BUS_SESSION);
+
+    if (sources.systemBus != nullptr) {
+	sources.session = logindSessionPath (sources.systemBus);
+
+	if (!sources.session.empty ()) {
+	    addMatch (
+		sources.systemBus,
+		"type='signal',sender='org.freedesktop.login1',path='" + sources.session
+		    + "',interface='org.freedesktop.DBus.Properties'"
+	    );
+	    addMatch (
+		sources.systemBus,
+		"type='signal',sender='org.freedesktop.login1',path='" + sources.session
+		    + "',interface='org.freedesktop.login1.Session'"
+	    );
+	    dbus_connection_add_filter (sources.systemBus, noteSignal, &sources, nullptr);
+	} else {
+	    sLog.debug ("Lock: no logind session, relying on the screen saver");
+	}
+    }
+
+    if (sources.sessionBus != nullptr) {
+	for (const auto& name : SCREEN_SAVERS) {
+	    addMatch (
+		sources.sessionBus,
+		std::string ("type='signal',interface='") + name.interface + "',member='ActiveChanged'"
+	    );
+	}
+
+	addMatch (
+	    sources.sessionBus,
+	    "type='signal',sender='org.gnome.Mutter.DisplayConfig',interface='org.freedesktop.DBus.Properties'"
+	);
+	dbus_connection_add_filter (sources.sessionBus, noteSignal, &sources, nullptr);
+    }
+
+    // an X server tells nothing by itself, it is asked once a second
+    if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type == nullptr || std::string_view (type) == "x11") {
+	sources.dpms = std::make_unique<X11Dpms> ();
+
+	if (!sources.dpms->open ()) {
+	    sources.dpms.reset ();
+	}
+    }
+
+    auto nextRecheck = std::chrono::steady_clock::now ();
+
+    while (!this->m_stop) {
+	if (sources.changed.exchange (false) || std::chrono::steady_clock::now () >= nextRecheck) {
+	    nextRecheck = std::chrono::steady_clock::now () + RECHECK_INTERVAL;
+
+	    // a call that timed out says nothing, the state from before stays
+	    if (!sources.session.empty ()) {
+		if (const auto hint = logindLockedHint (sources.systemBus, sources.session); hint.has_value ()) {
+		    sources.hint = *hint;
+		}
+	    }
+
+	    std::optional<bool> active;
+	    bool saverOnBus = false;
+
+	    if (sources.sessionBus != nullptr) {
+		for (const auto& name : SCREEN_SAVERS) {
+		    if (this->m_stop) {
+			break;
+		    }
+
+		    saverOnBus = saverOnBus || dbus_bus_name_has_owner (sources.sessionBus, name.service, nullptr);
+
+		    if (const auto answer = screenSaverActive (sources.sessionBus, name); answer.has_value ()) {
+			active = active.value_or (false) || *answer;
+		    }
+		}
+	    }
+
+	    if (this->m_stop) {
+		break;
+	    }
+
+	    // a locker that went away while locked never sends ActiveChanged(false)
+	    sources.screenSaver = active.value_or (saverOnBus && sources.screenSaverSignal == 1);
+
+	    if (sources.sessionBus != nullptr) {
+		if (const auto off = mutterDisplayOff (sources.sessionBus); off.has_value ()) {
+		    sources.mutterOff = *off;
+		}
+	    }
+
+	    const bool locked = sources.hint || sources.screenSaver;
+
+	    if (locked != this->m_locked) {
+		this->m_locked = locked;
+		sLog.out (
+		    "Lock: session ", locked ? "locked" : "unlocked", " (logind hint ", sources.hint ? "set" : "clear",
+		    ", screen saver ", sources.screenSaver ? "active" : "inactive", ")"
+		);
+	    }
+	}
+
+	pollfd fds[3] = {
+	    { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
+	    { .fd = -1, .events = POLLIN, .revents = 0 },
+	    { .fd = -1, .events = POLLIN, .revents = 0 },
+	};
+
+	// the blocking calls above read the socket and queue whatever else arrived, poll never sees that again
+	bool queued = false;
+
+	for (int i = 0; i < 2; i++) {
+	    DBusConnection* bus = i == 0 ? sources.systemBus : sources.sessionBus;
+
+	    if (bus != nullptr && dbus_connection_get_is_connected (bus)) {
+		int fd = -1;
+		dbus_connection_get_unix_fd (bus, &fd);
+		fds[1 + i].fd = fd;
+		queued = queued || dbus_connection_get_dispatch_status (bus) == DBUS_DISPATCH_DATA_REMAINS;
+	    }
+	}
+
+	bool displayOff = sources.mutterOff;
+
+	if (sources.dpms != nullptr) {
+	    displayOff = displayOff || sources.dpms->blanked ().value_or (false);
+	}
+
+	if (displayOff != this->m_displayOff) {
+	    this->m_displayOff = displayOff;
+	    sLog.out ("Display: ", displayOff ? "blanked (DPMS)" : "on again");
+	}
+
+	auto untilRecheck
+	    = std::chrono::duration_cast<std::chrono::milliseconds> (nextRecheck - std::chrono::steady_clock::now ());
+
+	if (sources.dpms != nullptr) {
+	    untilRecheck = std::min (untilRecheck, std::chrono::milliseconds (DPMS_POLL_MS));
+	}
+
+	poll (fds, 3, queued ? 0 : static_cast<int> (std::max<int64_t> (1, untilRecheck.count ())));
+
+	if (fds[0].revents & POLLIN) {
+	    uint64_t value;
+	    std::ignore = read (this->m_wakeFd, &value, sizeof (value));
+	}
+
+	// unread messages count against the session bus quota, read them even when only the other bus spoke
+	for (DBusConnection* bus : { sources.systemBus, sources.sessionBus }) {
+	    if (bus != nullptr) {
+		drainBus (bus);
+	    }
+	}
+    }
+}

+ 39 - 0
src/WallpaperEngine/Desktop/SessionMonitor.h

@@ -0,0 +1,39 @@
+#pragma once
+
+#include <atomic>
+#include <memory>
+#include <thread>
+
+namespace WallpaperEngine::Desktop {
+/**
+ * Whether the session is locked: logind's LockedHint of this session, or a screen saver that says it is active
+ * (org.freedesktop.ScreenSaver on KDE and others, org.gnome.ScreenSaver, Cinnamon, MATE). And whether the displays are
+ * blanked, where something tells: the DPMS state of an X server, Mutter's PowerSaveMode. Wayland compositors without
+ * either are left to their frame callbacks, which most stop for a blanked output. Runs on a thread of its own so the
+ * render thread never waits for a bus call.
+ */
+class SessionMonitor {
+public:
+    SessionMonitor ();
+    ~SessionMonitor ();
+
+    SessionMonitor (const SessionMonitor&) = delete;
+    SessionMonitor& operator= (const SessionMonitor&) = delete;
+
+    [[nodiscard]] bool locked () const { return this->m_locked; }
+    [[nodiscard]] bool displayOff () const { return this->m_displayOff; }
+
+    struct Sources;
+
+private:
+    void run ();
+    void wake () const;
+
+    std::atomic<bool> m_locked = false;
+    std::atomic<bool> m_displayOff = false;
+    std::atomic<bool> m_stop = false;
+    int m_wakeFd = -1;
+    std::unique_ptr<Sources> m_sources;
+    std::thread m_thread;
+};
+}

+ 155 - 11
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -2,14 +2,30 @@
 
 #include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
 
 #include <cstdio>
 #include <cstring>
 #include <sstream>
+#include <thread>
 #include <unistd.h>
 
 namespace WallpaperEngine::Input::Drivers {
 
+namespace {
+    constexpr std::chrono::seconds RELOAD_RETRY (5);
+}
+
+struct KDECursorInput::ScriptHandle {
+    DBusConnection* bus = nullptr;
+    std::unique_ptr<WallpaperEngine::Desktop::KWinScript> script;
+
+    ~ScriptHandle () {
+	this->script.reset ();
+	WallpaperEngine::Desktop::closeBus (this->bus);
+    }
+};
+
 KDECursorInput::KDECursorInput () {
     if (!initializeDBus ()) {
 	sLog.out ("KDE cursor input could not initialize DBus, mouse-reactive effects may not work on this session");
@@ -25,6 +41,10 @@ KDECursorInput::KDECursorInput () {
 }
 
 KDECursorInput::~KDECursorInput () {
+    if (m_reload.valid ()) {
+	m_reload.get ();
+    }
+
     unloadKWinScript ();
     stopDBus ();
 }
@@ -91,27 +111,117 @@ void KDECursorInput::stopDBus () {
     }
 }
 
-bool KDECursorInput::loadKWinScript () {
-    const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
-
+static std::string cursorScriptSource (const char* serviceName, const char* objectPath, const char* methodName) {
     std::ostringstream script;
-    script << "function lweReportCursorPos() {\n"
+    script << "var lweLastReport = 0;\n"
+	   << "var lweTimer = null;\n"
+	   << "var lweTimerFailed = false;\n"
+	   << "function lweSend() {\n"
+	   << "    lweLastReport = Date.now();\n"
 	   << "    var p = workspace.cursorPos;\n"
-	   << "    callDBus(\"" << serviceName << "\", \"" << kObjectPath << "\", \"" << serviceName << "\", \""
-	   << kMethodName << "\", p.x, p.y);\n"
+	   << "    callDBus(\"" << serviceName << "\", \"" << objectPath << "\", \"" << serviceName << "\", \""
+	   << methodName << "\", p.x, p.y);\n"
+	   << "}\n"
+	   << "function lweReportCursorPos() {\n"
+	   << "    if (Date.now() - lweLastReport >= 5) {\n"
+	   << "        lweSend();\n"
+	   << "        return;\n"
+	   << "    }\n"
+	   << "    if (lweTimer === null && !lweTimerFailed) {\n"
+	   << "        try {\n"
+	   << "            lweTimer = new QTimer();\n"
+	   << "            lweTimer.singleShot = true;\n"
+	   << "            lweTimer.interval = 5;\n"
+	   << "            lweTimer.timeout.connect(lweSend);\n"
+	   << "        } catch (e) {\n"
+	   << "            lweTimer = null;\n"
+	   << "            lweTimerFailed = true;\n"
+	   << "        }\n"
+	   << "    }\n"
+	   << "    if (lweTimer !== null && !lweTimer.active) {\n"
+	   << "        lweTimer.start();\n"
+	   << "    }\n"
 	   << "}\n"
 	   << "workspace.cursorPosChanged.connect(lweReportCursorPos);\n"
-	   << "lweReportCursorPos();\n";
+	   << "lweSend();\n";
 
-    this->m_script = std::make_unique<WallpaperEngine::Desktop::KWinScript> (
-	m_connection, "lwe-cursor-input-" + WallpaperEngine::Desktop::processTag (), script.str ()
+    return script.str ();
+}
+
+bool KDECursorInput::loadKWinScript () {
+    const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
+
+    auto handle = std::make_unique<ScriptHandle> ();
+    handle->script = std::make_unique<WallpaperEngine::Desktop::KWinScript> (
+	m_connection, "lwe-cursor-input-" + WallpaperEngine::Desktop::processTag (),
+	cursorScriptSource (serviceName.c_str (), kObjectPath, kMethodName)
     );
 
-    return this->m_script->isLoaded ();
+    if (!handle->script->isLoaded ()) {
+	return false;
+    }
+
+    this->m_script = std::move (handle);
+    return true;
 }
 
 void KDECursorInput::unloadKWinScript () { this->m_script.reset (); }
 
+void KDECursorInput::startReload () {
+    const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
+    // a reload that was dropped after a new pause is still being unloaded on its own thread, under its own name and
+    // file
+    const std::string pluginName
+	= "lwe-cursor-input-" + WallpaperEngine::Desktop::processTag () + "-r" + std::to_string (++m_reloadCount);
+    const std::string source = cursorScriptSource (serviceName.c_str (), kObjectPath, kMethodName);
+
+    // KWin may be busy closing the game's window, the render thread must not wait for its answers
+    this->m_reload = std::async (std::launch::async, [pluginName, source] {
+	std::unique_ptr<ScriptHandle> handle;
+
+	WallpaperEngine::Logging::guardThread ("KWin script reload", [&] {
+	    auto made = std::make_unique<ScriptHandle> ();
+	    made->bus = WallpaperEngine::Desktop::privateBus (DBUS_BUS_SESSION);
+
+	    if (made->bus != nullptr) {
+		made->script = std::make_unique<WallpaperEngine::Desktop::KWinScript> (made->bus, pluginName, source);
+
+		if (!made->script->isLoaded ()) {
+		    made->script.reset ();
+		}
+	    }
+
+	    handle = std::move (made);
+	});
+
+	return handle;
+    });
+}
+
+void KDECursorInput::pollReload () {
+    if (!m_reload.valid () || m_reload.wait_for (std::chrono::seconds (0)) != std::future_status::ready) {
+	return;
+    }
+
+    auto handle = m_reload.get ();
+
+    if (m_suspended || m_script != nullptr) {
+	if (handle != nullptr) {
+	    std::thread ([discarded = std::move (handle)] () mutable { discarded.reset (); }).detach ();
+	}
+
+	return;
+    }
+
+    if (handle != nullptr && handle->script != nullptr) {
+	m_script = std::move (handle);
+	return;
+    }
+
+    sLog.error ("KDE cursor input could not load its KWin script again, trying again in ", RELOAD_RETRY.count (), "s");
+    m_nextReload = std::chrono::steady_clock::now () + RELOAD_RETRY;
+}
+
 DBusHandlerResult KDECursorInput::handleMessage (DBusConnection* connection, DBusMessage* message, void* userData) {
     const auto input = static_cast<KDECursorInput*> (userData);
     return input->handleMessage (message);
@@ -164,12 +274,46 @@ std::optional<glm::dvec2> KDECursorInput::position () {
 	    dbus_connection_unregister_object_path (m_connection, kObjectPath);
 	    dbus_connection_unref (m_connection);
 	    m_connection = nullptr;
+	} else {
+	    pollReload ();
+
+	    if (!m_suspended && m_script == nullptr && !m_reload.valid ()
+		&& std::chrono::steady_clock::now () >= m_nextReload) {
+		startReload ();
+	    }
 	}
     }
 
+    // no script, no cursor: the last position would pin the pointer and keep the other sources unread
+    if (!m_suspended && m_script == nullptr) {
+	return std::nullopt;
+    }
+
     return m_pos;
 }
 
-bool KDECursorInput::isInitialized () const { return m_connection != nullptr && m_script && m_script->isLoaded (); }
+// the constructor drops the connection when the first load fails, so a missing script later is a reload in progress
+// and the input region must not flip to capturing every click meanwhile
+bool KDECursorInput::isInitialized () const { return m_connection != nullptr; }
+
+void KDECursorInput::setSuspended (bool suspended) {
+    if (m_connection == nullptr || m_suspended == suspended) {
+	return;
+    }
+
+    m_suspended = suspended;
+
+    if (suspended) {
+	unloadKWinScript ();
+	position ();
+	return;
+    }
+
+    m_nextReload = {};
+
+    if (!m_reload.valid ()) {
+	startReload ();
+    }
+}
 
 }

+ 13 - 1
src/WallpaperEngine/Input/Drivers/KDECursorInput.h

@@ -3,7 +3,9 @@
 #ifdef ENABLE_WAYLAND
 #ifdef ENABLE_KDE_FEATURES
 
+#include <chrono>
 #include <dbus/dbus.h>
+#include <future>
 #include <glm/vec2.hpp>
 #include <memory>
 #include <optional>
@@ -27,12 +29,18 @@ public:
 
     [[nodiscard]] bool isInitialized () const;
 
+    void setSuspended (bool suspended);
+
 private:
+    struct ScriptHandle;
+
     bool initializeDBus ();
     void stopDBus ();
 
     bool loadKWinScript ();
     void unloadKWinScript ();
+    void startReload ();
+    void pollReload ();
 
     static DBusHandlerResult handleMessage (DBusConnection* connection, DBusMessage* message, void* userData);
     DBusHandlerResult handleMessage (DBusMessage* message);
@@ -40,8 +48,12 @@ private:
 
     DBusConnection* m_connection = nullptr;
     std::optional<glm::dvec2> m_pos;
+    bool m_suspended = false;
+    unsigned m_reloadCount = 0;
 
-    std::unique_ptr<WallpaperEngine::Desktop::KWinScript> m_script;
+    std::unique_ptr<ScriptHandle> m_script;
+    std::future<std::unique_ptr<ScriptHandle>> m_reload;
+    std::chrono::steady_clock::time_point m_nextReload {};
 
     static constexpr const char* kServiceName = "org.linuxwallpaperengine.CursorInput";
     static constexpr const char* kObjectPath = "/org/linuxwallpaperengine/CursorInput";

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

@@ -52,10 +52,31 @@ void WaylandMouseInput::pollForwardedInput () {
 	= forwardedLeftDown (this->m_waylandDriver.getApp ().getContext ().settings.mouse.inputFile);
 }
 
+void WaylandMouseInput::drain () {
+#ifdef ENABLE_KDE_FEATURES
+    if (this->m_kdeCursor) {
+	this->m_kdeCursor->position ();
+    }
+#endif
+}
+
+void WaylandMouseInput::suspend (bool suspended) {
+#ifdef ENABLE_KDE_FEATURES
+    if (this->m_kdeCursor) {
+	this->m_kdeCursor->setSuspended (suspended);
+    }
+#else
+    (void)suspended;
+#endif
+}
+
 void WaylandMouseInput::update () {
     if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
 	this->m_globalCursor.reset ();
 	this->m_forwardedLeftDown = false;
+
+	// the cursor script is loaded anyway, unread calls count against the session bus quota
+	this->drain ();
 	return;
     }
 

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

@@ -27,6 +27,8 @@ public:
     explicit WaylandMouseInput (const WallpaperEngine::Render::Drivers::WaylandOpenGLDriver& driver);
 
     void update () override;
+    void drain () override;
+    void suspend (bool suspended) override;
 
     [[nodiscard]] glm::dvec2 position () const override;
     [[nodiscard]] MouseClickStatus leftClick () const override;

+ 4 - 0
src/WallpaperEngine/Input/InputContext.cpp

@@ -7,4 +7,8 @@ InputContext::InputContext (MouseInput& mouseInput) : m_mouse (mouseInput) { }
 
 void InputContext::update () { this->m_mouse.update (); }
 
+void InputContext::drain () { this->m_mouse.drain (); }
+
+void InputContext::suspend (bool suspended) { this->m_mouse.suspend (suspended); }
+
 const MouseInput& InputContext::getMouseInput () const { return this->m_mouse; }

+ 2 - 0
src/WallpaperEngine/Input/InputContext.h

@@ -12,6 +12,8 @@ public:
     explicit InputContext (MouseInput& mouseInput);
 
     void update ();
+    void drain ();
+    void suspend (bool suspended);
 
     [[nodiscard]] const MouseInput& getMouseInput () const;
 

+ 2 - 0
src/WallpaperEngine/Input/MouseInput.h

@@ -12,6 +12,8 @@ class MouseInput {
 public:
     virtual ~MouseInput () = default;
     virtual void update () = 0;
+    virtual void drain () { }
+    virtual void suspend (bool suspended) { (void)suspended; }
 
     [[nodiscard]] virtual glm::dvec2 position () const = 0;
     [[nodiscard]] virtual MouseClickStatus leftClick () const = 0;

+ 190 - 13
src/WallpaperEngine/Media/DBusMediaSource.cpp

@@ -2,8 +2,11 @@
 
 #include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 
+#include <thread>
+
 using namespace WallpaperEngine::Media;
 
 DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage* message, void* user_data) {
@@ -13,6 +16,11 @@ DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage*
 	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
     }
 
+    if (mediaSource->discarding ()) {
+	mediaSource->noteMissed ();
+	return DBUS_HANDLER_RESULT_HANDLED;
+    }
+
     const char* interface = nullptr;
     DBusMessageIter iter;
 
@@ -90,31 +98,112 @@ DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage*
     return DBUS_HANDLER_RESULT_HANDLED;
 }
 
+namespace {
+constexpr std::chrono::seconds RECONNECT_INTERVAL (5);
+}
+
 DBusMediaSource::DBusMediaSource (std::chrono::milliseconds updateInterval) : MediaSource (updateInterval) {
-    DBusError err;
+    if (!this->connect ()) {
+	sLog.exception ("Could not connect to the DBus session bus");
+    }
+}
 
-    dbus_error_init (&err);
+DBusMediaSource::~DBusMediaSource () {
+    if (this->m_pending) {
+	this->m_pending->abandoned = true;
+	Desktop::closeBus (this->m_pending->bus.exchange (nullptr));
+    }
+
+    this->disconnect ();
+}
 
-    this->m_connection = dbus_bus_get (DBUS_BUS_SESSION, &err);
+bool DBusMediaSource::connect () {
+    DBusConnection* connection = Desktop::privateBus (DBUS_BUS_SESSION);
 
-    if (!this->m_connection) {
-	sLog.exception ("Could not connect to DBus: ", err.message);
+    if (connection == nullptr) {
+	sLog.debug ("Media: session bus connection failed");
+	return false;
     }
 
-    dbus_connection_add_filter (this->m_connection, dbus_message_filter, this, nullptr);
+    this->attach (connection);
+    return true;
+}
 
+void DBusMediaSource::attach (DBusConnection* connection) {
+    dbus_connection_add_filter (connection, dbus_message_filter, this, nullptr);
     dbus_bus_add_match (
-	this->m_connection, "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'",
+	connection,
+	"type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',"
+	"path='/org/mpris/MediaPlayer2',arg0='org.mpris.MediaPlayer2.Player'",
 	nullptr
     );
+    dbus_connection_flush (connection);
 
-    dbus_connection_flush (this->m_connection);
+    this->m_connection = connection;
 }
 
-DBusMediaSource::~DBusMediaSource () {
-    dbus_connection_remove_filter (this->m_connection, dbus_message_filter, this);
+void DBusMediaSource::disconnect () {
+    if (this->m_connection == nullptr) {
+	return;
+    }
 
+    dbus_connection_remove_filter (this->m_connection, dbus_message_filter, this);
+    dbus_connection_close (this->m_connection);
     dbus_connection_unref (this->m_connection);
+    this->m_connection = nullptr;
+}
+
+bool DBusMediaSource::isConnected () const {
+    return this->m_connection != nullptr && dbus_connection_get_is_connected (this->m_connection);
+}
+
+void DBusMediaSource::handleLoss () {
+    sLog.error ("Media: the session bus dropped the connection, trying again every ", RECONNECT_INTERVAL.count (), "s");
+
+    this->m_currentPlayer.reset ();
+    this->disconnect ();
+    this->m_nextReconnect = std::chrono::steady_clock::now () + RECONNECT_INTERVAL;
+}
+
+void DBusMediaSource::tryReconnect () {
+    if (this->m_connection != nullptr) {
+	return;
+    }
+
+    if (this->m_pending) {
+	if (!this->m_pending->done) {
+	    return;
+	}
+
+	DBusConnection* connection = this->m_pending->bus.exchange (nullptr);
+	this->m_pending.reset ();
+
+	if (connection != nullptr) {
+	    this->attach (connection);
+	    sLog.out ("Media: reconnected to the session bus");
+	} else {
+	    this->m_nextReconnect = std::chrono::steady_clock::now () + RECONNECT_INTERVAL;
+	}
+
+	return;
+    }
+
+    if (std::chrono::steady_clock::now () < this->m_nextReconnect) {
+	return;
+    }
+
+    this->m_pending = std::make_shared<PendingConnect> ();
+
+    std::thread ([pending = this->m_pending] {
+	DBusConnection* connection = Desktop::privateBus (DBUS_BUS_SESSION);
+	pending->bus = connection;
+
+	if (pending->abandoned) {
+	    Desktop::closeBus (pending->bus.exchange (nullptr));
+	}
+
+	pending->done = true;
+    }).detach ();
 }
 
 void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
@@ -263,6 +352,10 @@ void DBusMediaSource::switchPlayer (const std::string& player) {
 }
 
 std::optional<std::string> DBusMediaSource::uniqueName (const std::string& name) {
+    if (!this->isConnected ()) {
+	return std::nullopt;
+    }
+
     const char* nameText = name.c_str ();
     DBusError err;
     dbus_error_init (&err);
@@ -302,18 +395,93 @@ void DBusMediaSource::parsePosition (DBusMessageIter& variant) {
 }
 
 void DBusMediaSource::update () {
+    this->tryReconnect ();
+
+    if (this->m_missed) {
+	this->m_missed = false;
+	this->resync ();
+    }
+
     this->MediaSource::update ();
+    this->drain ();
+}
+
+void DBusMediaSource::drain () {
+    if (this->m_connection != nullptr && !Desktop::drainBus (this->m_connection)) {
+	this->handleLoss ();
+    }
+}
+
+void DBusMediaSource::discard () {
+    if (this->m_connection == nullptr) {
+	return;
+    }
 
-    dbus_connection_read_write (this->m_connection, 0);
+    this->m_discarding = true;
+    const bool alive = Desktop::drainBus (this->m_connection);
+    this->m_discarding = false;
 
-    while (dbus_connection_dispatch (this->m_connection) == DBUS_DISPATCH_DATA_REMAINS)
-	;
+    if (!alive) {
+	this->handleLoss ();
+    }
+}
+
+// signals were thrown away while nothing was shown, the player is asked for what changed meanwhile
+void DBusMediaSource::resync () {
+    if (!this->m_currentPlayer.has_value ()) {
+	this->m_nextUpdate = {};
+	return;
+    }
+
+    this->initialStatusFetch ();
+
+    DBusMessage* reply = this->dbusMessage (
+	this->m_currentPlayer.value ().c_str (), "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties", "Get",
+	"org.mpris.MediaPlayer2.Player", "PlaybackStatus"
+    );
+
+    if (reply == nullptr) {
+	this->m_currentPlayer.reset ();
+	this->m_nextUpdate = {};
+	return;
+    }
+
+    Data::Utils::ScopeGuard guard ([reply] { dbus_message_unref (reply); });
+    DBusMessageIter outer;
+    dbus_message_iter_init (reply, &outer);
+
+    DBusMessageIter variant;
+    dbus_message_iter_recurse (&outer, &variant);
+
+    if (dbus_message_iter_get_arg_type (&variant) != DBUS_TYPE_STRING) {
+	return;
+    }
+
+    DBusMessageIter statusIter = variant;
+    const char* status = nullptr;
+    dbus_message_iter_get_basic (&statusIter, &status);
+
+    this->parsePlaybackStatus (variant, this->m_currentPlayer->c_str ());
+
+    // another player may have started while its signals were thrown away, detectPlayer only takes one that plays
+    if (status == nullptr || std::string_view (status) != "Playing") {
+	const auto previous = this->m_currentPlayer;
+	this->detectPlayer ();
+
+	if (this->m_currentPlayer != previous) {
+	    this->initialStatusFetch ();
+	}
+    }
 }
 
 DBusMessage* DBusMediaSource::dbusMessage (
     const char* bus_name, const char* path, const char* interface, const char* method, const char* iface,
     const char* prop
 ) {
+    if (!this->isConnected ()) {
+	return nullptr;
+    }
+
     DBusError err;
     dbus_error_init (&err);
 
@@ -442,6 +610,15 @@ void DBusMediaSource::initialStatusFetch () {
 }
 
 void DBusMediaSource::performUpdate () {
+    if (this->m_connection == nullptr) {
+	return;
+    }
+
+    if (!this->isConnected ()) {
+	this->handleLoss ();
+	return;
+    }
+
     if (!this->m_currentPlayer.has_value ()) {
 	this->detectPlayer ();
 	this->initialStatusFetch ();

+ 26 - 1
src/WallpaperEngine/Media/DBusMediaSource.h

@@ -1,7 +1,9 @@
 #pragma once
 
 #include "MediaSource.h"
+#include <atomic>
 #include <dbus/dbus.h>
+#include <memory>
 
 namespace WallpaperEngine::Media {
 class DBusMediaSource : public MediaSource {
@@ -14,12 +16,24 @@ public:
     void parsePosition (DBusMessageIter& variant);
 
     void update () override;
+    void drain () override;
+    void discard () override;
+
+    [[nodiscard]] bool discarding () const { return this->m_discarding; }
+    void noteMissed () { this->m_missed = true; }
 
     [[nodiscard]] bool isCurrentPlayer (const char* sender) const;
     void switchPlayer (const std::string& player);
 
 protected:
     void performUpdate () override;
+    bool connect ();
+    void attach (DBusConnection* connection);
+    void disconnect ();
+    void resync ();
+    void handleLoss ();
+    void tryReconnect ();
+    [[nodiscard]] bool isConnected () const;
     void initialStatusFetch ();
     void detectPlayer ();
     std::optional<std::string> uniqueName (const std::string& name);
@@ -31,6 +45,17 @@ protected:
 
     std::optional<std::string> m_currentPlayer = std::nullopt;
 
-    DBusConnection* m_connection;
+    // the session bus can take long to answer a new connection, that is waited for off the render thread
+    struct PendingConnect {
+	std::atomic<bool> done = false;
+	std::atomic<bool> abandoned = false;
+	std::atomic<DBusConnection*> bus = nullptr;
+    };
+
+    DBusConnection* m_connection = nullptr;
+    std::chrono::steady_clock::time_point m_nextReconnect {};
+    std::shared_ptr<PendingConnect> m_pending;
+    bool m_discarding = false;
+    bool m_missed = false;
 };
 }

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

@@ -37,6 +37,9 @@ public:
     virtual ~MediaSource ();
 
     virtual void update ();
+    virtual void drain () { }
+    /** Reads what is waiting and throws it away, for a loop that shows nothing: no listener runs for it */
+    virtual void discard () { }
 
     std::function<void ()> addMetadataListener (std::function<void (const MediaInfo&)> listener);
     std::function<void ()> addAlbumArtListener (std::function<void (const MediaInfo&)> listener);

+ 106 - 89
src/WallpaperEngine/Render/CTexture.cpp

@@ -1,4 +1,5 @@
 #include "CTexture.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <algorithm>
@@ -98,6 +99,7 @@ void CTexture::releaseMipmapData () {
 }
 
 void CTexture::uploadImages (const UploadFormat& upload) const {
+    LWE_ZONE ("texture upload");
     struct Decoded {
 	const Mipmap* mipmap = nullptr;
 	stbi_uc* pixels = nullptr;
@@ -117,56 +119,65 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 	}
     }
 
+    [[maybe_unused]] const auto description = [&] {
+	return std::to_string (this->m_header->textureWidth) + "x" + std::to_string (this->m_header->textureHeight)
+	    + " fif " + std::to_string (this->m_header->freeImageFormat) + (upload.compressed ? " compressed" : " raw")
+	    + " images " + std::to_string (this->m_header->imageCount);
+    };
+
     const auto decode = [] (Decoded& job) {
 	job.pixels = decodeImageRGBA (
 	    job.mipmap->uncompressedData.get (), job.mipmap->uncompressedSize, job.width, job.height
 	);
     };
 
-    if (decoded.size () == 1) {
-	decode (decoded.front ());
-    } else if (decoded.size () > 1) {
-	std::atomic<size_t> next = 0;
-	std::exception_ptr failure;
-	std::mutex failureMutex;
-	// an exception leaving a thread's function ends the process, the first one goes back to the caller instead
-	const auto worker = [&decoded, &next, &decode, &failure, &failureMutex] () {
-	    try {
-		for (size_t i = next++; i < decoded.size (); i = next++) {
-		    decode (decoded[i]);
-		}
-	    } catch (...) {
-		const std::scoped_lock lock (failureMutex);
+    {
+	LWE_ZONE_TEXT ("texture decode", description ());
+	if (decoded.size () == 1) {
+	    decode (decoded.front ());
+	} else if (decoded.size () > 1) {
+	    std::atomic<size_t> next = 0;
+	    std::exception_ptr failure;
+	    std::mutex failureMutex;
+	    // an exception leaving a thread's function ends the process, the first one goes back to the caller instead
+	    const auto worker = [&decoded, &next, &decode, &failure, &failureMutex] () {
+		try {
+		    for (size_t i = next++; i < decoded.size (); i = next++) {
+			decode (decoded[i]);
+		    }
+		} catch (...) {
+		    const std::scoped_lock lock (failureMutex);
 
-		if (!failure) {
-		    failure = std::current_exception ();
+		    if (!failure) {
+			failure = std::current_exception ();
+		    }
+
+		    next = decoded.size ();
 		}
+	    };
+	    const size_t threadCount
+		= std::min<size_t> (decoded.size (), std::max (1u, std::thread::hardware_concurrency ()));
+	    std::vector<std::thread> threads;
 
-		next = decoded.size ();
+	    for (size_t i = 1; i < threadCount; i++) {
+		threads.emplace_back (worker);
 	    }
-	};
-	const size_t threadCount
-	    = std::min<size_t> (decoded.size (), std::max (1u, std::thread::hardware_concurrency ()));
-	std::vector<std::thread> threads;
 
-	for (size_t i = 1; i < threadCount; i++) {
-	    threads.emplace_back (worker);
-	}
+	    worker ();
 
-	worker ();
-
-	for (auto& thread : threads) {
-	    thread.join ();
-	}
+	    for (auto& thread : threads) {
+		thread.join ();
+	    }
 
-	if (failure) {
-	    for (const auto& job : decoded) {
-		if (job.pixels != nullptr) {
-		    stbi_image_free (job.pixels);
+	    if (failure) {
+		for (const auto& job : decoded) {
+		    if (job.pixels != nullptr) {
+			stbi_image_free (job.pixels);
+		    }
 		}
-	    }
 
-	    std::rethrow_exception (failure);
+		std::rethrow_exception (failure);
+	    }
 	}
     }
 
@@ -180,67 +191,71 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
     glGetIntegerv (GL_UNPACK_ALIGNMENT, &previousAlignment);
     glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
 
-    for (const auto& [index, mipmaps] : this->m_header->images) {
-	this->setupOpenGLParameters (index);
-
-	int level = 0;
-
-	for (const auto& mipmap : mipmaps) {
-	    stbi_uc* handle = nullptr;
-	    const void* dataptr = mipmap->uncompressedData.get ();
-	    size_t dataSize = std::max (mipmap->uncompressedSize, 0);
-	    int width = mipmap->width;
-	    int height = mipmap->height;
-
-	    if (!mipmap->composedPixels.empty ()) {
-		dataptr = mipmap->composedPixels.data ();
-		dataSize = mipmap->composedPixels.size ();
-	    } else if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
-		dataptr = handle = nextDecoded->pixels;
-		width = nextDecoded->width;
-		height = nextDecoded->height;
-		dataSize = handle != nullptr ? static_cast<size_t> (width) * height * 4 : 0;
-		++nextDecoded;
-	    }
+    {
+	LWE_ZONE_TEXT ("texture gl upload", description ());
+	for (const auto& [index, mipmaps] : this->m_header->images) {
+	    this->setupOpenGLParameters (index);
 
-	    if (width <= 0 || height <= 0
-		|| (maxTextureSize > 0 && (width > maxTextureSize || height > maxTextureSize))) {
-		// GL refuses it, and the zero padding below would allocate width x height from the file's word
-		sLog.error (
-		    "Texture mipmap ", width, "x", height, " is past GL_MAX_TEXTURE_SIZE (", maxTextureSize,
-		    "), skipped"
-		);
-	    } else if (upload.compressed) {
-		glCompressedTexImage2D (
-		    GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, static_cast<GLsizei> (dataSize),
-		    dataptr
-		);
-	    } else {
-		const size_t expected = static_cast<size_t> (width) * height * upload.bytesPerPixel;
-		std::vector<unsigned char> padded;
-
-		if (dataSize < expected) {
-		    padded.resize (expected, 0);
-
-		    if (dataptr != nullptr && dataSize > 0) {
-			memcpy (padded.data (), dataptr, dataSize);
-		    }
+	    int level = 0;
 
-		    dataptr = padded.data ();
+	    for (const auto& mipmap : mipmaps) {
+		stbi_uc* handle = nullptr;
+		const void* dataptr = mipmap->uncompressedData.get ();
+		size_t dataSize = std::max (mipmap->uncompressedSize, 0);
+		int width = mipmap->width;
+		int height = mipmap->height;
+
+		if (!mipmap->composedPixels.empty ()) {
+		    dataptr = mipmap->composedPixels.data ();
+		    dataSize = mipmap->composedPixels.size ();
+		} else if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
+		    dataptr = handle = nextDecoded->pixels;
+		    width = nextDecoded->width;
+		    height = nextDecoded->height;
+		    dataSize = handle != nullptr ? static_cast<size_t> (width) * height * 4 : 0;
+		    ++nextDecoded;
 		}
 
-		glTexImage2D (
-		    GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, upload.format, upload.type, dataptr
-		);
-	    }
+		if (width <= 0 || height <= 0
+		    || (maxTextureSize > 0 && (width > maxTextureSize || height > maxTextureSize))) {
+		    // GL refuses it, and the zero padding below would allocate width x height from the file's word
+		    sLog.error (
+			"Texture mipmap ", width, "x", height, " is past GL_MAX_TEXTURE_SIZE (", maxTextureSize,
+			"), skipped"
+		    );
+		} else if (upload.compressed) {
+		    glCompressedTexImage2D (
+			GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, static_cast<GLsizei> (dataSize),
+			dataptr
+		    );
+		} else {
+		    const size_t expected = static_cast<size_t> (width) * height * upload.bytesPerPixel;
+		    std::vector<unsigned char> padded;
+
+		    if (dataSize < expected) {
+			padded.resize (expected, 0);
+
+			if (dataptr != nullptr && dataSize > 0) {
+			    memcpy (padded.data (), dataptr, dataSize);
+			}
+
+			dataptr = padded.data ();
+		    }
 
-	    if (handle != nullptr) {
-		stbi_image_free (handle);
-	    }
+		    glTexImage2D (
+			GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, upload.format, upload.type,
+			dataptr
+		    );
+		}
+
+		if (handle != nullptr) {
+		    stbi_image_free (handle);
+		}
 
-	    std::vector<unsigned char> ().swap (mipmap->composedPixels);
+		std::vector<unsigned char> ().swap (mipmap->composedPixels);
 
-	    level++;
+		level++;
+	    }
 	}
     }
 
@@ -436,6 +451,8 @@ void CTexture::decrementUsageCount () const {
 }
 
 void CTexture::update () const {
+    LWE_ZONE ("texture update");
+
     if (this->m_player) {
 	this->m_player->render ();
     }

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

@@ -1,5 +1,6 @@
 #include "GLFWOpenGLDriver.h"
 #include "VideoFactories.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include "WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h"
@@ -235,7 +236,10 @@ void GLFWOpenGLDriver::dispatchEventQueue () {
     glBindFramebuffer (GL_FRAMEBUFFER, 0);
 
     this->m_output->updateRender ();
-    glfwSwapBuffers (this->m_window);
+    {
+	LWE_ZONE ("swap");
+	glfwSwapBuffers (this->m_window);
+    }
     glfwPollEvents ();
     this->m_frameCounter++;
 }

+ 30 - 4
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -1,4 +1,5 @@
 #include "WaylandOutputViewport.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Desktop/GnomeShell.h"
 #include "WallpaperEngine/Logging/Log.h"
 
@@ -521,6 +522,12 @@ void WaylandOutputViewport::setupFractionalScale () {
 
     // a fractional buffer needs the viewport to tell the compositor its logical size
     if (!context->viewporter) {
+	const auto& scales = m_driver->getApp ().getContext ().settings.general.screenRenderScales;
+
+	if (scales.contains (this->name)) {
+	    sLog.error ("Output ", this->name, ": --render-scale needs wp_viewporter, which the compositor lacks");
+	}
+
 	return;
     }
 
@@ -672,6 +679,7 @@ void WaylandOutputViewport::renderFrame () {
 }
 
 void WaylandOutputViewport::swapOutput () {
+    LWE_ZONE ("swap");
     this->callbackInitialized = true;
     this->lastSwap = std::chrono::steady_clock::now ();
 
@@ -698,21 +706,39 @@ void WaylandOutputViewport::swapOutput () {
     wl_surface_commit (surface);
 }
 
+double WaylandOutputViewport::renderFactor () const {
+    if (!this->surfaceViewport) {
+	return 1.0;
+    }
+
+    const auto& scales = this->m_driver->getApp ().getContext ().settings.general.screenRenderScales;
+    const auto it = scales.find (this->name);
+
+    return it != scales.end () ? it->second : 1.0;
+}
+
 double WaylandOutputViewport::renderScale () const {
     if (this->surfaceViewport && this->preferredScale120 > 0) {
-	return this->preferredScale120 / 120.0;
+	return this->preferredScale120 / 120.0 * this->renderFactor ();
     }
 
-    return this->scale;
+    return this->scale * this->renderFactor ();
 }
 
 glm::ivec2 WaylandOutputViewport::bufferSize () const {
     // fractional-scale-v1: the buffer is the logical size times the scale, rounded half away from zero
+    glm::ivec2 buffer = this->size * this->scale;
+
     if (this->surfaceViewport && this->preferredScale120 > 0) {
-	return (this->size * static_cast<int> (this->preferredScale120) + 60) / 120;
+	buffer = (this->size * static_cast<int> (this->preferredScale120) + 60) / 120;
+    }
+
+    // the destination of wp_viewport stays the logical size, so the compositor does the rest
+    if (const double factor = this->renderFactor (); factor < 1.0) {
+	buffer = glm::max (glm::ivec2 (glm::round (glm::dvec2 (buffer) * factor)), glm::ivec2 (1));
     }
 
-    return this->size * this->scale;
+    return buffer;
 }
 
 void WaylandOutputViewport::updateBufferSize () {

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

@@ -123,6 +123,8 @@ namespace Output {
 	} pendingDescription;
 
 	[[nodiscard]] double renderScale () const;
+	/** --render-scale of this output, 1 where the compositor can not scale the buffer up */
+	[[nodiscard]] double renderFactor () const;
 	[[nodiscard]] glm::ivec2 bufferSize () const;
 	void updateBufferSize ();
 

+ 45 - 12
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -1,4 +1,5 @@
 #include "CPass.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Render/DepthRange.h"
 
 #include <algorithm>
@@ -1039,6 +1040,7 @@ std::string patchColorAlpha (const std::string& shader) {
 }
 
 GLuint CPass::compileShader (const char* shader, GLuint type) {
+    LWE_ZONE ("shader compile");
     const GLuint shaderID = glCreateShader (type);
 
     glShaderSource (shaderID, 1, &shader, nullptr);
@@ -1069,6 +1071,7 @@ GLuint CPass::compileShader (const char* shader, GLuint type) {
 }
 
 void CPass::setupShaders () {
+    LWE_ZONE ("pass shaders");
     const auto texture0 = this->m_renderable.getTexture ();
 
     this->m_combos.insert (this->m_pass.combos.begin (), this->m_pass.combos.end ());
@@ -1269,18 +1272,30 @@ void CPass::setupShaders () {
 	}
     }
 
-    this->setupShaderVariables ();
-    this->setupUniforms ();
-    this->setupAttributes ();
-    this->g_Texture0Rotation = glGetUniformLocation (this->m_programID, "g_Texture0Rotation");
-    this->g_Texture0Translation = glGetUniformLocation (this->m_programID, "g_Texture0Translation");
+    {
+	LWE_ZONE ("pass variables");
+	this->setupShaderVariables ();
+	this->setupUniforms ();
+	this->setupAttributes ();
+	this->g_Texture0Rotation = glGetUniformLocation (this->m_programID, "g_Texture0Rotation");
+	this->g_Texture0Translation = glGetUniformLocation (this->m_programID, "g_Texture0Translation");
+    }
+}
+
+std::deque<std::shared_ptr<CPass::CompiledShader>>& CPass::recentShaders () {
+    static std::deque<std::shared_ptr<CompiledShader>> shaders;
+    return shaders;
 }
 
+void CPass::dropRecentShaders () { recentShaders ().clear (); }
+
 std::unordered_map<std::string, std::weak_ptr<CPass::CompiledShader>>& CPass::sharedShaders () {
     static std::unordered_map<std::string, std::weak_ptr<CompiledShader>> shaders;
     return shaders;
 }
 
+constexpr size_t RECENT_SHADERS = 128;
+
 std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
     const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures, const bool fresh
 ) {
@@ -1299,10 +1314,11 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
 		stream << comboName << '=' << comboValue << ';';
 	    }
 	}
+	// the shader only asks which slots are filled, never with what
 	for (const TextureMap* textures : { &passTextures, &overrideTextures }) {
 	    stream << '\1';
-	    for (const auto& [index, name] : *textures) {
-		stream << index << '=' << name << ';';
+	    for (const auto& entry : *textures) {
+		stream << entry.first << ';';
 	    }
 	}
 	key = stream.str ();
@@ -1320,11 +1336,15 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
     compiled->overrideCombos = this->m_override.combos;
     compiled->passTextures = passTextures;
     compiled->overrideTextures = overrideTextures;
-    compiled->shader = std::make_unique<Render::Shaders::Shader> (
-	this->m_renderable.getAssetLocator (), shaderName, compiled->combos, compiled->overrideCombos,
-	compiled->passTextures, compiled->overrideTextures, shareable ? noConstants : this->m_override.constants
-    );
+    {
+	LWE_ZONE_TEXT ("shader parse", shaderName);
+	compiled->shader = std::make_unique<Render::Shaders::Shader> (
+	    this->m_renderable.getAssetLocator (), shaderName, compiled->combos, compiled->overrideCombos,
+	    compiled->passTextures, compiled->overrideTextures, shareable ? noConstants : this->m_override.constants
+	);
+    }
 
+    LWE_ZONE_TEXT ("shader translate", shaderName);
     auto sources = Shaders::GLSLContext::get ().toGlsl (
 	compiled->shader->vertex (), compiled->shader->fragment (), shaderName, compiled->shader->geometry ()
     );
@@ -1336,6 +1356,15 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
     if (shareable) {
 	std::erase_if (sharedShaders (), [] (const auto& entry) { return entry.second.expired (); });
 	sharedShaders ().insert_or_assign (key, compiled);
+
+	// a pass swaps its first guess for one with more combos once the shader says which it has, and the next pass
+	// starts from the same guess: hold on to the latest ones so that is a lookup and not another parse
+	auto& recent = recentShaders ();
+	recent.push_back (compiled);
+
+	if (recent.size () > RECENT_SHADERS) {
+	    recent.pop_front ();
+	}
     }
 
     return compiled;
@@ -1364,6 +1393,7 @@ GLuint CPass::linkProgram (
     const std::string& vertex, const std::string& unpatchedFragment, const std::string& geometry,
     const std::string& shaderName
 ) {
+    LWE_ZONE_TEXT ("shader program", shaderName);
     const std::string fragment = patchColorAlpha (unpatchedFragment);
     auto& cache = Shaders::ShaderCache::get ();
     const std::string cacheKey = vertex + '\0' + fragment + '\0' + geometry;
@@ -1387,7 +1417,10 @@ GLuint CPass::linkProgram (
     if (cache.programsSupported ()) {
 	glProgramParameteri (program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
     }
-    glLinkProgram (program);
+    {
+	LWE_ZONE_TEXT ("shader link", shaderName);
+	glLinkProgram (program);
+    }
     GLint result = GL_FALSE;
     int infoLogLength = 0;
 

+ 3 - 0
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -28,6 +28,8 @@ using namespace WallpaperEngine::Data::Model;
 
 class CPass final : public Helpers::ContextAware {
 public:
+    static void dropRecentShaders ();
+
     CPass (
 	CRenderable& renderable, std::shared_ptr<const FBOProvider> fboProvider, const MaterialPass& pass,
 	std::optional<std::reference_wrapper<const ImageEffectPassOverride>> override,
@@ -206,6 +208,7 @@ private:
 	bool released = false;
     };
     static std::unordered_map<std::string, std::weak_ptr<CompiledShader>>& sharedShaders ();
+    static std::deque<std::shared_ptr<CompiledShader>>& recentShaders ();
     std::shared_ptr<CompiledShader> compileShaderSources (
 	const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures,
 	bool fresh = false

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

@@ -8,6 +8,8 @@
 #include "SplitLayout.h"
 #include "Transition.h"
 
+#include "WallpaperEngine/Debugging/Profiling.h"
+
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
@@ -74,12 +76,15 @@ namespace {
 }
 
 void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
+    LWE_ZONE_TEXT ("render output", viewport->name);
+
     if (frameStatsEnabled ()) {
 	this->renderWithStats (viewport);
 	return;
     }
 
     viewport->makeCurrent ();
+    this->beginProfiledFrame ();
     this->m_textureCache->repaintConditionalTextures ();
 
 #if !NDEBUG
@@ -88,7 +93,11 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
 #endif
 
-    this->drawWallpapers (*viewport);
+    {
+	LWE_GPU_ZONE ("draw wallpapers");
+	this->drawWallpapers (*viewport);
+    }
+
     noteFirstFrame (viewport->name);
 
 #if !NDEBUG
@@ -96,6 +105,19 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
 #endif
 
     viewport->swapOutput ();
+    LWE_GPU_COLLECT ();
+    LWE_FRAME_MARK ();
+}
+
+void RenderContext::beginProfiledFrame () {
+#ifdef LWE_TRACY
+    static bool gpuContextCreated = false;
+
+    if (!gpuContextCreated) {
+	TracyGpuContext;
+	gpuContextCreated = true;
+    }
+#endif
 }
 
 void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport) {
@@ -112,13 +134,18 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     stats.lastFrame = frameStart;
 
     viewport->makeCurrent ();
+    this->beginProfiledFrame ();
     this->m_textureCache->repaintConditionalTextures ();
     glFinish ();
     VideoPlayback::MPV::GLPlayer::s_statsMillis = 0.0;
 
     const auto sceneStart = Clock::now ();
 
-    this->drawWallpapers (*viewport);
+    {
+	LWE_GPU_ZONE ("draw wallpapers");
+	this->drawWallpapers (*viewport);
+    }
+
     noteFirstFrame (viewport->name);
 
     glFinish ();
@@ -128,6 +155,8 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     const auto swapStart = Clock::now ();
 
     viewport->swapOutput ();
+    LWE_GPU_COLLECT ();
+    LWE_FRAME_MARK ();
 
     const double swap = millisSince (swapStart);
 

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

@@ -62,6 +62,7 @@ namespace Render {
 
     private:
 	void renderWithStats (Drivers::Output::OutputViewport* viewport);
+	void beginProfiledFrame ();
 	void drawWallpapers (Drivers::Output::OutputViewport& viewport);
 	void drawSplitScreen (
 	    Drivers::Output::OutputViewport& viewport, const Application::ApplicationContext::SplitScreen& split

+ 22 - 8
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -1,5 +1,6 @@
 #include "GLSLContext.h"
 #include "SourceMemo.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 
 #include <algorithm>
 #include <cassert>
@@ -241,21 +242,34 @@ GLSLContext::Sources GLSLContext::toGlsl (
     // pure function of the sources, and passes get rebuilt often
     static SourceMemo<Sources> cache (48 * 1024 * 1024);
 
-    const std::string cacheKey = sourceDigest ({ vertex, fragment, geometry });
+    std::string cacheKey;
+    {
+	LWE_ZONE ("translate digest");
+	cacheKey = sourceDigest ({ vertex, fragment, geometry });
+    }
 
-    if (auto cached = cache.find (cacheKey)) {
-	return *cached;
+    {
+	LWE_ZONE ("translate memo");
+	if (auto cached = cache.find (cacheKey)) {
+	    return *cached;
+	}
     }
 
     // glslang/SPIRV-Cross and the options below only change with a rebuild
     const std::string diskKey
-	= std::string ("glsl " __DATE__ " " __TIME__) + '\0' + vertex + '\0' + fragment + '\0' + geometry;
-
-    if (auto stored = ShaderCache::get ().loadTranslation (diskKey); stored.has_value ()) {
-	cache.insert (cacheKey, *stored, stored->vertex.size () + stored->fragment.size () + stored->geometry.size ());
-	return *stored;
+	= std::string ("glsl " LWE_SHADER_CACHE_ID) + '\0' + vertex + '\0' + fragment + '\0' + geometry;
+
+    {
+	LWE_ZONE ("translate disk load");
+	if (auto stored = ShaderCache::get ().loadTranslation (diskKey); stored.has_value ()) {
+	    cache.insert (
+		cacheKey, *stored, stored->vertex.size () + stored->fragment.size () + stored->geometry.size ()
+	    );
+	    return *stored;
+	}
     }
 
+    LWE_ZONE_TEXT ("shader transpile", name);
     const auto vertexShader = parseStage (EShLangVertex, vertex, name, "vertex");
     const auto fragmentShader = parseStage (EShLangFragment, fragment, name, "fragment");
     std::unique_ptr<glslang::TShader> geometryShader;

+ 20 - 0
src/WallpaperEngine/Render/Shaders/ShaderCache.cpp

@@ -272,6 +272,26 @@ void ShaderCache::storeTranslation (const std::string& key, const GLSLContext::S
     this->write (*entry, payload);
 }
 
+std::optional<std::string> ShaderCache::loadText (const std::string& kind, const std::string& key) {
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry (kind, key);
+
+    if (!entry.has_value ()) {
+	return std::nullopt;
+    }
+
+    return this->read (*entry);
+}
+
+void ShaderCache::storeText (const std::string& kind, const std::string& key, const std::string& text) {
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry (kind, key);
+
+    if (entry.has_value ()) {
+	this->write (*entry, text);
+    }
+}
+
 bool ShaderCache::programsSupported () {
     std::lock_guard lock (this->m_mutex);
 

+ 3 - 0
src/WallpaperEngine/Render/Shaders/ShaderCache.h

@@ -23,6 +23,9 @@ public:
     [[nodiscard]] std::optional<GLSLContext::Sources> loadTranslation (const std::string& key);
     void storeTranslation (const std::string& key, const GLSLContext::Sources& sources);
 
+    [[nodiscard]] std::optional<std::string> loadText (const std::string& kind, const std::string& key);
+    void storeText (const std::string& kind, const std::string& key, const std::string& text);
+
     [[nodiscard]] GLuint loadProgram (const std::string& key);
     /** needs GL_PROGRAM_BINARY_RETRIEVABLE_HINT */
     void storeProgram (const std::string& key, GLuint program);

+ 32 - 11
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -1,6 +1,9 @@
 #include "ShaderUnit.h"
+#include "ShaderCache.h"
 #include "SourceMemo.h"
 
+#include "WallpaperEngine/Debugging/Profiling.h"
+
 #include "WallpaperEngine/Logging/Log.h"
 #include <array>
 #include <cctype>
@@ -231,6 +234,7 @@ ShaderUnit::ShaderUnit (
 }
 
 void ShaderUnit::preprocess () {
+    LWE_ZONE_TEXT ("unit preprocess", this->m_file);
     this->m_preprocessed = this->m_content;
 
     this->preprocessIncludes ();
@@ -1857,6 +1861,7 @@ const std::string& ShaderUnit::compile () {
 	return this->m_final;
     }
 
+    LWE_ZONE_TEXT ("unit compile", this->m_file);
     this->m_final = SHADER_HEADER (this->m_file);
 
     // GLSL has no log10, a macro would mangle shaders that define their own under #if GLSL, so only add it when missing
@@ -1873,6 +1878,7 @@ const std::string& ShaderUnit::compile () {
     if (const auto found = definesLog10.find (contentKey)) {
 	hasLog10 = *found;
     } else {
+	LWE_ZONE ("unit log10 scan");
 	hasLog10 = std::regex_search (this->m_content, log10Definition);
 	definesLog10.insert (contentKey, hasLog10, contentKey.size ());
     }
@@ -1972,23 +1978,38 @@ const std::string& ShaderUnit::compile () {
 	return this->m_final;
     }
 
-    const std::string compat = this->applyNonConstantConstCompatibility (this->applyBoolArithmeticCompatibility (
-	this->applyFloatConditionCompatibility (this->applyVectorTruncationCompatibility (
-	    this->applyFragmentVaryingShadowCompatibility (this->applyFragmentTexCoordCompatibility (
-		this->applyNarrowFragmentVaryingCompatibility (this->applyLinkedVaryingCompatibility (
-		    this->applyNonConstantGlobalConstCompatibility (this->applyDirectiveSemicolonCompatibility (
-			this->applyHlslAttributeCompatibility (this->applyPackedFloatArrayCompatibility (
-			    this->m_type == GLSLContext::UnitType_Geometry
-				? this->applyGeometryDialect (this->m_preprocessed)
-				: this->applyGeometryOutputNames (this->m_preprocessed)
+    // the rewrites only change with a rebuild, so a run after the first one reads them back
+    const std::string diskKey = std::string ("compat " LWE_SHADER_CACHE_ID) + '\0' + cacheKey;
+
+    if (auto stored = ShaderCache::get ().loadText ("compat", diskKey); stored.has_value ()) {
+	compatCache.insert (cacheKey, *stored, stored->size ());
+	this->m_final += *stored;
+
+	return this->m_final;
+    }
+
+    std::string compat;
+    {
+	LWE_ZONE ("unit compat rewrites");
+	compat = this->applyNonConstantConstCompatibility (this->applyBoolArithmeticCompatibility (
+	    this->applyFloatConditionCompatibility (this->applyVectorTruncationCompatibility (
+		this->applyFragmentVaryingShadowCompatibility (this->applyFragmentTexCoordCompatibility (
+		    this->applyNarrowFragmentVaryingCompatibility (this->applyLinkedVaryingCompatibility (
+			this->applyNonConstantGlobalConstCompatibility (this->applyDirectiveSemicolonCompatibility (
+			    this->applyHlslAttributeCompatibility (this->applyPackedFloatArrayCompatibility (
+				this->m_type == GLSLContext::UnitType_Geometry
+				    ? this->applyGeometryDialect (this->m_preprocessed)
+				    : this->applyGeometryOutputNames (this->m_preprocessed)
+			    ))
 			))
 		    ))
 		))
 	    ))
-	))
-    ));
+	));
+    }
 
     compatCache.insert (cacheKey, compat, compat.size ());
+    ShaderCache::get ().storeText ("compat", diskKey, compat);
 
     this->m_final += compat;
 

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

@@ -1,6 +1,7 @@
 #include "TextureCache.h"
 
 #include "AlbumTexture.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/FileSystem/Container.h"
 
 #include "CTexture.h"
@@ -604,12 +605,17 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
     }
 
     const auto load = [&] (const Project& project) {
+	LWE_ZONE_TEXT ("texture load", filename);
 	TextureUniquePtr parsedTexture;
 
 	try {
-	    const auto contents = project.assetLocator->texture (filename);
+	    auto contents = [&] {
+		LWE_ZONE ("texture read");
+		return project.assetLocator->texture (filename);
+	    }();
 	    auto stream = BinaryReader (contents);
 
+	    LWE_ZONE ("texture parse");
 	    parsedTexture = TextureParser::parse (stream);
 	    applyTexturePatches (*parsedTexture, project);
 	} catch (AssetLoadException&) {

+ 15 - 3
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -1,4 +1,5 @@
 #include "WallpaperEngine/Data/Model/Property.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Render/DepthRange.h"
 #include "WallpaperEngine/Render/MissingTexture.h"
 #include "WallpaperEngine/Render/Objects/CCamera.h"
@@ -113,6 +114,7 @@ CScene::CScene (
     const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext,
     const WallpaperState::TextureUVsScaling& scalingMode, const uint32_t& clampMode
 ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
+    LWE_ZONE ("scene construct");
     // the caller checks this, std::bad_cast otherwise
     auto scene = wallpaper.as<Scene> ();
     this->m_startTime = g_Time;
@@ -256,8 +258,11 @@ CScene::CScene (
 	}
     }
 
-    for (const auto& object : scene->objects) {
-	this->createObject (*object);
+    {
+	LWE_ZONE ("create objects");
+	for (const auto& object : scene->objects) {
+	    this->createObject (*object);
+	}
     }
 
     for (const auto& object : scene->objects) {
@@ -300,6 +305,7 @@ CScene::CScene (
 
 CScene::~CScene () {
     Led::releaseFeed (this);
+    Objects::Effects::CPass::dropRecentShaders ();
 
     if (this->m_nullTexture != GL_NONE) {
 	glDeleteTextures (1, &this->m_nullTexture);
@@ -359,7 +365,10 @@ Render::CObject* CScene::createObject (const Object& object) {
 	return nullptr;
     }
 
-    renderObject = this->dispatchObjectType (object);
+    {
+	LWE_ZONE_TEXT ("create object", object.name);
+	renderObject = this->dispatchObjectType (object);
+    }
 
     if (renderObject != nullptr) {
 	this->m_objects.emplace (renderObject->getId (), renderObject);
@@ -408,6 +417,7 @@ Render::CObject* CScene::dispatchObjectType (const Object& object) {
     const auto scriptMark = this->getScriptEngine ().moduleMark ();
 
     try {
+	LWE_ZONE ("construct");
 	renderObject = this->constructObject (object);
     } catch (const std::exception& e) {
 	// the half built object is gone, the scripts its constructor queued still point at it
@@ -422,6 +432,7 @@ Render::CObject* CScene::dispatchObjectType (const Object& object) {
     }
 
     try {
+	LWE_ZONE ("setup");
 	renderObject->setup ();
     } catch (const std::exception& e) {
 	sLog.error ("Failed to setup object ", object.id, ": ", e.what ());
@@ -532,6 +543,7 @@ double stallThresholdMs () {
 }
 
 template <typename Step> void timeStep (const std::string& label, Step&& step) {
+    LWE_ZONE_NAMED (label);
     static const bool enabled = std::getenv ("LWE_FRAME_STATS") != nullptr;
     static const double threshold = stallThresholdMs ();
 

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

@@ -1,4 +1,5 @@
 #include "CVideo.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
@@ -179,6 +180,7 @@ void CVideo::copyFromSource () {
 }
 
 void CVideo::renderFrame (const glm::ivec4& viewport) {
+    LWE_ZONE ("video frame");
     this->m_presentBackBuffer = false;
 
     if (this->m_source != nullptr) {

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

@@ -4,6 +4,7 @@
 #include "CWeb.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
 #include "WallpaperEngine/Audio/Drivers/PulseProcessVolume.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
@@ -351,6 +352,7 @@ void CWeb::setSize (const int width, const int height) {
 }
 
 void CWeb::renderFrame (const glm::ivec4& viewport) {
+    LWE_ZONE ("web frame");
     if (!this->m_helperFailureLogged && this->m_shm->helperFailed.load (std::memory_order_relaxed)) {
 	sLog.error ("CWeb: host process failed to start, this web wallpaper will not render");
 	this->m_helperFailureLogged = true;
@@ -439,6 +441,7 @@ void CWeb::noteFirstContent () {
 }
 
 void CWeb::renderDmabufFrame () {
+    LWE_ZONE ("web dmabuf import");
     using namespace std::chrono;
 
     bool closed = false;
@@ -549,6 +552,7 @@ void CWeb::rejectFrame () {
 }
 
 void CWeb::requestPageFrame () {
+    LWE_ZONE ("web begin frame request");
     const auto now = std::chrono::steady_clock::now ();
 
     if (this->m_lastRender != std::chrono::steady_clock::time_point {}) {

+ 2 - 0
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -1,4 +1,5 @@
 #include "ScriptEngine.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 
 #include "WallpaperEngine/Media/ThumbnailPalette.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
@@ -1708,6 +1709,7 @@ void ScriptEngine::tick () {
 	}
 	auto& module = entry->second;
 
+	LWE_ZONE_NAMED (key);
 	const v8::HandleScope handleScope (this->m_isolate);
 
 	this->m_runningModule = &module;

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

@@ -75,7 +75,7 @@ void BrowserApp::OnBeforeCommandLineProcessing (const CefString& process_type, C
 
     // Chromium 146's GPU process loses its context on the first decoded video frame under the headless platform
     // ("Could not find SharedImageBackingFactory ... BGRA_8888", then a restart loop and a page that never paints, seen
-    // with 2681203626's webm), software decoding is fine
+    // with 2681203626's webm), software decoding is fine; not rechecked on CEF 156
     const bool headlessPlatform
 	= (!dmabufFrames && (display == nullptr || *display == '\0')
 	   && (extra == nullptr || std::string_view (extra).find ("--ozone-platform") == std::string_view::npos))

+ 37 - 0
src/main.cpp

@@ -1,5 +1,7 @@
 #include <csignal>
+#include <cstdlib>
 #include <iostream>
+#include <malloc.h>
 #include <string_view>
 
 #include <SDL.h>
@@ -28,7 +30,42 @@ void initLogging () {
     sLog.addError (&error);
 }
 
+// Hotswapping between wallpapers grew the resident size by 40 MB a minute with glibc's defaults (72 swaps: 638 MB to
+// 1019 MB, all anonymous memory, heaptrack saw no leak): per thread arenas and a mmap threshold that rises with every
+// freed big buffer leave freed textures and scene data scattered through the heap, and trimming never finds a free top.
+// With these it stays at 330 MB. Explicit MALLOC_* variables win.
+static void tuneAllocator () {
+    if (std::getenv ("MALLOC_ARENA_MAX") == nullptr) {
+	mallopt (M_ARENA_MAX, 2);
+    }
+
+    if (std::getenv ("MALLOC_MMAP_THRESHOLD_") == nullptr) {
+	mallopt (M_MMAP_THRESHOLD, 256 * 1024);
+    }
+
+    if (std::getenv ("MALLOC_TRIM_THRESHOLD_") == nullptr) {
+	mallopt (M_TRIM_THRESHOLD, 64 * 1024);
+    }
+}
+
+// the CEF host and Chromium's children keep glibc's defaults, Chromium allocates most of its memory itself
+static bool isWebChild (int argc, char* argv[]) {
+    for (int i = 1; i < argc; i++) {
+	const std::string_view arg = argv[i];
+
+	if (arg == "--web-host" || arg.starts_with ("--type=")) {
+	    return true;
+	}
+    }
+
+    return false;
+}
+
 int main (int argc, char* argv[]) {
+    if (!isWebChild (argc, argv)) {
+	tuneAllocator ();
+    }
+
     WallpaperEngine::Scripting::JS::useNamedTimeZone ();
 
     try {

+ 25 - 0
tests/desktops/test_fractional_scale.py

@@ -95,3 +95,28 @@ def test_pointer_is_in_buffer_pixels(desktop, engine, tmp_path):
             process.terminate()
             process.wait(10)
         desktop.set_scale(1)
+
+
+@pytest.mark.parametrize("desktop", ["sway", "labwc", "niri"], indirect=True)
+def test_render_scale_shrinks_the_buffer_only(desktop, engine, tmp_path):
+    """--render-scale draws below the output's pixels, the viewport destination stays the logical size"""
+    log = tmp_path / "engine.log"
+    process = desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                              desktop.output_names()[0], "--render-scale", "0.5", "--silent", "--fps", "30",
+                              engine["wallpaper"]], log=log, env={"WAYLAND_DEBUG": "1"})
+    try:
+        width, height = desktop.size
+        deadline = time.monotonic() + 40
+        buffers, destinations = [], []
+        while time.monotonic() < deadline and not (buffers and destinations):
+            time.sleep(2)
+            assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+            text = log.read_text(errors="replace")
+            buffers = [tuple(map(int, found)) for found in BUFFER.findall(text)]
+            destinations = [tuple(map(int, found)) for found in DESTINATION.findall(text)]
+        assert buffers and destinations, f"nothing was attached on {desktop.name}"
+        assert buffers[-1] == (round(width / 2), round(height / 2)), f"buffer {buffers[-1]}"
+        assert destinations[-1] == (width, height), f"viewport destination {destinations[-1]}"
+    finally:
+        process.terminate()
+        process.wait(10)

+ 123 - 0
tests/desktops/test_kde.py

@@ -140,3 +140,126 @@ def test_script_ids_stay_unique_after_an_unload(kde, tmp_path):
         call("unloadScript", name)
     if third == second:
         pytest.xfail(f"this KWin hands the id {second} of a live script to the next one (ids {first}, {second}, {third})")
+
+
+def _cursor_scripts(desktop):
+    return sorted(desktop.run_dir.glob("lwe-cursor-input-*.js"))
+
+
+def _watch_cursor_calls(desktop, name):
+    log = desktop.dir / f"{name}.log"
+    log.unlink(missing_ok=True)
+    monitor = desktop.client(["dbus-monitor", "--session", "type='method_call',member='OnCursorMoved'"], log=log)
+    time.sleep(1)
+    return monitor, log
+
+
+def _calls(log):
+    """(x, y) of every OnCursorMoved call dbus-monitor saw"""
+    lines = Path(log).read_text(errors="replace").splitlines()
+    calls = []
+    for index, line in enumerate(lines):
+        if "member=OnCursorMoved" in line:
+            numbers = [int(part.split()[-1]) for part in lines[index + 1:index + 3] if part.strip().startswith("int32")]
+            if len(numbers) == 2:
+                calls.append(tuple(numbers))
+    return calls
+
+
+def _wiggle(desktop, steps=12):
+    for step in range(steps):
+        desktop.pointer("move", 300 + step * 20, 300 + (step % 2) * 40)
+        time.sleep(0.15)
+
+
+def test_cursor_script_follows_the_pause(kde, engine, tmp_path):
+    """a long pause unloads the engine's cursor script so KWin sends nothing, resuming loads it again (off the render
+    thread) and the pointer reaches the engine once more"""
+    log = tmp_path / "engine.log"
+    process = _engine(kde, engine, log, kde.output_names()[0])
+    probe = None
+    monitor = None
+    try:
+        time.sleep(8)
+        assert len(_cursor_scripts(kde)) == 1, "the cursor script is not loaded on KDE"
+        monitor, calls = _watch_cursor_calls(kde, "before")
+        _wiggle(kde)
+        assert _calls(calls), "the pointer does not reach the engine"
+        terminate([monitor.pid])
+
+        probe = _window(kde, "fullscreen")
+        time.sleep(8)
+        assert not _renders(log, 3), "still rendering under a fullscreen window"
+        assert not _cursor_scripts(kde), "the cursor script is still loaded after a long pause"
+        monitor, calls = _watch_cursor_calls(kde, "paused")
+        _wiggle(kde)
+        assert not _calls(calls), "KWin still sends cursor calls to a paused engine"
+        terminate([monitor.pid])
+
+        terminate([probe.pid])
+        probe = None
+        for _ in range(20):
+            if _cursor_scripts(kde):
+                break
+            time.sleep(1)
+        assert len(_cursor_scripts(kde)) == 1, "the cursor script did not come back after the pause"
+        monitor, calls = _watch_cursor_calls(kde, "resumed")
+        _wiggle(kde)
+        assert _calls(calls), "the pointer does not reach the engine after the pause"
+        assert "could not load its KWin script again" not in log.read_text(errors="replace")
+    finally:
+        for stray in (monitor, probe):
+            if stray is not None:
+                terminate([stray.pid])
+        process.terminate()
+        process.wait(10)
+
+
+def test_cursor_script_reports_where_the_pointer_stopped(kde, engine, tmp_path):
+    """a fast flick ends on a call within a few ms of the last one, the final position has to be reported anyway"""
+    log = tmp_path / "engine.log"
+    process = _engine(kde, engine, log, kde.output_names()[0])
+    monitor = None
+    try:
+        time.sleep(8)
+        monitor, calls = _watch_cursor_calls(kde, "flick")
+        for run in range(5):
+            target = (900 + run * 37, 500 + run * 11)
+            kde.pointer("move", 400, 300, "move", 500, 340, "move", 600, 380, "move", 700, 420, "move", *target)
+            time.sleep(0.5)
+            seen = _calls(calls)
+            assert seen and seen[-1] == target, f"the engine ended at {seen[-1] if seen else None}, not at {target}"
+    finally:
+        if monitor is not None:
+            terminate([monitor.pid])
+        process.terminate()
+        process.wait(10)
+
+
+def test_media_signals_while_paused(kde, engine, tmp_path):
+    """MPRIS signals that pile up behind a pause are read and dropped, the engine keeps its media connection, renders
+    again afterwards and does not crash"""
+    log = tmp_path / "engine.log"
+    process = _engine(kde, engine, log, kde.output_names()[0])
+    probe = None
+    try:
+        time.sleep(8)
+        probe = _window(kde, "fullscreen")
+        time.sleep(5)
+        assert not _renders(log, 3), "still rendering under a fullscreen window"
+        flood = kde.run(["python3", str(REPO / "tools/desktops/mpris_flood.py"), "3000", "4096"], timeout=120)
+        assert flood.returncode == 0, flood.stderr
+        time.sleep(3)
+        assert process.poll() is None, "the engine died while paused"
+        terminate([probe.pid])
+        probe = None
+        time.sleep(6)
+        assert _renders(log), "rendering did not resume after the flood"
+        text = log.read_text(errors="replace")
+        assert "the session bus dropped the connection" not in text
+        assert "Media: reconnected" not in text
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)

+ 155 - 0
tests/desktops/test_lock_pause.py

@@ -0,0 +1,155 @@
+"""A session that reports itself locked pauses the engine, and unlocking resumes it."""
+import os
+import subprocess
+import time
+
+import pytest
+
+from test_kde import REPO, _engine, _renders
+
+
+@pytest.fixture
+def screen_saver(desktop, tmp_path):
+    state = tmp_path / "screen-saver-active"
+    process = desktop.spawn("screen-saver", ["python3", str(REPO / "tools/desktops/screen_saver_owner.py"), str(state)])
+    time.sleep(2)
+
+    def send(active):
+        if active:
+            state.touch()
+        else:
+            state.unlink(missing_ok=True)
+
+    yield send
+    process.terminate()
+
+
+@pytest.mark.parametrize("desktop", ["sway", "labwc"], indirect=True)
+def test_screen_saver_signal_pauses(desktop, engine, screen_saver, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(desktop, engine, log, desktop.output_names()[0])
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render"
+        screen_saver(True)
+        time.sleep(3)
+        assert not _renders(log), "still rendering while the screen saver is active"
+        assert "Paused: lock" in log.read_text(errors="replace")
+        screen_saver(False)
+        time.sleep(3)
+        assert _renders(log), "rendering did not resume after the screen saver ended"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_no_lock_pause_keeps_rendering(desktop, engine, screen_saver, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(desktop, engine, log, desktop.output_names()[0], "--no-lock-pause")
+    try:
+        time.sleep(8)
+        screen_saver(True)
+        time.sleep(3)
+        assert _renders(log), "--no-lock-pause still paused"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.fixture
+def logind(tmp_path):
+    dbusmock = pytest.importorskip("dbusmock")
+    bus = dbusmock.DBusTestCase
+    bus.start_system_bus()
+    bus.setUpClass()
+    server, mock = bus.spawn_server_template("logind", {}, stdout=subprocess.DEVNULL)
+    import dbus
+
+    manager = dbus.Interface(bus.get_dbus(True).get_object("org.freedesktop.login1", "/org/freedesktop/login1"),
+                             "org.freedesktop.DBus.Mock")
+    session = manager.AddSession("c1", "seat0", 1000, "lwe", True)
+    yield os.environ["DBUS_SYSTEM_BUS_ADDRESS"], session
+    server.terminate()
+    server.wait()
+    bus.tearDownClass()
+
+
+@pytest.mark.parametrize("desktop", ["sway"], indirect=True)
+def test_logind_locked_hint_pauses(desktop, engine, logind, tmp_path):
+    import dbus
+
+    address, session = logind
+    log = tmp_path / "engine.log"
+    process = desktop.client(
+        [engine["binary"], "--assets-dir", engine["assets"], "--screen-root", desktop.output_names()[0], "--silent",
+         "--fps", "30", engine["wallpaper"]],
+        log=log, env={"LWE_FRAME_STATS": "1", "DBUS_SYSTEM_BUS_ADDRESS": address, "XDG_SESSION_ID": "c1"})
+    hint = dbus.Interface(dbus.bus.BusConnection(address).get_object("org.freedesktop.login1", session),
+                          "org.freedesktop.login1.Session")
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render"
+        hint.SetLockedHint(True)
+        time.sleep(3)
+        assert not _renders(log), "still rendering with LockedHint set"
+        hint.SetLockedHint(False)
+        time.sleep(3)
+        assert _renders(log), "rendering did not resume when LockedHint cleared"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", ["i3", "xfce"], indirect=True)
+def test_x11_dpms_off_pauses(desktop, engine, tmp_path):
+    display = {"DISPLAY": f":{desktop.display}"}
+    probe = desktop.run(["xset", "q"], display)
+
+    if "does not have the DPMS" in probe.stdout:
+        pytest.skip(f"the X server of {desktop.name} has no DPMS extension")
+
+    log = tmp_path / "engine.log"
+    process = desktop.client(
+        [engine["binary"], "--assets-dir", engine["assets"], "--screen-root", desktop.output_names()[0], "--silent",
+         "--fps", "30", engine["wallpaper"]], log=log, env={"LWE_FRAME_STATS": "1"})
+    try:
+        desktop.run(["xset", "+dpms", "s", "off"], display)
+        time.sleep(8)
+        assert _renders(log), "the engine does not render"
+        desktop.run(["xset", "dpms", "force", "off"], display)
+        time.sleep(4)
+        assert not _renders(log), "still rendering with the display in DPMS off"
+        assert "Paused: display off" in log.read_text(errors="replace")
+        desktop.run(["xset", "dpms", "force", "on"], display)
+        time.sleep(4)
+        assert _renders(log), "rendering did not resume after DPMS on"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
+def _power_save(desktop, mode):
+    result = desktop.run(["busctl", "--user", "set-property", "org.gnome.Mutter.DisplayConfig",
+                          "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig", "PowerSaveMode", "i",
+                          str(mode)])
+    assert result.returncode == 0, result.stderr
+
+
+@pytest.mark.parametrize("desktop", ["gnome"], indirect=True)
+def test_mutter_power_save_mode_pauses(desktop, engine, tmp_path):
+    log = tmp_path / "engine.log"
+    process = _engine(desktop, engine, log, desktop.output_names()[0])
+    try:
+        time.sleep(10)
+        assert _renders(log), "the engine does not render"
+        _power_save(desktop, 3)
+        time.sleep(4)
+        assert not _renders(log), "still rendering with PowerSaveMode off"
+        assert "Paused: display off" in log.read_text(errors="replace")
+        _power_save(desktop, 0)
+        time.sleep(4)
+        assert _renders(log), "rendering did not resume after PowerSaveMode on"
+    finally:
+        process.terminate()
+        process.wait(10)

+ 21 - 0
tools/dbus_quota_watch.sh

@@ -0,0 +1,21 @@
+#!/bin/bash
+# Logs what the session bus holds while a wallpaper is paused behind a fullscreen window: the broker's memory, how many
+# cursor calls KWin sends the engine per second and how often the broker kicked programs off the bus.
+# Usage: tools/dbus_quota_watch.sh [interval seconds, default 10]
+
+interval=${1:-10}
+broker=$(pgrep -u "$(id -u)" -xo dbus-broker)
+
+if [ -z "$broker" ]; then
+    echo "no dbus-broker running for this user" >&2
+    exit 1
+fi
+
+while true; do
+    calls=$(timeout 5 dbus-monitor --session "type='method_call',member='OnCursorMoved'" 2>/dev/null | grep -c 'member=OnCursorMoved')
+    rss=$(ps -o rss= -p "$broker" | tr -d ' ')
+    kicked=$(journalctl --user -b --no-pager 2>/dev/null | grep -c 'being disconnected as it does not have the resources')
+    quota=$(journalctl --user -b --no-pager 2>/dev/null | grep -c "exceeded its 'bytes' quota")
+    printf '%s broker_rss_kb=%s cursor_calls_per_5s=%s kicked_peers=%s quota_hits=%s\n' "$(date +%T)" "$rss" "$calls" "$kicked" "$quota"
+    sleep "$interval"
+done

+ 27 - 0
tools/desktops/mpris_flood.py

@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+"""mpris_flood.py <count> [bytes]: emits <count> MPRIS PropertiesChanged signals with a title of <bytes> characters on
+the session bus of DBUS_SESSION_BUS_ADDRESS, what a player does at every track change, only much faster"""
+import sys
+
+import dbus
+
+
+def main():
+    count = int(sys.argv[1])
+    size = int(sys.argv[2]) if len(sys.argv) > 2 else 2048
+    bus = dbus.SessionBus(private=True)
+    changed = dbus.Dictionary({
+        "PlaybackStatus": "Playing",
+        "Metadata": dbus.Dictionary({"xesam:title": "x" * size, "xesam:artist": dbus.Array(["flood"], signature="s")},
+                                    signature="sv"),
+    }, signature="sv")
+    for _ in range(count):
+        message = dbus.lowlevel.SignalMessage("/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties",
+                                              "PropertiesChanged")
+        message.append("org.mpris.MediaPlayer2.Player", changed, dbus.Array([], signature="s"), signature="sa{sv}as")
+        bus.send_message(message)
+    bus.flush()
+
+
+if __name__ == "__main__":
+    main()

+ 37 - 0
tools/desktops/screen_saver_owner.py

@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""screen_saver_owner.py <state file>: owns org.freedesktop.ScreenSaver on the session bus of DBUS_SESSION_BUS_ADDRESS,
+the way a locker does, but has no GetActive (calls get an error back). ActiveChanged(true) is sent when the state file
+appears, ActiveChanged(false) when it is gone again"""
+import sys
+from pathlib import Path
+
+import dbus
+import dbus.lowlevel
+import dbus.mainloop.glib
+import dbus.service
+from gi.repository import GLib
+
+
+def main():
+    state = Path(sys.argv[1])
+    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
+    bus = dbus.SessionBus(private=True)
+    name = dbus.service.BusName("org.freedesktop.ScreenSaver", bus)
+    active = [False]
+
+    def poll():
+        if state.exists() != active[0]:
+            active[0] = not active[0]
+            message = dbus.lowlevel.SignalMessage("/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver",
+                                                  "ActiveChanged")
+            message.append(dbus.Boolean(active[0]), signature="b")
+            bus.send_message(message)
+
+        return True
+
+    GLib.timeout_add(100, poll)
+    GLib.MainLoop().run()
+
+
+if __name__ == "__main__":
+    main()

+ 12 - 0
tools/linuxvm/RELEASE_TESTING.md

@@ -74,6 +74,18 @@ in the log), missing frames, black desktop, a leftover process, a log line match
 After a failed first pass the driver repeats only the failed groups in the same boot. A failure that only shows in the retry
 is a state problem of the session, not of the first run.
 
+## Session bus during a pause (guest_test.sh, every Plasma 6 row)
+
+Part of the fullscreen `pause_check`, switched on by `XDG_CURRENT_DESKTOP=KDE`. A session bus whose quota is used up kicks
+plasmashell, the portals and powerdevil off it (seen on a real Nobara desktop 2026-10-27), so while a fullscreen window
+has the engine paused for longer than 3 s: the KWin cursor script is unloaded (`$XDG_RUNTIME_DIR/lwe-cursor-input-*.js`
+is gone, KWin sends nothing), 300 MPRIS `PropertiesChanged` signals of 4 KB (`gdbus emit`) leave the engine alive, and
+after the window closes the cursor script is back within 20 s, the log has no "could not load its KWin script again",
+"session bus dropped the connection" or "DBus connection dropped", the journal has no new `exceeded its 'bytes' quota`
+line and plasmashell is still on the bus. The same behaviour runs in the KDE lab on every change:
+`tests/desktops/test_kde.py -k "cursor_script or media_signals"` (script unloaded while paused and reloaded after,
+pointer calls counted with `dbus-monitor`, the final position of a flick reported, an MPRIS flood while paused).
+
 ## Web frames (guest_test.sh, every wallpaper run)
 
 The engine runs with `LWE_WEB_STATS=1`; each web wallpaper reports `web frames arrive as dmabufs` or `through shared memory`, and

+ 40 - 0
tools/linuxvm/guest_test.sh

@@ -128,6 +128,44 @@ wait_for_log() {
     return 1
 }
 
+kde_session() { case ":${XDG_CURRENT_DESKTOP:-}:" in *:KDE:*) command -v gdbus >/dev/null ;; *) return 1 ;; esac; }
+cursor_scripts() { find "$XDG_RUNTIME_DIR" -maxdepth 3 -name 'lwe-cursor-input-*.js' 2>/dev/null | wc -l; }
+bus_quota_hits() { journalctl --user -b --no-pager 2>/dev/null | grep -c "exceeded its 'bytes' quota"; }
+
+cursor_pause_check() {
+    local title i
+    CURSOR_QUOTA_BEFORE=$(bus_quota_hits)
+    CURSOR_PLASMASHELL=0
+    busctl --user list 2>/dev/null | grep -q "org.kde.plasmashell" && CURSOR_PLASMASHELL=1
+    sleep 6
+    if [ "$(cursor_scripts)" = 0 ]; then pass "fullscreen pause: the KWin cursor script is unloaded after a long pause"
+    else fail "fullscreen pause: the KWin cursor script is still loaded after a long pause"; fi
+    title=$(head -c 4096 /dev/zero | tr '\0' x)
+    for i in $(seq 300); do
+        gdbus emit --session --object-path /org/mpris/MediaPlayer2 --signal org.freedesktop.DBus.Properties.PropertiesChanged \
+            "'org.mpris.MediaPlayer2.Player'" "{'PlaybackStatus': <'Playing'>, 'Metadata': <{'xesam:title': <'$title'>}>}" "@as []" > /dev/null 2>&1
+    done
+    sleep 2
+    if [ -n "$(engine_pids)" ]; then pass "fullscreen pause: the engine survived 300 media signals piling up"
+    else fail "fullscreen pause: the engine died while media signals piled up"; fi
+}
+
+cursor_resume_check() {
+    local log=$1
+    for _ in $(seq 20); do [ "$(cursor_scripts)" -ge 1 ] && break; sleep 1; done
+    if [ "$(cursor_scripts)" -ge 1 ]; then pass "fullscreen pause: the KWin cursor script is back after the pause"
+    else fail "fullscreen pause: the KWin cursor script did not come back after the pause"; fi
+    if grep -q "could not load its KWin script again" "$log"; then fail "fullscreen pause: the KWin cursor script failed to reload"; fi
+    if grep -q "the session bus dropped the connection\|KDE cursor input: DBus connection dropped" "$log"; then fail "fullscreen pause: the engine's session bus connection was dropped"
+    else pass "fullscreen pause: the engine kept its session bus connections"; fi
+    if [ "$(bus_quota_hits)" -gt "${CURSOR_QUOTA_BEFORE:-0}" ]; then fail "fullscreen pause: the session bus quota was used up"
+    else pass "fullscreen pause: no session bus quota hit"; fi
+    if [ "$CURSOR_PLASMASHELL" = 1 ]; then
+        if busctl --user list 2>/dev/null | grep -q "org.kde.plasmashell"; then pass "fullscreen pause: plasmashell is still on the session bus"
+        else fail "fullscreen pause: plasmashell left the session bus"; fi
+    fi
+}
+
 # pause_check <label> <command>: a window opened by the command must pause the engine (a "Paused: windows" log line) and
 # closing it must resume it. An empty command is skipped.
 pause_check() {
@@ -150,6 +188,7 @@ pause_check() {
         echo "SKIP $label pause: the compositor has no window state detection"
     elif wait_for_log "$log" "Paused: windows" 45 "$paused_before"; then
         pass "$label pause: engine paused"
+        [ "$label" = fullscreen ] && kde_session && cursor_pause_check
         local minimized_resumed=0
         if [ "$label" = fullscreen ] && [ -n "$MINIMIZE_CMD" ]; then
             if command -v xdotool >/dev/null; then
@@ -164,6 +203,7 @@ pause_check() {
         kill "$fs_pid" 2>/dev/null; stop_fullscreen_window
         if [ $minimized_resumed = 1 ]; then :
         elif wait_for_log "$log" "Resumed" 45 "$resumed_before"; then pass "$label pause: engine resumed"; else fail "$label pause: no resume after the window closed"; fi
+        [ "$label" = fullscreen ] && kde_session && cursor_resume_check "$log"
     else
         fail "$label pause: no pause within 45s of a $label window"
         {

+ 63 - 0
tools/nocore.c

@@ -0,0 +1,63 @@
+// nocore <cmd> [args]: runs a command and all its descendants under ptrace and kills any of them that gets a
+// fatal signal (SEGV, ABRT, BUS, ILL, FPE) with SIGKILL before the kernel starts a core dump. RLIMIT_CORE=0 does not
+// help with a core_pattern that pipes to systemd-coredump, the handler still runs and the desktop shows a crash report.
+// gcc -O2 -o nocore tools/nocore.c
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/ptrace.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+int main(int argc, char **argv) {
+    if (argc < 2) {
+        fprintf(stderr, "usage: nocore <cmd> [args]\n");
+        return 2;
+    }
+    pid_t root = fork();
+    if (root < 0) {
+        perror("fork");
+        return 2;
+    }
+    if (root == 0) {
+        ptrace(PTRACE_TRACEME, 0, 0, 0);
+        execvp(argv[1], argv + 1);
+        perror(argv[1]);
+        _exit(127);
+    }
+    int rootStatus = 0;
+    int first = 1;
+    for (;;) {
+        int status;
+        pid_t pid = waitpid(-1, &status, __WALL);
+        if (pid < 0) {
+            if (errno == EINTR)
+                continue;
+            break;
+        }
+        if (WIFEXITED(status) || WIFSIGNALED(status)) {
+            if (pid == root)
+                rootStatus = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
+            continue;
+        }
+        if (!WIFSTOPPED(status))
+            continue;
+        if (first && pid == root) {
+            ptrace(PTRACE_SETOPTIONS, pid, 0,
+                   PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_EXITKILL);
+            first = 0;
+        }
+        int sig = WSTOPSIG(status);
+        if (status >> 16 || sig == SIGTRAP || sig == SIGSTOP) {
+            ptrace(PTRACE_CONT, pid, 0, 0);
+        } else if (sig == SIGSEGV || sig == SIGABRT || sig == SIGBUS || sig == SIGILL || sig == SIGFPE) {
+            fprintf(stderr, "nocore: pid %d got signal %d, killed without a core dump\n", pid, sig);
+            kill(pid, SIGKILL);
+            ptrace(PTRACE_CONT, pid, 0, SIGKILL);
+        } else {
+            ptrace(PTRACE_CONT, pid, 0, sig);
+        }
+    }
+    return rootStatus;
+}

+ 42 - 0
tools/runtime_analysis.py

@@ -113,6 +113,45 @@ def group_rss_mb(pgid):
     return total // 1024
 
 
+def mapping_rss_kb(pgid):
+    """resident kB of a process group per kind of mapping: the heap, anonymous memory, each file or device"""
+    totals = {}
+    for entry in Path('/proc').iterdir():
+        if not entry.name.isdigit():
+            continue
+        try:
+            stat = (entry / 'stat').read_text()
+            if int(stat[stat.rindex(')') + 2:].split()[3]) != pgid:
+                continue
+            lines = (entry / 'smaps').read_text().splitlines()
+        except (OSError, ValueError):
+            continue
+        name = '[anon]'
+        for line in lines:
+            words = line.split(None, 5)
+            if len(words) >= 2 and '-' in words[0] and not words[0].endswith(':'):
+                name = words[5] if len(words) == 6 else '[anon]'
+                if name.startswith('/memfd:') or name.startswith('/dev/shm'):
+                    name = name.split(' (')[0]
+            elif line.startswith('Rss:'):
+                totals[name] = totals.get(name, 0) + int(line.split()[1])
+    return totals
+
+
+def print_mapping_growth(rounds, rows=8):
+    """which mappings grew between the first and the last round of a swap run"""
+    # a round after the engine died has no mappings to compare
+    seen = [(number, snapshot) for number, snapshot in enumerate(rounds, 1) if snapshot]
+    if len(seen) < 2:
+        return
+    (first_round, first), (last_round, last) = seen[1] if len(seen) > 2 else seen[0], seen[-1]
+    growth = sorted(((last.get(name, 0) - first.get(name, 0), name) for name in set(first) | set(last)), reverse=True)
+    print(f'mapping growth, round {first_round} -> {last_round} (MB):')
+    for delta, name in growth[:rows]:
+        if delta > 1024:
+            print(f'  {delta / 1024:+8.1f}  {name}')
+
+
 class Watchdog(threading.Thread):
     def __init__(self, pgid, rss_limit, min_available, log):
         super().__init__(daemon=True)
@@ -408,6 +447,7 @@ def command_swap(options):
     run = Run(options.tool, binary_dir, out, [str(items[0])], False, options.rss_limit, options.min_available)
     time.sleep(options.wait)
     swaps = 0
+    snapshots = []
     for round_number in range(options.rounds):
         for item in items:
             if not run.alive():
@@ -416,6 +456,8 @@ def command_swap(options):
             swaps += 1
             time.sleep(options.wait)
         print(f'round {round_number + 1}: rss {group_rss_mb(run.proc.pid)} MB, alive={run.alive()}', flush=True)
+        snapshots.append(mapping_rss_kb(run.proc.pid))
+    print_mapping_growth(snapshots)
     code = run.finish()
     failed = run.log.read_text(errors='replace').count('Hotswap failed')
     line = f'swap: swaps={swaps} failed-swaps={failed} ' + summarize(options.tool, out, run, code)

+ 51 - 0
tools/tracy_profile.sh

@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Renders a wallpaper headlessly with a Tracy build (-DLWE_TRACY=ON), captures the zones and prints the busiest ones
+# and the GPU time per frame. Open the saved capture with tracy-profiler for the timeline.
+#
+# Usage:
+#   tools/tracy_profile.sh <tracy build binary> <item dir> [seconds] [engine args...]
+#
+# The loader zones are only recorded by a build configured with -DLWE_TRACY_ON_DEMAND=OFF, an on demand build starts
+# recording when the capture connects, after the wallpaper has loaded.
+#
+# Needs tracy-capture and tracy-csvexport (0.14.x, the client is 0.14.1). HEADLESS_RENDER_SIZE=WxH, LWE_ASSETS_DIR and
+# TRACY_OUT (capture file, default /tmp/lwe-<item>.tracy) are read from the environment.
+set -euo pipefail
+
+if [ "$#" -lt 2 ]; then
+    echo "Usage: $0 <binary> <item dir> [seconds] [engine args...]" >&2
+    exit 1
+fi
+
+BINARY="$1"
+ITEM="$2"
+SECONDS_TO_CAPTURE="${3:-10}"
+shift 2
+[ "$#" -gt 0 ] && shift
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+OUT="${TRACY_OUT:-/tmp/lwe-$(basename "$ITEM").tracy}"
+LOG="$(mktemp)"
+
+# the wait for the client below takes up to 90 s and the capture starts 3 s after it, the engine has to live that long.
+# Its own process group, so stopping it reaches the timeout and the engine below the script as well
+HEADLESS_RENDER_KEEP_RUNNING=1 HEADLESS_RENDER_TIMEOUT=$((SECONDS_TO_CAPTURE + 130)) \
+    setsid "$SCRIPT_DIR/headless_render.sh" "$BINARY" "$(mktemp -u).png" ${LWE_ASSETS_DIR:+--assets-dir "$LWE_ASSETS_DIR"} \
+    --silent "$@" "$ITEM" > "$LOG" 2>&1 &
+ENGINE=$!
+
+# the client listens on 8086 once the first frame is out, scenes take a while to load
+for _ in $(seq 90); do
+    ss -ltn 2>/dev/null | grep -q ':8086 ' && break
+    kill -0 "$ENGINE" 2>/dev/null || { echo "the engine stopped before Tracy could connect:" >&2; tail -20 "$LOG" >&2; exit 1; }
+    sleep 1
+done
+
+sleep 3
+timeout $((SECONDS_TO_CAPTURE + 30)) tracy-capture -o "$OUT" -a 127.0.0.1 -s "$SECONDS_TO_CAPTURE" -f > /dev/null
+kill -- "-$ENGINE" 2>/dev/null || true
+wait "$ENGINE" 2>/dev/null || true
+rm -f "$LOG"
+
+echo "capture: $OUT"
+"$SCRIPT_DIR/tracy_summary.py" "$OUT"

+ 53 - 0
tools/tracy_summary.py

@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Prints the busiest zones of a Tracy capture (tracy-csvexport), and the GPU time of the zones that have it.
+
+    tools/tracy_summary.py <capture.tracy> [rows]
+"""
+import csv
+import io
+import statistics
+import subprocess
+import sys
+
+
+def export(args):
+    result = subprocess.run(["tracy-csvexport", *args], capture_output=True, text=True, check=True)
+    return list(csv.DictReader(io.StringIO(result.stdout)))
+
+
+def main():
+    if len(sys.argv) < 2:
+        sys.exit(__doc__)
+
+    capture = sys.argv[1]
+    rows = int(sys.argv[2]) if len(sys.argv) > 2 else 25
+
+    # the aggregated export groups by source location, so zones named at run time all end up as one; each event
+    # carries its own name
+    times = {}
+
+    for event in export(["-u", capture]):
+        times.setdefault(event["name"], []).append(float(event["exec_time_ns"]) / 1e6)
+
+    print(f"{'zone':44} {'count':>8} {'mean ms':>9} {'max ms':>9} {'total ms':>10}")
+
+    for name, values in sorted(times.items(), key=lambda item: -sum(item[1]))[:rows]:
+        print(f"{name[:44]:44} {len(values):>8} {statistics.fmean(values):>9.3f} {max(values):>9.3f} {sum(values):>10.1f}")
+
+    gpu = {}
+
+    for zone in export(["-g", capture]):
+        gpu.setdefault(zone["name"], []).append(float(zone["GPU execution time"]) / 1e6)
+
+    if gpu:
+        print(f"\n{'gpu zone':44} {'count':>8} {'mean ms':>9} {'p99 ms':>9} {'max ms':>9}")
+
+        for name, times in gpu.items():
+            times.sort()
+            print(
+                f"{name[:44]:44} {len(times):>8} {statistics.fmean(times):>9.3f} "
+                f"{times[int(len(times) * 0.99)]:>9.3f} {times[-1]:>9.3f}"
+            )
+
+
+main()